Skip to content

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.

28 min read0/6 questions

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 a context (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.
handler.py
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}),
    }

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:

Pythonlocal_test.py
import json def handler(event, context): body = json.loads(event.get("body") or "{}") name = body.get("name", "world") return {"statusCode": 200, "body": json.dumps({"message": f"hello {name}"})} fake_event = {"rawPath": "/hello", "body": json.dumps({"name": "Priya"})}response = handler(fake_event, None)print(response["statusCode"], response["body"])print(handler({}, None)["body"])
Output
Press Run (⌘ Enter) to see what happens.

Triggers

Common Lambda triggers
BrowserBrowserAPI Gateway: or function URLAPI Gatewayor function URLS3: ObjectCreatedS3ObjectCreatedSQS: batch of 10SQSbatch of 10EventBridge: cron(0 3 * * ? *)EventBridgecron(0 3 * * ? *)Lambda: many copiesLambdamany copiesDynamoDBDynamoDBCloudWatch LogsCloudWatch LogsHTTPSsyncasyncpollschedule

Synchronous: API Gateway waits for the function and returns its response to the caller.

1/5

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.

Quick check
Your Python handler creates a boto3 client and a database connection inside handler(). Every request is slow. What is the first fix?
Need a nudge? A hint rules out a wrong answer.

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).

SnapStartProvisioned concurrency
Cold startStill happens, but is a fast restoreNone, up to the provisioned number
Cost shapeNo idle charge; Java has no extra charge, Python and .NET pay for snapshot caching and restoresHourly charge for every provisioned environment
Best forHeavy init (Java frameworks, big Python imports) with unpredictable trafficStrict latency targets with known, steady traffic
Watch out forState captured in the snapshotPaying 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.

Quick check
After enabling SnapStart on a Python function, you notice many environments generate the same 'unique' job IDs. The IDs come from random.Random() seeded at module level. Why?
Need a nudge? A hint rules out a wrong answer.

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.
Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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).

CDK: a function with a schedule and a secret
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.

orders/handler.py
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_start flag, so the Logs Insights queries from Monitoring and Logs work immediately. append_keys adds order_id to every later line.
  • Metrics writes Embedded Metric Format, so OrdersCharged becomes a CloudWatch metric with no PutMetricData calls, 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 charge in DynamoDB, keyed on a hash of order_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:

partial batch response
{ "batchItemFailures": [ { "itemIdentifier": "m2" } ] }

Lambda deletes the rest and only m2 comes back. Run this simulation with one bad message in a batch of four:

Pythonpartial_batch.py
import json charged: list[str] = [] def process(record: dict) -> None: order = json.loads(record["body"]) if order["total"] < 0: raise ValueError(f"bad total in {order['id']}") charged.append(order["id"]) # a side effect: this customer was charged def handler(event: dict, partial: bool) -> dict: failures = [] for record in event["Records"]: try: process(record) except ValueError: if not partial: raise # whole batch fails, every message comes back failures.append({"itemIdentifier": record["messageId"]}) return {"batchItemFailures": failures} def run(partial: bool, attempts: int = 3) -> None: charged.clear() queue = [{"messageId": f"m{i}", "body": json.dumps({"id": f"A{i}", "total": t})} for i, t in enumerate([20, 35, -1, 50])] for attempt in range(1, attempts + 1): if not queue: break try: result = handler({"Records": queue}, partial) failed = {f["itemIdentifier"] for f in result["batchItemFailures"]} queue = [r for r in queue if r["messageId"] in failed] except ValueError: pass # Lambda reports the batch as failed; all messages become visible again print(f" attempt {attempt}: {len(queue)} message(s) back on the queue") print(" charges:", charged) print("without ReportBatchItemFailures")run(partial=False)print("with ReportBatchItemFailures")run(partial=True)
Output
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 batchItemFailures list (or None) means everything succeeded.
  • Raising an exception still fails the whole batch, even with the setting on. Catch per record. Powertools' process_partial_response does this for you.
  • An itemIdentifier that 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 maxReceiveCount on 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.
Quick check
ReportBatchItemFailures is enabled. Your handler loops over 10 messages, and on message 7 an unexpected KeyError escapes the loop. What happens?
Need a nudge? A hint rules out a wrong answer.

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
Pythonlambda_cost.py
REQUEST_PRICE = 0.20 / 1_000_000GB_SECOND = 0.0000166667 # example price def monthly_cost(invocations, avg_ms, memory_mb): gb_s = invocations * (avg_ms / 1000) * (memory_mb / 1024) return invocations * REQUEST_PRICE + gb_s * GB_SECOND print(f"Small API, 3M calls, 120 ms, 512 MB: ${monthly_cost(3_000_000, 120, 512):.2f}")print(f"Same at 1024 MB but 60 ms: ${monthly_cost(3_000_000, 60, 1024):.2f}")print(f"Busy API, 300M calls, 120 ms, 512 MB: ${monthly_cost(300_000_000, 120, 512):.2f}")
Output
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

EC2LambdaECS on Fargate
UnitA VM you manageA function per eventA container task
Scales to zeroNoYesNo (min 1 task, usually)
Max run timeUnlimited15 minutesUnlimited
Cold startsNoYesOnly when scaling out (slower, ~30-60 s)
You manageOS, patching, scalingJust codeImage and task sizing
BillingPer second while runningPer request + per msPer second for vCPU + memory
Sweet spotSpecial hardware, full controlSpiky or event-driven workSteady 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.
Match the pairs0/4 matched

Lambda or not?

Choose an item, then its match on the other side.
Quick check
Your Lambda needs to reach a private RDS database AND call a third-party HTTPS API. You attach it to the VPC's private subnets. The DB works, but the HTTPS call times out. Why?
Need a nudge? A hint rules out a wrong answer.

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.json
sam 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 seconds

generate-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.

ChallengeEasy

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
def lambda_cost(invocations: int, avg_ms: float, memory_mb: int) -> float: pass
Key terms
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 batchItemFailures so 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.