Cheatsheet

Load Balancing

L4 vs L7, balancing algorithms and when to use each, health checks, session affinity, connection draining, TLS termination and common failure modes.

01What a load balancer does

  • Spreads requests across a pool of backends so no single server is overloaded.
  • Removes unhealthy backends from rotation and adds them back when they recover.
  • Gives clients one stable address while servers are added, removed or replaced.
  • Often also terminates TLS, enforces limits, and records access logs and metrics.
Backend pool / target group
The set of servers eligible to receive traffic.
Listener
The address, port and protocol the balancer accepts traffic on.
Global vs local
DNS or anycast steers users to a region (global); a regional balancer picks a server (local).

02Layer 4 vs layer 7

Transport-level versus application-level balancing
AspectLayer 4 (TCP/UDP)Layer 7 (HTTP/gRPC)
Decides onIP addresses and portsPath, host, headers, cookies, method
Sees payloadNoYes (after TLS termination)
Unit balancedConnectionsIndividual requests
OverheadVery low; can pass packets throughHigher; parses every request
FeaturesFast failover, any TCP protocolRouting rules, retries, header rewrites, auth, compression
Long-lived connectionsOne connection pinned to one backendHTTP/2 and gRPC streams can be spread per request
Typical useDatabases, MQTT, raw TCP, very high throughputWeb apps, APIs, microservice ingress

03Algorithms

Balancing algorithms and when to use them
AlgorithmHow it picksUse whenWatch out for
Round robinNext server in a fixed cycleIdentical servers, similar request costsUneven request costs pile up on unlucky servers
Weighted round robinCycle where server i appears w_i timesMixed instance sizes, canary at 5%Weights go stale when capacity changes
Least connectionsFewest open connectionsLong or variable requests, WebSocketsNeeds accurate connection counts; new servers get flooded
Least response timeLowest recent latency (often combined with connections)Heterogeneous or noisy backendsFeedback loops; a fast-failing server looks fast
Power of two choicesSample two at random, pick the less loadedMany balancers with stale load dataSlightly worse than perfect least-load, far cheaper
IP hashhash(client IP) mod NSimple affinity without cookiesNAT clusters users; resizing N remaps almost everyone
Consistent hashingKey placed on a hash ring, nearest node clockwiseCaches and shards: keep keys on the same nodeUse virtual nodes to avoid hot spots
RandomUniformly random serverLarge pools, stateless workShort-term imbalance with small pools
Resizing cost
modulo hashing:      adding 1 node to N remaps about N/(N+1) of keys
consistent hashing:  adding 1 node to N remaps about 1/(N+1) of keys

04Health checks

Active check
The balancer probes each backend on an interval (e.g. GET /healthz every 5 s).
Passive check
The balancer watches real traffic and ejects backends that return errors or time out (outlier detection).
Liveness
Is the process alive? Failure means restart it. Keep it cheap and dependency-free.
Readiness
Can it serve traffic now? Failure means stop sending requests, not restart.
Thresholds
Mark unhealthy after N consecutive failures and healthy after M successes to avoid flapping.
  • Do not make readiness depend on a shared dependency (e.g. the database): one blip ejects every server at once.
  • Detection time ≈ interval × unhealthy threshold. 5 s × 3 = up to 15 s of errors before removal.
  • Fail open: if every backend looks unhealthy, many balancers keep sending to all rather than to none.

05Affinity, draining and TLS

Session affinity (sticky sessions)
Pin a client to one backend via a cookie or IP hash. Convenient for in-memory sessions, but uneven load and lost sessions when that server dies. Prefer a shared session store.
Connection draining
When removing a server, stop new requests but let in-flight ones finish (e.g. 30 s), then terminate. Essential for zero-downtime deploys.
Slow start
Ramp traffic to a newly added server gradually so cold caches and JIT warm up.
TLS termination
Decrypt at the balancer, forward plain HTTP inside a trusted network. Centralises certificates and enables L7 routing.
TLS re-encryption
Terminate, inspect, then open a new TLS connection to the backend. Required where internal traffic must be encrypted.
TLS passthrough
Forward encrypted bytes untouched (L4). Backend holds the certificate; no L7 features.

06Failure modes

Common load-balancing failures and mitigations
FailureSymptomMitigation
Balancer is a single point of failureEverything down at onceRun balancers in pairs or managed, multi-zone; DNS or anycast in front
Thundering herd on recoveryRestarted server collapses immediatelySlow start, gradual weight increase
Retry stormsLoad doubles during an incidentRetry budgets, exponential backoff with jitter
Hot backend from long connectionsOne server at 100%, others idleLeast connections, per-request L7 balancing for HTTP/2
Health check too shallowTraffic sent to broken serversReadiness checks that exercise the request path
Health check too deepWhole pool ejected when a dependency blipsKeep dependency checks out of readiness; degrade instead
Capacity lost with one zoneRemaining servers overloadN+1 per zone, cross-zone balancing