Lesson 11 of 30Modern AWS
Lambda and Serverless
Write Lambda handlers, wire up triggers, reason about cold starts, concurrency and cost, and know when not to use it.
The first two units gave you servers, storage, networks and databases, and then locked them down. This unit moves up a level, starting with code that runs without any server you manage. Lambda lets you run code without owning a single server: upload a function, attach a trigger, and AWS runs it once per event, scaling from zero to thousands of copies and back. It is the glue of modern AWS (resizing uploads, processing queues, nightly jobs, small APIs) and a frequent interview topic because its trade-offs are so sharp.
A function, a trigger, an execution role
A Lambda function has three parts:
- Code with a handler: the function AWS calls with an
event(what happened) and acontext(metadata like time remaining). - A trigger: what causes it to run. An HTTP request, a file landing in S3, a message on a queue, a schedule.
- An execution role (from the IAM lesson): the permissions the code runs with.
import json
import os
TABLE = os.environ["TABLE_NAME"] # read once per environment, not per call
def handler(event, context):
body = json.loads(event.get("body") or "{}")
name = body.get("name", "world")
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps({"message": f"hello {name}", "table": TABLE}),
}import type { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from "aws-lambda";
const TABLE = process.env.TABLE_NAME!; // read once per environment
export const handler = async (event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> => {
const body = JSON.parse(event.body ?? "{}");
return {
statusCode: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify({ message: `hello ${body.name ?? "world"}`, table: TABLE }),
};
};The handler returns a dict (or object) in the shape the trigger expects. For an HTTP trigger, that is statusCode, headers and a string body.
You can simulate the call locally, since a handler is just a function:
Press Run (⌘ Enter) to see what happens.Triggers
Synchronous: API Gateway waits for the function and returns its response to the caller.
Cold starts, memory and timeouts
Each copy of your function runs in an execution environment (a small Firecracker micro-VM). The first request to a new environment pays a cold start: download code, start the runtime, run your top-level imports. Later requests reuse the warm environment and skip all that.
- Cold starts are typically 100 ms to 1 s for Python and Node, more for big packages or Java (where SnapStart helps).
- Do expensive setup (SDK clients, config, DB connections) at module level, outside the handler, so warm calls reuse it.
- Provisioned concurrency keeps N environments warm for latency-critical APIs, at an hourly cost.
Memory is the one dial you turn, from 128 MB to 10,240 MB, and CPU scales with it (at 1,769 MB you get one full vCPU). Doubling memory often halves duration, so it can cost the same and be faster. Timeout defaults to 3 seconds and maxes out at 15 minutes.
boto3 client and a database connection inside handler(). Every request is slow. What is the first fix?SnapStart or provisioned concurrency
Both attack cold starts, in opposite ways.
SnapStart moves the init phase to deploy time. When you publish a function version, Lambda runs your initialization once, takes a snapshot of the memory and disk of the initialized environment, and caches it. A cold start then restores that snapshot instead of starting the runtime and running your imports. It is available for Java, Python and .NET (on recent runtime versions), and works on published versions and aliases, not $LATEST.
Provisioned concurrency keeps a number of environments fully initialized and waiting, all the time. Requests up to that number never see a cold start. You pay for those environments every hour whether they serve traffic or not, and you usually scale the number on a schedule with Application Auto Scaling (more during business hours, fewer at night).
| SnapStart | Provisioned concurrency | |
|---|---|---|
| Cold start | Still happens, but is a fast restore | None, up to the provisioned number |
| Cost shape | No idle charge; Java has no extra charge, Python and .NET pay for snapshot caching and restores | Hourly charge for every provisioned environment |
| Best for | Heavy init (Java frameworks, big Python imports) with unpredictable traffic | Strict latency targets with known, steady traffic |
| Watch out for | State captured in the snapshot | Paying for idle capacity |
The SnapStart trap is uniqueness. Everything your init code created is copied into every restored environment. A random seed, a generated instance ID, or a cached temporary credential made at init time is now identical in hundreds of environments. Network connections opened at init may be dead after restore. The fix is to create such things after restore: lazily inside the handler, or in an after-restore runtime hook that each runtime provides. Check the SnapStart docs for the hooks in your language and for current limits; at the time of writing it cannot be combined with provisioned concurrency or EFS.
random.Random() seeded at module level. Why?Concurrency
Concurrency is how many copies run at the same moment. One request that takes 200 ms, arriving 50 times a second, needs about 50 × 0.2 = 10 concurrent environments.
Each account has a Regional concurrency limit (1,000 by default, raisable). Two controls matter:
- Reserved concurrency caps one function (and guarantees it that much), so a runaway function cannot starve the others or flood a database.
- Downstream limits: 1,000 Lambdas each opening a Postgres connection will exhaust the database. Use RDS Proxy, or put SQS in front to smooth the load.
Requests arrive at 300 per second and each takes 0.5 seconds. Roughly how many concurrent executions?
rps = 300 duration_s = 0.5 print(int(rps * duration_s))
Packaging, environment variables and secrets
Two ways to ship code:
- Zip (up to 50 MB zipped, 250 MB unzipped including layers). Fastest cold starts. Good for most functions.
- Container image (up to 10 GB) from ECR, built from an AWS base image. Use it for big dependencies (ML libraries) or when your team already ships containers.
Configuration goes in environment variables. Secrets (API keys, DB passwords) should not: anyone with lambda:GetFunctionConfiguration can read them. Store secrets in Secrets Manager or SSM Parameter Store, give the execution role permission to read that one secret, and fetch it once at module level (the AWS Parameters and Secrets Lambda Extension can cache it for you).
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as events from "aws-cdk-lib/aws-events";
import * as targets from "aws-cdk-lib/aws-events-targets";
import * as secrets from "aws-cdk-lib/aws-secretsmanager";
import { Duration } from "aws-cdk-lib";
const apiKey = secrets.Secret.fromSecretNameV2(this, "StripeKey", "prod/stripe");
const fn = new lambda.Function(this, "NightlyReport", {
runtime: lambda.Runtime.PYTHON_3_13,
handler: "handler.handler",
code: lambda.Code.fromAsset("lambda/report"),
memorySize: 1024,
timeout: Duration.minutes(2),
environment: { SECRET_ID: apiKey.secretArn },
});
apiKey.grantRead(fn);
new events.Rule(this, "Nightly", {
schedule: events.Schedule.cron({ minute: "0", hour: "3" }),
targets: [new targets.LambdaFunction(fn)],
});Powertools for AWS Lambda
Every serious Lambda codebase ends up writing the same helpers: JSON logging with the request ID, custom metrics, tracing, safe retries, batch handling. Powertools for AWS Lambda is the AWS-maintained library that does all of it, for Python, TypeScript, Java and .NET. On a team you will probably find it already in use, and if not, adding it is an easy first contribution.
from aws_lambda_powertools import Logger, Metrics, Tracer
from aws_lambda_powertools.metrics import MetricUnit
from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType, process_partial_response
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer, IdempotencyConfig, idempotent_function,
)
logger = Logger(service="orders")
metrics = Metrics(namespace="Shop", service="orders")
tracer = Tracer(service="orders")
processor = BatchProcessor(event_type=EventType.SQS)
idempotency = IdempotencyConfig(event_key_jmespath="order_id")
store = DynamoDBPersistenceLayer(table_name="orders-idempotency")
@idempotent_function(data_keyword_argument="order", config=idempotency, persistence_store=store)
def charge(order: dict) -> dict:
# call the payment provider here; a retry with the same order_id returns the stored result
return {"charged": order["order_id"]}
@tracer.capture_method
def record_handler(record: SQSRecord) -> None:
order = record.json_body
logger.append_keys(order_id=order["order_id"])
charge(order=order)
metrics.add_metric(name="OrdersCharged", unit=MetricUnit.Count, value=1)
@logger.inject_lambda_context
@tracer.capture_lambda_handler
@metrics.log_metrics(capture_cold_start_metric=True)
def handler(event, context):
idempotency.register_lambda_context(context)
return process_partial_response(
event=event, record_handler=record_handler, processor=processor, context=context,
)What each piece buys you:
- Logger writes one JSON object per line with the request ID, function name and a
cold_startflag, so the Logs Insights queries from Monitoring and Logs work immediately.append_keysaddsorder_idto every later line. - Metrics writes Embedded Metric Format, so
OrdersChargedbecomes a CloudWatch metric with noPutMetricDatacalls, and flushes once at the end of the invocation. - Tracer creates trace segments for the handler and each decorated function, and annotates cold starts. AWS is moving tracing towards OpenTelemetry, so check the Powertools docs for the recommended tracing setup in your language.
- Idempotency stores the result of
chargein DynamoDB, keyed on a hash oforder_id. A retried message (and SQS does deliver some messages more than once) gets the stored result back instead of charging twice. This is the single most valuable utility for anything that moves money or sends email. - Batch processing handles partial batch failures, which the next section explains.
The API names above match the current Python major version; check the Powertools docs for yours, because decorators and imports have changed between majors.
SQS batches and partial failures
When Lambda reads from SQS, your function receives a batch of up to 10 messages by default (more with a batching window). Here is the default behavior that causes real incidents: if the function raises, the whole batch counts as failed. Every message becomes visible again after the visibility timeout and is delivered again, including the ones you already processed.
With one bad message in the batch, that means duplicate side effects for the good ones and, if the bad message never succeeds, the good messages that came after it in the batch never get processed at all until the bad one is moved to the DLQ.
The fix is to turn on ReportBatchItemFailures on the event source mapping and return the IDs of only the messages that failed:
{ "batchItemFailures": [ { "itemIdentifier": "m2" } ] }Lambda deletes the rest and only m2 comes back. Run this simulation with one bad message in a batch of four:
Press Run (⌘ Enter) to see what happens.Without partial responses, A0 and A1 are charged three times and A3 is never processed. With them, each good order is charged exactly once and only the bad message cycles until the redrive policy moves it to the dead-letter queue.
The rules to remember:
- An empty
batchItemFailureslist (orNone) means everything succeeded. - Raising an exception still fails the whole batch, even with the setting on. Catch per record. Powertools'
process_partial_responsedoes this for you. - An
itemIdentifierthat is empty or not a message ID in the batch makes Lambda treat the whole batch as failed. - Set the queue's visibility timeout to at least six times the function timeout (AWS's guidance), so a slow batch is not redelivered while still running, and set
maxReceiveCounton a redrive policy so poison messages end up in a DLQ. - For FIFO queues, stop at the first failure and report it and every message after it, so order within a message group is kept.
ReportBatchItemFailures is enabled. Your handler loops over 10 messages, and on message 7 an unexpected KeyError escapes the loop. What happens?The pricing model
You pay for requests and for duration × memory (GB-seconds), billed per millisecond. Idle costs nothing. Example prices for x86 in us-east-1 (Arm is about 20% cheaper per GB-second; check current pricing):
- $0.20 per million requests
- about $0.0000166667 per GB-second
Press Run (⌘ Enter) to see what happens.Notice the second line: double the memory, half the duration, same compute cost and faster responses. Notice the third line too: at sustained high traffic, a couple of containers may be cheaper.
Lambda vs containers vs servers
| EC2 | Lambda | ECS on Fargate | |
|---|---|---|---|
| Unit | A VM you manage | A function per event | A container task |
| Scales to zero | No | Yes | No (min 1 task, usually) |
| Max run time | Unlimited | 15 minutes | Unlimited |
| Cold starts | No | Yes | Only when scaling out (slower, ~30-60 s) |
| You manage | OS, patching, scaling | Just code | Image and task sizing |
| Billing | Per second while running | Per request + per ms | Per second for vCPU + memory |
| Sweet spot | Special hardware, full control | Spiky or event-driven work | Steady web APIs, long jobs |
When serverless is a bad fit
- Jobs longer than 15 minutes (video processing, big ETL). Use Fargate or AWS Batch.
- Steady, high traffic where per-request pricing beats always-on containers.
- Long-lived connections like WebSockets held for hours (API Gateway WebSockets helps, but the model is awkward).
- Workloads that need GPUs or local state.
- Very latency-sensitive paths where cold starts hurt and you would rather not pay for provisioned concurrency.
Lambda or not?
Newer options: durable functions and Managed Instances
Two features from late 2025 push Lambda past its classic limits. Both are new, so check the docs for current runtimes, Regions and limits before you design around them.
Lambda durable functions let a single function run a multi-step workflow that can wait for hours or days without paying for compute while it waits. You wrap work in checkpointed steps; after a wait or a crash, the function replays and skips the steps that already finished. Step Functions and Durable Workflows covers how replay works, the determinism rule it imposes, and when to pick it over a Step Functions state machine.
Lambda Managed Instances run your functions on EC2 instances in your account that Lambda provisions, patches and scales for you. Three things differ from normal Lambda:
- You choose the instance profile, including Graviton and other families, and EC2 pricing options such as Savings Plans apply.
- One execution environment handles several requests at once, so your code must be safe for concurrent requests (no per-request data in globals), more like a web server than a classic handler.
- Capacity scales with utilization rather than per request, so it does not scale to zero the way standard Lambda does.
It targets the gap the table above shows: steady, high-volume traffic where per-millisecond pricing gets expensive but the team wants to keep the Lambda programming model and tooling instead of moving to containers.
Testing locally with SAM CLI
Unit tests come first and need no AWS at all: a handler is a function, so call it with a fixture event, as at the top of this lesson, and stub AWS calls as The AWS CLI and boto3 for Developers shows in "Testing without touching AWS". The AWS SAM CLI adds the next level: it runs your function in a Docker container built from the same base image Lambda uses, with the real event shapes.
sam local generate-event sqs receive-message > events/sqs.jsonsam local invoke OrdersFunction --event events/sqs.jsonsam local start-api # API Gateway routes on localhost:3000sam build # build the deployment artifacts firstsam sync --watch --stack-name orders-dev # push code changes to a real dev stack in secondsgenerate-event produces a realistic event for many sources, which is the easiest way to get the shape exactly right. Edit the body in the file to your own message (there is also a --body option), and commit a few of these fixtures next to the tests. invoke needs Docker running. It also works for CDK projects: synthesize first, then point SAM at the generated template with -t, for example sam local invoke -t cdk.out/OrdersStack.template.json OrdersFunction.
Know the limits. A local invoke runs your code, not the service around it: IAM is not enforced the same way, event source mappings, retries and partial batch handling are not simulated, and VPC networking is your laptop's. So the usual ladder is unit tests for logic, sam local invoke for packaging and event shape, and sam sync or a deployed test stack for anything involving permissions, triggers and real service behavior.
Estimate a Lambda bill
Lambda charges for requests and for compute, measured in GB-seconds (memory in GB times run time in seconds). Use these example prices (real prices vary by region and change over time, and the free tier is ignored here):
- $0.20 per 1 million requests
- $0.0000166667 per GB-second
Write lambda_cost(invocations, avg_ms, memory_mb) that returns the monthly cost in dollars. Memory in GB is memory_mb / 1024.
lambda_cost(1_000_000, 100, 512) → about 1.0333
requests: 1M × 0.20 / 1M = 0.20
compute: 1M × 0.1 s × 0.5 GB = 50,000 GB-s × 0.0000166667 ≈ 0.8333- handler
- The function Lambda calls with
(event, context)for each invocation. - cold start
- Extra latency when a new execution environment initializes the runtime and your module code.
- concurrency
- Copies running at once. About requests per second times average duration.
- reserved concurrency
- A per-function cap (and guarantee) on concurrent executions.
- execution role
- The IAM role whose permissions the function's code runs with.
- GB-second
- Lambda's compute billing unit: memory in GB times run time in seconds.
- SnapStart
- Snapshots an initialized environment at publish time so cold starts restore it instead of re-running init.
- partial batch response
- Returning
batchItemFailuresso only failed SQS messages are retried, not the whole batch. - Powertools for AWS Lambda
- AWS's library for structured logs, EMF metrics, tracing, idempotency and batch handling in Lambda.