Serverless on AWS

System Design · Cloud Building Blocks · Intermediate · 22 min

Build an API with API Gateway, Lambda and DynamoDB, orchestrate work with EventBridge and Step Functions, and judge when serverless is the right call.

A row of food stalls that only light up when a customer arrives: the first customer waits while the cook fires up the grill (cold start), the next ones are served instantly (warm), and a sudden crowd makes new stalls appear, each with its own short warm-up.

The idea in everyday words

Serverless is like using taxis instead of owning a car. No parking, no insurance, no maintenance, and you pay per ride. The first taxi takes a moment to arrive, rush hour needs many taxis at once, and if you drive 10 hours every day, owning a car becomes cheaper.

What 'serverless' really means

There are still servers. You just never see, patch or size them. A service is "serverless" when it has:

  • No servers to manage (no OS, no instance types).
  • Automatic scaling, including down to zero when idle.
  • Pay per use (requests, duration, storage), not per hour of uptime.
  • Built-in high availability across AZs.

The AWS serverless toolbox:

Need Service Role
HTTP front door API Gateway (or Lambda Function URLs) Routing, auth, throttling, request validation
Compute Lambda Run a function per event
Database DynamoDB Key-value/document store, single-digit ms, scales per request
Files S3 Object storage, emits events
Messaging SQS, SNS, EventBridge Queues, pub/sub, event routing
Workflows Step Functions Multi-step processes with retries and state
Users Cognito Sign-up, sign-in, tokens

Other clouds: GCP: API Gateway, Cloud Run functions, Firestore, Eventarc and Workflows. Azure: API Management, Azure Functions, Cosmos DB, Event Grid and Durable Functions or Logic Apps. Open source: Knative or OpenFaaS on Kubernetes.

The classic path: API Gateway → Lambda → DynamoDB

  1. API Gateway receives POST /orders, checks the caller (Cognito JWT, IAM or a Lambda authorizer), applies throttling, and invokes the function. HTTP APIs are simpler and cheaper; REST APIs add features like usage plans, API keys and request validation.
  2. Lambda parses the body, validates it, and writes to DynamoDB. Keep the handler small and stateless.
  3. DynamoDB stores the order. Design the partition key around how you read (for example PK = customer_id, SK = order_time). Use on-demand capacity for unpredictable traffic.

Code outside the handler runs once per environment (during INIT); code inside runs every request. Put SDK clients outside so warm requests reuse connections.

import json

# --- INIT: runs once per execution environment ---
TABLE = {}                         # stand-in for boto3.resource("dynamodb").Table("orders")
print("INIT: clients created")

# --- INVOKE: runs on every request ---
def handler(event, context=None):
    order = json.loads(event["body"])
    if "id" not in order:
        return {"statusCode": 400, "body": "missing id"}
    TABLE[order["id"]] = order     # table.put_item(Item=order)
    return {"statusCode": 201, "body": json.dumps({"saved": order["id"]})}

print(handler({"body": json.dumps({"id": "o-1", "total": 42})}))
print(handler({"body": json.dumps({"total": 7})}))
print("rows:", len(TABLE))

Infrastructure as code with the AWS CDK (TypeScript, not runnable here):

const table = new dynamodb.Table(this, "Orders", {
  partitionKey: { name: "id", type: dynamodb.AttributeType.STRING },
  billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
});
const fn = new lambda.Function(this, "CreateOrder", {
  runtime: lambda.Runtime.PYTHON_3_12, handler: "app.handler", code: lambda.Code.fromAsset("src"),
});
table.grantWriteData(fn);                       // least-privilege IAM, generated for you
new apigw.LambdaRestApi(this, "Api", { handler: fn });

Cold starts, warm starts and concurrency

Every Lambda execution environment goes through INIT → INVOKE (many times) → SHUTDOWN.

  • Cold start: no free environment, so Lambda creates one, loads your code, starts the runtime and runs your INIT code. This adds latency to that one request (from well under a second to a few seconds, depending on runtime, package size and what INIT does).
  • Warm start: a free environment already exists; only the handler runs.
  • Environments are reused for a while, then reclaimed when idle.

Each environment serves one request at a time. So:

concurrency ≈ requests per second × average duration (seconds)

for rps, duration_s in [(50, 0.2), (500, 0.2), (500, 2.0)]:
    print(f"{rps} req/s x {duration_s}s -> about {round(rps * duration_s)} environments busy")

Ways to reduce cold-start pain:

  • Smaller deployment packages, fewer and lazier imports.
  • More memory (Lambda gives proportionally more CPU), which speeds INIT too.
  • SnapStart (for supported runtimes) restores a snapshot of an initialized environment.
  • Provisioned concurrency keeps N environments initialized; you pay for them while they wait.

Cold starts cost money too, not just latency. Since 1 August 2025 AWS bills the INIT phase like invoke duration for on-demand functions packaged as ZIP files on managed runtimes (container images and custom runtimes were already billed for it). A function that loads a big model or many libraries in INIT now pays for that time on every cold start, so trimming INIT saves both latency and money. Check the Lambda pricing page for details.

Concurrency controls: your account has a per-Region concurrency quota. Reserved concurrency guarantees and caps capacity for one function (also protects a fragile database from a flood). Exceeding limits gives throttling (a 429 TooManyRequests error for direct callers). Lambda retries throttled asynchronous invokes for you, but nobody retries a synchronous call (API Gateway, the SDK in your own code) automatically: the caller sees an error and should retry with backoff.

Events and workflows: EventBridge and Step Functions

Not everything should happen while the user waits. After saving an order, charging the card, reserving stock and sending an email can happen asynchronously.

Amazon EventBridge is an event bus. Producers publish events like {"detail-type": "OrderPlaced", ...}; rules match on event fields and send them to targets (Lambda, Step Functions, SQS, other buses). Producers don't know who listens, so teams can add consumers without touching the producer. EventBridge Scheduler handles cron-like and one-off schedules; EventBridge Pipes connects a source to a target with filtering.

AWS Step Functions runs a state machine: a diagram of steps with built-in retries, timeouts, branching, parallel steps and error handling.

  • Standard workflows: long-running (up to a year), exactly-once workflow execution, full history. Good for orders and approvals. Careful: a Retry rule on a Task runs that Task again, so a payment step still needs an idempotency key.
  • Express workflows: very high rate, short (up to 5 minutes). Asynchronous Express runs are at-least-once (a step may run twice); synchronous Express runs are at-most-once (a step may not run at all if something fails). Good for streaming and high-volume event processing. See Choosing a workflow type.

Why not just chain Lambdas calling each other? Then you write retries, timeouts and state yourself, pay for functions waiting on functions, and lose visibility. Step Functions makes the workflow explicit.

Design rules for async:

  • Make handlers idempotent (safe to run twice), because async delivery can repeat.
  • Send failures to a dead-letter queue (DLQ) or an on-failure destination so nothing is lost silently.
  • Use SQS between producer and consumer when you need buffering or rate control.

Cost model: when serverless fits and when it doesn't

Lambda cost = requests × price per request + GB-seconds × price per GB-second.

Two details people miss:

  • Billed duration includes INIT on cold starts for on-demand functions (since August 2025), so the "average duration" you plug in should include cold-start time, weighted by how often cold starts happen.
  • Architecture changes the rate: Arm (Graviton, arm64) functions are cheaper per GB-second than x86, and often as fast or faster. If your code has no x86-only native libraries, switching is usually the easiest saving.

Provisioned concurrency, API Gateway, DynamoDB and data transfer are billed separately.

A GB-second is one second of run time at 1 GB of memory. 1 million requests × 100 ms × 512 MB = 1,000,000 × 0.1 s × 0.5 GB = 50,000 GB-seconds. There is a monthly free tier; check the AWS Lambda pricing page for current numbers. API Gateway, DynamoDB and data transfer are billed separately.

Fits well:

  • Spiky or unpredictable traffic, or long idle periods (scale to zero).
  • Event processing: S3 uploads, queue messages, streams, schedules.
  • Glue between AWS services, small APIs, prototypes, internal tools.
  • Teams that want to ship features rather than run servers.

Fits poorly:

  • Steady, high throughput all day: always-on containers or instances usually cost less.
  • Long jobs over 15 minutes (use ECS, Batch or Step Functions to split work).
  • Strict low-latency tails where any cold start is unacceptable (unless you pay for provisioned concurrency).
  • Heavy GPU work, big in-memory state, or long-lived custom protocols.

How to decide in an interview: estimate the traffic shape, compute a rough monthly cost for both (with prices as variables), and name the non-cost factors: ops effort, latency, limits and vendor lock-in.

Step by step

  1. Request arrives:

    POST /orders hits API Gateway. It validates the Cognito token, applies throttling, and invokes the createOrder Lambda synchronously.

  2. Cold start:

    No free environment. Lambda creates one and runs INIT (imports, DynamoDB client): about 450 ms in our illustrative numbers.

  3. Handler:

    The handler parses the body and calls PutItem: about 33 ms. The client gets 201 after roughly 490 ms.

  4. Warm request:

    A second request a moment later reuses the warm environment: no INIT, about 43 ms end to end.

  5. Burst:

    3 requests arrive at once with 1 warm environment. One reuses it; two need new environments and pay cold starts. Concurrency = 3.

  6. Async work:

    The handler publishes OrderPlaced to EventBridge and returns. A rule starts a Step Functions workflow: charge → reserve stock → ship → email, with retries.

Code example

import math


def round_cents(x):
    return math.floor(x * 100 + 0.5) / 100     # half-up, same in every language


def lambda_cost(requests, avg_ms, memory_mb, prices):
    gb_seconds = requests * avg_ms * memory_mb / 1024000    # ms->s (/1000), MB->GB (/1024)
    billable_gbs = max(0, gb_seconds - prices["free_gb_seconds"])
    billable_req = max(0, requests - prices["free_requests"])
    request_cost = billable_req / 1000000 * prices["per_million_requests"]
    compute_cost = billable_gbs * prices["per_gb_second"]
    return {
        "gb_seconds": round_cents(gb_seconds),
        "request_cost": round_cents(request_cost),
        "compute_cost": round_cents(compute_cost),
        "total": round_cents(request_cost + compute_cost),
    }


# Compare Lambda with an always-on container fleet. ALL PRICES ARE MADE UP: use the pricing pages.
prices = {"per_million_requests": 0.25, "per_gb_second": 0.00002, "free_requests": 0, "free_gb_seconds": 0}
fleet_monthly = 120.0        # pretend cost of two small always-on containers
for name, monthly_requests in [("internal tool", 200_000), ("startup API", 20_000_000), ("busy API", 300_000_000)]:
    bill = lambda_cost(monthly_requests, avg_ms=120, memory_mb=512, prices=prices)
    winner = "Lambda" if bill["total"] < fleet_monthly else "containers"
    print(f"{name:14} {monthly_requests:>11,} req/month  lambda={bill['total']:>8.2f}  fleet={fleet_monthly:.2f}  cheaper: {winner}")

# Cold vs warm: environments are reused while they stay warm.
warm_pool = 0
for t, concurrent in enumerate([1, 1, 3, 1]):
    cold = max(0, concurrent - warm_pool)
    warm_pool = max(warm_pool, concurrent)
    print(f"t={t}: {concurrent} at once -> {cold} cold start(s), {concurrent - cold} warm")

Interview tips

  • Draw the canonical path: Client → API Gateway → Lambda → DynamoDB, with EventBridge or SQS for async work and Step Functions for multi-step processes.

  • Bring up cold starts yourself and give mitigations: smaller packages, more memory, SnapStart where supported, provisioned concurrency for latency-critical paths.

  • Explain concurrency = rate × duration, and protect downstream databases with reserved concurrency or a queue.

  • Say when you would NOT use serverless: steady high load, jobs over 15 minutes, strict tail latency, GPU work.

  • Mention idempotency keys and DLQs for every async flow; at-least-once delivery means duplicates happen.

Challenge: Lambda Cost Estimator

Estimate a monthly Lambda bill. Prices are parameters: never hard-code real prices, they change.

Write lambda_cost(requests, avg_ms, memory_mb, prices) where prices has per_million_requests, per_gb_second, free_requests and free_gb_seconds.

  1. gb_seconds = requests × avg_ms × memory_mb ÷ 1,024,000 (ms → s and MB → GB).
  2. Billable amounts subtract the free tier and never go below 0.
  3. request_cost = billable_requests ÷ 1,000,000 × per_million_requests, compute_cost = billable_gb_seconds × per_gb_second.
  4. Return gb_seconds, request_cost, compute_cost and total (= request_cost + compute_cost before rounding), each rounded to 2 decimals with half-up: floor(x × 100 + 0.5) / 100.

Example (made-up prices):

lambda_cost(10_000_000, 100, 512, {"per_million_requests": 0.25, "per_gb_second": 0.00002,
                                    "free_requests": 0, "free_gb_seconds": 0})
→ {"gb_seconds": 500000.0, "request_cost": 2.5, "compute_cost": 10.0, "total": 12.5}

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Cloud Building Blocks

Previous: VPC Networking · Next: Scaling & Load Balancers