Chapter 10: Load Balancing

A load balancer distributes incoming requests across multiple servers, ensuring no single server is overwhelmed.

L4 vs L7 Load Balancing

LayerOperates OnCan SeeSpeedExamples
L4 (Transport)TCP/UDP packetsIP + port onlyVery fastAWS NLB, HAProxy (TCP mode)
L7 (Application)HTTP requestsURL, headers, cookies, bodySlower but smarternginx, Envoy, AWS ALB

Algorithms

AlgorithmHow It WorksBest For
Round RobinRotate through servers sequentiallyEqual-capacity servers
Weighted Round RobinMore requests to higher-capacity serversMixed server sizes
Least ConnectionsSend to server with fewest active connectionsVarying request durations
IP HashHash client IP → consistent serverSession affinity (sticky sessions)
Consistent HashingHash-ring based distributionCache servers, minimal redistribution

Health Checks

// Load balancer periodically checks each server:
GET /health → 200 OK (server is healthy, keep sending traffic)
GET /health → 503 or timeout (server is unhealthy, remove from pool)

// When server recovers → add back to pool

High Availability for the Load Balancer Itself

Active-Passive LB pair: ┌──────────┐ ┌──────────┐ │ LB (A) │◄───►│ LB (B) │ ← heartbeat │ ACTIVE │ │ STANDBY │ └────┬─────┘ └──────────┘ │ ↑ ▼ (takes over if A dies) [App Servers]
Key Takeaways