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
| Aspect | Layer 4 (TCP/UDP) | Layer 7 (HTTP/gRPC) |
|---|---|---|
| Decides on | IP addresses and ports | Path, host, headers, cookies, method |
| Sees payload | No | Yes (after TLS termination) |
| Unit balanced | Connections | Individual requests |
| Overhead | Very low; can pass packets through | Higher; parses every request |
| Features | Fast failover, any TCP protocol | Routing rules, retries, header rewrites, auth, compression |
| Long-lived connections | One connection pinned to one backend | HTTP/2 and gRPC streams can be spread per request |
| Typical use | Databases, MQTT, raw TCP, very high throughput | Web apps, APIs, microservice ingress |
03Algorithms
| Algorithm | How it picks | Use when | Watch out for |
|---|---|---|---|
| Round robin | Next server in a fixed cycle | Identical servers, similar request costs | Uneven request costs pile up on unlucky servers |
| Weighted round robin | Cycle where server i appears w_i times | Mixed instance sizes, canary at 5% | Weights go stale when capacity changes |
| Least connections | Fewest open connections | Long or variable requests, WebSockets | Needs accurate connection counts; new servers get flooded |
| Least response time | Lowest recent latency (often combined with connections) | Heterogeneous or noisy backends | Feedback loops; a fast-failing server looks fast |
| Power of two choices | Sample two at random, pick the less loaded | Many balancers with stale load data | Slightly worse than perfect least-load, far cheaper |
| IP hash | hash(client IP) mod N | Simple affinity without cookies | NAT clusters users; resizing N remaps almost everyone |
| Consistent hashing | Key placed on a hash ring, nearest node clockwise | Caches and shards: keep keys on the same node | Use virtual nodes to avoid hot spots |
| Random | Uniformly random server | Large pools, stateless work | Short-term imbalance with small pools |
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 /healthzevery 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
| Failure | Symptom | Mitigation |
|---|---|---|
| Balancer is a single point of failure | Everything down at once | Run balancers in pairs or managed, multi-zone; DNS or anycast in front |
| Thundering herd on recovery | Restarted server collapses immediately | Slow start, gradual weight increase |
| Retry storms | Load doubles during an incident | Retry budgets, exponential backoff with jitter |
| Hot backend from long connections | One server at 100%, others idle | Least connections, per-request L7 balancing for HTTP/2 |
| Health check too shallow | Traffic sent to broken servers | Readiness checks that exercise the request path |
| Health check too deep | Whole pool ejected when a dependency blips | Keep dependency checks out of readiness; degrade instead |
| Capacity lost with one zone | Remaining servers overload | N+1 per zone, cross-zone balancing |