After building scalable infrastructure using EC2, Terraform, and Secrets Manager, it’s time to go fully serverless. In this post, we’ll migrate your app to use:
- 🧠 AWS Lambda — run code without managing servers
- 🌐 API Gateway — expose HTTPS endpoints
- 🔐 Secrets Manager — keep secrets out of your code
- 🗃️ DynamoDB or RDS Proxy — handle your database layer
📦 Architecture Overview
Client → API Gateway → Lambda Functions → DB (DynamoDB or RDS via Proxy)
↓
Secrets Manager
✅ Benefits of This Serverless Stack
Feature | Benefit |
---|---|
No server to manage | Pay-per-use compute |
Autoscaling | Lambda scales on demand |
Secure secrets | AWS Secrets Manager or Parameter Store |
Low ops overhead | No patching, no EC2, no autoscaling setup |
Fast deployment | Single command using CDK or SAM |
🔧 Step-by-Step: Deploy with AWS SAM (Serverless Application Model)
1. 🛠 Install SAM CLI
brew install aws/tap/aws-sam-cli
sam --version
2. 📁 Project Structure
restaurant-booking-api/
├── template.yaml # SAM template (Infra as code)
├── app/
│ ├── __init__.py
│ └── handler.py # Lambda function code
├── events/ # Example test events
└── requirements.txt
3. ✍️ Sample SAM Template (template.yaml)
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
BookingAPI:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler.lambda_handler
Runtime: python3.11
MemorySize: 512
Timeout: 10
Environment:
Variables:
DB_SECRET: /myapp/db-creds
Events:
ApiEvent:
Type: Api
Properties:
Path: /bookings
Method: post
4. 🧠 handler.py (Lambda Code)
import json, boto3, os
def lambda_handler(event, context):
secrets = boto3.client('secretsmanager')
response = secrets.get_secret_value(SecretId=os.environ['DB_SECRET'])
creds = json.loads(response['SecretString'])
booking = json.loads(event['body'])
# Connect to DB, store booking using creds
return {
"statusCode": 200,
"body": json.dumps({"message": "Booking successful"})
}
5. 🚀 Deploy to AWS
sam build
sam deploy --guided
🔐 Storing DB Credentials in Secrets Manager
aws secretsmanager create-secret \
--name /myapp/db-creds \
--secret-string '{"username":"admin","password":"mypassword"}'
📊 Monitoring with CloudWatch
Each Lambda execution gets its own logs under /aws/lambda/. You can:
- Set up CloudWatch alarms for failure rates or latency
- Enable X-Ray tracing for distributed tracing
🌍 Bonus: Custom Domain with API Gateway + ACM
aws acm request-certificate \
--domain-name api.mkcloudai.com \
--validation-method DNS
# Then link ACM to API Gateway via custom domain mappings.