Lambda Best Practices: A Beginner's Guide
Building your first Lambda function on AWS? This guide covers the essential best practices for performance, cost optimization, and reliability based on real-world experience.
Introduction
Building your first Lambda function on AWS? This guide covers the essential best practices for performance, cost optimization, and reliability based on real-world experience.
1. Choose the Right Architecture: ARM64 (Graviton)
Why ARM64?
Cost Savings: 20% cheaper than x86_64 for the same performance
Better Performance: Often faster due to modern architecture
Energy Efficient: Lower carbon footprint
How to Use ARM64
In your CloudFormation template:
MyLambdaFunction: Type: AWS::Lambda::Function Properties: Runtime: python3.12 Architectures: - arm64 # ← Use this instead of x86_64 Handler: index.lambda_handler MemorySize: 512When to Use x86_64
- You need specific libraries only available for x86
- You're using compiled dependencies that don't support ARM
- You're migrating existing code and want to minimize changes
Recommendation: Start with ARM64 unless you have a specific reason not to.
2. Right-Size Your Lambda Memory
The Problem
Lambda pricing is based on memory allocation and execution time:
- Too small: Slow execution, timeouts, poor user experience
- Too large: Fast execution but wasted money
- Just right: Balanced cost and performance
The Impact
From our testing with a real AI application:
Memory | Duration | Cost per 1M | Monthly (10M) | Verdict |
|---|---|---|---|---|
128MB | 2,300ms | $4.79 | $47.91 | ❌ 99% failures |
512MB | 1,773ms | $14.77 | $147.73 | ✅ Optimal |
3008MB | 1,333ms | $65.25 | $652.52 | 💸 Wasteful |
Key Insight: The 3008MB configuration costs 4.4x more but is only 25% faster. The 128MB configuration saves money but fails 99% of the time.
How to Right-Size (The Easy Way)
Use the AWS Lambda Power Tuning tool - it automates the testing for you!
Step 1: Deploy the Power Tuning Tool
- Go to the AWS Serverless Application Repository
- Click "Deploy"
- Accept the default settings
- Wait 2-3 minutes for deployment
Step 2: Run the Power Tuning
- Go to AWS Step Functions console
- Find the
powerTuningStateMachinestate machine
- Click "Start execution"
- Use this input (replace with your function name):
{ "lambdaARN": "arn:aws:lambda:us-east-1:YOUR-ACCOUNT:function:YOUR-FUNCTION-NAME", "powerValues": [128, 256, 512, 1024, 1536, 2048, 3008], "num": 100, "payload": {}, "parallelInvocation": true, "strategy": "balanced"}Step 3: Review Results
The tool will:
- Test your Lambda at different memory sizes
- Generate a visualization showing cost vs performance
- Recommend the optimal memory configuration
- Show you exactly how much you'll save
Time investment: 5-10 minutes
Potential savings: Hundreds to thousands of dollars per year
Manual Testing (If You Prefer)
If you want to test manually:
- Baseline: Start with 512MB (good default)
- Test Higher: Try 1024MB, 1536MB
- Test Lower: Try 256MB, 128MB
- Measure: Duration, cost, failure rate
- Choose: Best balance of cost and performance
3. Set Up Proper Monitoring and Alarms
Why Monitoring Matters
Without alarms, you won't know when:
- Your Lambda is failing
- Performance is degrading
- You're being throttled
- Costs are spiking
Essential CloudWatch Alarms
Alarm 1: Error Rate
LambdaErrorAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: lambda-errors AlarmDescription: Alert when Lambda has errors MetricName: Errors Namespace: AWS/Lambda Statistic: Sum Period: 300 EvaluationPeriods: 1 Threshold: 1 ComparisonOperator: GreaterThanOrEqualToThreshold Dimensions: - Name: FunctionName Value: !Ref MyLambdaFunction AlarmActions: - !Ref AlertTopic # SNS topic for emailWhy: Catches code errors immediately
Alarm 2: Throttles
LambdaThrottleAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: lambda-throttles AlarmDescription: Alert when Lambda is throttled MetricName: Throttles Namespace: AWS/Lambda Statistic: Sum Period: 300 EvaluationPeriods: 1 Threshold: 1 ComparisonOperator: GreaterThanOrEqualToThreshold Dimensions: - Name: FunctionName Value: !Ref MyLambdaFunction AlarmActions: - !Ref AlertTopicWhy: Tells you when you're hitting concurrency limits
Alarm 3: Duration (Slow Responses)
LambdaSlowResponseAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: lambda-slow-response AlarmDescription: Alert when Lambda is consistently slow MetricName: Duration Namespace: AWS/Lambda Statistic: Average Period: 300 EvaluationPeriods: 3 Threshold: 3000 # 3 seconds ComparisonOperator: GreaterThanThreshold Dimensions: - Name: FunctionName Value: !Ref MyLambdaFunction AlarmActions: - !Ref AlertTopicWhy: Catches when Lambda is undersized or experiencing issues
Alarm 4: High Duration (Approaching Timeout)
LambdaHighDurationAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: lambda-high-duration AlarmDescription: Alert when Lambda approaches timeout MetricName: Duration Namespace: AWS/Lambda Statistic: Maximum Period: 300 EvaluationPeriods: 1 Threshold: 45000 # 45 seconds (if timeout is 60s) ComparisonOperator: GreaterThanThreshold Dimensions: - Name: FunctionName Value: !Ref MyLambdaFunction AlarmActions: - !Ref AlertTopicWhy: Warns you before timeouts occur
SNS Topic for Email Alerts
AlertTopic: Type: AWS::SNS::Topic Properties: TopicName: lambda-alerts Subscription: - Endpoint: your-email@example.com Protocol: emailImportant: Check your email and confirm the subscription!
4. Enable Structured Logging
Why Structured Logging?
- Easy to search and filter
- Machine-readable for analysis
- Better for CloudWatch Logs Insights
Example: Python Lambda with Structured Logging
import jsonimport time
def lambda_handler(event, context): start_time = time.time() # Log invocation print(json.dumps({ "level": "INFO", "message": "Lambda invoked", "request_id": context.aws_request_id, "function_name": context.function_name, "memory_limit_mb": context.memory_limit_in_mb })) try: # Your Lambda logic here result = process_request(event) # Log success duration_ms = (time.time() - start_time) * 1000 print(json.dumps({ "level": "INFO", "message": "Request completed successfully", "request_id": context.aws_request_id, "duration_ms": duration_ms })) return { "statusCode": 200, "body": json.dumps(result) } except Exception as e: # Log error duration_ms = (time.time() - start_time) * 1000 print(json.dumps({ "level": "ERROR", "message": "Request failed", "request_id": context.aws_request_id, "error": str(e), "error_type": type(e).__name__, "duration_ms": duration_ms })) raiseCloudWatch Logs Insights Queries
Find errors:
fields @timestamp, message, error, error_type| filter level = "ERROR"| sort @timestamp desc| limit 20Average duration:
fields @timestamp, duration_ms| filter level = "INFO" and message = "Request completed successfully"| stats avg(duration_ms), max(duration_ms), min(duration_ms)
- **## 5. Set Appropriate Timeouts### The Problem Too short: Legitimate requests timeout
- Too long: Failed requests waste money and time### Recommendations| Use Case | Timeout | Reasoning | | ------------------ | -------- | --------------------------- | | API Gateway | 29s | API Gateway max is 29s | | Simple processing | 10-30s | Most tasks complete quickly | | Complex processing | 60-300s | AI, video, large data | | Background jobs | 300-900s | Max is 15 minutes |### How to Set```yaml MyLambdaFunction: Type: AWS::Lambda::Function Properties: Timeout: 60 # seconds
* Subsequent requests are faster (warm)### How to Minimize Cold Starts#### 1. Use ARM64* Faster initialization than x86\_64#### 2. Keep Dependencies Small```bash# Bad: Include entire librarypip install boto3
# Good: Only include what you needpip install boto3 --no-deps```#### 3. Initialize Outside Handler```pythonimport boto3
# Initialize once (outside handler)dynamodb = boto3.resource('dynamodb')table = dynamodb.Table('my-table')
def lambda_handler(event, context): # Use initialized resources table.put_item(Item={'id': '123'})```#### 4. Use Provisioned Concurrency (If Needed)```yamlMyLambdaFunction: Type: AWS::Lambda::Function Properties: # ... other properties
ProvisionedConcurrency: Type: AWS::Lambda::Alias Properties: FunctionName: !Ref MyLambdaFunction FunctionVersion: !GetAtt MyLambdaVersion.Version Name: live ProvisionedConcurrencyConfig: ProvisionedConcurrentExecutions: 5```**Cost**: More expensive, only use for latency-critical applications***## 7. Set Appropriate Concurrency Limits### Why Concurrency Limits?* Prevent runaway costs* Protect downstream services* Ensure predictable behavior### How to Set```yamlMyLambdaFunction: Type: AWS::Lambda::Function Properties: ReservedConcurrentExecutions: 100 # Max 100 concurrent executions```### Recommendations| Use Case | Concurrency | Reasoning || --------------- | ----------- | ------------------- || Development | 10-50 | Prevent accidents || Production API | 100-1000 | Based on traffic || Background jobs | 10-100 | Protect downstream || Unlimited | null | Only if you're sure |***## 8. Use Environment Variables for Configuration### Why?* No code changes for different environments* Easy to update without redeployment* Secure with encryption### Example```yamlMyLambdaFunction: Type: AWS::Lambda::Function Properties: Environment: Variables: TABLE_NAME: !Ref MyDynamoDBTable API_ENDPOINT: https://api.example.com LOG_LEVEL: INFO ENVIRONMENT: production```In your code:```pythonimport os
TABLE_NAME = os.environ['TABLE_NAME']LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')```***## 9. Tag Everything for Cost Tracking### Why Tags?Track costs by project, team, environmentIdentify cost optimization opportunitiesAllocate costs to departments### Example```yamlMyLambdaFunction: Type: AWS::Lambda::Function Properties: Tags: - Key: Project Value: my-project - Key: Environment Value: production - Key: Team Value: backend - Key: CostCenter Value: engineering```***## Quick Start ChecklistWhen creating a new Lambda function:* \[ ] Use ARM64 architecture (unless you have a reason not to)* \[ ] Start with 512MB memory* \[ ] Run AWS Lambda Power Tuning to optimize* \[ ] Set up 4 CloudWatch alarms (errors, throttles, duration, high duration)* \[ ] Configure SNS topic for email alerts* \[ ] Enable X-Ray tracing* \[ ] Implement structured logging (JSON format)* \[ ] Set appropriate timeout (2x expected duration)* \[ ] Set concurrency limits* \[ ] Use environment variables for configuration* \[ ] Add tags for cost tracking* \[ ] Test with realistic load* \[ ] Monitor for 1-2 weeks* \[ ] Adjust based on real-world data***## Real-World ExampleHere's a complete CloudFormation snippet with all best practices:```yaml# SNS Topic for AlertsAlertTopic: Type: AWS::SNS::Topic Properties: TopicName: my-lambda-alerts Subscription: - Endpoint: team@example.com Protocol: email
# Lambda FunctionMyLambdaFunction: Type: AWS::Lambda::Function Properties: FunctionName: my-optimized-function Runtime: python3.12 Architectures: - arm64 Handler: index.lambda_handler MemorySize: 512 Timeout: 60 ReservedConcurrentExecutions: 100 TracingConfig: Mode: Active Environment: Variables: TABLE_NAME: !Ref MyTable LOG_LEVEL: INFO Tags: - Key: Project Value: my-project - Key: Environment Value: production Code: ZipFile: | import json import time def lambda_handler(event, context): start_time = time.time() print(json.dumps({ "level": "INFO", "message": "Lambda invoked", "request_id": context.aws_request_id })) try: # Your logic here result = {"message": "Success"} duration_ms = (time.time() - start_time) * 1000 print(json.dumps({ "level": "INFO", "message": "Request completed", "duration_ms": duration_ms })) return { "statusCode": 200, "body": json.dumps(result) } except Exception as e: print(json.dumps({ "level": "ERROR", "message": "Request failed", "error": str(e) })) raise
# CloudWatch AlarmsLambdaErrorAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: my-lambda-errors MetricName: Errors Namespace: AWS/Lambda Statistic: Sum Period: 300 EvaluationPeriods: 1 Threshold: 1 ComparisonOperator: GreaterThanOrEqualToThreshold Dimensions: - Name: FunctionName Value: !Ref MyLambdaFunction AlarmActions: - !Ref AlertTopic
LambdaThrottleAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: my-lambda-throttles MetricName: Throttles Namespace: AWS/Lambda Statistic: Sum Period: 300 EvaluationPeriods: 1 Threshold: 1 ComparisonOperator: GreaterThanOrEqualToThreshold Dimensions: - Name: FunctionName Value: !Ref MyLambdaFunction AlarmActions: - !Ref AlertTopic
LambdaSlowResponseAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: my-lambda-slow-response MetricName: Duration Namespace: AWS/Lambda Statistic: Average Period: 300 EvaluationPeriods: 3 Threshold: 3000 ComparisonOperator: GreaterThanThreshold Dimensions: - Name: FunctionName Value: !Ref MyLambdaFunction AlarmActions: - !Ref AlertTopic
LambdaHighDurationAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: my-lambda-high-duration MetricName: Duration Namespace: AWS/Lambda Statistic: Maximum Period: 300 EvaluationPeriods: 1 Threshold: 45000 ComparisonOperator: GreaterThanThreshold Dimensions: - Name: FunctionName Value: !Ref MyLambdaFunction AlarmActions: - !Ref AlertTopic```***## Cost Optimization Summary### What We LearnedFrom our real-world testing:**Choosing ARM64 over x86\_64**: 20% savings**Right-sizing from 3008MB to 512MB**: 77% savings**Avoiding undersizing (128MB)**: Prevented 99% failure rate**Combined impact**: For 10M requests/month, we went from $652/month (3008MB x86) to $118/month (512MB ARM64) = **82% cost reduction** while maintaining performance.### Your Action Plan1. **Week 1**: Deploy with ARM64 and 512MB2. **Week 2**: Run AWS Lambda Power Tuning3. **Week 3**: Adjust memory based on results4. **Week 4**: Monitor and validate savings**Time investment**: 2-3 hours**Potential savings**: Hundreds to thousands per year**Improved reliability**: Priceless***## Additional Resources* [AWS Lambda Power Tuning](https://serverlessrepo.aws.amazon.com/applications/arn\:aws\:serverlessrepo\:us-east-1:451282441545\:applications~aws-lambda-power-tuning)* [AWS Lambda Best Practices](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html)* [AWS Lambda Pricing](https://aws.amazon.com/lambda/pricing/)* [CloudWatch Alarms Documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)* [X-Ray Documentation](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-python.html)***## Questions?Common questions from beginners:**Q: Should I always use ARM64?**A: Yes, unless you have specific x86-only dependencies. Start with ARM64.**Q: What memory size should I start with?**A: 512MB is a good default. Then use Power Tuning to optimize.**Q: How many alarms do I really need?**A: Minimum 4: Errors, Throttles, Slow Response, High Duration.**Q: Is X-Ray worth the cost?**A: Yes for production. The cost is minimal (~$5/month) and the insights are invaluable.**Q: How often should I re-test memory sizing?**A: Every 3-6 months, or when your code changes significantly.Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article