AWS Lambda Deep Dive Cheat Sheet
Practical reference for writing, deploying, and configuring AWS Lambda functions including triggers, layers, and CLI usage.
Python Handler
Basic Lambda function handler signature.
import jsondef lambda_handler(event, context): # event: dict with the trigger payload # context: runtime info (request_id, remaining time, etc.) body = json.loads(event.get('body', '{}')) return { 'statusCode': 200, 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps({'message': f"Hello {body.get('name', 'World')}"}) }
CLI: Create & Update Function
Deploy and update a function via the AWS CLI.
# Zip and createzip function.zip lambda_function.pyaws lambda create-function \ --function-name my-func \ --runtime python3.12 \ --role arn:aws:iam::123456789012:role/lambda-exec-role \ --handler lambda_function.lambda_handler \ --zip-file fileb://function.zip# Update code after changesaws lambda update-function-code \ --function-name my-func --zip-file fileb://function.zip# Invokeaws lambda invoke --function-name my-func out.json
Environment & Config Update
Set memory, timeout, and environment variables.
aws lambda update-function-configuration \ --function-name my-func \ --timeout 30 \ --memory-size 256 \ --environment "Variables={STAGE=prod,LOG_LEVEL=info}"
Common Event Sources
Key common event sources to know.
- API Gateway- HTTP requests invoke the function synchronously (REST or HTTP API)
- S3- Object created/removed events trigger the function asynchronously
- EventBridge- Scheduled (cron) or event-pattern based invocations
- SQS- Lambda polls the queue and processes messages in batches
- DynamoDB Streams- Invoked on table item changes (insert/update/delete)
Key Concepts
Key key concepts to know.
- Cold Start- Latency from initializing a new execution environment before first invoke
- Layer- Shared zip archive of libraries/dependencies attached to multiple functions
- Concurrency- Number of simultaneous executions; can set reserved or provisioned concurrency
- Execution Role- IAM role granting the function permissions to call other AWS services
- Timeout- Max runtime per invocation, configurable up to 900 seconds (15 min)
Provisioned Concurrency (Eliminate Cold Starts)
Keep a fixed number of execution environments pre-initialized for latency-sensitive endpoints.
# Publish a version first — provisioned concurrency targets a version or alias, not $LATESTaws lambda publish-version --function-name my-funcaws lambda put-provisioned-concurrency-config \ --function-name my-func \ --qualifier 3 \ --provisioned-concurrent-executions 5# Auto-scale provisioned concurrency with Application Auto Scalingaws application-autoscaling register-scalable-target \ --service-namespace lambda \ --resource-id function:my-func:prod \ --scalable-dimension lambda:function:ProvisionedConcurrency \ --min-capacity 2 --max-capacity 20
Building & Publishing a Layer
Share dependencies across functions and keep deployment packages small.
mkdir -p python-layer/pythonpip install requests -t python-layer/pythoncd python-layer && zip -r ../layer.zip python && cd ..aws lambda publish-layer-version \ --layer-name shared-deps \ --zip-file fileb://layer.zip \ --compatible-runtimes python3.12aws lambda update-function-configuration \ --function-name my-func \ --layers arn:aws:lambda:us-east-1:123456789012:layer:shared-deps:1
Error Handling: DLQ vs Destinations
Configure asynchronous invocation failure handling — destinations supersede the older dead-letter-queue mechanism.
# Destinations: route based on success/failure, richer payload than DLQaws lambda put-function-event-invoke-config \ --function-name my-func \ --maximum-retry-attempts 2 \ --destination-config '{ "OnSuccess": {"Destination": "arn:aws:sns:us-east-1:123456789012:success-topic"}, "OnFailure": {"Destination": "arn:aws:sqs:us-east-1:123456789012:failure-queue"} }'# Legacy DLQ (only captures the failed event, no context)aws lambda update-function-configuration \ --function-name my-func \ --dead-letter-config TargetArn=arn:aws:sqs:us-east-1:123456789012:dlq
AWS SAM Template
Declarative IaC for a Lambda function with an API Gateway trigger, deployable via 'sam deploy'.
Transform: AWS::Serverless-2016-10-31Resources: MyFunction: Type: AWS::Serverless::Function Properties: CodeUri: src/ Handler: app.lambda_handler Runtime: python3.12 MemorySize: 256 Timeout: 10 ReservedConcurrentExecutions: 20 Environment: Variables: STAGE: prod Events: Api: Type: Api Properties: Path: /hello Method: get Policies: - DynamoDBReadPolicy: TableName: my-table
Advanced Runtime & Scaling Concepts
Terms that matter once you're tuning throughput and cost, not just shipping a first function.
- Reserved Concurrency- Caps (and guarantees) the max concurrent executions for one function, isolating it from account-wide concurrency exhaustion
- SnapStart- Java-only feature that snapshots an initialized execution environment to cut cold-start latency by up to 90%
- Execution Environment Reuse- Warm invocations reuse /tmp (up to 512MB-10GB ephemeral storage) and module-level state between invocations of the same environment
- Event Source Mapping Batch Window- For SQS/Kinesis/DynamoDB triggers, controls how long Lambda buffers records before invoking, trading latency for batch efficiency
- Function URL- Built-in HTTPS endpoint for a function without needing API Gateway, supports IAM auth or public access
- Lambda Extensions- Companion processes (via Extensions API) for telemetry/monitoring that run alongside the function, independent of the handler
- Graviton (arm64)- ARM-based architecture option offering up to 34% better price-performance versus x86_64 for compatible workloads
Initialize SDK clients and heavy imports outside the handler function body — code outside the handler runs once per execution environment and is reused across warm invocations, cutting latency significantly.