Sub topic 16
Cold starts and performance tuning
This chapter assumes you can write a Python Lambda handler, deploy it behind an HTTP API with AWS SAM, and read CloudWatch Logs. It covers why some requests are slower than others and what you can change to speed them up.
What a cold start is
Lambda runs your code inside an execution environment. This is an isolated sandbox with a runtime, your code, and the memory and CPU you configured. When a request arrives and no idle environment is available, Lambda must create one. This is a cold start. When an idle environment exists, Lambda reuses it. This is a warm start.
A cold start has two parts:
- Environment setup. Lambda downloads your code package, starts the runtime, and creates the sandbox. You control this only indirectly, through package size, runtime choice and configuration.
- Initialization (the init phase). Lambda runs the code outside your handler function: module imports, SDK client creation, and any other top-level statements. You control this directly.
After init, Lambda calls your handler. On a warm start, only the handler runs.
Cold starts affect a small share of requests in a steady workload. They show up more after a deployment, after a quiet period, and when traffic grows quickly, because each additional concurrent request needs its own environment.
Measuring before tuning
Do not guess. Lambda writes a REPORT line to CloudWatch Logs for each invocation. A cold start includes an Init Duration field:
REPORT RequestId: 8f2c... Duration: 3.41 ms Billed Duration: 4 ms Memory Size: 256 MB Max Memory Used: 61 MB Init Duration: 412.87 msWarm invocations have no Init Duration. You can count cold starts with CloudWatch Logs Insights:
filter @type = "REPORT"
| stats count(*) as invocations,
count(@initDuration) as coldStarts,
avg(@initDuration) as avgInit,
pct(@duration, 95) as p95Duration
by bin(5m)Look at percentiles (p95, p99), not only averages. Cold starts hurt the tail of the latency distribution. API Gateway also publishes a Latency metric (total time) and an IntegrationLatency metric (time spent waiting for Lambda). The difference between them is time spent in API Gateway itself, which is usually small.
Move expensive work into the init phase
Code outside the handler runs once per environment and is reused for every warm invocation. Create SDK clients and load configuration there, not inside the handler.
import json
import os
import boto3
TABLE_NAME = os.environ["TABLE_NAME"]
# Runs once per execution environment.
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(TABLE_NAME)
def handler(event, context):
item_id = event["pathParameters"]["id"]
# Runs on every invocation, reusing the client created above.
result = table.get_item(Key={"id": item_id})
item = result.get("Item")
if item is None:
return {
"statusCode": 404,
"headers": {"content-type": "application/json"},
"body": json.dumps({"message": "Not found"}),
}
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps(item, default=str),
}Reusing the client avoids repeating the TLS handshake and credential lookup on every request.
There is a trade-off. Work in the init phase delays the first request in every new environment. Move work into the handler, or load it lazily, when it is rarely needed. For example, a large machine-learning model used by one route should not be loaded by every route that shares the function.
_model = None
def get_model():
global _model
if _model is None:
_model = load_model() # your expensive loader
return _modelKeep the package small
Lambda must fetch and unpack your code on a cold start. Larger packages take longer.
- Include only the dependencies you import. Remove test libraries and unused packages from the deployment.
- Import only what you need.
import boto3is already in the Python runtime, so you usually do not need to bundle it. Pin a version only if you need newer features. - Avoid importing heavy libraries (such as pandas) in a function that serves a simple route.
- Consider splitting very different workloads into separate functions, so a lightweight route does not pay for the heavy route's imports.
Tune memory
In Lambda, the memory setting also controls CPU. More memory gives proportionally more CPU, so a CPU-bound function can finish faster at a higher setting. Because billing is memory multiplied by duration, a higher setting does not always cost more. If doubling memory halves the duration, the cost per invocation stays about the same and latency improves.
Memory also speeds up init, because init code gets the same CPU allocation.
You can find the best setting by testing. Run the same load at several memory sizes (for example 128, 256, 512, 1024 and 2048 MB) and compare Duration and cost. The open-source AWS Lambda Power Tuning tool automates this. In SAM, change one property:
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
MemorySize: 512
Timeout: 10Check Max Memory Used in the REPORT line to make sure you are not paying for memory you never touch, and to confirm you have headroom.
Choose the architecture and runtime deliberately
- arm64 (Graviton). Many functions run faster and cost less on arm64. Set
Architectures: [arm64]in SAM. Pure Python code usually works unchanged. Packages with compiled extensions must be built for arm64. - Runtime. Interpreted runtimes such as Python and Node.js generally have shorter init times than Java or .NET with default settings. If you use Java, look at Lambda SnapStart, which restores an environment from a snapshot taken after init.
- Timeout. Set a timeout close to what the route needs. An API Gateway HTTP API has an integration timeout limit of 30 seconds, so a Lambda timeout longer than that cannot help a client waiting on the response.
Provisioned concurrency
Provisioned concurrency keeps a number of execution environments initialized and ready. Requests that fit within that number never see a cold start. It is billed whether or not the environments are used, so use it for latency-sensitive routes with predictable traffic.
Provisioned concurrency applies to a function version or alias, not to $LATEST. In SAM, an AutoPublishAlias creates the alias:
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
AutoPublishAlias: live
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: 5Events defined on the function point at the alias, so the API invokes the provisioned environments. Traffic beyond five concurrent requests still uses on-demand environments and can cold start.
Other sources of latency
Not every slow request is a cold start. Check these too:
- Downstream calls. A slow database query or HTTP call usually dominates handler time. Set client timeouts and reuse connections.
- VPC access. Functions in a VPC no longer pay a large per-environment network setup cost, but they still need a route (NAT gateway or VPC endpoint) to reach AWS services. A missing route shows up as a timeout, not a fast failure.
- Logging volume. Very verbose logging adds time and cost. Log what you need to diagnose failures.
- Authorizers. A Lambda authorizer is an extra invocation, and it can cold start too. Enable authorizer result caching so repeated requests with the same identity skip it.
- Payload size. Large request and response bodies add serialization and network time.
Concurrency limits
Each concurrent request needs an environment, and your account has a regional concurrency quota. If a burst exceeds it, Lambda throttles the extra invocations and the client typically receives an error response. Reserved concurrency on a function sets a ceiling for that function and also guarantees it capacity out of the account pool. Use it to stop one noisy route's function from starving others, and combine it with API-level throttling from the earlier chapter.
A tuning workflow
- Measure with
REPORTlines and Logs Insights. Separate cold-start latency from warm latency. - Move client creation and configuration loading out of the handler.
- Remove unused dependencies and heavy imports.
- Test several memory sizes and pick the best cost and latency balance.
- Try arm64.
- Add provisioned concurrency only for routes where the measured cold-start tail breaks your latency goal.
- Re-measure after each change, so you know which change helped.
Exercise
A function shows an Init Duration of about 600 ms on cold starts and a warm Duration of 5 ms. The handler creates a new boto3 DynamoDB client on every invocation. Which change reduces warm latency, and which change reduces the number of requests that see the 600 ms?
Show answer
Moving client creation to module level (outside the handler) reduces warm latency, because later invocations reuse the connection and credentials. Provisioned concurrency reduces the number of requests that see the 600 ms init, because it keeps initialized environments ready. Shrinking the package and raising memory can also shorten the init itself.
Exercise
You raise a CPU-bound function from 256 MB to 1024 MB. Duration drops from 800 ms to 190 ms. Did the cost per invocation go up or down?
Show answer
It went down slightly. Cost is proportional to memory times duration: 256 x 800 = 204,800 versus 1024 x 190 = 194,560 (MB-ms). Latency also improved by more than four times.