System Design

The building blocks

Every component is described four ways — what it’s for, what it is inside a monolith, what it becomes in a distributed system, and what AWS calls it — plus how it fails and what interviewers ask next.

Clients Where requests start

Edge & network Getting traffic in (and out)

Compute Where your code runs

Data Where state lives

Messaging Async communication

Platform Cross-cutting and third-party

X vs Y The comparisons interviews love

Middleware Runs before your handler, in this order

  1. Request ID & tracing

    Assigns or propagates a correlation/trace ID and opens a span for every request.

    Monolith
    Logging middleware stamps a request ID on every log line.
    Distributed
    The edge assigns a trace ID and every service forwards it (W3C traceparent), so one request can be followed across hops.
    AWS
    ALB adds X-Amzn-Trace-Id; X-Ray / ADOT SDKs continue the trace in each service.
  2. TLS termination

    Decrypts HTTPS at the edge so the hops behind it can be simpler (or re-encrypted).

    Monolith
    Nginx or the app server holds the certificate.
    Distributed
    Terminated at the CDN/LB/gateway; internal traffic is re-encrypted (mTLS) by a mesh where required.
    AWS
    ACM certificates on CloudFront, ALB or API Gateway — free and auto-renewed.
  3. WAF

    Blocks malicious patterns (SQL injection, bots, bad IPs) before they reach your code.

    Monolith
    Often nothing, or a few Nginx rules / a third-party proxy in front.
    Distributed
    One WAF at the edge protects every service behind it.
    AWS
    AWS WAF on CloudFront, ALB or API Gateway; AWS Shield for DDoS.
  4. Rate limiting

    Caps requests per client (token bucket / sliding window) to protect capacity and stop abuse.

    Monolith
    In-memory counters — wrong as soon as there are two instances, because each counts separately.
    Distributed
    Enforced at the gateway with shared counters (Redis) so limits hold across every instance.
    AWS
    API Gateway throttling and usage plans; AWS WAF rate-based rules.
  5. CORS

    Tells browsers which origins may call your API.

    Monolith
    Framework middleware sets the Access-Control-* headers.
    Distributed
    Configured once at the gateway instead of in every service.
    AWS
    API Gateway CORS configuration.
  6. Authentication

    Verifies who the caller is (session lookup or JWT signature) and rejects anonymous requests.

    Monolith
    Session middleware loads the user from the session store.
    Distributed
    The gateway verifies JWTs; services trust the verified identity (and still authorize).
    AWS
    API Gateway JWT / Cognito / Lambda authorizers; ALB’s OIDC authentication action.
  7. Request validation

    Rejects malformed requests (schema, sizes, types) before business logic runs.

    Monolith
    Pydantic / Zod schemas on each endpoint.
    Distributed
    Coarse schema checks at the gateway, detailed validation in the service.
    AWS
    API Gateway request validators (REST APIs) with JSON Schema models.
  8. Idempotency keys

    Stores the result per Idempotency-Key so a retried POST returns the first result instead of acting twice.

    Monolith
    A table keyed by idempotency key that stores the response.
    Distributed
    Every service that moves money or state on retryable calls keeps its own idempotency store.
    AWS
    Usually DynamoDB conditional writes or a Postgres unique constraint; Powertools for Lambda ships an idempotency utility.
  9. Compression

    Gzip/Brotli responses to cut bandwidth and download time.

    Monolith
    Middleware compresses responses.
    Distributed
    Usually done at the CDN/edge for static and cacheable content.
    AWS
    CloudFront automatic compression; API Gateway content encoding.

Cheap rejections (WAF, rate limits) run before expensive work (auth lookups, validation), and tracing wraps everything so even rejected requests are visible.

Zones Where things live on the network

Region · AWS: AWS Region
A geographic area with several isolated datacenters (AZs). Multi-region means copying everything here into a second one.
Private network · AWS: VPC
Your isolated virtual network. Resources inside get private IPs; the subnets decide what’s reachable from the internet.
Datacenter (AZ) · AWS: Availability Zone
One or more datacenters with independent power and networking. Spread replicas across at least two.
Public zone (DMZ) · AWS: Public subnet
Has a route to the internet gateway. Load balancers and NAT gateways go here — never databases.
Private zone · AWS: Private subnet
No inbound route from the internet. App servers, databases and caches live here; outbound calls go through NAT.

Connection rules Row connects to column — exactly what the canvas enforces

validonly under a conditionneverno direct connectionHover a cell for the reason.

from ↓ · to →ClientsDNSCDNLoad balancerAPI gatewayNAT gatewayApp serverServiceWorkerSchedulerRealtime serverWorkflowSQL databaseRead replicaNoSQL storeCacheObject storageSearchDB proxyQueueDLQPub/sub topicEvent streamIdentity providerSecretsThird-party API
Clientsnonevalidvalidvalidvalidnoneconditionalconditionalinvalidnoneconditionalnoneconditionalinvalidconditionalinvalidconditionalinvalidinvalidinvalidinvalidinvalidinvalidvalidnoneconditional
DNSnonenonevalidvalidvalidnonevalidvalidnonenonevalidnonenonenonenonenonenonenonenonenonenonenonenonenonenonenone
CDNnonenonenonevalidvalidnonevalidvalidnonenonenonenoneinvalidinvalidinvalidinvalidvalidinvalidinvalidnonenonenonenonenonenonenone
Load balancernonenonenonenoneconditionalnonevalidvalidinvalidnonevalidnoneinvalidinvalidinvalidinvalidinvalidinvalidinvalidnonenonenonenonenonenonenone
API gatewaynonenonenonevalidnonenonevalidvalidinvalidnonevalidconditionalinvalidinvalidconditionalinvalidinvalidinvalidinvalidconditionalnoneconditionalconditionalvalidnonenone
NAT gatewaynonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonevalid
App servernonenoneinvalidvalidconditionalvalidvalidvalidinvalidnonevalidvalidvalidvalidvalidvalidvalidvalidvalidvalidinvalidvalidvalidvalidvalidvalid
Servicenonenoneinvalidvalidconditionalvalidvalidvalidinvalidnonevalidvalidvalidvalidvalidvalidvalidvalidvalidvalidinvalidvalidvalidvalidvalidvalid
Workernonenoneinvalidvalidnonevalidvalidvalidinvalidnonevalidvalidvalidvalidvalidvalidvalidvalidvalidvalidinvalidvalidvalidvalidvalidvalid
Schedulernonenonenonenonenonenonenonevalidvalidnonenonevalidnonenonenonenonenonenonenonevalidnonevalidnonenonenonenone
Realtime servernonenonenonenonenonevalidvalidvalidinvalidnoneinvalidnonevalidvalidvalidvalidvalidvalidvalidvalidnonevalidvalidvalidvalidvalid
Workflownonenonenonenonenonenonevalidvalidvalidnonenonenonenonenonevalidnonenonenonenonevalidnonevalidnonenonenonevalid
SQL databasenonenonenonenonenonenonenonenonenonenonenonenoneconditionalvalidnonenonenonenonenoneconditionalnoneconditionalvalidnonenonenone
Read replicanonenonenonenonenonenonenonenonenonenonenonenonenoneconditionalnonenonenonenonenonenonenonenonenonenonenonenone
NoSQL storenonenonenonenonenonenonenonenonenonenonenonenonenonenoneconditionalnonenonenonenoneconditionalnoneconditionalvalidnonenonenone
Cachenonenonenonenonenonenonenonenonenonenonenonenoneconditionalnoneconditionalnonenonenonenonenonenonenonenonenonenonenone
Object storagenonenonenonenonenonenonenonenoneconditionalnonenonenonenonenonenonenonenonenonenonevalidnonevalidnonenonenonenone
Searchnonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenone
DB proxynonenonenonenonenonenonenonenonenonenonenonenonevalidvalidnonenonenonenonenonenonenonenonenonenonenonenone
Queuenonenonenonenonenonenonevalidvalidvalidnonenonenoneinvalidinvalidinvalidinvalidinvalidinvalidinvalidnonevalidnonenonenonenoneinvalid
DLQnonenonenonenonenonenonenoneconditionalconditionalnonenonenonenonenonenonenonenonenonenoneconditionalnonenonenonenonenonenone
Pub/sub topicnonenonenonenonenonenonevalidvalidvalidnonevalidnoneinvalidinvalidinvalidinvalidinvalidinvalidinvalidvalidnonenonenonenonenoneconditional
Event streamnonenonenonenonenonenonevalidvalidvalidnonenonenoneinvalidinvalidinvalidinvalidconditionalconditionalinvalidnonenonenonenonenonenoneinvalid
Identity providernonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenone
Secretsnonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenone
Third-party APInonenonenonevalidvalidnoneconditionalconditionalnonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenonenone

Concepts The vocabulary

API gateway

A single entry point that handles auth, rate limits, validation and routing for many services.

Microservices with several client types.

Keep business logic out of it.

Async processing with queues

The request enqueues work and returns; consumers process it later at their own pace.

Emails, image processing, fan-out, anything slow or retryable.

Queues turn traffic spikes into backlog instead of errors.

At-least-once delivery

Every message is delivered, but some may arrive more than once.

SQS Standard, SNS, most brokers after consumer crashes or timeouts.

Exactly-once delivery is rare — aim for exactly-once *effect* with idempotent consumers.

Backpressure

Signalling upstream to slow down when a component can’t keep up.

Queues with bounded size, 429s, TCP flow control, stream consumers.

Better to reject early and cheaply than to accept work you can’t finish.

Cache busting

Giving each build’s assets new URLs (content hashes) so CDNs and browsers never serve old versions.

JS/CSS bundles and images behind a CDN.

Hash filenames and cache them forever; keep HTML short-lived.

Cache stampede / thundering herd

A hot key expires (or the cache restarts) and many requests miss at once, all hitting the database.

Cold caches after deploys or failovers; popular keys with the same TTL.

Fixes: request coalescing (single flight), locks on recompute, jittered TTLs, early refresh.

Cache-aside

Read the cache; on a miss read the database and populate the cache. Writes update the DB and invalidate the cached key.

The default caching pattern with Redis/Memcached.

Compare with write-through (cache updated on write) and write-behind (DB updated later).

CAP and PACELC

During a network Partition choose Availability or Consistency; Else trade Latency vs Consistency.

Multi-region databases, replicated stores.

Use it to explain a concrete choice (e.g. async cross-region replicas favour latency).

Change data capture

Turning a database’s log of committed changes into a stream of events.

Feeding search indexes, caches, analytics, the outbox pattern.

Avoids dual writes from application code.

Circuit breaker

After enough failures, stop calling a dependency for a while and fail fast; probe occasionally to see if it recovered.

Calls to flaky or slow dependencies.

Pair it with a fallback (cached value, degraded response, queue for later).

Consistent hashing

Mapping keys to nodes on a hash ring so adding/removing a node moves only ~1/N of the keys.

Sharded caches and databases, load balancing with affinity.

Virtual nodes smooth out uneven distribution.

Dead-letter queue

Where messages go after failing a set number of times, so they stop retrying forever.

Every queue whose messages matter.

Alarm on it and own the redrive process.

Eventual consistency

Replicas or derived views converge to the same state if updates stop — but may disagree briefly.

Async replication, caches, search indexes, event-driven services.

Name where it’s acceptable (feeds, counts) and where it isn’t (balances).

Fan-out on write vs read

Write: precompute each reader’s view when content is created. Read: assemble the view at read time.

News feeds, timelines, inboxes.

Hybrid for celebrities: pull their posts at read time.

Fault isolation

A failure in one part of the system stays in that part.

Separate services, separate queues per channel, bulkheads, cell-based architectures.

Ask: what’s the blast radius of this component failing?

Hot partition / hot key

One key or shard gets a disproportionate share of traffic.

Celebrity accounts, viral products, timestamp-based keys.

Add a random suffix (write sharding), cache the hot item, or split the key.

Idempotency

Doing an operation twice has the same effect as doing it once.

Payment APIs (Idempotency-Key), message consumers, retries.

Store the key with the result (unique constraint) and return the stored result on repeats.

Latency numbers

Orders of magnitude: memory ~100 ns, same-datacenter round trip ~0.5 ms, cross-continent round trip ~100+ ms.

Every network hop you add, every cross-region call, every cache hit vs miss.

Count network hops on the critical path and add them up out loud.

Microservices

Independently deployable services, each owning one capability and its data.

Large teams, very different scaling or availability needs per capability.

Justify with team autonomy and fault isolation — not “for scale”.

Multi-AZ

Running every tier across several isolated datacenters in one region.

Production systems on any cloud.

Databases get synchronous standbys; stateless tiers just spread instances.

N+1 capacity

Provisioning enough spare capacity to lose one unit (an instance, an AZ) and still carry the load.

Multi-AZ fleets, database clusters, worker pools.

With 2 AZs, each must handle 100% of peak — so run at ~50% or less.

Nines of availability

99.9% ≈ 43 minutes of downtime a month; 99.99% ≈ 4.4 minutes.

SLAs/SLOs; dependencies in series multiply their availabilities.

Each extra nine usually needs redundancy at every layer — and costs a lot more.

Observability

Metrics, logs and traces that let you ask new questions about a running system.

Anything with more than one service; alerting on SLOs.

Propagate a trace ID on every hop; alert on symptoms (errors, latency, saturation).

Presigned URLs

A short-lived URL your backend signs that lets a client PUT or GET one object directly in storage.

Photo/video uploads, private downloads.

Bytes skip your servers; validate the object after upload.

Rate limiting

Capping how many requests a client can make in a time window.

Public APIs, login endpoints, expensive operations.

Token bucket allows bursts; sliding window is smoother; share counters across instances.

Read-your-writes

A user always sees their own updates, even when other reads come from lagging replicas.

Profile edits, posting a comment, updating an address.

Route that user’s reads to the primary for a short window after a write, or track the replica position.

Replication lag

Asynchronous replicas apply the primary’s changes slightly later, so reads can be stale.

Read replicas, cross-region replicas, search indexes fed by CDC.

Say how stale reads are acceptable — and which reads must go to the primary.

Retries with backoff and jitter

Retry transient failures after increasing, randomised delays.

Network calls, queue consumers, client SDKs.

Unbounded retries amplify outages (retry storms) — cap them with a retry budget.

Saga

A multi-step business transaction across services where each step has a compensating action if a later step fails.

Checkout across orders, payments and inventory services.

Orchestrated (central coordinator, e.g. Step Functions) vs choreographed (events).

Service discovery

How a service finds the current addresses of another service’s instances.

Microservices on ECS/Kubernetes.

DNS-based registries, internal load balancers, or a service mesh.

Sharding

Splitting data across several databases by a key, so each holds and serves a fraction.

Write-heavy tables that outgrow one primary.

The shard key decides everything: even spread, and most queries on one shard.

Single point of failure

A component whose failure alone takes a user-facing flow down.

One app server, one database primary, one self-hosted load balancer, one NAT in one AZ.

Walk the request path and ask of each box: what happens if this dies right now?

Stateless services

Any instance can handle any request because no request depends on data kept in one instance’s memory or disk.

Sessions in Redis or signed tokens, files in object storage, caches that are shared or disposable.

It’s the precondition for load balancing, autoscaling and painless deploys.

Sticky sessions

The load balancer pins a user to one instance so in-memory sessions keep working.

A stopgap for stateful apps behind a load balancer.

Mention it as the shortcut — then say why you’d rather move the state out (uneven load, lost sessions).

Strangler fig

Migrate a monolith by routing one capability at a time to new services until the old code is gone.

Monolith → microservices migrations.

Use the load balancer/gateway to route paths to the new service.

Tail latency (p99)

The latency 99% of requests beat; the slowest 1% often dominate user experience at scale.

Fan-out calls (the slowest of N calls), SLOs.

Averages hide tails — talk in percentiles.

Timeouts

A bound on how long a caller waits for a dependency.

Every network call — especially third-party APIs.

No timeout = threads pile up during slowdowns = cascading failure.

Transactional outbox

Write the event to an outbox table in the same DB transaction as the data change; a relay publishes it.

Any service that updates its DB and must also publish an event.

It removes the “wrote the DB but failed to publish” dual-write bug.

TTL and invalidation

Cached data lives until its TTL expires or it’s explicitly deleted; until then it can be stale.

Prices, stock, profiles — anything that changes after being cached.

Pick TTLs from how stale the data may be, and delete keys on writes.

Vertical vs horizontal scaling

Vertical: a bigger machine. Horizontal: more machines sharing the load.

Vertical is simple but has a ceiling and keeps the SPOF; horizontal needs stateless servers and a load balancer.

Scale up first when it’s cheap; scale out for availability and past the biggest box.