Lambda
AWS Lambda runs Python handlers without managing servers. boto3 lets you invoke functions, publish versions, and wire automation around deployments while keeping function code in your repo.
Search across all documentation pages
AWS Lambda runs Python handlers without managing servers. boto3 lets you invoke functions, publish versions, and wire automation around deployments while keeping function code in your repo.
import json
import boto3
client = boto3.client("lambda")
resp = client.invoke(
FunctionName="process-order",
InvocationType="RequestResponse",
Payload=json.dumps({"order_id": "ord_123"}),
)
print(resp["StatusCode"], resp["Payload"].read())When to reach for this:
InvocationType="Event"Deploy artifact metadata update, synchronous invoke, and async invoke with error handling.
import json
import logging
import boto3
from botocore.exceptions import ClientError
log = logging.getLogger(__name__)
lambda_client = boto3.client("lambda")
def invoke_sync(function_name: str, payload: dict) -> dict:
try:
resp = lambda_client.invoke(
FunctionName=function_name,
InvocationType="RequestResponse",
Payload=json.dumps(payload).encode(),
)
except ClientError as exc:
log.error("invoke failed: %s", exc.response["Error"]["Code"])
raise
raw = resp["Payload"].read()
return json.loads(raw or b"{}")
def invoke_async(function_name: str, payload: dict) -> int:
resp = lambda_client.invoke(
FunctionName=function_name,
InvocationType="Event",
Payload=json.dumps(payload).encode(),
)
return resp["StatusCode"]
if __name__ == "__main__":
result = invoke_sync("demo-python-fn", {"action": "ping"})
print(result)
status = invoke_async("demo-python-fn", {"action": "enqueue"})
print("async status", status)What this demonstrates:
RequestResponse waits for handler return; Event is fire-and-forgetClientError codes include ResourceNotFoundException, TooManyRequestsExceptionmodule.functionprod) enable safe rollouts| Approach | Pros |
|---|---|
| Zip + layers | Simple deps separation |
| Container image | Heavy deps (ML libs) |
| SAR / IaC | Repeatable deploys |
# handler.py - create boto3 clients outside handler
import boto3
s3 = boto3.client("s3")
def handler(event, context):
return {"ok": True, "remaining_ms": context.get_remaining_time_in_millis()}request_id from context.aws_request_id.| Alternative | Use When | Don't Use When |
|---|---|---|
| ECS/Fargate | Long-running HTTP, websockets | Short sporadic jobs |
| Step Functions | Multi-step orchestration | Single-function transforms |
| Celery workers | Existing Redis/Rabbit ops culture | Want zero server management |
Match Lambda runtime version in AWS; build deps in Amazon Linux container or CI image matching runtime ABI.
Just above p99 runtime with headroom; pair with SQS visibility timeout > Lambda timeout for queue triggers.
Resource-based policy on function allowing caller account principal.
RequestResponse for RPC-style; Event for decoupled processing where caller does not need result inline.
Publish immutable version from $LATEST, point prod alias to version for rollback by retargeting alias.
Yes - validate event dict early; keep models small to reduce import time.
Reserved concurrency on function or account limits; SQS max concurrency for event source mapping.
Fetch from Secrets Manager at init if needed; prefer env vars injected from SSM/Secrets at deploy.
Invoke handler function directly in pytest with sample events; use SAM or LocalStack for integration.
update_function_code uploads zip from CI; prefer IaC (SAM, Pulumi, Terraform) wrapping that API.
Stack versions: This page was written for Python 3.14.0 (stable 3.14, maintenance 3.13), FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.
Reviewed by Chris St. John·Last updated Jul 19, 2026