Sub topic 3
Lambda essentials for API backends
This chapter covers the parts of AWS Lambda that an API Gateway HTTP API backend depends on: the handler, the event and context arguments, the execution role, and the settings that decide how your function behaves under load. It assumes you know basic HTTP, can read Python, have an AWS account, and understand IAM roles at a basic level (a role is an identity with attached permissions).
What a Lambda function is, from the API's point of view
A Lambda function is code that AWS runs on demand. You upload the code and Lambda runs it only when something invokes it. For an HTTP API, the invoker is API Gateway. It receives an HTTP request, builds a JSON document describing that request, calls your function with that document, and turns the return value into an HTTP response.
Your function therefore never opens a socket or listens on a port. It is a plain function that takes a dictionary and returns a dictionary.
The handler
The handler is the function Lambda calls for each invocation. You tell Lambda where it is with the Handler setting, written as file.function. In the SAM template later in this tutorial, Handler: app.handler means "the function named handler in app.py".
def handler(event, context):
return {"statusCode": 200, "body": "ok"}The handler takes two arguments:
eventis a dictionary holding the request data. Its shape depends on who invoked the function. For an HTTP API it is the payload format 2.0 document covered in a later chapter.contextis an object with information about the invocation and the runtime.
The context object
The context object is rarely used for business logic, but a few members are useful in an API backend.
| Member | Meaning |
|---|---|
| `aws_request_id` | A unique ID for this invocation. Include it in logs so you can find one request later. |
| `function_name` | The name of the running function. |
| `memory_limit_in_mb` | The memory size configured for the function. |
| `get_remaining_time_in_millis()` | Milliseconds left before Lambda stops the invocation at the timeout. |
The remaining-time method lets you stop work gracefully instead of being cut off:
import json
def handler(event, context):
if context.get_remaining_time_in_millis() < 500:
return {
"statusCode": 503,
"headers": {"content-type": "application/json"},
"body": json.dumps({"message": "Not enough time left to process"}),
}
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps({"requestId": context.aws_request_id}),
}The execution model
Understanding what Lambda does between invocations explains most of the performance and correctness questions that come up with APIs.
Lambda runs your code inside an execution environment, which is an isolated sandbox with your code, the language runtime, and the memory you configured. When a request arrives and no idle environment exists, Lambda creates one. This is a cold start. It downloads your code, starts the runtime, and runs your initialization code (everything outside the handler). When a later request arrives and an idle environment exists, Lambda reuses it and only runs the handler. This is a warm start.
Two rules follow from this:
- One environment handles one request at a time. If ten requests arrive at once, Lambda uses ten environments. Your code does not need to be thread-safe for concurrent requests within a single environment.
- Code outside the handler runs once per environment, not once per request. Anything you put there is reused by later requests on that environment.
Initialize expensive objects outside the handler
Create clients, load configuration and compile regular expressions at module level. Warm invocations then skip that work.
import json
import os
import boto3
TABLE_NAME = os.environ["TABLE_NAME"]
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(TABLE_NAME)
def handler(event, context):
item_id = event["pathParameters"]["id"]
result = table.get_item(Key={"id": item_id})
item = result.get("Item")
if item is None:
return {
"statusCode": 404,
"headers": {"content-type": "application/json"},
"body": json.dumps({"message": "Not found"}),
}
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps(item, default=str),
}This example assumes a DynamoDB table whose name is passed in the TABLE_NAME environment variable and a function role that may call dynamodb:GetItem on it. If the variable is missing, the module fails at import time and every invocation returns an error, which is a useful early signal of a misconfigured deployment.
Do not keep per-request state in globals
Because environments are reused, a module-level variable survives across requests. That is correct for clients and configuration. It is a bug for request data.
# Wrong: leaks data from one request into the next
current_user = None
def handler(event, context):
global current_user
if current_user is None:
current_user = event["requestContext"]["http"]["sourceIp"]
return {"statusCode": 200, "body": current_user}The first caller's IP address is returned to every later caller served by the same environment. Keep per-request values in local variables.
Also treat /tmp carefully. Each environment has a writable /tmp directory (512 MB by default). Its contents persist between warm invocations of the same environment, but you cannot count on a file being there, because another environment may serve the next request.
The execution role
The execution role is the IAM role that Lambda assumes when your function runs. It decides what your code may do in AWS. It is separate from the permission API Gateway needs to invoke the function.
| Permission | Who has it | Controls |
|---|---|---|
| Execution role | The function | What the function can call, such as DynamoDB, S3 or CloudWatch Logs |
| Resource-based policy on the function | API Gateway | Whether API Gateway may invoke the function |
At minimum the execution role must allow the function to write logs to CloudWatch Logs. The managed policy AWSLambdaBasicExecutionRole grants that. Without it, your print and logging output has nowhere to go and debugging becomes guesswork.
Apply least privilege: grant only the actions and resources the function needs. A function that reads one table should not receive dynamodb:* on *.
When you use SAM, it creates the execution role for you and attaches the basic logging policy. It also adds the resource-based policy that lets API Gateway invoke the function when you declare an HttpApi event. You add extra permissions with the Policies property:
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
Environment:
Variables:
TABLE_NAME: !Ref ItemsTable
Policies:
- DynamoDBReadPolicy:
TableName: !Ref ItemsTableIf your function can run but an AWS call fails with AccessDeniedException, the execution role is the place to look. If API Gateway returns an error and your function never logs anything, the invoke permission is more likely the cause.
Settings that matter for an API
Memory and CPU
You choose memory from 128 MB to 10,240 MB. Lambda allocates CPU in proportion to memory, so a function with more memory also runs faster on CPU-bound work. A small increase in memory can lower duration enough to leave the cost unchanged or lower, because billing is per millisecond of duration multiplied by memory. Measure with real requests instead of guessing.
Timeout
The timeout is the longest an invocation may run, up to 15 minutes. An HTTP API integration has its own limit: API Gateway waits at most 30 seconds by default for the integration to respond. A function timeout longer than the API's wait gives the client an error while the function keeps running. Set the function timeout slightly below what the client can tolerate, and well below 30 seconds for typical request-response work. The examples in this tutorial use 10 seconds.
Environment variables
Environment variables carry configuration such as table names and feature flags. Read them at module level, as in the DynamoDB example. Do not put secrets in plain environment variables. Fetch them from AWS Secrets Manager or Systems Manager Parameter Store at initialization and cache the value.
Payload size
A synchronous Lambda invocation accepts a request or response up to 6 MB. For an API, that means a function cannot return a response body larger than that. Return large files through a pre-signed S3 URL instead.
Logging from the handler
Anything written to standard output or through the logging module goes to CloudWatch Logs, in a log group named /aws/lambda/<function-name>. Structured JSON logs are easier to search than free text.
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def handler(event, context):
logger.info(
json.dumps(
{
"requestId": context.aws_request_id,
"route": event["requestContext"]["routeKey"],
}
)
)
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps({"ok": True}),
}Avoid logging whole events in production. They contain headers such as authorization, which would copy credentials into your logs.
Invoking a handler locally
Because a handler is an ordinary function, you can call it from a script with a hand-built event and a stand-in context. This catches mistakes before you deploy.
import json
from types import SimpleNamespace
from app import handler
event = {
"requestContext": {"routeKey": "GET /items/{id}"},
"pathParameters": {"id": "42"},
}
context = SimpleNamespace(aws_request_id="local-test")
response = handler(event, context)
print(response["statusCode"], json.loads(response["body"]))This only works when app.py has no module-level code that needs AWS resources, such as the os.environ["TABLE_NAME"] lookup above. Set the variable first or mock the client when testing that version.
Common errors
Runtime.HandlerNotFoundorRuntime.ImportModuleError: theHandlerstring does not match the file and function name, or a dependency is missing from the deployment package.Task timed out after N seconds: the function exceeded its timeout. Raise it only after checking whether a downstream call is hanging.KeyErroronevent[...]: the event does not have the shape you assumed, often because the API uses a different payload format version or the route has no path parameters.- Client sees a 500 or 502-style error and the function log shows an unhandled exception: the function raised instead of returning a response. Catch expected failures and return a proper status code.
Exercise
A function creates its DynamoDB client inside the handler on every call. A teammate moves the boto3.resource(...) line to module level. What improves, and what must you check before assuming it is safe?
Show answer
Warm invocations no longer pay the cost of building the client, so duration drops. It is safe because the client holds configuration and connections, not request data. Check that no request-specific values are stored in module-level variables, and that the environment variable or setting used to build the client is available at import time.
Exercise
An HTTP API route returns an error to the client, and the function's log group has no entries for that request. Which two things would you check first?
Show answer
Check that API Gateway has permission to invoke the function (the resource-based policy on the function) and that the route's integration points at the correct function. If the function had run, the execution role's logging permission would be the next check. A function that never ran writes no log lines.