Sub topic 3
Lambda essentials for API backends
This chapter assumes you can write basic Python and know what an IAM role is. It covers the four Lambda pieces an API backend depends on: the handler, the event, the context, and the execution role.
The handler, event and context
A Lambda function is code that the Lambda service runs on demand. You tell Lambda which function to call by giving it a handler. The setting app.handler means "the function handler in the file app.py."
Lambda calls the handler with two arguments:
- event is a dictionary built from the incoming request. For an HTTP API, it holds the route, headers, query string and body.
- context is an object with facts about the invocation. It includes
aws_request_id,function_nameandget_remaining_time_in_millis().
The handler returns a value. For an HTTP API, that value becomes the HTTP response. A later chapter covers its exact shape.
import json
import logging
import os
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Runs once per execution environment, not on every request.
TABLE_NAME = os.environ.get("TABLE_NAME", "items")
def handler(event, context):
logger.info(
"request_id=%s remaining_ms=%s",
context.aws_request_id,
context.get_remaining_time_in_millis(),
)
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps({"table": TABLE_NAME}),
}Execution environments and reuse
Lambda runs your code inside an execution environment. On the first request, Lambda creates the environment, loads your code and runs everything outside the handler. This is the init phase, and it is the cause of a cold start. Later requests can reuse the same environment, and only the handler body runs again.
Put expensive setup in the init phase. Examples are SDK clients, configuration lookups and compiled regular expressions. Never store per-user data in module-level variables, because a reused environment shares them across requests.
Configuration that matters for APIs
- Memory ranges from 128 MB to 10,240 MB. Lambda allocates CPU in proportion to memory, so a CPU-bound function can run faster and sometimes cost less with more memory.
- Timeout defaults to 3 seconds. An HTTP API waits at most 30 seconds for an integration, so setting a longer function timeout does not help API callers.
- Environment variables hold configuration such as table names. Do not put secrets in plain text there.
The execution role
The execution role is the IAM role that Lambda assumes when it runs your function. Your code gets permissions only through this role. At minimum, the role needs permission to write logs to CloudWatch Logs. The managed policy AWSLambdaBasicExecutionRole grants this. Add narrow permissions for anything else the function touches, such as one DynamoDB table.
The execution role is separate from the permission that lets API Gateway call your function. That is a resource-based policy on the function. SAM creates it for you when you declare an HttpApi event, which a later chapter shows.
Exercise
A handler creates a boto3 client inside the handler function on every call. Where should the client be created instead, and why?
Show answer
Create it at module level, outside the handler. Lambda runs that code once per execution environment, and warm invocations reuse the client. This avoids repeating the setup cost on every request.