System DesignVol. 12 · Part XII
0 / 0

Shelves / System Design

SD·123

Fundamental Building Blocks

The components every architecture is assembled from, each explained by what problem it solves, how it works inside, its key design choices and failure modes, and concrete technologies: DNS, load balancers (L4/L7, algorithms, health checks), API gateways and BFFs, stateless application services, caches, databases (relational, key-value, document, wide-column, graph, time-series, analytical, vector), object storage, message queues, event streams, search engines, CDNs, schedulers and workers, plus service discovery, configuration and coordination services, and a reference architecture tying them together.

30 topics · ~20 min read · 31-question quiz
Updated Suggest a correction

Start here: the boxes on every diagram

Almost every architecture diagram is assembled from the same dozen components: DNS, load balancers, API gateways, application servers, caches, databases, object storage, queues and streams, CDNs, search indexes and coordination services. Each exists to solve one problem, and each brings its own ways of failing. This chapter goes through them; the experiments here look closely at the first one a request usually meets after DNS, the load balancer.

A load balancer spreads work, and how it spreads matters

Three copies of the kitchen service sit behind HAProxy. Two answer in 10 ms; the third is on a slow machine and takes 100 ms. At 400 requests per second:

Text
algorithm    requests to k1 / k2 / k3      avg      p50      p90       p95
roundrobin   2,001 / 2,000 / 2,000      41.4 ms  11.5 ms  101.5 ms  101.7 ms
leastconn    2,760 / 2,769 /   439      18.8 ms  11.2 ms   12.6 ms  101.1 ms

Round robin gives every server the same share, so a third of all requests waited on the slow one. Least connections sends each request to the server with the fewest requests in progress; the slow server holds its requests longer, so it naturally received fewer (7% instead of 33%). Average latency more than halved, and p90 fell from 101 ms to 13 ms. The p95 stayed at about 100 ms because 7% of requests still went to the slow server; a weighted or latency-aware balancer, or simply removing the slow machine, would fix that too.

A load balancer also hides failures, if you let it

During a steady 200 requests per second, one of the fast servers was killed with kill -9:

Interactive diagram: A load balancer spreads requests, and stops sending to a dead server. It needs JavaScript; the text around it says the same.
Text
health checks every 500 ms, mark down after 2 failures, no retries:
  2,401 requests, 81 failed, all within 0.57 s of the kill
add "retries 2" and "option redispatch":
  2,401 requests, 0 failed

Health checks removed the dead server within about half a second, but every request sent to it before then failed. Letting the load balancer retry a failed connection on a different server turned those 81 errors into 81 slightly slower successes. (Retrying is safe here because the connection was refused before any request was sent; retrying requests that might have been processed needs idempotency, chapter 130.)

Every block, in one line

Block Problem it solves Typical way it fails
DNS find a service by name stale records cached for their TTL
Load balancer spread load, hide instance failures uneven spreading, slow detection
API gateway one front door: auth, limits, routing becomes a bottleneck or a single point of failure
Cache serve hot data fast stale data, stampedes on expiry
Database durable, queryable state write ceiling, replication lag
Object storage cheap durable blobs high per-request latency
Queue / stream decouple and absorb bursts backlog growth, duplicates
CDN serve static content near users serving outdated content
Coordination (etcd, ZooKeeper) leader election, config, locks unavailable without a quorum

How deep to go in the building blocks

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Name each building block and the problem it solves
L2 Place the right blocks in a design and configure the basics (health checks, TTLs, timeouts)
L3 Explain how each works inside: LB algorithms, L4 vs L7, cache eviction, replication, partitions
L4 Diagnose a block misbehaving: uneven load, slow failover, stale DNS, hot partitions
L5 Choose and combine blocks for a system, with their failure modes and costs
L6 Operate shared platform blocks for many teams at scale

Thinking in building blocks

Most systems, however large, are composed from a small vocabulary of components. Knowing each block's purpose, guarantees, limits, and failure modes lets you assemble designs quickly and reason about them precisely. The reference picture:

client DNS CDN / edge LB gateway appstateless× N cache database object storage queue stream workers indexer search scheduler observability · config · secrets · service discovery
A reference architecture built from standard blocks. Clients resolve DNS and fetch static content from a CDN; dynamic requests pass through a load balancer and API gateway to stateless application services. Services read through a cache to databases, store files in object storage, publish work to queues and events to streams, and query a search index kept in sync from the stream. Schedulers trigger workers for background and periodic jobs.

DNS

The Domain Name System maps names to addresses and is the first hop of nearly every request.

  • Records: A/AAAA (IPv4/IPv6 addresses), CNAME (alias), ALIAS/ANAME (provider-specific apex aliases), MX (mail), TXT (verification, SPF/DKIM/DMARC), SRV (service locations), CAA (allowed certificate authorities), HTTPS/SVCB (advertise HTTP/3, ECH keys, alternative endpoints).
  • TTL controls caching by resolvers: long TTLs reduce load and latency but slow failover; short TTLs (30–60 s) allow traffic shifting but some resolvers and clients ignore or extend them.
  • Traffic management: managed DNS (Route 53, Cloud DNS, Azure DNS, Cloudflare, NS1) supports weighted, latency-based, geolocation and failover routing with health checks (chapter 134). Anycast announces the same IP from many locations so the network routes users to the nearest point of presence (used by CDNs and DNS providers themselves).
  • Failure modes: DNS outages make healthy services unreachable (several large internet incidents were DNS or BGP problems); misconfigured records; cached stale answers. Mitigate with reputable providers, possibly two providers, reasonable TTLs, and monitoring.

Load balancers

Purpose

A load balancer (LB) distributes incoming connections or requests across a pool of backends, enabling horizontal scaling and high availability (unhealthy backends are removed). It's also a natural place for TLS termination, connection management and basic protection.

Layer 4 vs layer 7

L4 (transport) L7 (application)
Operates on TCP/UDP connections (IP, port) HTTP/gRPC requests (method, path, headers, cookies)
Decisions Per connection Per request (multiplexed HTTP/2 streams distributed individually)
Features Very high throughput, low latency, protocol-agnostic, can preserve client IP Path/host routing, header-based routing, retries, timeouts, compression, auth, WAF, request logging, canary splits
Examples AWS NLB, Google passthrough Network LB, Azure Load Balancer, IPVS, Maglev, Katran (eBPF) AWS ALB, Google Application LB, Azure Application Gateway / Front Door, Envoy, NGINX, HAProxy, Traefik

Important subtlety: with long-lived HTTP/2 or gRPC connections, an L4 balancer distributes connections, not requests, so load can become very uneven; gRPC typically needs L7 balancing or client-side balancing (Vol. 6 ch. 82).

Algorithms

Algorithm How Good for
Round robin (weighted) Rotate through backends Homogeneous backends and requests
Least connections / least outstanding requests Pick the backend with fewest in-flight Variable request durations
Power of two random choices Pick two at random, choose the less loaded Near-optimal with little coordination (Envoy's default for least-request)
Consistent hashing / ring hash / Maglev Hash a key (client IP, user ID, cache key) to a backend; minimal remapping when backends change Session affinity, cache locality (chapter 124)
Latency/EWMA-based Prefer backends responding fastest Heterogeneous or degraded backends

Health checks and connection handling

  • Active health checks (probe /healthz periodically) and passive ones (outlier detection: eject backends returning errors). Distinguish liveness (process alive) from readiness (able to serve, dependencies reachable, warmed up).
  • Connection draining (deregistration delay): stop sending new requests to a backend being removed, let in-flight ones finish (graceful shutdown).
  • Slow start: ramp traffic to new instances gradually (JIT warm-up, cold caches).
  • Session affinity ("sticky sessions") pins a client to a backend; it hurts load distribution and failover, so prefer stateless services with external session storage.
  • Global vs regional: global load balancers (Google's global external LB, Cloudflare, AWS Global Accelerator/CloudFront, Azure Front Door) route users to the nearest healthy region.

The load balancer itself must not be a single point of failure: managed cloud LBs are redundant across zones; self-managed ones use pairs with VRRP/keepalived or anycast/ECMP.

API gateways and BFFs

An API gateway is an L7 entry point specialised for APIs: authentication and token validation, rate limiting and quotas, request/response transformation, routing to services by path/version, API keys and developer portals, request validation against schemas, caching, observability (Vol. 10 ch. 110).

  • Products: Kong, Apigee, AWS API Gateway, Azure API Management, Tyk, Gravitee, KrakenD, Envoy Gateway and other Kubernetes Gateway API implementations.
  • A Backend for Frontend (BFF) is a gateway-like service tailored to one client type (web, iOS, Android, partner API): it aggregates calls to several services, shapes responses for that client, and can hold OAuth tokens server-side for browsers. GraphQL servers often play this role (chapter 132).

Pitfalls: putting business logic in the gateway (it becomes a distributed monolith's bottleneck owned by no one); a single gateway deployment shared by everything becoming a blast-radius risk; excessive latency from many plugins.

Application services

Stateless application services contain business logic, handle requests, and keep no durable state locally; any instance can serve any request, so they scale horizontally behind a load balancer and can be replaced at will (chapter 124).

Design considerations:

  • State goes elsewhere: sessions in a store or signed tokens, files in object storage, data in databases, in-memory caches only as optimisation.
  • Concurrency model: thread-per-request (Java with virtual threads, which make blocking code cheap again), async event loops (Node.js, Rust Tokio, Python asyncio), goroutines (Go), actors (Erlang/Elixir BEAM, Akka/Pekko).
  • Timeouts and deadlines on every outbound call; bounded pools and queues (chapter 130).
  • Graceful startup and shutdown: readiness only after warm-up; on SIGTERM stop accepting, drain in-flight requests, close connections.
  • Packaging and runtime: containers on Kubernetes or managed container services, or serverless functions (Lambda, Cloud Run functions, Azure Functions) for spiky or event-driven workloads (Vol. 7 ch. 86).
  • Granularity: a well-structured modular monolith is often the right starting point; split into services along domain boundaries when teams, scaling needs or failure isolation demand it.

Caches

A cache stores copies of data closer to where it's needed or in a faster medium, trading freshness and memory for latency and backend load. Caches appear at every layer: CPU caches, in-process memory (Caffeine, Ristretto, moka), distributed caches (Redis, Valkey, Memcached), reverse-proxy caches (Varnish, NGINX), CDNs, browser caches (HTTP Cache-Control), database buffer pools, DNS resolvers.

Key choices: what to cache, where, patterns (cache-aside, read/write-through, write-back), invalidation and TTLs, eviction policy (LRU, LFU, W-TinyLFU), stampede and hot-key protection. Chapter 126 covers caching architecture in depth.

Redis 8 is again available under an open-source licence (AGPLv3, alongside source-available options); Valkey, the Linux Foundation fork created in 2024, is the default "Redis-compatible" engine in several cloud services. Both offer strings, hashes, lists, sets, sorted sets, streams, pub/sub, Lua/functions, and replication/cluster modes.

Databases

Choose databases by data model, access patterns, consistency needs and scale, not by fashion:

Family Model Strengths Examples
Relational (OLTP) Tables, SQL, joins, ACID transactions, constraints General purpose, strong consistency, rich queries, mature tooling PostgreSQL, MySQL/MariaDB, SQL Server, Oracle; managed Aurora, Cloud SQL, AlloyDB, Azure Database
Distributed SQL (NewSQL) SQL with automatic sharding and consensus replication Horizontal scale with ACID, multi-region CockroachDB, Google Spanner, YugabyteDB, TiDB, Aurora DSQL
Key-value Key → value Extreme throughput, simple access by key DynamoDB, Redis/Valkey, etcd (for config), FoundationDB, RocksDB (embedded)
Document JSON-like documents Flexible schema, aggregate-oriented access MongoDB, Couchbase, Firestore, DocumentDB; PostgreSQL jsonb
Wide-column Partitioned rows with clustering columns Massive write throughput, predictable queries by partition key Cassandra, ScyllaDB, Bigtable, HBase
Graph Nodes and edges Traversals, relationships Neo4j, Amazon Neptune, JanusGraph, Memgraph
Time-series Timestamped measurements Compression, downsampling, time-range queries TimescaleDB, InfluxDB, Prometheus/Mimir, VictoriaMetrics, QuestDB
Analytical (OLAP) Columnar storage Aggregations over billions of rows ClickHouse, Snowflake, BigQuery, Redshift, DuckDB, Apache Druid/Pinot
Vector Embeddings with approximate nearest-neighbour indexes Semantic search, RAG pgvector, Qdrant, Milvus, Weaviate, OpenSearch k-NN

Guidance: start with a relational database unless you have a specific reason not to; PostgreSQL (18 is current) covers relational, JSON, full-text, geospatial (PostGIS), time-series (Timescale), and vectors (pgvector) well enough for most systems. Specialise when a workload clearly outgrows it. Chapter 127 covers replicas, partitioning, sharding, indexes, materialized views, CDC and CQRS; storage internals and SQL are in Vol. 4.

Object storage

Object storage (Amazon S3, Google Cloud Storage, Azure Blob Storage, Cloudflare R2, MinIO, Ceph RGW) stores immutable blobs addressed by bucket + key, accessed over HTTP:

  • Virtually unlimited capacity, very high durability (S3: designed for eleven nines), cheap per GB, multiple storage classes (standard, infrequent access, archive) with lifecycle policies moving data between them.
  • Whole-object PUT/GET (plus range reads and multipart uploads); not a file system (no in-place edits, rename = copy + delete). S3 has provided strong read-after-write consistency since December 2020, and supports conditional writes (If-None-Match, If-Match), which enable simple coordination patterns.
  • Patterns: pre-signed URLs (clients upload/download directly without passing bytes through your servers), event notifications on object creation (trigger thumbnail generation), static website hosting behind a CDN, data lakes (Parquet/Iceberg tables queried by Spark, Trino, Athena, DuckDB), backups and logs.
  • Costs: storage per GB-month, requests (per 1,000 PUT/GET), retrieval fees for cold classes, and egress.
Python
# Direct-to-storage upload with a pre-signed URL (boto3): the API never handles the bytes
url = s3.generate_presigned_url(
    "put_object",
    Params={"Bucket": "uploads-prod", "Key": f"users/{user_id}/{uuid4()}.jpg", "ContentType": "image/jpeg"},
    ExpiresIn=300,
)
# client: PUT <url> with the file; an S3 event then triggers the image-processing worker

Message queues

A message queue decouples producers from consumers for work distribution: each message is processed by one consumer (competing consumers), then removed.

  • Buffers load spikes (queue-based load leveling, chapter 130), lets producers continue when consumers are slow or down, and lets you scale consumers independently.
  • Features: acknowledgements and redelivery, visibility timeouts, dead-letter queues, delayed messages, priorities, FIFO/ordering groups, exactly-once processing only with idempotent consumers.
  • Products: RabbitMQ (AMQP; quorum queues; streams), Amazon SQS (standard and FIFO), Azure Service Bus, Google Cloud Tasks/Pub/Sub, NATS JetStream, ActiveMQ Artemis, Redis-based queues (Sidekiq, BullMQ), and Kafka share groups (production-ready in Kafka 4.2) bringing queue semantics to Kafka topics.

Chapter 128 compares queues and streams in depth; Vol. 5 ch. 66–68 covers messaging semantics.

Event streams

An event stream (log) is an append-only, durable, replayable, partitioned sequence of records. Consumers track their own offsets, so many independent consumer groups can read the same events at their own pace, and new consumers can replay history.

  • Uses: event-driven architectures, CDC pipelines, analytics ingestion, stream processing, audit logs, feeding search indexes and caches.
  • Ordering is guaranteed within a partition; partition by an entity key (order ID) to keep each entity's events ordered.
  • Products: Apache Kafka (4.x, KRaft-only), Redpanda, Confluent Cloud, Amazon Kinesis/MSK, Azure Event Hubs, Google Pub/Sub (with ordering keys), Apache Pulsar, NATS JetStream, WarpStream/Bufstream-style object-storage-backed Kafka-compatible systems.
  • Stream processing: Kafka Streams, Apache Flink, Spark Structured Streaming, ksqlDB, RisingWave, Materialize.

Search engines

A search engine builds inverted indexes (term → list of documents) for full-text search with relevance ranking (BM25), plus filters, facets, aggregations, autocomplete, typo tolerance, geo search and, increasingly, hybrid search combining keyword and vector similarity.

  • Products: Elasticsearch, OpenSearch, Apache Solr, Meilisearch, Typesense, Vespa, Algolia (hosted), PostgreSQL full-text search for modest needs.
  • Search indexes are derived data: the source of truth is the database; changes flow to the index via CDC or events (eventually consistent, typically within seconds). Design for reindexing from the source (new analyzers, mappings) using aliases to swap indexes without downtime.
  • Scale: shards (parallelism, size per shard roughly tens of GB), replicas (read throughput, availability); heavy aggregations and deep pagination are costly.

CDNs

A content delivery network caches and serves content from edge locations near users:

  • Reduces latency (fewer, shorter round trips), offloads origins (high hit ratio), absorbs traffic spikes and DDoS attacks, terminates TLS close to users, supports HTTP/3.
  • Caches static assets (immutable hashed filenames with long max-age), media, downloads, and also dynamic responses with short TTLs or stale-while-revalidate; edge compute (Cloudflare Workers, CloudFront Functions/Lambda@Edge, Fastly Compute, Akamai EdgeWorkers) runs logic at the edge (redirects, A/B routing, auth checks, personalisation).
  • Cache keys, Vary headers, cache invalidation/purging (by URL, tag/surrogate key), origin shield (a mid-tier cache that collapses requests to the origin), signed URLs/cookies for private content.
  • Products: Cloudflare, Akamai, Fastly, Amazon CloudFront, Google Cloud CDN/Media CDN, Azure Front Door.

Schedulers and workers

Workers run background jobs outside the request path: sending emails, generating reports, resizing images, calling slow third parties, data pipelines. Schedulers trigger jobs at times or intervals.

Need Options
Async jobs from requests Queue + worker pool (SQS + Lambda/containers, Sidekiq, Celery, BullMQ, River for Go+Postgres, Oban for Elixir)
Periodic jobs Kubernetes CronJob, cloud schedulers (EventBridge Scheduler, Cloud Scheduler), Quartz/ShedLock in JVM apps, pg_cron
Multi-step, long-running workflows with retries, timers and state Durable execution engines: Temporal, AWS Step Functions, Azure Durable Functions, Restate, Inngest, DBOS
Data pipelines and batch DAGs Airflow, Dagster, Prefect, Argo Workflows

Design rules for jobs:

  • Idempotent handlers (jobs are retried; scheduled triggers can fire twice).
  • At-most-one concurrent execution where needed (leases/locks with expiry and fencing tokens, Vol. 5 ch. 77), and handling of missed schedules (catch up or skip?).
  • Timeouts, retries with backoff, dead-letter handling, and visibility (job dashboards, metrics on queue age).
  • Don't run periodic jobs on every replica of a service by accident ("the cron in the app ran on 12 pods").
Python
# Celery task: idempotent by design, with bounded retries and backoff
@app.task(bind=True, autoretry_for=(TransientError,), retry_backoff=True, retry_jitter=True, max_retries=6)
def send_invoice_email(self, invoice_id: str):
    if outbox.already_sent("invoice_email", invoice_id):     # dedupe on business key
        return
    invoice = invoices.get(invoice_id)
    mailer.send(to=invoice.customer_email, template="invoice", data=invoice.as_dict(),
                idempotency_key=f"invoice-email:{invoice_id}")
    outbox.mark_sent("invoice_email", invoice_id)

Supporting infrastructure

  • Service discovery: how services find each other: DNS (Kubernetes Services), registries (Consul, Eureka), service meshes (Istio, Linkerd), cloud service connect features.
  • Configuration and feature flags: centralised config (Kubernetes ConfigMaps, AWS AppConfig, Consul KV), feature flag services (LaunchDarkly, Unleash, Flagsmith, OpenFeature as the standard API) for decoupling deploy from release.
  • Secrets management: Vault/OpenBao, cloud secret managers (Vol. 10 ch. 111).
  • Coordination: leader election, distributed locks, membership, configuration with strong consistency: etcd, ZooKeeper, Consul, or database-based leases (Vol. 5 ch. 77).
  • Identity: an identity provider for users (OIDC) and workload identity for services (Vol. 10 ch. 109).
  • Observability: metrics, logs, traces, profiles (Vol. 9).

Choosing blocks: a checklist

For each requirement, ask which block addresses it:

Requirement Block(s)
Spread load, survive instance failure Load balancer + stateless services + health checks
Authenticate and throttle API clients API gateway
Cut read latency and DB load Cache (in-process + distributed), CDN for public content
Durable transactional records Relational/distributed SQL database
Large files, media, backups, data lake Object storage (+ CDN)
Absorb spikes, do work later, retry safely Queue + workers
Many consumers of the same facts, replay Event stream
Full-text, fuzzy, faceted search Search engine fed by CDC/events
Periodic and long-running processes Scheduler + workers / durable workflow engine
Global low latency CDN, geo-routing DNS, regional deployments (chapter 134)

Every added block brings operational cost (provisioning, upgrades, monitoring, on-call, failure modes, data consistency between them). The best designs use as few blocks as the requirements allow, often managed services, and add more only when a requirement demands it.

Lab: load-balancing algorithms and failover, measured

HAProxy 2.8.30 in HTTP mode on the lab machine, in front of three copies of the Go kitchen service from Volume 11's chapter 119 (64 concurrent slots each, so they don't saturate): k1 and k2 take 10 ms per request, k3 takes 100 ms. k6 1.3 sent load at fixed arrival rates. Per-server request counts came from HAProxy's stats socket (show stat, column stot).

Experiment 1: round robin versus least connections

Text
backend kitchens
  balance roundrobin            # or: balance leastconn
  option httpchk GET /order
  default-server inter 500ms fall 2 rise 2
  server k1 127.0.0.1:8331 check
  server k2 127.0.0.1:8332 check
  server k3 127.0.0.1:8333 check
Rate Algorithm k1 / k2 / k3 avg p50 p90 p95
150/s roundrobin (not recorded) — 11.1 ms — 101.7 ms
150/s leastconn (not recorded) — 10.9 ms — 101.0 ms
400/s roundrobin 2,001 / 2,000 / 2,000 41.4 ms 11.5 ms 101.5 ms 101.7 ms
400/s leastconn 2,760 / 2,769 / 439 18.8 ms 11.2 ms 12.6 ms 101.1 ms

Least connections needs concurrency to work with: at 150/s only a handful of requests were ever in flight, so most choices were ties. At 400/s about 7 to 8 were in flight on average (Little's law: 400/s × 18.8 ms ≈ 7.5), enough for the slow server's longer-held requests to show. Other algorithms and when they fit:

Algorithm Picks Good for
round robin / weighted next server in turn (by weight) identical servers, short uniform requests
least connections fewest in-flight varied request times, uneven servers
power of two choices the less loaded of two random servers many balancers with stale views (Envoy's default LEAST_REQUEST)
consistent hashing by a key (user, session, cache key) cache affinity, sticky state
latency / EWMA based lowest recent latency heterogeneous fleets (e.g. Linkerd, Finagle)

Experiment 2: failover timing

At 200 requests per second, k2 was killed with SIGKILL 4 seconds into a 12-second run:

Text
inter 500ms fall 2, retries 0:                       2,401 requests, 81 failed, all in t=+0.00…+0.57 s
inter 500ms fall 2, retries 2 + option redispatch:   2,401 requests, 0 failed

The detection window is roughly fall × inter (2 × 500 ms) or less, depending on when the next check lands. If k2 had kept its one-third share for those 0.57 s, about 38 requests would have failed; 81 did, because this run used leastconn, and a dead server that refuses connections instantly always has zero requests in flight, so least-connections preferred it. A server failing fast looks like the least loaded server, which is why passive health checks and outlier detection matter alongside active checks. retries re-attempts a failed connection; option redispatch lets that retry go to a different server. This lab's failure was the friendly kind: a killed process refuses connections instantly. A server that hangs (blackholed network, stuck process) only shows up when timeout connect or timeout server fires, so those timeouts must be set from your latency requirements, not left at defaults of tens of seconds. Passive health checking (observe layer7 with error-limit) also takes a server out after real requests fail, without waiting for the next active check.

Experiment 3: what a load balancer can't hide

Things the experiments above would not have survived:

  • All servers slow (a shared database is slow): balancing just spreads the pain; you need timeouts, shedding and caching.
  • The balancer itself fails: run two with a floating IP (keepalived/VRRP) or rely on DNS/anycast to several, and test it.
  • Long-lived connections (WebSockets, gRPC streams): balancing happens per connection, so new servers get no load until clients reconnect; use connection age limits or L7 balancing per request.
  • Sticky sessions: pinning users to servers defeats spreading and makes server loss visible to those users; move session state to a shared store.

Try it yourself

  1. Add weight 1 to k3 and weight 10 to k1 and k2 with round robin. Predict p90 and p95, then measure.
  2. Replace the kill with kill -STOP (the process hangs). How long until requests fail, with timeout server 10s and with 1s?
  3. Use balance uri with hash-type consistent, then remove one server and count how many URIs moved.
  4. Put two HAProxy instances behind a third and kill one of the two. What does the client see?

Revision sheet: fundamental building blocks

Key ideas

  • DNS: names → addresses; TTLs trade agility for load; resolvers cache, so changes are never instant.
  • Load balancers: L4 (connections) vs L7 (requests, headers, paths); algorithms (round robin, weighted, least connections, power of two choices, consistent hash, EWMA); active and passive health checks; retries and redispatch; connection draining.
  • API gateways: authentication, rate limiting, routing, request shaping; keep them thin and redundant.
  • Application servers: stateless where possible; state in shared stores.
  • Caches: in-process vs distributed; eviction (LRU, LFU); TTLs; invalidation.
  • Databases: relational vs key-value, document, wide-column, graph, time-series; replication and partitioning.
  • Object storage: cheap, durable, high-latency blobs with HTTP APIs; pair with a CDN.
  • Queues and streams: decouple producers and consumers, absorb bursts, enable replay (streams).
  • CDN: edge caching of static and cacheable dynamic content.
  • Search: inverted indexes, eventually consistent with the source of truth.
  • Coordination: consensus stores (etcd, ZooKeeper) for leader election, config and locks; need a quorum.

Numbers to remember

  • Lab: a 10× slower server got 33% of traffic with round robin and 7% with least connections; average latency 41 → 19 ms.
  • Lab: health checks at 500 ms × fall 2 → 81 failures in 0.57 s at 200/s; retries + redispatch → 0.
  • A 3-node quorum tolerates 1 failure; 5 nodes tolerate 2.

Pitfalls

  • Round robin across uneven servers or uneven requests.
  • Default timeouts of tens of seconds hiding hung backends.
  • Retrying non-idempotent requests at the balancer.
  • A single load balancer or gateway as a hidden single point of failure.
  • Long-lived connections never rebalancing.
  • Low DNS TTLs everywhere (load) or very high ones (slow failover).

Glossary

  • L4 / L7 load balancing: by connection / by HTTP request.
  • Health check (active / passive): probing servers / observing real traffic.
  • Redispatch: retrying on a different server.
  • Connection draining: letting in-flight requests finish before removing a server.
  • Quorum: a majority of members required for decisions.