AWS Lambda
AWS Lambda runs your code without servers that you manage. You upload a function, connect it to a trigger, and Lambda runs it each time an event arrives, scaling from zero to thousands of parallel copies automatically. You pay per request and per millisecond of compute, and nothing when it is idle.
A function
A Lambda function is a handler that receives an event (what happened) and a context (runtime info):
# handler.py
import json
def lambda_handler(event, context):
name = (event.get("queryStringParameters") or {}).get("name", "world")
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"message": f"Hello, {name}!"}),
}zip function.zip handler.py
aws lambda create-function --function-name hello \
--runtime python3.13 --handler handler.lambda_handler \
--role arn:aws:iam::123456789012:role/hello-lambda-role \
--zip-file fileb://function.zip --memory-size 256 --timeout 10
aws lambda invoke --function-name hello \
--payload '{"queryStringParameters": {"name": "Ada"}}' \
--cli-binary-format raw-in-base64-out response.json
cat response.jsonSample output:
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
{"statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": "{\"message\": \"Hello, Ada!\"}"}The handler is ordinary Python, so you can run it locally with a fake event. That is exactly what this playground does:
import json
def lambda_handler(event, context):
name = (event.get("queryStringParameters") or {}).get("name", "world")
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"message": f"Hello, {name}!"}),
}
for event in [{"queryStringParameters": {"name": "Ada"}}, {"queryStringParameters": None}, {}]:
response = lambda_handler(event, context=None)
print(response["statusCode"], response["body"])200 {"message": "Hello, Ada!"}
200 {"message": "Hello, world!"}
200 {"message": "Hello, world!"}
Tip: Keep the handler thin and put the logic in plain functions. Then you can unit-test it without AWS.
Triggers and limits
Common triggers: API Gateway / function URLs (HTTP), S3 (object uploaded), DynamoDB Streams, SQS, SNS, EventBridge (schedules and events), Kinesis.
| Setting | Range |
|---|---|
| Memory | 128 MB to 10,240 MB (CPU grows in proportion) |
| Timeout | up to 15 minutes |
| Deployment package | 50 MB zipped / 250 MB unzipped, or a container image up to 10 GB |
/tmp storage |
512 MB to 10,240 MB |
Long-running servers, jobs over 15 minutes or workloads needing GPUs belong on EC2 or containers instead.
Model: the Lambda bill
Lambda charges per request and per GB-second (memory in GB × duration in seconds). Using example prices (check the AWS pricing pages; the free tier also gives a monthly allowance):
PRICE_PER_MILLION_REQUESTS = 0.20 # example
PRICE_PER_GB_SECOND = 0.0000166667 # example (x86)
FREE_REQUESTS = 1_000_000 # example monthly free tier
FREE_GB_SECONDS = 400_000
def monthly_cost(invocations, avg_ms, memory_mb, free_tier=True):
gb_seconds = invocations * (avg_ms / 1000) * (memory_mb / 1024)
req = invocations
if free_tier:
req = max(0, req - FREE_REQUESTS)
gb_seconds = max(0, gb_seconds - FREE_GB_SECONDS)
return req / 1e6 * PRICE_PER_MILLION_REQUESTS + gb_seconds * PRICE_PER_GB_SECOND
scenarios = [
("small API", 2_000_000, 120, 256),
("busy API", 50_000_000, 80, 512),
("image resizer", 3_000_000, 1500, 2048),
]
for name, n, ms, mem in scenarios:
print(f"{name:<14} {n:>11,} calls x {ms:>4} ms @ {mem:>4} MB: "
f"${monthly_cost(n, ms, mem):9.2f}/month")small API 2,000,000 calls x 120 ms @ 256 MB: $ 0.20/month
busy API 50,000,000 calls x 80 ms @ 512 MB: $ 36.47/month
image resizer 3,000,000 calls x 1500 ms @ 2048 MB: $ 143.73/month
Model: does more memory cost more?
Memory also buys CPU, so a CPU-bound function often finishes faster with more memory. If duration halves when memory doubles, the cost stays the same and users get faster responses:
price = 0.0000166667 # example $ per GB-second
measurements = {128: 2400, 256: 1180, 512: 600, 1024: 330, 2048: 310} # memory MB -> duration ms
for mem, ms in measurements.items():
cost_per_million = 1e6 * (mem / 1024) * (ms / 1000) * price
print(f"{mem:>5} MB {ms:>5} ms ${cost_per_million:7.2f} per million calls")
best = min(measurements, key=lambda m: m * measurements[m])
print("cheapest setting:", best, "MB") 128 MB 2400 ms $ 5.00 per million calls
256 MB 1180 ms $ 4.92 per million calls
512 MB 600 ms $ 5.00 per million calls
1024 MB 330 ms $ 5.50 per million calls
2048 MB 310 ms $ 10.33 per million calls
cheapest setting: 256 MB
Beyond 1024 MB this function stops getting faster (it isn't CPU-bound any more), so extra memory just costs more. Tools such as AWS Lambda Power Tuning automate this measurement.
Cold starts
When no warm copy (execution environment) is free, Lambda creates one: it downloads your code, starts the runtime and runs your initialisation code. That cold start adds latency, from tens of milliseconds to a few seconds. Mitigations: keep packages small, initialise SDK clients outside the handler (so warm invocations reuse them), and use provisioned concurrency or SnapStart for latency-sensitive functions.
Test yourself
What is the maximum timeout of a Lambda function?
- 30 seconds
- 5 minutes
- 15 minutes
- 1 hour
Lambda compute is billed in GB-seconds. What is that?
- Storage used per second
- Configured memory in GB multiplied by run time in seconds
- Network traffic
- The package size
Where should you create SDK clients and database connections in a Lambda function?
- Inside the handler on every call
- Outside the handler, so warm invocations reuse them
- In a separate Lambda
- In /tmp