Sub topic 9
Understanding and reducing cold starts
This chapter assumes you can write a Lambda handler, know how memory and timeout settings work, and know that Lambda reuses execution environments between invocations. It covers what a cold start is, what makes it slow, and the options for reducing it.
What a cold start is
When a request arrives and no idle execution environment is available, Lambda creates a new one. This is a cold start. Lambda does the following before your handler runs:
- It allocates a micro-VM and downloads your code package or container image.
- It starts the language runtime.
- It runs your initialization code, which is everything outside the handler function.
The time spent on these steps appears in the Init Duration field of the REPORT line in CloudWatch Logs. A warm invocation reuses an existing environment and skips all three steps.
Cold starts usually affect a small share of requests. They matter most for latency-sensitive synchronous calls, such as an API behind API Gateway. They matter much less for asynchronous or queue-driven work.
What makes a cold start slow
Several factors add to the initialization time:
- Runtime. Interpreted runtimes such as Python and Node.js generally start faster than Java or .NET, which load a larger runtime.
- Package size. More code and dependencies mean more to download and load.
- Init code. Imports, SDK client creation, and configuration fetches all run during the cold start.
- Memory size. CPU power scales with memory, so a low setting slows init work.
- VPC attachment. Modern Lambda networking creates shared network interfaces ahead of time, so the penalty is small. The first deployment of a function with a new VPC configuration can still take longer.
Measure before you tune
Search the logs for cold starts with CloudWatch Logs Insights:
filter @type = "REPORT"
| stats count() as invocations,
count(@initDuration) as coldStarts,
avg(@initDuration) as avgInitMs,
max(@initDuration) as maxInitMsCompare coldStarts to invocations to see how often it happens. If cold starts are under 1% of traffic and your latency target allows for them, you may not need to change anything.
Reducing cold starts in your code
The cheapest improvements are in the function itself.
- Create SDK clients and database connections outside the handler, so warm invocations reuse them.
- Import only what you need. In Python, import a single boto3 client rather than unrelated libraries.
- Remove unused dependencies and keep the package small.
- Defer rarely used work. Load a heavy module inside the code path that needs it.
import json
import os
import boto3
# Runs once per cold start.
s3 = boto3.client("s3")
BUCKET = os.environ["BUCKET_NAME"]
def handler(event, context):
# Imported only when this path runs, so it does not slow every cold start.
if event.get("report"):
import csv # noqa: F401
obj = s3.get_object(Bucket=BUCKET, Key=event["key"])
return {"statusCode": 200, "body": json.dumps({"size": obj["ContentLength"]})}Do not move work outside the handler without checking it. Anything that runs at init time is paid for on every cold start, even if the request never needs it.
Reducing cold starts with configuration
Raising memory often shortens init and run time, because Lambda allocates CPU in proportion to memory. A function at 1024 MB can cost the same or less than one at 128 MB if it finishes much faster. Test several sizes with your real workload.
Two features target cold starts directly:
| Option | What it does | Trade-off |
|---|---|---|
| Provisioned concurrency | Keeps a set number of environments initialized and ready | You pay for the configured capacity whether or not it is used |
| SnapStart | Takes a snapshot of the initialized environment and restores it for new ones | Available for specific runtimes, and code must handle state such as random seeds and connections after restore |
Provisioned concurrency suits steady, predictable traffic with strict latency targets. SnapStart suits runtimes with heavy init, such as Java. Check the current list of supported runtimes in the AWS documentation.
A scheduled "warming" ping keeps only one environment warm. It does not help when traffic needs several at once, so provisioned concurrency is the better tool.
Common mistakes
- Tuning before measuring. Check
Init Durationfirst. - Adding provisioned concurrency to a queue-driven function that tolerates delay.
- Putting a slow network call in init code, which makes every cold start slower and can cause init timeouts.
- Treating a pre-created connection as always valid. After a long idle period it may have closed, so handle reconnects.
Exercise
A function behind API Gateway shows an average Init Duration of 1800 ms, and cold starts are 0.3% of invocations. The p99 latency target is missed only by those requests. Name two changes you would try first, and say whether you would add provisioned concurrency.
Show answer
First try cheap code and config changes: remove unused dependencies, defer heavy imports, and test a higher memory size to speed up init. Then re-measure with Logs Insights. Provisioned concurrency is justified only if the p99 target is strict and the cold start rate still breaks it after those changes, because it costs money continuously. At 0.3% of invocations, tuning the code is the better first step.