Sub topic 2
The Execution Environment Lifecycle and Reuse
Assume you know Python, JSON, HTTP APIs, and basic AWS IAM. This chapter focuses on what happens after Lambda receives an invocation.
The execution environment lifecycle and reuse
Lambda creates an execution environment for a function. It initializes the runtime and runs code outside the handler. Then it calls the handler for one or more requests. When the environment is idle, Lambda may freeze it and later reuse it. Lambda can also discard it at any time.
This creates two rules:
- Put reusable clients and configuration outside the handler.
- Keep request-specific state inside the handler.
A reused environment can reduce startup work. It does not provide a guarantee. The first request in a new environment is a cold start.
import json
import os
import boto3
table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])
def handler(event, context):
item = json.loads(event["body"])
table.put_item(Item={"id": item["id"], "value": item["value"]})
return {"statusCode": 201, "body": json.dumps({"ok": True})}The global DynamoDB resource can be reused, but the event is read inside the handler. Do not store one request's user data in a global variable.
Invocation types and event sources
Invocation style determines who waits and how failures are retried.
| Invocation | Common source | Failure behavior |
|---|---|---|
| Synchronous | API Gateway | Caller receives the function result or error |
| Asynchronous | S3 events | Lambda retries failed processing, then uses a destination or DLQ |
| Poll-based | SQS | Lambda polls messages and retries messages that remain unacknowledged |
API Gateway usually invokes Lambda synchronously. S3 commonly invokes it asynchronously. For SQS, Lambda reads batches and deletes messages only after successful processing.
Failures and partial batches
For asynchronous events, configure a dead-letter queue (DLQ) or an on-failure destination when failed events must be retained or routed. For SQS, set the visibility timeout long enough for processing and configure a redrive policy. A failed message can then become visible again and be retried.
Without partial batch responses, one bad SQS message can cause the whole batch to return. Enable ReportBatchItemFailures and return only failed message IDs:
def handler(event, context):
failures = []
for record in event["Records"]:
try:
process(record["body"])
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}This lets Lambda remove successful messages while retrying only failures. Make processing idempotent because retries can still occur.
Exercise
Which data should be placed outside the handler, and what is the main danger of placing request data there?
Show answer
Reusable clients and immutable configuration can go outside the handler. Request data must remain inside it because the environment may be reused for another request.