arthrop0d

Brief articles on varied topics.

AWS Lambda Execution Environment Lifecycle

amazon web servicesconcurrency

AWS Lambda runs your function inside an execution environment: an isolated runtime instance containing your code, its language runtime, extensions, memory, and temporary filesystem. Lambda creates that environment to process an invocation, may keep it for later invocations, and can discard it at any time.

That lifecycle explains two familiar log patterns: a cold start, where Lambda must initialize a new environment, and a warm start, where it reuses one that already exists. It also explains why a module-level cache can make one invocation faster, while the same cache can be empty—or contain old data—the next time your function runs.

The problem Lambda is solving

Without reuse, every request would need a new process, runtime, loaded libraries, and application initialization. That would make invocation latency higher and waste work for functions that run only occasionally.

Lambda therefore separates the work that must happen once per environment from the work that happens once per invocation. You put reusable setup outside the handler, and put request-specific work inside it.

For example, this Python client is created during environment initialization, not once for every request:

import boto3

s3 = boto3.client("s3")


def handler(event, context):
    return s3.get_object(
        Bucket=event["bucket"],
        Key=event["key"],
    )["Body"].read()

The client may be reused on later invocations handled by the same environment. That can reduce connection setup and initialization cost, but it is an optimization—not a storage guarantee.

What initialization does

When Lambda needs a new execution environment, it performs the Init phase. In practical terms, the environment must start the language runtime, load your function code and dependencies, and run initialization code outside the handler.

Lambda describes this work in three parts:

  1. Extension initialization starts any Lambda extensions attached to the function. An extension is a companion process or component that can observe lifecycle events or support tasks such as telemetry.
  2. Runtime initialization starts the language runtime, such as Python, Node.js, or Java, and prepares it to execute your code.
  3. Function initialization loads your application modules and runs top-level code, including global variable assignments, class definitions, and client construction.

Only after this work succeeds does Lambda enter the invocation phase and call your handler with an event and context. Initialization failures commonly appear in logs before the handler’s own output, which is why a missing dependency or exception in module-level code can look like a failure that happened “before” the function ran.

Code outside the handler runs once per environment, not once per deployment and not necessarily once per process across the whole service. If Lambda creates ten environments to handle concurrent traffic, that initialization can happen ten times.

Reuse and the warm path

After the handler returns, Lambda may keep the execution environment available. A later invocation can be routed to that same environment. This is a warm start: Lambda resumes an already initialized runtime and calls the handler again, avoiding the Init phase.

The runtime’s memory remains in place during reuse. That includes module-level variables, objects held by globals, and in-memory caches. The /tmp directory also remains available to the reused environment, so temporary files may survive as well.

Neither behavior should be treated as durable. Lambda does not promise that a later invocation will use the same environment. The service can remove an idle environment, replace it during infrastructure or configuration changes, or create a new one because traffic requires more capacity.

A warm environment is a performance opportunity, not a reliable database.

This makes the following counter local to one environment:

count = 0


def handler(event, context):
    global count
    count += 1
    return {"invocations_seen_by_this_environment": count}

It might return 1, then 2, then 3 for successive invocations routed to the same environment. A new environment starts at 1. With concurrent traffic, each environment maintains its own counter, so there is no single process-wide sequence.

Freezing after an invocation

When Lambda retains an environment, it can freeze its processes after the invocation finishes. Freezing pauses the environment so it does not consume active execution resources while waiting to be reused. If Lambda later routes another invocation there, it thaws the environment and continues with the existing runtime state.

This is why a global cache can survive an invocation without your code explicitly saving it. It is also why background work started by the handler is unsafe: a thread, child process, or unfinished asynchronous operation may be paused when the invocation ends and may never resume if the environment is discarded. The handler should complete the work that matters before returning.

Freezing is not a scheduling primitive that your application can observe or control. Do not use it to implement a timer, a queue, a lock, or a guarantee that cleanup will run. Perform essential cleanup and persistence during the invocation, and use a durable service for work that must outlive it.

Replacement and concurrency

Lambda can replace an environment at any point after an invocation. Replacement means the old runtime is gone and a new environment must perform initialization before handling work. Causes include scale-down, a new function version or configuration, runtime maintenance, failures, and ordinary lifecycle decisions that are not exposed as a promise to the function.

Concurrency makes the isolation especially important. Lambda generally handles concurrent invocations by placing them in separate execution environments rather than running them all through one handler instance at the same time. Each environment therefore has its own memory, globals, and /tmp. A cache populated in environment A is invisible to environment B, and changing a global in one does not synchronize it with the others.

Design in-memory state as best-effort, per-environment state:

Once you distinguish initialization, invocation, freezing, and replacement, cold-start timing and surprising “lost” globals stop being mysterious. The environment is a reusable container for one possible sequence of invocations—not the lifetime of your function or the identity of your application.

← All articles