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.
