Sub topic 9
Understanding and reducing cold starts
This chapter assumes you can write a Lambda handler, set memory and timeout, and know that an execution environment is reused across invocations. It builds on the execution environment lifecycle and on function configuration. By the end you should be able to tell when a cold start is hurting you, measure it, and choose the cheapest fix.
What a cold start is
A cold start is the extra time Lambda spends preparing a new execution environment before your handler can run. It happens when no idle environment is available for a request. Lambda must then create one.
The preparation has these phases:
- Lambda allocates a micro VM and downloads your code package or container image.
- The runtime starts (for example the Python interpreter or the JVM).
- Your initialization code runs. This is everything outside the handler: imports, client creation, configuration loading.
- The handler runs. This phase is the same on warm and cold invocations.
Phases 1 to 3 together make the cold start. The CloudWatch REPORT line for a cold invocation shows them as Init Duration. Warm invocations have no Init Duration field.
When cold starts happen
Cold starts are not a fault. They are a normal result of scaling from zero or of scaling out. They occur in these situations:
- The first invocation after a deployment or a configuration change, because a new function version needs fresh environments.
- After a period of inactivity. Lambda reclaims idle environments, and you cannot control when. Do not assume a fixed timeout.
- When concurrent requests exceed the number of warm environments. Each extra concurrent request needs a new environment.
- When Lambda recycles an environment for maintenance or after it has run for a long time.
In production, cold starts typically affect a small fraction of invocations, often well under 1% for steady traffic. Bursty traffic, such as a spike after a quiet period, produces many cold starts at once.
Measuring before tuning
Do not optimize on a guess. Measure the actual cold start frequency and duration first.
The REPORT log line looks like this:
REPORT RequestId: 3f1c... Duration: 12.40 ms Billed Duration: 13 ms Memory Size: 256 MB Max Memory Used: 82 MB Init Duration: 410.22 msCloudWatch Logs Insights can summarize it across many invocations:
filter @type = "REPORT"
| stats count(*) as invocations,
count(@initDuration) as coldStarts,
avg(@initDuration) as avgInit,
max(@initDuration) as maxInit,
pct(@duration, 99) as p99Duration
by bin(5m)Compare coldStarts to invocations to get the rate. If the rate is low and your latency target tolerates the occasional slow request, you may not need to do anything.
X-Ray traces, covered in the observability chapter, show an Initialization subsegment for cold invocations. This is useful for seeing which downstream call inside init is slow.
What drives cold start duration
| Factor | Effect | Notes |
|---|---|---|
| Runtime | Large | Python, Node.js and Go usually start in tens to a few hundred milliseconds. Java and .NET take longer because of JIT compilation and class loading. |
| Package size | Moderate | Larger zip files and images take longer to fetch and unpack. Unused dependencies add to both. |
| Init code | Often the largest part you control | Heavy imports, loading models, reading many parameters and opening connections all run at init. |
| Memory size | Moderate | More memory also means proportionally more CPU, so init code finishes faster. |
| VPC attachment | Small today | Network interfaces are now shared per subnet and security group combination, so the old multi-second penalty is gone. The VPC chapter covers the remaining points. |
| Packaging type | Varies | Container images are cached and lazily loaded, so they are usually fine, but very large images can still be slower on first use. |
Reducing cold start impact
Work through these from cheapest to most expensive.
Keep init code lean
Init code runs on every cold start, so move expensive work out of it where you can. Import heavy modules only in the code path that needs them, and avoid loading data you may never use.
import json
import os
import boto3
# Cheap and always needed: created once per environment.
table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])
def handler(event, context):
if event.get("action") == "report":
# Heavy dependency imported only when this path runs.
import pandas as pd
frame = pd.DataFrame(event["rows"])
return {"statusCode": 200, "body": frame.describe().to_json()}
item = {"id": event["id"], "item": event.get("item", "unknown")}
table.put_item(Item=item)
return {"statusCode": 201, "body": json.dumps(item)}Lazy imports trade a faster cold start for a slower first call on the rare path. This is a good trade only when the rare path really is rare. Importing inside the handler on every request is not slow after the first call, because Python caches imported modules in the environment.
You can also time your own init to find the slow parts:
import time
_start = time.perf_counter()
import boto3
table = boto3.resource("dynamodb").Table("orders")
print(f"init took {(time.perf_counter() - _start) * 1000:.1f} ms")
def handler(event, context):
return {"statusCode": 200}Shrink the package
Remove dependencies you do not use. Put shared libraries in a layer only if you share them, since layers still count toward the unpacked size and do not by themselves speed up the start. For Node.js, bundle and tree-shake with a tool such as esbuild. For Python, avoid installing whole frameworks when one small library will do. The AWS SDK is already present in the runtime, so you usually do not need to ship it.
Choose memory deliberately
Lambda allocates CPU in proportion to memory. A function at 128 MB gets a small slice of one vCPU, so init is slow. Raising memory can shorten both init and handler time. Because billing is memory multiplied by duration, a faster run can cost the same or less. Test several sizes with real traffic or with a tool such as AWS Lambda Power Tuning, and pick the point where cost and latency are both acceptable.
Pick a runtime that fits the latency target
If a function sits on a user-facing path with a tight latency budget, a lightweight runtime helps. If you must use Java, consider the next option.
Use SnapStart
SnapStart is a feature for Java, and for some newer Python and .NET runtimes where supported. Lambda runs your init code once when you publish a version, takes a snapshot of the initialized memory and disk state, and restores that snapshot for new environments. Restores are much faster than a full init.
SnapStart has gotchas:
- It applies to published versions and aliases, not to
$LATEST. - State captured in the snapshot is shared. Random seeds, unique IDs and open network connections created during init may be duplicated or stale after restore. Use runtime hooks to refresh them.
- Check current runtime support in the AWS documentation before relying on it.
Use provisioned concurrency
Provisioned concurrency keeps a set number of environments initialized and ready. Requests that fit within that number never see a cold start. You pay for the provisioned capacity while it is configured, whether or not it is used.
Resources:
ApiFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
CodeUri: src/
AutoPublishAlias: live
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: 5Provisioned concurrency attaches to a version or alias, not $LATEST, which is why AutoPublishAlias is set. Traffic above 5 concurrent requests still spills over to on-demand environments, and those can cold start. You can schedule changes with Application Auto Scaling to match daily traffic patterns. The concurrency chapter covers the cost and limits in more detail.
What not to do
Scheduled "warming" pings that invoke the function every few minutes keep one environment alive at best. They do not help when several requests arrive at once, they add invocations you pay for, and they may not hit the environment that real traffic uses. If you need guaranteed warm capacity, use provisioned concurrency.
Also avoid reading all configuration from remote services at init without caching. A slow call to a parameter store inside init adds directly to every cold start.
Choosing an approach
| Situation | Reasonable choice |
|---|---|
| Background job, queue consumer, or batch task | Accept cold starts. Latency rarely matters. |
| API with a loose latency target and steady traffic | Lean init code and tuned memory. |
| User-facing API with a strict p99 target | Provisioned concurrency, possibly scheduled. |
| Java service with heavy framework startup | SnapStart, or provisioned concurrency if SnapStart does not fit. |
Summary of the working model
A cold start is the cost of creating an environment. You can make it rarer (provisioned concurrency, steady traffic), shorter (lean init, small package, right-sized memory, SnapStart) or irrelevant (asynchronous workloads). Measure with Init Duration first, then apply the cheapest change that meets your latency target.
Exercise
A function has an average duration of 40 ms but its p99 is 900 ms. Logs Insights shows that 1.5% of invocations have an Init Duration near 800 ms. Name two changes that could reduce the p99 without paying for always-on capacity, and one change that would remove cold starts for a fixed number of concurrent requests.
Show answer
Without always-on capacity: reduce init work (lazy-import heavy modules, remove unused dependencies, shrink the package) and increase memory so init gets more CPU. To remove cold starts for a fixed number of concurrent requests, configure provisioned concurrency on an alias or version. Requests above that number can still cold start.
Exercise
You enable a scheduled ping every 5 minutes to "keep the function warm", but users still see slow responses when ten requests arrive together. Why?
Show answer
The ping keeps at most one environment warm. Ten simultaneous requests need ten environments, so nine must be created and each one cold starts. Provisioned concurrency set to a suitable number is the correct tool.