Sub topic 16
Cold starts and performance tuning
This chapter assumes you can deploy a Lambda-backed HTTP API with SAM and read CloudWatch Logs. It covers why some requests are slower than others and which settings help.
What a cold start is
Lambda runs your code in an execution environment. When a request arrives and no idle environment exists, Lambda creates one. It downloads your code, starts the runtime, and runs your initialization code. This is a cold start. Later requests reuse the same environment (warm invocations) and skip those steps.
Code outside the handler runs once per environment. Code inside the handler runs on every request.
Move reusable work out of the handler
Create SDK clients and read configuration during initialization so warm requests reuse them.
import json
import os
import boto3
TABLE_NAME = os.environ["TABLE_NAME"]
table = boto3.resource("dynamodb").Table(TABLE_NAME)
def handler(event, context):
item_id = event["pathParameters"]["id"]
result = table.get_item(Key={"id": item_id})
item = result.get("Item")
if item is None:
return {"statusCode": 404, "body": json.dumps({"message": "Not found"})}
return {"statusCode": 200, "body": json.dumps(item, default=str)}The client is built once per environment. Building it inside the handler would repeat that cost on every call.
Tuning settings
| Setting | Effect | Trade-off |
|---|---|---|
| Memory | Lambda allocates CPU in proportion to memory, so more memory often means faster execution | Higher price per millisecond, but shorter runs can cost the same or less |
| Package size | Smaller packages load faster | Requires trimming dependencies |
| Imports | Importing only what you use shortens initialization | Lazy imports move cost to the first call that needs them |
| Timeout | Should sit below the API's integration limit of 30 seconds | A low value fails slow calls early |
| Provisioned concurrency | Keeps environments initialized | You pay while it is configured |
You can set memory and provisioned concurrency in SAM:
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
MemorySize: 512
Timeout: 10
AutoPublishAlias: live
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: 2Provisioned concurrency applies to a published version or alias, so AutoPublishAlias is required. Point your API events at the alias, which SAM does when you set AutoPublishAlias.
Measuring before tuning
Each invocation writes a REPORT line to CloudWatch Logs. A cold start adds an Init Duration field. Search for it with Logs Insights:
filter @type = "REPORT"
| stats count() as invocations,
count(@initDuration) as coldStarts,
avg(@duration) as avgMs,
max(@initDuration) as maxInitMsIf cold starts are a small share of invocations, tune the handler's own duration first. If they dominate on a latency-sensitive route, consider provisioned concurrency.
Exercise
Your GET /items/{id} route is fast on most calls but occasionally takes two seconds longer. The REPORT lines for slow calls contain Init Duration. Name two code-level changes that reduce this delay, and one configuration change.
Show answer
Code: trim unused dependencies and imports to shorten initialization, and keep client creation outside the handler so it happens once per environment rather than per request. Configuration: enable provisioned concurrency on a published alias, or raise memory to give initialization more CPU.