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 a function's memory and timeout. It explains how Lambda creates and reuses the sandbox your code runs in, and how to take advantage of that.
What an execution environment is
An execution environment is an isolated sandbox that Lambda builds to run your function. It holds the runtime (for example Python 3.12), your code, its layers, the environment variables, and a writable /tmp directory. One environment handles one request at a time. Lambda keeps the environment after a request finishes and may send a later request to it.
The three phases
Lambda drives each environment through three phases.
- Init. Lambda starts the runtime, loads your code, and runs everything at module level, outside the handler function. This happens once per environment.
- Invoke. Lambda calls your handler with the event. This phase repeats for every request the environment serves.
- Shutdown. When Lambda decides the environment is no longer needed, it ends the runtime and discards the sandbox. You do not control when this happens.
Between requests the environment is frozen. Your process is paused and does no work, and you are not billed for it. A later request thaws it, which is a warm start. If no idle environment exists, Lambda must create a new one and run Init first. This is a cold start, covered in a later chapter.
What persists between invocations
On a warm start, everything created during Init and everything stored in global variables is still there. The contents of /tmp are also still there.
The table shows what you can and cannot rely on.
| Item | Survives a warm invocation? | Safe to depend on? |
|---|---|---|
| Module-level variables and clients | Yes | Only as a cache or optimization |
| Files in `/tmp` | Yes | Only as a cache |
| Variables local to the handler | No | Not applicable |
| Background threads or processes | Paused when frozen | No |
| The same environment for the next request | Not guaranteed | No |
Treat reuse as an optimization, never as storage. Lambda may start a new environment at any time, and several environments can run at once, each with its own copy of globals.
Reusing resources
Put expensive setup in the Init phase so that it runs once and warm invocations skip it. SDK clients, database connections, and loaded configuration are typical examples.
import os
import boto3
# Init phase: runs once per execution environment.
table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])
invocation_count = 0
def handler(event, context):
global invocation_count
invocation_count += 1
table.put_item(Item={"id": context.aws_request_id, "n": invocation_count})
return {"statusCode": 200, "body": str(invocation_count)}If you invoke this function several times in a row, the returned count usually climbs. It resets to 1 whenever a new environment starts. That reset is the visible proof that globals are per environment.
Init work is also limited. Lambda caps the Init phase at 10 seconds for on-demand functions, and slow Init adds directly to cold start latency.
Common mistakes
- Storing per-request data in globals. A value from one user's request can leak into the next request served by the same environment. Keep request data in local variables.
- Assuming a connection is still open. A database connection created in Init may be closed by the server after the environment sat frozen. Check it, or reconnect and retry on failure.
- Writing results to
/tmpand expecting them later. Another environment will not see the file, and the file can vanish. - Starting background work and returning. The environment freezes when the handler returns, so unfinished threads stop mid-task. Finish the work before you return.
- Creating clients inside the handler. This repeats setup on every request and wastes billed time.
Exercise
A handler creates a database connection inside the handler function and stores a user's ID in a global variable for later use. Name one performance problem and one correctness problem, and say how to fix each.
Show answer
Performance: opening a new connection on every request wastes billed time, so create the connection at module level during Init (and reconnect if it has gone stale). Correctness: the global user ID persists in a warm environment and can be read by a later request from a different user, so keep it in a local variable inside the handler.