Complete Guide to AWS Lambda in Production
Run AWS Lambda in production: cold starts, deployment patterns, connection pooling, observability, security, retries and cost tuning with code.
Introduction
Getting a Lambda function to work takes an afternoon. Keeping it healthy in production is where teams get surprised: the API that is fast in staging adds two seconds on cold start, the RDS proxy bill nobody budgeted for, the canary deploy that shipped anyway because nobody set a rollback alarm. Most Lambda incidents aren’t exotic — they’re the same handful of operational details skipped during the happy path.
This guide covers the whole lifecycle: cold start mitigation, deployment patterns, connection pooling, observability, security hardening, retries and cost tuning. Every pattern ships with runnable code (Python + SAM/CLI, because the ideas transfer to any runtime), the trade-offs that only show up under real load, and pointers to sibling resources where a topic deserves its own guide — like the broader serverless architecture guide for system design, or AWS Lambda Cold Start Optimization for the recipe-level deep dive.
Cold Start Optimization
A cold start is the price of Lambda’s on-demand model: when no warm execution environment exists, AWS provisions one, downloads your code, boots the runtime, and runs your module-level init before your handler ever sees the event. Depending on runtime and package size that costs anywhere from ~100 ms (Go) to several seconds (JVM, VPC-attached functions used to pay extra for ENI creation too, though modern VPC networking has mostly removed that penalty).
The mitigation strategy should match your traffic shape — this is a decision, not a checkbox:
| Mitigation | Cost | Best when |
|---|---|---|
| Small package + lazy imports | Free | Always — the baseline you should hit first |
| Lambda Layers | Free | Shared deps across several functions |
| Init outside handler | Free | SDK clients, secrets, connection setup |
| Fast runtime (Go/Node/Rust) | Free (rewrite cost) | Latency-critical endpoints, new functions |
| SnapStart (Java) | Free | JVM functions — huge win, few constraints |
| Provisioned Concurrency | ~$$$/month per env | P99-sensitive APIs, steady traffic |
Measuring Cold Starts
You can’t tune what you can’t see. Log init time separately from handler time — CloudWatch splits them (REPORT lines show Init Duration), but instrumenting it yourself makes the numbers explicit:
import json
import time
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
init_start = time.time()
# Heavy init outside the handler: runs once per environment
import boto3
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("users")
init_ms = round((time.time() - init_start) * 1000)
logger.info(json.dumps({"event": "cold_start_init", "duration_ms": init_ms}))
def lambda_handler(event, context):
start = time.time()
user_id = event["pathParameters"]["userId"]
response = table.get_item(Key={"id": user_id})
logger.info(json.dumps({
"event": "invocation_complete",
"duration_ms": round((time.time() - start) * 1000),
"request_id": context.aws_request_id,
}))
return {
"statusCode": 200,
"body": json.dumps(response.get("Item", {}), default=str),
}
Reducing Package Size
Every megabyte in the deployment package is downloaded and unpacked on cold start. The two biggest offenders in Python are bundling the kitchen sink and importing heavy libraries for trivial work:
# Bad: importing the whole library for a mean
import numpy # ~55MB unpacked
# Better but still heavy: from-import loads the same library
from numpy import array, mean
# Best for trivial math: no dependency at all
def calculate_average(numbers):
return sum(numbers) / len(numbers)
The dependency problem compounds when you also ship test frameworks, botocore (already in the runtime), or wheels compiled for your laptop — the recipe AWS Lambda Python Dependencies covers packaging wheels correctly for the Amazon Linux runtime.
Lambda Layers
Layers share dependencies across functions without bloating every package. They also speed up deploys, since you ship only your code:
# Package the layer (path layout matters: python/ for runtimes)
mkdir -p python/lib/python3.11/site-packages
pip install requests -t python/lib/python3.11/site-packages/
zip -r requests-layer.zip python/
aws lambda publish-layer-version \
--layer-name requests-layer \
--zip-file fileb://requests-layer.zip \
--compatible-runtimes python3.11
# requests comes from the layer ARN attached to the function
import requests
def lambda_handler(event, context):
response = requests.get("https://api.example.com/data")
return {"statusCode": 200, "body": response.text}
Honest caveat: layers don’t reduce total cold start much — the layer still gets downloaded into the environment. Their real win is smaller per-function packages and faster deploys. Don’t expect magic.
Provisioned Concurrency
Provisioned concurrency keeps N environments pre-initialized so a burst never sees init at all. It works — and it bills continuously, around $0.015/environment-hour before request charges, so reserve it for endpoints where a P99 spike actually hurts revenue or SLAs.
aws lambda put-provisioned-concurrency-config \
--function-name my-api \
--qualifier live \
--provisioned-concurrent-executions 20
import os
def lambda_handler(event, context):
# AWS_LAMBDA_INITIALIZATION_TYPE reports how this env was started:
# "provisioned-concurrency" | "on-demand" | "snap-start"
is_provisioned = (
os.environ.get("AWS_LAMBDA_INITIALIZATION_TYPE")
== "provisioned-concurrency"
)
if is_provisioned:
logger.info("Warm pool hit — init already ran")
return handle_request(event)
Runtime Selection
If you’re writing a latency-critical function from scratch, runtime choice is the cheapest cold-start fix available:
| Runtime | Cold start (typical) | Best for |
|---|---|---|
| Rust / Go | ~100 ms | Latency-critical APIs |
| Node.js | ~200 ms | Web APIs, fast startup |
| Python | ~300 ms | Data processing, glue code |
| .NET | ~500 ms | Enterprise apps (AOT helps) |
| Java | ~1 s+ | Heavy frameworks — use SnapStart |
Numbers vary with package size and init work, but the ordering holds. Python’s cold start is fine for most jobs — don’t rewrite a working function for 200 ms.
Deployment Patterns
Lambda versions are immutable snapshots; aliases are the pointer you move. That simple model enables the two patterns that matter — and skipping them is how “it worked in dev” becomes a 2 a.m. rollback.
Canary Deploys (Blue/Green via Aliases)
Publish a version, shift a slice of traffic, watch for errors, promote or roll back:
# Publish the new version
aws lambda publish-version --function-name my-api
# Alias "live" sends 90% to v1, 10% canary to v2
aws lambda update-alias \
--function-name my-api \
--name live \
--function-version 2 \
--routing-config '{"AdditionalVersionWeights": {"1": 0.9}}'
# Healthy? Shift 100% to v2
aws lambda update-alias \
--function-name my-api \
--name live \
--function-version 2 \
--routing-config '{}'
Traffic Shifting with CodeDeploy
CodeDeploy automates the same dance with built-in rollback on CloudWatch alarms. Canary10Percent5Minutes is the sane default for user-facing APIs; linear shifts (Linear10PercentEveryNMinutes) spread risk when 10% is too coarse:
# SAM template — CodeDeploy reads DeploymentPreference
ApiFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: app.handler
Runtime: python3.11
AutoPublishAlias: live
DeploymentPreference:
Type: Canary10Percent5Minutes
Alarms:
- !Ref ApiErrorAlarm # rollback trigger
- !Ref ApiLatencyAlarm
The piece people forget is the alarm. A canary without a CloudWatch alarm on Errors/Duration isn’t a canary — it’s just a slower deploy that will happily ship a broken version.
Infrastructure as Code with SAM
Anything you can’t reproduce isn’t infrastructure — it’s luck. A minimal SAM template with table, alias, canary and rollback alarm looks like this:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
ApiFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: app.handler
Runtime: python3.11
MemorySize: 512
Timeout: 30
Environment:
Variables:
TABLE_NAME: !Ref UsersTable
Policies:
- DynamoDBReadPolicy:
TableName: !Ref UsersTable
Events:
GetUser:
Type: Api
Properties:
Path: /users/{userId}
Method: GET
AutoPublishAlias: live
DeploymentPreference:
Type: Canary10Percent5Minutes
Alarms:
- !Ref ApiErrorAlarm
UsersTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ApiErrorAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
MetricName: Errors
Namespace: AWS/Lambda
Statistic: Sum
Period: 300
EvaluationPeriods: 1
Threshold: 5
ComparisonOperator: GreaterThanThreshold
Connection Pooling
This is the classic “worked fine in load tests, died on launch day” failure. Every execution environment opens its own database connection, and environments scale with concurrency:
100 concurrent invocations
→ 100 separate execution environments
→ 100 database connections
→ RDS pool exhausted (e.g. max_connections: 90)
→ Connection refused during the traffic spike
Solution: RDS Proxy
RDS Proxy multiplexes Lambda connections onto a smaller real pool. It adds cost (per ACU-hour) and a little latency, but it’s the difference between scaling and falling over:
import os
import json
import psycopg2
def get_db_connection():
# Point at the PROXY endpoint, not the RDS instance directly
return psycopg2.connect(
host=os.environ["DB_PROXY_ENDPOINT"],
dbname=os.environ["DB_NAME"],
user=os.environ["DB_USER"],
password=get_secret()["password"], # Secrets Manager call (see below)
)
def lambda_handler(event, context):
conn = get_db_connection()
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE id = %s",
(event["user_id"],))
user = cursor.fetchone()
return {"statusCode": 200, "body": json.dumps(user, default=str)}
finally:
cursor.close()
conn.close()
Two operational notes that bite in production. First, pin connection behavior with RDS_PROXY settings — don’t open a new client per invocation if you can reuse one at module scope. Second, proxy or not, close connections in finally: a leaked cursor holds a pooled slot.
Alternative: DynamoDB
If the workload can tolerate NoSQL, DynamoDB sidesteps the whole problem — it’s an HTTP API, so there is no connection pool to exhaust. That’s one of the reasons serverless architectures so often pair Lambda with DynamoDB; the trade-offs live in the serverless databases guide.
import boto3
import json
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("users")
def lambda_handler(event, context):
response = table.get_item(Key={"id": event["user_id"]})
return {
"statusCode": 200,
"body": json.dumps(response.get("Item", {}), default=str),
}
Observability
Lambda gives you console.log out of the box — grep-able is not the same as observable. In production you want structured logs you can query, traces that follow the request across services, and metrics that describe business health, not just invocation counts.
Structured Logging with CloudWatch
Emit JSON and CloudWatch Logs Insights can filter on any field:
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
request_id = context.aws_request_id
logger.info(json.dumps({
"level": "INFO",
"request_id": request_id,
"function": context.function_name,
"event_type": "request_start",
"user_id": event.get("user_id"),
"path": event.get("path"),
}))
try:
result = process_request(event)
logger.info(json.dumps({
"level": "INFO",
"request_id": request_id,
"event_type": "request_success",
"duration_ms": 150,
}))
return result
except Exception as e:
logger.error(json.dumps({
"level": "ERROR",
"request_id": request_id,
"event_type": "request_error",
"error": str(e),
"error_type": type(e).__name__,
}))
return {"statusCode": 500,
"body": json.dumps({"error": "Internal error"})}
Note the request_id on every line — that’s your join key across a distributed trace. For the broader alerting story (what to alarm on, SLOs, noise control), see the monitoring and alerting guide.
AWS X-Ray Tracing
patch_all() instruments boto3 and HTTP calls automatically; custom subsegments annotate the parts that matter to you:
import boto3
import json
from aws_xray_sdk.core import patch_all, xray_recorder
patch_all()
def lambda_handler(event, context):
user_id = event["user_id"]
with xray_recorder.in_subsegment("fetch_user_data"):
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("users")
response = table.get_item(Key={"id": user_id})
with xray_recorder.in_subsegment("transform_data"):
user = response.get("Item", {})
user["full_name"] = (
f"{user.get('first_name', '')} {user.get('last_name', '')}"
)
return {"statusCode": 200, "body": json.dumps(user, default=str)}
Enable tracing on the function (Mode: Active in SAM) and the X-Ray service map will show you where latency actually lives — usually not where you guessed.
Custom Metrics with CloudWatch
Business metrics (“orders processed”, “payment retries”) belong in put_metric_data. Keep dimensions low-cardinality — a metric per user_id is a bill, not observability:
import boto3
import time
cloudwatch = boto3.client("cloudwatch")
def emit_metric(name, value, unit="Count"):
cloudwatch.put_metric_data(
Namespace="MyApp/Lambda",
MetricData=[{
"MetricName": name,
"Value": value,
"Unit": unit,
"Dimensions": [{"Name": "Function", "Value": "user-api"}],
}],
)
def lambda_handler(event, context):
start = time.time()
try:
result = process_request(event)
emit_metric("RequestDuration", (time.time() - start) * 1000,
"Milliseconds")
return result
except Exception:
emit_metric("ErrorCount", 1)
raise
Security Hardening
Least Privilege IAM Roles
The default SAM-managed role is broader than most functions need. Write the smallest policy that works — every extra * in an execution role is blast radius:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["dynamodb:GetItem", "dynamodb:Query"],
"Resource": "arn:aws:dynamodb:us-east-1:123:table/users"
},
{
"Effect": "Allow",
"Action": ["secretsmanager:GetSecretValue"],
"Resource": "arn:aws:secretsmanager:us-east-1:123:secret:db-*"
}
]
}
Secrets Management
Fetch secrets once at module scope — the same execution environment reuses them across warm invocations, and you avoid paying Secrets Manager per request:
import os
import json
import boto3
import psycopg2
from functools import lru_cache
@lru_cache(maxsize=1)
def get_db_credentials():
"""Loaded once per execution environment, cached for warm calls."""
client = boto3.client("secretsmanager")
response = client.get_secret_value(
SecretId=os.environ["DB_SECRET_ARN"]
)
return json.loads(response["SecretString"])
def lambda_handler(event, context):
creds = get_db_credentials()
conn = psycopg2.connect(
host=creds["host"],
dbname=creds["dbname"],
user=creds["username"],
password=creds["password"],
)
# ...
VPC Configuration
Private RDS, ElastiCache and internal services require VPC attachment. The ENI cold-start penalty that made this painful years ago is mostly gone with modern Lambda networking, but you still need AWSLambdaVPCAccessExecutionRole permissions and NAT for outbound internet from private subnets:
VpcFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: app.handler
Runtime: python3.11
VpcConfig:
SubnetIds: [subnet-abc123, subnet-def456]
SecurityGroupIds: [sg-abc123]
Policies:
- VPCAccessPolicy: {}
- DynamoDBReadPolicy:
TableName: users
Input Validation
The handler is the trust boundary — validate before anything downstream sees the payload:
import json
import re
EMAIL_RE = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
def lambda_handler(event, context):
body = json.loads(event.get("body", "{}"))
for field in ("email", "name"):
if field not in body:
return {"statusCode": 400, "body": json.dumps(
{"error": f"Missing field: {field}"})}
if not re.match(EMAIL_RE, body["email"]):
return {"statusCode": 400,
"body": json.dumps({"error": "Invalid email"})}
if len(body["name"]) > 100:
return {"statusCode": 400,
"body": json.dumps({"error": "Name too long"})}
user = create_user(body)
return {"statusCode": 201, "body": json.dumps(user, default=str)}
For larger schemas use a validator (Pydantic, aws-lambda-powertools event parser) instead of hand-rolled checks — same result, less code to maintain.
Error Handling and Retries
Async invocations (SQS, EventBridge, SNS) retry by default — up to two times for async events, and SQS retries until the message expires. If your function isn’t idempotent, a transient failure means double-charged customers or duplicated rows.
Idempotent Functions
import json
import hashlib
def lambda_handler(event, context):
# Idempotency key derived from the event itself
event_hash = hashlib.md5(
json.dumps(event, sort_keys=True).encode()
).hexdigest()
key = f"idempotency:{event_hash}"
# `redis` is an app-provided client (VPC-attached ElastiCache)
cached = redis.get(key)
if cached:
return {"status": "already_processed",
"result": json.loads(cached)}
result = process_event(event)
redis.setex(key, 3600, json.dumps(result)) # TTL > retry window
return {"status": "processed", "result": result}
A subtle point: deriving the key from the event payload makes two different events that happen to serialize the same way collide — if that’s possible in your domain, key on the message ID instead (record["messageId"] for SQS) plus your own dedup attribute.
Dead Letter Queues
Anything that still fails after retries needs somewhere to go — a DLQ preserves the payload for replay instead of silently dropping it:
FunctionWithDLQ:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: app.handler
Runtime: python3.11
EventInvokeConfig:
MaximumEventAgeInSeconds: 3600
MaximumRetryAttempts: 2
DestinationConfig:
OnFailure:
Destination: !GetAtt FailureQueue.Arn
FailureQueue:
Type: AWS::SQS::Queue
Properties:
MessageRetentionPeriod: 1209600 # 14 days
Add an alarm on the DLQ depth — a queue that fills silently is the same as losing events, just slower to notice.
Cost Optimization
Lambda bills on GB-seconds. The counterintuitive part: more memory also means more CPU, so doubling memory can reduce the bill if the function finishes in half the time.
Memory Tuning
Don’t guess — AWS Lambda Power Tuning runs your function across memory settings and plots the cost/latency curve:
# Rough starting points (max memory is 10,240 MB, not 3,008):
# 128MB: trivial I/O, webhooks
# 256MB: light API handlers
# 512MB: DB queries, moderate processing
# 1024MB: CPU-heavy work — often cheaper than 512 at half the duration
# 3008MB+: parallel/vectorized jobs, video, ML inference
Avoiding Unnecessary Invocations
Batch wherever the upstream service allows it — SQS delivers up to 10 messages per invocation with BatchSize, and batchItemFailures lets you retry only the bad ones:
import json
def lambda_handler(event, context):
batch_failures = []
for record in event["Records"]:
try:
process_message(json.loads(record["body"]))
except Exception:
batch_failures.append(
{"itemIdentifier": record["messageId"]})
return {"batchItemFailures": batch_failures}
Returning partial failures instead of failing the whole batch is the difference between retrying one message and replaying ten.
Best Practices
- Init outside the handler. SDK clients, secrets, DB pools — anything at module scope is paid once per environment instead of once per request.
- Canary with an alarm, or don’t call it a canary. Traffic shifting without a rollback alarm is just a slower deploy.
- Close connections in
finally. Whether proxied or not, leaked cursors hold pooled slots. - Structured logs from day one. Retrofitting JSON logging into printf-style output mid-incident is miserable.
- Key metrics at low cardinality. Dimension on function/route/status, never on user IDs.
- Set timeouts deliberately. A 15-minute timeout on an API endpoint is an unbounded bill; 30 s is usually honest.
Common Mistakes
- Treating layers as a cold-start fix. They shrink deploys and dedupe dependencies, but the environment still downloads them — expect packaging gains, not latency magic.
- Provisioned concurrency on bursty endpoints. It bills while idle. On truly unpredictable traffic the cure costs more than the disease.
- Wildcard IAM “for now”.
Resource: "*"in dev has a way of surviving to prod; the compromised-function blast radius is exactly the policy’s width. - Retry storms without idempotency. SQS redelivers and async events retry — a non-idempotent handler turns one transient error into duplicated side effects.
- RDS without a proxy (or without math). Either pay for RDS Proxy, or do the connection budget per expected concurrency — “it’ll probably be fine” is how outages start.
- No DLQ on async events. Failed retries vanish without it, and you’ll find out from users, not dashboards.
Production Checklist
- Cold start mitigated appropriately (small package, lazy init, layers, or provisioned concurrency for P99-critical paths)
- Memory tuned with power-tuning data, not vibes
- Timeout set deliberately — not the default 3 s, not the 15 min max
- IAM role scoped to the exact ARNs needed
- Secrets in Secrets Manager, cached at module scope
- DB access via RDS Proxy or DynamoDB — connection math done
- Structured logging with request IDs on every line
- X-Ray active tracing enabled
- Business metrics emitted at sane cardinality
- DLQ + alarm on all async invocations
- Handlers idempotent under redelivery
- Canary deploy with rollback alarms via SAM/CDK
- Input validation at the handler boundary
- VPC only when required, with NAT path for internet egress
See Also
- Complete Guide to Serverless Architecture
- AWS Lambda Cold Start Optimization
- AWS Lambda Python Dependencies
- Complete Guide to Serverless Databases
- Complete Guide to Monitoring and Alerting
- Serverless Cold Start Runbook
- Complete Guide to Apache Kafka in Production
- Alert Management: On-Call Alerting That Works
Frequently Asked Questions
How do I reduce Lambda cold starts?
In order of cost: shrink the package, move init to module scope, share deps via layers, pick a faster runtime if it's new code, and only then pay for provisioned concurrency on P99-critical endpoints. For Java, SnapStart is essentially free latency.
Should I use RDS Proxy with Lambda?
If your function touches RDS at meaningful concurrency — yes. Environments each hold their own connection, and the pool dies before your traffic does. At low concurrency a direct connection plus careful reuse is cheaper.
What concurrency does Lambda allow by default?
1,000 concurrent executions per region per account — see the Lambda quotas doc. You can request increases, and reserved concurrency caps individual functions so one runaway doesn't starve the rest of the account.
Can Lambda run jobs longer than 15 minutes?
Not in one shot. Chain functions with Step Functions, chunk the work itself, or move it to AWS Batch/Fargate. Fighting the timeout with a loop and checkpoints inside one invocation is a hack that breaks at the worst moment.
What's the best way to test Lambda locally?
sam local invoke and sam local start-api cover most handler logic; LocalStack emulates the AWS services around it. The pattern that pays off: keep handlers thin and put logic in plain functions you can unit test without any AWS emulator.
Do provisioned concurrency and SnapStart work together?
They're alternatives for different runtimes — SnapStart (Java) restores from a snapshot of the initialized environment, while provisioned concurrency keeps live environments warm. SnapStart is free; provisioned concurrency bills per environment-hour.
Related Resources
Complete Guide to Serverless Architecture
Decide when to go serverless and when not to. FaaS patterns, cold starts, cost models, vendor lock-in, and migration strategies for production.
RecipeReduce AWS Lambda Cold Start with Provisioned Concurrency
Minimize Lambda cold start latency using provisioned concurrency, ARM64 Graviton, lighter dependencies, and initialization code optimization.
RecipePackage Python Dependencies for AWS Lambda with Layers
Package Python dependencies for AWS Lambda using Lambda Layers, Docker builds for native extensions, and SAM/Serverless Framework integration.
PatternCircuit Breaker Pattern in Python, JavaScript, and Java
Prevent cascading failures by stopping requests to failing services. An architectural pattern for resilient distributed systems.
GuideComplete Guide to Serverless Databases
Choose and operate serverless databases for event-driven apps: DynamoDB, Aurora Serverless, FaunaDB, PlanetScale — pricing, scaling, and trade-offs.
GuideComplete Guide to Redis Caching Strategies
Choose and implement the right Redis caching pattern — cache-aside to refresh-ahead — with eviction, TTL, and production ops guidance.