AWS Lambda & Serverless
AWS Lambda runs your code in response to events without you managing any servers. You upload a function, connect it to a trigger such as an HTTP request or a file upload, and AWS runs as many copies as needed, from zero to thousands. You pay for the number of requests and the time your code runs, not for idle servers. This style is called serverless.
How Lambda works
A Lambda function has a few key settings:
- Runtime: the language environment, such as Python 3.13, Node.js, Java or .NET. You can also package a function as a container image.
- Handler: the function Lambda calls, written as
file_name.function_name, for exampleapp.lambda_handler. - Memory: from 128 MB up to 10,240 MB. CPU power grows in proportion to memory, so more memory can make code faster.
- Timeout: how long one invocation may run, up to a maximum of 15 minutes. Lambda is not for jobs that run for hours.
- Execution role: the IAM role whose permissions your code uses.
- Triggers: the event sources that invoke the function.
Your first handler
Every Python Lambda function has a handler that takes two arguments: event (a dictionary describing what happened) and context (information about the invocation, such as the request ID and remaining time). Here is a function that receives a mobile-money style payment notification over HTTP:
app.py
import json
def lambda_handler(event, context):
body = json.loads(event.get("body") or "{}")
amount = body.get("amount")
phone = body.get("phone")
if amount is None or phone is None:
return {
"statusCode": 400,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"error": "amount and phone are required"}),
}
print(f"Payment of KES {amount} received from {phone[-4:]}")
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"message": f"Received KES {amount}", "receipt": body.get("receipt", "unknown")}),
}
When API Gateway's HTTP API invokes a function with a proxy integration (payload format 2.0), the event looks like this (shortened). Note that body arrives as a string of JSON, so the handler must parse it:
{
"version": "2.0",
"routeKey": "POST /payments",
"rawPath": "/payments",
"headers": {"content-type": "application/json"},
"requestContext": {"http": {"method": "POST", "path": "/payments"}},
"body": "{\"amount\": 1500, \"phone\": \"254700000000\", \"receipt\": \"QK12AB34CD\"}",
"isBase64Encoded": false
}
The function's response must have a statusCode, optional headers, and a body that is also a string, which is why the code uses json.dumps. Testing with that event in the console returns:
And the function's log in CloudWatch contains the line:
The older REST API (payload format 1.0) sends a slightly different event, with keys such as httpMethod, path and pathParameters. The response shape (statusCode, headers, string body) is the same. Logging only the last four digits of the phone number is deliberate: keep personal data out of logs.
Creating and invoking a function from the CLI
Assume an execution role named payments-fn-role exists with the AWSLambdaBasicExecutionRole managed policy attached (its trust policy names lambda.amazonaws.com). Zip the code and create the function:
zip function.zip app.py
aws lambda create-function --function-name payments-notify \
--runtime python3.13 --handler app.lambda_handler \
--role arn:aws:iam::123456789012:role/payments-fn-role \
--zip-file fileb://function.zip --timeout 10 --memory-size 256
aws lambda invoke --function-name payments-notify \
--cli-binary-format raw-in-base64-out \
--payload file://event.json response.json
Here StatusCode 200 means Lambda ran the function; your function's own response, including its statusCode, is written to response.json. The --cli-binary-format option tells CLI v2 that the payload file is plain JSON.
Things to know
- Cold starts: the first request to a new copy of your function takes extra time while Lambda prepares the environment. Code outside the handler (imports, creating boto3 clients) runs once per copy and is reused, so put setup there.
- Statelessness: do not rely on files in
/tmpor variables between invocations; store data in S3 or DynamoDB. - Concurrency: each simultaneous request uses one copy. Accounts have a concurrency quota per Region, and you can reserve concurrency for important functions.
- Pricing: you pay per request and per unit of duration multiplied by memory (GB-seconds), plus any services the function calls. Idle functions cost nothing. Check the Lambda pricing page for current rates and any free allowance.
Creating an accidental infinite loop: a function triggered by uploads to a bucket that writes its output back into the same bucket triggers itself again and again. Write outputs to a different bucket or prefix, and set a budget alert so a runaway loop is noticed quickly.
Key points
- Lambda runs your code on events, scales automatically and charges only while code runs.
- A Python handler is
def lambda_handler(event, context). - With API Gateway proxy integration, the request body arrives as a string, and you return
statusCode,headersand a stringbody. - The execution role grants permissions; print statements go to CloudWatch Logs.
- Limits to remember: up to 15 minutes per invocation and up to 10,240 MB of memory.
Tip: use the ← and → keys to move between pages.
