Sub topic 5
The execution environment lifecycle and reuse
This chapter assumes you can write a basic Lambda handler in Python, know what the event and context arguments are, and have set memory, timeout and environment variables on a function. Here you will learn what Lambda creates around your code, how long it lives, and how to write code that benefits from reuse without leaking state between requests.
What an execution environment is
An execution environment is an isolated, short-lived sandbox that Lambda creates to run your function. It contains the runtime (for example the Python interpreter), your code and layers, the environment variables you configured, the /tmp directory, and the memory and CPU share you chose. Your handler runs inside it.
Lambda does not run your function on a server you manage. It creates environments when it needs them, reuses them while they are useful, and destroys them on its own schedule. You never start or stop one directly.
Two facts shape everything else in this chapter:
- One environment handles one invocation at a time. A second request that arrives while the first is running goes to a different environment.
- An environment can handle many invocations one after another, but Lambda gives no promise about how many or for how long.
The three phases
The lifecycle of an environment has three phases: Init, Invoke and Shutdown.
Init
Init runs once when Lambda creates a new environment. It has three steps:
- Lambda downloads your code and layers and starts the environment.
- Lambda starts the runtime.
- Lambda runs your function's initialization code. This is all code outside the handler: imports, module-level variables, client construction.
A request that has to wait for Init is a cold start. The next chapters on cold starts cover how to shorten it. Here the point is that Init happens once per environment, not once per request.
The Init phase has its own time limit of 10 seconds for standard on-demand functions. If initialization code exceeds it, Lambda treats the Init as failed and, for an on-demand function, retries initialization when the invoke happens, this time inside the handler's own timeout. Keep initialization code quick and free of long network calls.
Invoke
Invoke runs your handler with the event and context. When the handler returns, the environment is frozen, not destroyed. Freezing suspends the process: CPU is not available, background threads do not run, and you are not billed for the time between invocations.
When another request arrives and Lambda picks this environment, it thaws the environment and runs the handler again. This is a warm invocation. Init does not run again, so everything created outside the handler is still in memory.
The invocation's timeout applies to the Invoke phase only. If the handler exceeds the configured timeout, Lambda stops the invocation and the environment is discarded rather than reused.
Shutdown
Lambda eventually reclaims idle environments. It does this when an environment has been idle for a while, when you deploy new code or configuration, when it rotates the underlying infrastructure, or after an error that leaves the runtime in an unknown state. The idle time is not documented as a fixed number, so do not rely on a particular value. Minutes are typical, but treat that as an observation, not a guarantee.
During Shutdown, Lambda sends a shutdown signal to the runtime, and extensions get a short window to finish. The window is about 500 ms for a function with no extensions, and a little longer with them. You cannot count on cleanup code running, so never use shutdown as the only place to save important data.
Reusing resources across invocations
Because Init runs once and Invoke runs many times, the placement of code decides how often it runs. The rule: create expensive, reusable objects outside the handler, and compute request-specific values inside it.
import os
import boto3
# Init phase: runs once per environment.
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["TABLE_NAME"])
INIT_COUNT = {"invocations": 0}
def handler(event, context):
# Invoke phase: runs on every request.
INIT_COUNT["invocations"] += 1
return {
"invocations_in_this_environment": INIT_COUNT["invocations"],
"request_id": context.aws_request_id,
}If you invoke this function several times in quick succession, the counter rises on warm invocations. When Lambda creates a new environment, the counter starts again at 1. Seeing the counter reset is a quick way to confirm that a new environment was created.
Good candidates for initialization code:
- SDK clients such as
boto3.client("s3"). Creating one is slow compared with calling it, and a reused client also keeps its HTTP connections open. - Database connection objects or connection pools.
- Configuration read from environment variables or parameter stores, when the value does not change often.
- Large files or machine-learning models loaded into memory.
Using the /tmp directory
Each environment has an ephemeral /tmp directory. Its default size is 512 MB, and you can configure it up to 10,240 MB. Files written there survive between warm invocations in the same environment, which makes it useful as a cache for downloaded data.
import os
import boto3
s3 = boto3.client("s3")
CACHE_PATH = "/tmp/model.bin"
def handler(event, context):
if not os.path.exists(CACHE_PATH):
s3.download_file(os.environ["BUCKET"], "model.bin", CACHE_PATH)
with open(CACHE_PATH, "rb") as f:
size = len(f.read())
return {"model_bytes": size}On a cold start the file is downloaded. On later warm invocations in the same environment it is already there. Other environments each have their own /tmp, so every new environment repeats the download.
Edge cases and gotchas
Reuse is an optimization, not a feature to design around. These are the common errors.
State leaks between requests
Module-level variables persist, so a request can see data left by an earlier one. This is a correctness bug when the data is request-specific and a security bug when it belongs to a different user.
# Wrong: the list grows across warm invocations and mixes users' data.
results = []
def handler(event, context):
results.append(event["user"])
return {"users_seen": results}Keep request data in local variables inside the handler. Use module-level state only for things that are safe to share: clients, configuration and read-only caches.
Do not treat memory as storage
Any given request can land on a new environment, and environments disappear without notice. If you need data to persist or be shared, use DynamoDB, S3 or another external store. A cache in memory or /tmp is only a shortcut that the function must be able to rebuild.
Stale connections
An environment can stay frozen for a long time. When it thaws, a database connection or HTTP keep-alive connection opened earlier may have been closed by the other side. The next call then fails with a connection reset or timeout. Either catch the error and reconnect, or check that the connection is alive at the start of the handler.
Frozen background work
Because the environment freezes as soon as the handler returns, work you start in a background thread or an unawaited task stops mid-way and may resume on a later, unrelated invocation. Finish all work before returning. If you need work to continue after the response is sent, use asynchronous invocation or a queue.
Cached values that expire
Credentials, tokens and values fetched at Init can become invalid while the environment lives on. Store an expiry time with each cached secret or token and refresh it in the handler when it is close to expiring. The AWS SDK refreshes the function's own role credentials for you.
Randomness and time
Seed values or unique identifiers generated once at module level are shared by every invocation in that environment. Generate request IDs, random numbers and timestamps inside the handler.
Observing reuse
You can see environment reuse in CloudWatch Logs. Each environment writes to its own log stream, so a new log stream means a new environment. The REPORT line at the end of each invocation includes an Init Duration field only on cold starts.
REPORT RequestId: 3f1c... Duration: 12.40 ms Billed Duration: 13 ms Memory Size: 256 MB Max Memory Used: 78 MB Init Duration: 412.55 msA warm invocation has the same line without Init Duration. If you see Init Duration on many requests, your traffic is creating many environments, or your environments are being retired quickly.
Reuse and concurrency
Reuse is per environment. If ten requests arrive at the same moment, Lambda needs ten environments, and each pays Init if none are warm. Warm environments are not shared between concurrent requests, so a spike mostly produces cold starts, and a steady trickle of requests mostly produces warm ones. The chapter on concurrency covers how to control this.
Summary of rules
| Put it here | What belongs there |
|---|---|
| Outside the handler (Init) | SDK clients, connection objects, configuration, models, imports |
| Inside the handler (Invoke) | Request data, IDs, timestamps, results, anything user-specific |
| `/tmp` | Rebuildable cache files, never the only copy of data |
| External store | Anything that must survive or be shared across environments |
Exercise
A function stores the current user's name in a module-level variable inside the handler flow, and a user occasionally sees another user's name in their response. Explain the cause and give the fix.
Show answer
Module-level variables live for the lifetime of the execution environment, and one environment serves many requests in sequence. A warm invocation therefore sees the value left by the previous request. The fix is to keep the user's name in a local variable inside the handler (or pass it as an argument) so each invocation starts clean, and to reserve module-level state for shared, read-only items such as clients.
Exercise
Your function opens a database connection at module level. After a quiet period, the first request fails with a "connection reset" error, but later requests work. What happened, and how can you handle it?
Show answer
The environment was frozen between invocations, and the database or a network device closed the idle connection. The connection object still existed in memory, so the first use failed. Handle it by catching connection errors and reconnecting, or by validating the connection at the start of the handler and recreating it when it is not alive.
Exercise
In the CloudWatch REPORT line, how can you tell a cold start from a warm invocation, and what does a new log stream indicate?
Show answer
Only cold starts include an Init Duration field in the REPORT line. A new log stream means Lambda created a new execution environment, because each environment writes to its own stream.