Guide / System design Fundamentals
1.4 Load balancing
What a load balancer actually does, when to introduce one, L4 vs L7, every common algorithm and configuration knob, health checks, sticky sessions, HA, global balancing and what real production setups look like.
“Put a load balancer in front” is the most-drawn box in system design and the least-explained. This page explains what it does, when you need it, how to configure it and how it fails.
Fundamentals#
1.4.1 What a load balancer does (and why you introduce one)#
A load balancer (LB) is a reverse proxy with a list of backends. Clients talk to one stable address; the LB picks a healthy backend for each connection or request. Its jobs, in order of importance:
- Horizontal scaling: one server tops out; N servers behind an LB give roughly N× capacity. This only works if the servers are stateless (see Scaling patterns).
- High availability: health checks remove dead servers from rotation, so one crash is invisible to users.
- Zero-downtime deploys: drain a server (finish in-flight requests, take no new ones), update it, return it. Rolling, blue/green and canary releases are all LB traffic shifts.
- A single, stable entry point: clients never learn backend IPs; backends can be added, removed or moved freely (autoscaling).
- TLS termination and offload: certificates and handshake CPU live in one place.
- Edge protection and policy: rate limiting, WAF, connection limits, IP allow/deny, request size limits, DDoS absorption.
- Routing (L7 only): one hostname fronting many services by path/header (
/api→ API pool,/static→ CDN origin), canary routing, A/B routing. - Observability: a central place for request counts, latency and error rates per backend.
Introduce one when you have more than one instance of anything, or any component’s failure must not be user-visible. You do not need one for a single-instance internal tool, a batch job, or when a managed platform already hides it (Kubernetes Service, serverless, a CDN). In an interview, mention the LB the moment you draw a second server and state its type (L4 or L7) and algorithm.
1.4.2 Where load balancers sit#
Users
│ DNS (GeoDNS / latency routing / anycast)
▼
CDN / edge ── static & cacheable content, DDoS, WAF
▼
Global or regional L7 LB ── TLS termination, routing by host/path (ALB, Cloud LB, NGINX, Envoy)
▼
API gateway / ingress ── authentication, rate limit, request shaping
▼
Service A pods ◄──► internal LB / service mesh / client-side LB ◄──► Service B pods
▼
DB / cache pools ── L4 proxy (HAProxy, PgBouncer, ProxySQL) or driver-level balancing
Every tier can have its own balancing. The three flavours of where the logic runs:
| Flavour | How it works | Examples | Good for |
|---|---|---|---|
| Server-side (proxy) | Dedicated LB in the path | NGINX, HAProxy, AWS ALB/NLB, Envoy | Public entry, simple clients |
| Client-side | Client has the backend list (from DNS or service discovery) and picks | gRPC round_robin, Netflix Ribbon, Kafka and Cassandra drivers | Internal traffic with no extra hop, long-lived connections (gRPC) |
| Sidecar / service mesh | A proxy next to every service instance does the balancing, retries and mTLS | Istio and Linkerd (Envoy sidecars) | Large microservice estates needing uniform policy |
1.4.3 Layer 4 vs layer 7#
| Aspect | L4 (transport) | L7 (application) |
|---|---|---|
| Sees | IP, port, TCP/UDP | Full HTTP: host, path, headers, cookies, body |
| Decision unit | Connection (all packets of a TCP flow go to one backend) | Request (each request can go elsewhere) |
| TLS | Passthrough (end-to-end) or terminate | Terminate (typically) |
| Features | Speed, millions of connections, static IPs, any protocol (DB, MQTT, game servers) | Path/host routing, header rewriting, retries, auth, caching, compression, WebSocket upgrade, gRPC awareness, WAF |
| Cost | Very cheap CPU, minimal latency | More CPU and memory, ~ms latency |
| Examples | AWS NLB, HAProxy (tcp mode), IPVS/LVS, Maglev, Google Network LB | AWS ALB, NGINX, HAProxy (http mode), Envoy, Traefik |
| Pitfall | Cannot balance multiplexed protocols per request: HTTP/2 and gRPC pin a client to one backend | Terminating TLS means it sees plaintext; slower; the LB becomes a big shared component |
Production default: L7 for HTTP/HTTPS/gRPC traffic (most business systems), L4 for non-HTTP protocols (databases, MQTT, TCP game servers), for static IPs, extreme throughput or when end-to-end TLS is required. Many stacks use both: L4 in front (for IPs and scale) → L7 behind (for routing), which is what big cloud providers do internally.
L3 / “GWLB”: a layer-3 balancer (AWS Gateway Load Balancer) steers packets through security appliances (firewalls, IDS) transparently. Rarely asked.
Direct Server Return (DSR): the LB forwards the request, but the backend answers the client directly, bypassing the LB on the response path. Good for asymmetric traffic (small requests, huge responses: video); needs L4 and network configuration.
1.4.4 Balancing algorithms: what each does and when to use it#
| Algorithm | How it picks | Use when | Avoid when |
|---|---|---|---|
| Round robin | Next server in a cycle | Homogeneous servers and similar request cost: the default | Requests vary a lot in cost, or servers differ in power |
| Weighted round robin | Cycle, but bigger weight gets more turns | Mixed instance sizes; canary (weight 5% to the new version) | Cost per request still varies a lot |
| Least connections | Fewest active connections | Long or uneven requests (uploads, websockets, slow queries) | Very short requests (the counter is noisy), no shared state across LB nodes |
| Weighted least connections | Least connections scaled by weight | Mixed hardware and uneven requests | n/a |
| Least response time / peak EWMA | Lowest recent latency (and few connections) | Backends of varying speed; heterogeneous or noisy neighbours | Latency measurement is noisy, risk of herding to the “fast” one |
| Power of two choices (P2C) | Pick 2 random backends, send to the less loaded | Many LB nodes without shared state; Envoy’s least_request uses this idea; near-optimal and cheap | n/a |
| Random | Uniform random | Simple, no state; fine at large N | Small N |
| IP hash / source hash | hash(client_ip) % N | Cheap stickiness without cookies | Many users behind one NAT (all hit one server); changing N reshuffles everyone |
| Consistent hashing (ring hash, Maglev) | Key (user, URL, header) mapped on a ring | Cache affinity (CDN, caches), sharded stateful backends, sticky routing with minimal reshuffle when nodes change | Hot keys overload one node (use bounded-load variant) |
| URL / header hash | Hash of a request attribute | Send the same URL to the same cache node; per-tenant routing | Skewed keys |
| Resource-based / adaptive | Backends report CPU or queue depth | Heterogeneous, long-running work | Complexity; reporting lag causes oscillation |
| Geographic / latency-based | Nearest or fastest region | Global load balancing (GSLB) | n/a |
How to answer “which algorithm?”: default to round robin for stateless, similar requests; least connections (or least-request/P2C) when request durations vary; consistent hashing when you need affinity (caches, sharded state); weighted for canaries and mixed hardware.
Notes that show depth:
- Round robin is fair in count, not in load. 10 expensive requests can land on one server while another idles.
- With several LB nodes each keeping local counters, “least connections” can still herd. P2C avoids the herd without coordination.
- Consistent hashing with bounded loads caps any node at, say, 1.25× the average load to survive hot keys.
- Slow start: ramp a new or recovering instance’s weight gradually. Otherwise least-connections floods a freshly started (cold, JIT-uncompiled, cache-empty) instance and it falls over.
1.4.5 Health checks and failure handling#
| Kind | What it does | Notes |
|---|---|---|
| Active | LB probes GET /healthz every 5–10 s | Unhealthy after N consecutive failures (2–3), healthy after M successes. Too aggressive makes flapping, too lax makes slow detection |
| Passive (outlier detection) | LB watches real traffic; ejects a backend with consecutive 5xx or timeouts | Detects problems active checks miss (a “healthy” node returning errors). Envoy outlier_detection, NGINX max_fails |
| Liveness (Kubernetes) | “Is the process alive?” Failing restarts the container | Keep it shallow: never check the database here, or one DB blip restarts the whole fleet |
| Readiness | “Can it take traffic now?” (warmed up, DB connected) | Failing removes it from the LB, no restart |
| Startup | Gives slow-booting apps time before liveness starts | Avoids restart loops |
Design rules:
- Shallow vs deep checks: a shallow check (
200 OKif the process is up) catches crashes; a deep check (queries DB and cache) catches broken dependencies but can take the entire fleet out of rotation at once when a shared dependency fails (a cascading outage). Prefer shallow for liveness, a local-resource deep check for readiness, and graceful degradation over “mark everything unhealthy”. - Connection draining (deregistration delay): on removal, stop new requests but let in-flight ones finish (30–300 s). Combine with graceful shutdown in the app (SIGTERM: fail readiness, finish requests, exit).
- Panic threshold (“fail-open”): if more than e.g. 50% of backends are unhealthy, route to all of them anyway: a bad health check should not cause a total blackout.
- Retries: retry only idempotent requests, on a different backend, with a budget (≤ 10–20% extra load) and timeouts shorter than the client’s. Retrying POSTs without idempotency keys duplicates writes.
- Circuit breaking / max pending requests: cap concurrent requests per backend and shed excess immediately with 503 rather than queueing without bound.
1.4.6 Session persistence (sticky sessions)#
Sticky sessions pin a client to one backend using an LB cookie (AWSALB), source IP hash, or a header/consistent hash on user ID.
When it is justified: legacy apps that keep session in memory, WebSocket/long-lived connections (naturally sticky for their duration), in-memory caches that give good hit rates per user, upload sessions.
Costs: uneven load (a heavy user pins a node), harder deploys (draining kills sessions), failover loses state. Better design: keep services stateless; store sessions in Redis or in a signed token (JWT/cookie); use consistent hashing only for performance affinity, never for correctness.
1.4.7 Configuration reference: the knobs that matter#
| Setting | What it controls | Typical guidance |
|---|---|---|
| Algorithm | Backend choice | See table above |
| Idle timeout | How long an idle connection stays open (ALB default 60 s) | Backends’ keep-alive must be longer than the LB’s, otherwise random 502s |
| Connect / request / response timeouts | Max wait to connect, send, receive | Set tight, per route; a missing timeout is how one slow dependency eats all your threads |
| Max connections / pending requests | Concurrency cap per backend | Protects backends; returns 503 quickly instead of queueing |
| Retries and retry budget | Which errors, how many | Idempotent only; 1–2 retries; different host; backoff |
| Health check path, interval, thresholds | Failure detection speed | 5–10 s interval, 2–3 failures to eject, 2–5 successes to return |
| Draining / deregistration delay | In-flight completion on removal | Longer than your slowest request |
| Slow start | Gradual weight ramp | 30–120 s for JVM or cache-heavy services |
| Session stickiness | Cookie or hash affinity | Off by default |
| TLS | Protocols, ciphers, certificates, mTLS, SNI | TLS 1.2+ (prefer 1.3), automated renewal, HSTS |
| HTTP/2, HTTP/3, gRPC | Protocol support client side and backend side | HTTP/2 or 3 to clients, HTTP/1.1 or 2 to backends; gRPC needs HTTP/2 end to end |
| Forwarded headers | X-Forwarded-For, X-Forwarded-Proto, Forwarded, PROXY protocol (L4) | Backends must trust these only from the LB, and the rate limiter must read the real client IP |
| Request size and header limits | Max body, slow-loris protection (header and body read timeouts) | Defends against resource-exhaustion attacks |
| WebSocket support | Upgrade/Connection headers, long idle timeout | Raise idle timeout or send heartbeats |
| Cross-zone balancing | Spread across AZs evenly | On for even load; off to save cross-AZ data cost when zones are evenly populated |
| Rate limiting / WAF / IP rules | Edge protection | Coarse limits at the LB, fine-grained in the app (Rate limiting) |
| Access logs and metrics | Observability | Log request ID, backend, latency, status; propagate a trace ID |
1.4.8 Making the LB itself highly available#
An LB is a single point of failure unless you remove it:
- Managed cloud LBs (ALB, NLB, GCP Cloud LB, Azure) are already distributed across zones; you do not manage failover. This is the default answer.
- Active-passive pair with a floating/virtual IP (VRRP via keepalived): the standby takes the IP on failure. Simple, wastes the standby.
- Active-active with ECMP / anycast: routers spread flows across several LB nodes using equal-cost paths (the same IP announced by many nodes, BGP). Used by large operators (Google Maglev, Facebook Katran).
- DNS with multiple LB IPs across regions (coarse, subject to TTL).
- Capacity planning: LB nodes autoscale on connections, new connections per second, and bandwidth (not only CPU). Cloud LBs “pre-warm” slowly, so for a known flash sale ask the provider to pre-provision, or ramp traffic.
1.4.9 Global load balancing (GSLB)#
Spreads users across regions: GeoDNS or latency-based DNS, anycast IPs (a CDN’s edge), or a global L7 LB (Google Global LB, AWS Global Accelerator, Cloudflare). It adds health-checked regional failover: if a region fails, traffic drains to the next one, provided that region has capacity (N+1 capacity planning) and the data tier can serve it (see Replication and sharding for multi-region data).
1.4.10 What is used in real production#
| Layer | Most common choice | Why |
|---|---|---|
| Public web/API on a cloud | CDN + managed L7 LB (AWS ALB / GCP HTTPS LB), round robin or least outstanding requests, TLS terminated at the edge, health-checked target groups across 2–3 AZs | No operations, autoscaling, integrates with autoscaling groups and WAF |
| Kubernetes | Cloud LB → Ingress controller (NGINX, Envoy/Contour, Traefik, ALB controller) → Service (kube-proxy iptables/IPVS round robin) → pods | Standard stack |
| Service-to-service | Service mesh sidecar (Envoy, with least-request/P2C) or client-side balancing (gRPC) | Per-request balancing for HTTP/2 and gRPC, retries, mTLS, outlier detection |
| Non-HTTP, extreme scale, static IPs | L4: AWS NLB, HAProxy tcp-mode, IPVS | Throughput and protocol freedom |
| Caches, sharded systems | Consistent hashing in the client library or proxy (Redis Cluster slots, twemproxy, Envoy ring hash) | Key affinity |
| Databases | Connection pooler / proxy (PgBouncer, ProxySQL, RDS Proxy), read/write splitting, driver-side host lists | Protects the DB from connection storms |
| Edge security | CDN with WAF and DDoS scrubbing in front | Absorbs attack traffic away from origin |
Typical answer: “CDN → L7 managed load balancer terminating TLS with health checks across AZs → stateless services in autoscaling groups or pods; round robin by default, least-request for variable-cost endpoints, consistent hashing for the cache tier; internal calls via a mesh with retries and outlier detection.”
1.4.11 Using the LB optimally: checklist#
- Stateless services, so any server can answer.
- Right type: L7 for HTTP routing, L4 for raw TCP and static IPs.
- Spread instances across availability zones with cross-zone balancing on.
- Meaningful readiness check, graceful shutdown and connection draining.
- Tight timeouts, bounded retries (idempotent only), and limits on pending requests.
- Slow start for cold instances; autoscale on request rate or latency, not only CPU.
- Match keep-alive timeouts (backend > LB).
- Preserve the client IP (
X-Forwarded-For/PROXY protocol) and a request/trace ID. - Monitor per-backend request rate, error rate, latency, active connections, and unhealthy host count; alert on skew between backends.
- Test failure: kill an instance, an AZ, and the LB’s dependencies in a game day.
1.4.12 Common failure modes#
| Symptom | Cause | Fix |
|---|---|---|
| One backend hot, others idle | Sticky sessions, hash skew, a long-lived connection (gRPC/HTTP2) | L7/per-request balancing, P2C, recycle connections, drop stickiness |
| Intermittent 502/504 | Backend closes idle connections before the LB does; backend slower than LB timeout; deploys without draining | Backend keep-alive > LB idle; align timeouts; drain |
| Whole fleet “unhealthy” | Deep health check hits a failing shared dependency | Shallow checks, panic threshold |
| New instance dies after joining | Gets full load while cold | Slow start, warm-up, readiness after caches load |
| Retry storm | Retries at every layer, no budget | Budget, backoff + jitter, retry only at one layer |
| LB overloaded | TLS handshakes, connection spikes, small instance | Scale out LB, use TLS session resumption, offload to CDN, L4 in front |
| Wrong client IP in logs and limits | Backend sees the LB’s IP | X-Forwarded-For/PROXY protocol, trust only the LB |
Most asked questions#
1. What does a load balancer do, and when would you add one? It distributes requests across multiple identical servers, removes unhealthy ones, enables zero-downtime deploys, terminates TLS and gives one stable address. Add it as soon as there is more than one instance or the service must survive an instance failure. Mention that the services must be stateless.
2. L4 vs L7: which would you choose? L7 for HTTP APIs because it can route by path and host, terminate TLS, retry and inspect headers. L4 for raw TCP or UDP protocols, static IPs, the highest throughput or when TLS must stay end to end. In many systems both appear: L4 at the edge, L7 inside.
3. Which algorithm and why? Start with round robin for homogeneous, short, stateless requests. If request cost varies, least connections or least outstanding requests (or P2C). Weighted for canary or mixed hardware. Consistent hashing when affinity improves cache hits or state is sharded. State the trade-off for your pick.
4. How does the LB know a server is down? Active health checks (probe an endpoint every few seconds, mark unhealthy after consecutive failures) plus passive outlier detection on live traffic; readiness separate from liveness; draining on removal.
5. How do you handle sessions with a load balancer? Avoid sticky sessions; make servers stateless with a shared session store (Redis) or signed tokens. If stickiness is unavoidable (WebSockets, legacy), use a cookie or hash and accept the costs, and design failover to rebuild state.
6. How do you avoid the load balancer being a single point of failure? Use a managed multi-AZ LB, or an active-passive pair with a floating IP, or active-active via ECMP/anycast; use DNS or a global LB across regions; test failover.
7. How do you do a canary or blue-green deploy with a load balancer? Blue-green: two full environments, flip the LB target group (instant rollback). Canary: weighted routing sends 1%, then 5%, 25%, 100% to the new version while watching error rate and latency, with automatic rollback.
8. What is the difference between a load balancer, a reverse proxy and an API gateway? A reverse proxy forwards client requests to servers (and may cache or terminate TLS). A load balancer is a reverse proxy focused on spreading traffic and health. An API gateway is an L7 proxy with API-management features: authentication, rate limiting, request transformation, routing, quotas, analytics.
9. How do you balance WebSocket connections? Balance when connections open (least connections works well because they are long-lived), set long idle timeouts or heartbeats, support connection draining on deploy, and use a registry plus pub/sub so messages reach the right gateway node. Rebalancing existing connections requires forcing clients to reconnect gradually.
10. DNS load balancing vs a real LB? DNS round robin is free and global but not health-aware (without provider checks), cached by clients and resolvers (slow changes) and cannot balance by load. A real LB gives instant failover and per-request control. Use DNS for region selection and an LB for instances.
Senior-level questions#
1. “You have 20 backends behind 5 LB nodes using least connections, and the new deployment is overloaded immediately. Why?” Each LB node tracks connections locally. A freshly started backend has zero connections, so every LB node sends it traffic at once (herding), before it has warmed JIT, pools and caches. Fix: slow start (ramp weight), readiness that waits for warm-up, P2C or least-request with random choice (no herd), and limit concurrency per backend.
2. “gRPC traffic is unevenly distributed behind our NLB. Why and how do you fix it?”
gRPC multiplexes all calls over a long-lived HTTP/2 connection and an L4 LB balances connections, not requests, so a client’s calls all hit one backend, and scaling out does not help existing clients. Use an L7 balancer that understands HTTP/2 (Envoy, ALB with gRPC), client-side balancing with a service-discovery resolver, or a mesh; also set max_connection_age so connections rotate when new backends are added.
3. “Design the traffic path for a flash sale expecting 100× traffic.” Pre-provision the LB and instances (managed LBs scale gradually, so request pre-warming), CDN and cached pages for everything cacheable, a virtual waiting room that admits users at a controlled rate, rate limiting and admission control, separate pools or dedicated queues for checkout, shallow health checks, connection draining, load testing in advance, and a degradation plan (disable recommendations, serve static fallback pages). Autoscaling is too slow for the first minutes, so pre-scale.
4. “Health check marks all instances unhealthy during a database outage. What do you do?” It is the deep-health-check anti-pattern: the readiness check includes a dependency the instance cannot fix, so the LB empties the pool and turns a partial outage into a total one. Make readiness reflect only what the instance itself needs; handle dependency failure with circuit breakers, cached/degraded responses and meaningful errors; use a panic threshold so traffic is not dropped entirely.
5. “How do you keep a cache tier efficient while nodes are added and removed?” Consistent hashing (ring or Maglev) so only ~1/N keys move; virtual nodes for balance; bounded-load variant for hot keys; gradual warm-up or a second-chance lookup to the old node; replicas for hot keys. Compare with modulo hashing, where adding a node remaps almost every key and causes a stampede on the database.
6. “Where would you put retries and timeouts in a request path with four hops?” Retry at one layer (usually the edge or the caller closest to the user), with a budget, only for idempotent calls. Set timeouts as a deadline that shrinks per hop (client 3 s, gateway 2.5 s, service 2 s, DB 1 s) so downstream work stops when the caller has given up (propagate deadlines or cancellation). Retrying at every layer multiplies load exponentially during an incident.
7. “How do you verify load is actually balanced?” Per-backend metrics: requests/s, active connections, CPU, p50/p99 latency; compute the coefficient of variation or max/avg ratio; alert on skew; check for sticky cookies and long connections; compare algorithm choices under a replayed traffic profile.
8. “One tenant sends 40% of traffic and degrades others. What can the LB layer do?” Per-tenant rate limits and connection limits at the gateway, weighted fair queuing or per-tenant concurrency caps (bulkheads), route the tenant to a dedicated pool/cell via header-based routing, and apply priority classes so critical traffic is shed last.
9. “Zero-downtime deploys still drop requests. Why?”
The pod receives SIGTERM before the LB stops sending traffic (Kubernetes endpoint removal and SIGTERM race), so add a preStop sleep of a few seconds, fail readiness first, and then drain; align the deregistration delay with the termination grace period; ensure keep-alive timeouts do not cause closed-connection reuse errors; make long requests resumable.
10. “Active-active across two regions: how do you route, and what if one region fails?” GeoDNS/anycast to the nearest region, health-checked failover that shifts traffic to the survivor, each region sized at 100% of peak (or accepting degradation), data tier designed for it (writes to a home region or conflict-free), session state portable, and failover drills. Watch DNS TTL, cold caches and the thundering herd of re-logins after failover.
Quiz#
1. L4 or L7 for a Postgres cluster read replicas pool? For routing /api and /admin to different services?
Database pool: L4 (TCP), usually through a pooler such as PgBouncer or HAProxy in TCP mode. Path routing: L7, because only an application-layer balancer can read the URL.
2. Which algorithm for 3 identical stateless instances and short requests? For uploads that take 1 second to 10 minutes?
Round robin for the first. Least connections (or least outstanding requests) for the second, because round robin would stack long uploads unevenly.
3. Why do you get random 502 errors when backend keep-alive is 30 s and the LB idle timeout is 60 s?
The backend closes a connection that the LB still considers open; the LB sends a request into a closing socket. The backend’s keep-alive must be longer than the LB’s idle timeout.
4. What is the difference between liveness and readiness?
Liveness failing means the process is broken, so restart it. Readiness failing means “do not send traffic now” (warming up, dependency unavailable); the process stays running and is removed from the LB until ready again.
5. Why prefer consistent hashing over hash(key) % N for cache nodes?
With modulo, changing N remaps nearly all keys (a mass cache miss). Consistent hashing remaps about 1/N of keys.
6. How do you roll out a release to 5% of users using the LB?
Weighted target groups (95/5) or header/cookie-based routing, observe error rate and latency, increase gradually, roll back by setting the new weight to 0.
7. Why are sticky sessions discouraged?
They create uneven load, complicate failover and deploys (sessions lost when a node drains) and hide stateful designs. Use a shared session store or signed tokens.
8. What does connection draining do?
When an instance is deregistered, it stops receiving new requests but keeps serving in-flight ones until they finish or a timeout expires, so deploys and scale-ins do not drop requests.
9. Name three ways to make the LB layer highly available.
A managed multi-AZ load balancer, an active-passive pair with a floating IP (VRRP), and active-active via ECMP/anycast; plus DNS/global balancing across regions.
10. What is a retry budget and why use it?
A cap such as “retries may add at most 10% extra load”. It prevents retry storms in which retries from many clients amplify an overload into a full outage.
11. Why is power-of-two-choices good for many LB nodes?
Each node samples two random backends and picks the less loaded; it needs no shared state, avoids herding on a single “least loaded” server and gives near-optimal balance.
12. A user's real IP is missing from your logs and rate limiter. Why?
The backend sees the LB’s IP. Read X-Forwarded-For (trust only from the LB) or use the PROXY protocol for L4, and configure the limiter to use that value.