AWS Lambda
Run code without thinking about servers
AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume.
Serverless Computing
Lambda automatically scales, from a few requests per day to thousands per second. You never pay for idle capacity.
Key Concepts
Functions
The core unit of Lambda. Contains your code and configuration.
Triggers
Events that invoke your function:
- API Gateway HTTP requests
- S3 bucket events
- DynamoDB streams
- CloudWatch Events/EventBridge
- SQS messages
- SNS notifications
Lambda Execution Flow
Layers
Reusable code packages shared across functions.
Execution Environment
Isolated runtime environment with:
- Memory: 128 MB to 10,240 MB
- Timeout: Up to 15 minutes
- Ephemeral storage: Up to 10 GB
Supported Runtimes
| Runtime | Versions |
|---|---|
| Node.js | 18.x, 20.x |
| Python | 3.9, 3.10, 3.11, 3.12 |
| Java | 11, 17, 21 |
| .NET | 6, 8 |
| Go | 1.x (provided.al2) |
| Ruby | 3.2 |
| Custom | provided.al2, provided.al2023 |
Function Structure
export const handler = async (event, context) => {
console.log('Event:', JSON.stringify(event, null, 2));
return {
statusCode: 200,
body: JSON.stringify({
message: 'Hello from Lambda!',
requestId: context.awsRequestId
})
};
};import json
def handler(event, context):
print(f"Event: {json.dumps(event)}")
return {
'statusCode': 200,
'body': json.dumps({
'message': 'Hello from Lambda!',
'requestId': context.aws_request_id
})
}package main
import (
"context"
"github.com/aws/aws-lambda-go/lambda"
)
type Response struct {
Message string `json:"message"`
}
func handler(ctx context.Context) (Response, error) {
return Response{Message: "Hello from Lambda!"}, nil
}
func main() {
lambda.Start(handler)
}Event Sources
{
"httpMethod": "POST",
"path": "/users",
"headers": {
"Content-Type": "application/json"
},
"body": "{\"name\": \"John\"}"
}{
"Records": [
{
"eventName": "ObjectCreated:Put",
"s3": {
"bucket": {"name": "my-bucket"},
"object": {"key": "uploads/file.txt"}
}
}
]
}{
"Records": [
{
"messageId": "msg-123",
"body": "{\"action\": \"process\"}",
"attributes": {
"ApproximateReceiveCount": "1"
}
}
]
}Environment Variables
Access configuration without hardcoding:
const tableName = process.env.TABLE_NAME;
const apiKey = process.env.API_KEY;Security
Use AWS Secrets Manager or Parameter Store for sensitive values like API keys and database credentials.
VPC Configuration
Connect Lambda to resources in your VPC:
{
"VpcConfig": {
"SubnetIds": ["subnet-123", "subnet-456"],
"SecurityGroupIds": ["sg-789"]
}
}VPC Considerations
- Adds cold start latency (~1-2 seconds)
- Requires NAT Gateway for internet access
- Use VPC endpoints for AWS services (S3, DynamoDB, etc.)
Layers
Share code and dependencies across functions:
aws lambda publish-layer-version \
--layer-name my-dependencies \
--zip-file fileb://layer.zip \
--compatible-runtimes nodejs18.x nodejs20.xLayer structure:
layer.zip
└── nodejs/
└── node_modules/
└── ... dependenciesConcurrency
Concurrency Model
Reserved Concurrency
Guarantee capacity for critical functions.
Provisioned Concurrency
Pre-initialized execution environments to eliminate cold starts.
aws lambda put-provisioned-concurrency-config \
--function-name my-function \
--qualifier prod \
--provisioned-concurrent-executions 100Provisioned concurrency is billed even when not in use. Use it strategically for latency-sensitive applications.
Error Handling
Dead Letter Queues
Send failed async invocations to SQS or SNS:
aws lambda update-function-configuration \
--function-name my-function \
--dead-letter-config TargetArn=arn:aws:sqs:us-east-1:123456789012:dlqRetry Behavior
| Invocation Type | Retries |
|---|---|
| Synchronous | Caller handles |
| Asynchronous | 2 retries |
| Event source | Depends on source |
Always implement idempotency in your functions since retries may cause duplicate executions.
Best Practices
Performance
- Minimize cold starts with provisioned concurrency
- Keep deployment packages small
- Use layers for dependencies
- Reuse connections outside handler
Security
- Use IAM roles with least privilege
- Store secrets in Secrets Manager
- Enable VPC for private resources
- Use reserved concurrency for rate limiting
Cost Optimization
- Right-size memory allocation
- Use Graviton2 (ARM) for up to 34% cost savings
- Optimize code for faster execution
- Use provisioned concurrency only when needed
Monitoring
CloudWatch Metrics
- Invocations - Number of times function was invoked
- Duration - Execution time in milliseconds
- Errors - Invocations that resulted in errors
- Throttles - Invocations that were throttled
- ConcurrentExecutions - Number of concurrent executions
X-Ray Tracing
Enable active tracing for distributed tracing:
aws lambda update-function-configuration \
--function-name my-function \
--tracing-config Mode=ActiveX-Ray helps identify performance bottlenecks and errors across distributed applications.