Modern System Design & API Architecture · Chapter 5 · ~24 min · Intermediate
Load Balancing Algorithms & Consistent Hashing
Master traffic distribution algorithms at internet scale. Compare Round-Robin, Weighted Least Connections, IP Hash, and Consistent Hashing with virtual nodes (vnodes) to guarantee zero-downtime cache survival.
- Compare Layer 4 (TCP/UDP) vs. Layer 7 (HTTP) load balancing trade-offs
- Understand why classic modulo hashing (hash % N) fails during horizontal scaling
- Master Consistent Hashing rings and virtual nodes (vnodes) for uniform key allocation
- Implement health check heartbeats to isolate degraded nodes without cascading outages
Load Balancing Algorithms & Consistent Hashing: learn it visually
Explore Layer 4 vs Layer 7 load balancers, round-robin, least connections, consistent hashing rings, and virtual node distribution to minimize rehashing keys.
1The Traffic Gatekeeper: How Load Balancers Distribute Work
A single high-performance web server can handle 20,000 to 50,000 concurrent HTTP connections before its CPU and network file descriptors saturate. To scale to millions of users, a Load Balancer (Reverse Proxy) sits in front of a server fleet, distributing incoming packets so no individual machine is overwhelmed.
Layer 4 Load Balancing (L4)
Operates at the TCP/UDP protocol level without inspecting application payloads. Does not terminate HTTP or decrypt TLS. Extremely fast (10,000,000+ packets/sec) with minimal CPU usage. Examples: AWS Network Load Balancer (NLB), IPVS.
Layer 7 Load Balancing (L7)
Terminates TLS and parses HTTP headers, cookies, URL paths, and JSON payloads. Routes requests intelligently (e.g., /api/video → GPU cluster; /api/auth → Auth cluster). Higher CPU cost. Examples: AWS Application Load Balancer (ALB), Nginx, Envoy.
Why would an architecture place an L4 load balancer in front of a fleet of L7 Envoy proxies?
2Load Balancing Algorithms: From Round-Robin to Least Connections
The choice of distribution algorithm depends directly on the nature of the workload:
1. Round-Robin & Weighted Round-Robin
Sequentially cycles through nodes: 1 → 2 → 3 → 1. Weighted variant sends 3x more requests to 64-core servers than 16-core servers. Ideal when all requests take roughly equal processing time.
2. Least Connections & Weighted Least Connections
Routes each request to the server with the fewest active TCP connections. Essential for long-lived connections such as WebSockets, database pools, or complex multi-second SQL report queries.
3. IP Hash / Client Stickiness
Hashes client IP address to ensure a particular customer always reaches the same backend instance. Useful for legacy stateful session caches, but creates hotspots behind corporate NAT gateways.
3The Modulo Flaw & Consistent Hashing Rings
When sharding cached data across N servers, the intuitive formula is:
// Modulo Sharding: Simple but catastrophic when scaling
const serverIndex = hash(cacheKey) % numberOfServers;Suppose you have 10 servers. When traffic surges during Black Friday, you add 1 server (now 11). Every key whose hash value was not an exact multiple of both 10 and 11 will change its remainder! In practice, 10 / 11 (≈ 91%) of all keys instantly remap to the wrong server. Your cache hit ratio crashes from 99% to 9%, dumping millions of queries onto your primary database.
Wrong idea: Simple modulo hashing (hash(key) % N) scales horizontally without issue
Assuming that adding or removing a single node from an N-server cluster only impacts keys belonging to that specific node.
Real system: Consistent hashing ring limits key migration strictly to K / N keys
Both servers and keys map to a 360-degree circular hash space. A key is routed to the next clockwise server. Adding node N+1 only takes keys from its immediate neighbor.
What percentage of keys are disrupted when resizing an N-server cluster to N+1 under traditional modulo hashing (hash % N)?
4Hands-On: Consistent Hashing 360° Ring Visualizer
Explore a live 360-degree consistent hash ring. Click different client keys to trace their clockwise path to server nodes, and add or remove servers to observe how only neighboring keys migrate:
Consistent Hashing 360° Ring Visualizer
Key session:884 hashes to position 80°. Traversing clockwise, the first available server node is Server Beta at 165°.
Topology Event Log:
Stable cluster: 3 physical servers covering 360-degree hash ring.
5Virtual Nodes (Vnodes): Eliminating Hot-Spot Skew
With only 3 or 4 physical machines placed on a 360-degree ring, random hash placement rarely yields equal pie slices. One server might end up owning a 220-degree arc while another gets only 20 degrees.
The industry standard solution (used by Amazon DynamoDB, Apache Cassandra, and Discord) is Virtual Nodes (Vnodes). Each physical server is assigned 100 to 256 virtual tokens scattered randomly across the ring. The law of large numbers smooths out the arc distribution, keeping traffic variance across physical hardware within ±3%.
Why do distributed storage engines like DynamoDB and Cassandra assign 100+ virtual nodes (vnodes) to each physical server?
6Bug Hunt: Fix the Consistent Hash Ring Router
A distributed caching gateway was deployed with three severe routing defects: it relies on fragile modulo hashing that wipes out caches on scale events, virtual nodes are set to 1 causing massive load imbalance, and dead node health check evictions are disabled.
Fix the configuration below and click Run & verify:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Enable ring routing: set
algorithm: "consistent-ring". - Homogenize arc distribution: set
vnodesPerNodeto a balanced value like150(between 50 and 500). - Prune crashed machines: set
healthCheckEviction: true.
7Recap
- Layer 4 balances raw TCP/UDP packets at line speed; Layer 7 terminates TLS and inspects HTTP paths and cookies.
- Least Connections is best for heterogeneous or long-lived connections (WebSockets, DB queries).
- Modulo Hashing (hash % N) causes catastrophic 90%+ cache wipes when cluster sizes change.
- Consistent Hashing limits key migration strictly to K / N keys when nodes join or leave.
- Virtual Nodes (Vnodes) homogenize the ring, eliminating hot-spot skew across physical hardware.
Ready for Chapter 6 (Stateless Authentication & JWTs)? Mark this chapter as complete to proceed: