Load Balancing
L4 vs L7 load balancers, balancing algorithms, health checks, session affinity, global load balancing, and avoiding the load balancer as a single point of failure.
A load balancer distributes incoming requests across a pool of servers. It lets you scale horizontally, take unhealthy servers out of rotation, and deploy without downtime.
Layer 4 vs layer 7
| Layer 4 (transport) | Layer 7 (application) | |
|---|---|---|
| Sees | IPs and ports (TCP/UDP) | HTTP: URLs, headers, cookies, gRPC methods |
| Routing | Per connection | Per request: path-based, host-based, header-based |
| Speed | Very fast, minimal processing | More CPU (parses HTTP, often terminates TLS) |
| Features | Simple balancing, TLS passthrough | TLS termination, compression, caching, retries, auth, rate limiting, canary routing |
| Examples | AWS NLB, IPVS, Maglev | nginx, HAProxy, Envoy, AWS ALB, Cloudflare |
L7 balancers are effectively reverse proxies, and in microservices they become API gateways and service-mesh sidecars.
Algorithms
| Algorithm | How | Good for |
|---|---|---|
| Round robin | Each server in turn | Identical servers, similar requests |
| Weighted round robin | Proportionally to capacity weights | Mixed server sizes, canary (5% weight) |
| Least connections | Server with fewest active connections | Long or variable-length requests (WebSockets) |
| Least response time | Fastest recent responses | Heterogeneous performance |
| Power of two choices | Pick 2 random servers, use the less loaded | Near-optimal and cheap at scale; avoids herding |
| IP / consistent hash | Hash of client IP or a key → server | Affinity, cache locality |
| Random | Uniformly random | Surprisingly fine with many servers |
Health checks
- Active: the balancer polls
GET /healthevery few seconds; after N failures the server is removed, after M successes it returns. - Passive: watch real traffic; eject servers that return errors or time out (outlier detection).
Design health endpoints carefully:
- Liveness — "is the process alive?" Keep it cheap. (Kubernetes restarts the container if it fails.)
- Readiness — "can I serve traffic right now?" Checks critical dependencies; fails during startup and warm-up.
- Don't make every instance fail its health check when a shared dependency (the database) is down — the balancer would remove all servers and turn a partial outage into a total one.
Session affinity
Sticky sessions route a user to the same server (cookie or IP hash). They help when servers hold local state, but cause uneven load and lose sessions on failures. Prefer stateless servers with shared session storage (Scalability basics).
Graceful operations
- Connection draining: when removing a server (deploy, scale-in), stop sending new requests but let in-flight ones finish.
- Slow start: ramp traffic up gradually to new instances so cold caches and JITs aren't overwhelmed.
- Retries at the balancer for idempotent requests, with budgets to avoid retry storms.
The load balancer itself must not fail
- Redundant pairs: active–passive with a floating virtual IP (keepalived/VRRP), or active–active.
- DNS returns several balancer IPs.
- Anycast: many balancers announce the same IP; BGP spreads traffic (Google's Maglev, Cloudflare).
- Managed cloud load balancers are already distributed and highly available.
Global load balancing
To route users to the nearest healthy region: GeoDNS / latency-based DNS (Route 53), anycast networks, or global L7 balancers (Cloudflare, Google Cloud's global LB). Combine with health checks for regional failover.
Client-side load balancing
In service-to-service traffic, clients can balance themselves using a service registry (gRPC with xDS, Netflix Ribbon, Kubernetes headless services). That removes a network hop and a central bottleneck, at the cost of logic in every client — which is what service-mesh sidecars (Envoy) take over.
- Load balancers spread traffic, remove unhealthy servers and enable zero-downtime deploys.
- L4 balances connections fast; L7 understands HTTP for smart routing and TLS termination.
- Algorithms: round robin, least connections, power of two choices, consistent hashing.
- Separate liveness and readiness; drain connections on removal.
- Make the balancer redundant (pairs, DNS, anycast); use global LB for multi-region.