AWS Lambda canary deployment implementation using aliases and weighted traffic shifting to gradually roll out new versions with automated rollback capabilities.
This project demonstrates a production-ready serverless real estate property management API built with AWS CDK, implementing canary deployments for Lambda functions using Lambda aliases and AWS CodeDeploy. The architecture showcases best practices for gradual rollouts with automated monitoring and rollback mechanisms.
- π Canary Deployments: Automated gradual rollouts using AWS CodeDeploy (10% traffic for 5 minutes)
- π Automatic Rollback: CloudWatch Alarms trigger rollbacks on deployment failures
- π¦ Lambda Versioning: Code hash-based versioning for deterministic deployments
- π― Lambda Aliases: Production aliases with traffic shifting capabilities
- π Monitoring: CloudWatch error alarms for each Lambda function
- ποΈ Infrastructure as Code: Complete AWS CDK implementation
- ποΈ Single-Table Design: Optimized DynamoDB schema with PynamoDB ORM
- πΌοΈ Image Management: S3 + CloudFront for property images with presigned URLs
Code Change β Hash Generation β Lambda Version β Alias Update β Canary Deployment
β
10% traffic β Monitor errors for 5 min
β
Success β 100% traffic
Failure β Rollback
Each CRUD operation has its own Lambda function with canary deployment:
- CreatePropertyLambda: Create new property listings
- GetPropertyLambda: Retrieve single or multiple properties with filters
- UpdatePropertyLambda: Update existing property data
- DeletePropertyLambda: Delete properties and associated images
- API Gateway: RESTful API endpoints
- Lambda Functions: Serverless compute with production aliases
- DynamoDB: Two tables for properties and image metadata
- S3: Property image storage with versioning
- CloudFront: CDN for image delivery with Origin Access Control
- CloudWatch: Error monitoring and alarming
- CodeDeploy: Canary deployment orchestration
- Lambda Layers: Shared dependencies (PynamoDB, AWS Lambda Powertools)
- Type:
CANARY_10_PERCENT_5_MINUTES - Initial Traffic: 10% to new version
- Evaluation Period: 5 minutes
- Monitoring: CloudWatch error alarms (2 datapoints in 30-second periods)
- Auto-Rollback: Enabled for failed and stopped deployments
Lambda versions are automatically created based on code hash:
def _get_code_hash(self, directory: str) -> str:
"""Generate a hash of all files in the Lambda code directory."""
# Hashes all .py, .json, .txt, .yaml, .yml files
# Returns first 8 characters of MD5 hashThe hash is stored in the Lambda function description as v-{hash}, enabling deterministic version tracking.
https://{api-id}.execute-api.{region}.amazonaws.com/prod/properties
| Method | Endpoint | Description |
|---|---|---|
POST |
/properties |
Create new property |
GET |
/properties |
Get all properties (with filters) |
GET |
/properties/{id} |
Get single property |
PUT |
/properties/{id} |
Update property |
DELETE |
/properties/{id} |
Delete property |
city,state,type,statusfeatured=true,isNew=trueminPrice,maxPricelimit,offset(pagination)
.
βββ app.py # CDK stack definition
βββ cdk.json # CDK configuration
βββ requirements.txt # CDK dependencies
βββ models.py # PynamoDB models
βββ install_deps.sh # Layer dependencies installer
βββ CreatePropertyHandler/
β βββ handler.py # POST handler
βββ GetPropertyHandler/
β βββ handler.py # GET handler
βββ UpdatePropertyHandler/
β βββ handler.py # PUT handler
βββ DeletePropertyHandler/
β βββ handler.py # DELETE handler
βββ layers/
βββ common_layer/
βββ requirements.txt # Layer dependencies
βββ python/
βββ models.py # Shared models
βββ aws_lambda_powertools/
- Python 3.12+
- Node.js 18+ (for AWS CDK)
- AWS CLI configured
- AWS CDK CLI installed (
npm install -g aws-cdk)
-
Clone the repository
git clone <repository-url> cd lambda-alias-canary-deployment
-
Create virtual environment
python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Install Lambda layer dependencies
chmod +x install_deps.sh ./install_deps.sh
-
Bootstrap CDK (first time only)
cdk bootstrap
cdk deployThe deployment will output:
- API Gateway endpoint URL
- Lambda alias ARNs for each function
- CloudFront distribution domain
When you update Lambda handler code:
- Modify handler code in respective directories
- Deploy changes
cdk deploy
- Monitor deployment
- CodeDeploy will automatically:
- Create a new Lambda version
- Shift 10% traffic to new version
- Monitor for errors for 5 minutes
- Complete rollout or rollback based on alarms
- CodeDeploy will automatically:
AWS Console:
- Navigate to CodeDeploy β Deployments
- View deployment status and traffic shifting progress
CLI:
aws deploy list-deployments --application-name <deployment-group-name>Main property table with single-table design:
- PK:
PROPERTY#{id} - SK:
METADATA
Attributes:
- Basic: title, description, price, address, city, state, zip
- Details: beds, baths, sqft, type
- Media: images count, features list
- Status: featured, isNew, status (active/sold/pending)
- Analytics: viewCount, saveCount
- Timestamps: createdAt, updatedAt
Image metadata and analysis table:
- PK:
PROPERTY#{property_id} - SK:
IMAGE#{image_id}
Attributes:
- imageKey (S3 key)
- imageUrl (CloudFront URL)
- rekognitionLabels (AI-detected labels)
- uploadedAt
Lambda functions use the following environment variables:
PROPERTY_TABLE_NAME: DynamoDB property tablePROPERTY_IMAGES_TABLE: DynamoDB images tablePROPERTY_BUCKET: S3 bucket for imagesCLOUDFRONT_DOMAIN: CloudFront distribution domainALLOWED_ORIGIN: CORS allowed originCODE_VERSION: Lambda version hash
- Update handler code in respective directories
- Update models if schema changes
- Run install_deps.sh if new dependencies added
- Deploy with
cdk deploy - Monitor CodeDeploy for canary deployment progress
To remove all resources:
cdk destroyThis will delete:
- Lambda functions and versions
- API Gateway
- DynamoDB tables
- S3 bucket (with auto-delete enabled)
- CloudFront distribution
- CodeDeploy deployment groups
- CloudWatch alarms
- Traffic Shifting: Gradual rollout reduces blast radius of bugs
- Automated Monitoring: CloudWatch alarms enable automatic rollback
- Lambda Versioning: Immutable versions enable reliable rollbacks
- Aliases: Production alias provides stable ARN for API Gateway integration
- β Use Lambda layers for shared dependencies
- β Implement code hash versioning for deterministic deployments
- β Configure CloudWatch alarms for deployment monitoring
- β Enable auto-rollback for failed deployments
- β Use single-table design for DynamoDB optimization
- β Implement structured logging with AWS Lambda Powertools
- β Use presigned URLs for secure S3 access
- β Enable CloudFront OAC for S3 security
- AWS CDK (Python) - Infrastructure as Code
- AWS Lambda - Serverless compute
- AWS CodeDeploy - Deployment automation
- Amazon DynamoDB - NoSQL database
- Amazon S3 - Object storage
- Amazon CloudFront - CDN
- Amazon API Gateway - REST API
- AWS Lambda Powertools - Structured logging and tracing
- PynamoDB - Pythonic DynamoDB ORM
MIT
Note: This project is designed for educational purposes to demonstrate Lambda canary deployments with aliases. For production use, consider adding:
- Authentication/Authorization (Cognito, Lambda authorizers)
- Rate limiting and throttling
- Input validation and sanitization
- Comprehensive error handling
- Unit and integration tests
- CI/CD pipeline integration
- Cost monitoring and optimization