Build Stateful Round-Robin and Consistent Hash Load Balancers
Data Structure DesignModel answerLast updated
Implement thread-safe Round-Robin and Consistent Hashing balancers supporting health checks and dynamic nodes, then analyze their performance.
Design and write thread-safe load balancer implementations in Python (or your preferred language) for two distinct algorithms:
-
Stateful Round-Robin Balancer:
- Maintains an ordered set of server nodes, where each node has a health status (
HEALTHYorUNHEALTHY). - Cycles through available servers sequentially to handle request delegation.
- Bypasses
UNHEALTHYservers cleanly without resetting or corrupting the sequence for standard nodes. - Correctly updates its internal state across concurrent calls, safely handles adding/removing servers dynamically, and throws a custom exception if zero operational nodes remain.
- Maintains an ordered set of server nodes, where each node has a health status (
-
Consistent-Hashing Balancer:
- Assigns request keys to nodes situated on a dynamic hash ring utilizing virtual nodes (
vnodes) for each physical backend server. - Routes incoming keys to the nearest clockwise operational node on the ring.
- Allows dynamically registering or unregistering physical nodes while minimizing data re-mapping (re-keying) across remaining cluster members.
- Handles offline nodes by continuing clockwise past inactive virtual nodes until reaching an operational server.
- Assigns request keys to nodes situated on a dynamic hash ring utilizing virtual nodes (
Following your implementations, provide a theoretical comparison that covers:
- Time and space complexity for request lookup, server registration, and node removal.
- Key migration characteristics under cluster topology shifts.
- Cache affinity, load distribution uniformness (hotspot prevention), and fault tolerance.
- Concrete real-world production cases suited to each approach.
Hints
Hint 1
Use an explicit Enum for health status to prevent string-matching bugs, and ensure state variables like index counters survive across function invocations.
Hint 2
When removing nodes during active operation, ensure index pointer recalculation prevents out-of-bounds access or skipped elements.
Hint 3
Ensure hashing is deterministic across executions; avoid standard Python hash() which uses per-process random seeds.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Overview
Load balancers distribute traffic across a pool of compute resources.
- Stateful Round-Robin (RR) distributes requests sequentially across an ordered pool. It requires minimal state overhead and offers optimal balance for stateless compute, but it completely lacks key-to-node affinity.
- Consistent Hashing (CH) maps both servers and incoming request keys onto a unified dynamic ring using a deterministic hash function. It preserves key affinity and minimizes key churn when servers join or leave the ring.
Implementation Details & Key Pitfalls
When designing load balancer implementations, several operational pitfalls must be mitigated:
- Type-Safe Health States: Relying on arbitrary string flags introduces subtle bugs (e.g.,
"unhealthy"vs"UNHEALTHY"). We use an explicitEnum. - State Persistence & Concurrency: The round-robin cursor index must persist at the instance level and be protected against data races using mutual exclusion mechanisms (
threading.Lock). - Infinite Loop Prevention: When all nodes are offline, linear or ring scans must terminate within one full traversal ($N$ nodes or $N \times V$ virtual nodes) and raise an explicit
ServerUnavailableException. - Index Bounds under Dynamic Removal: Deleting a node shrinks the target list, which can leave a persistent pointer out-of-bounds. Index positions must be re-calibrated via modulo arithmetic (
idx % len(nodes)). - Deterministic Hashing: Python's built-in
hash()function uses randomized per-process seeds. Consistent hashing requires a deterministic algorithm such asMD5orMurmurHash3.
Python Code Implementation
import bisect
from enum import Enum, auto
import hashlib
import threading
from typing import Dict, List, Optional
class HealthStatus(Enum):
HEALTHY = auto()
UNHEALTHY = auto()
class ServerUnavailableException(Exception):
"""Raised when no operational backend server can handle the request."""
pass
class ServerNode:
def __init__(self, name: str, status: HealthStatus = HealthStatus.HEALTHY):
self.name = name
self.status = status
def is_healthy(self) -> bool:
return self.status == HealthStatus.HEALTHY
class RoundRobinBalancer:
def __init__(self, initial_nodes: Optional[List[ServerNode]] = None):
self._nodes: List[ServerNode] = []
self._cursor: int = 0
self._lock = threading.Lock()
if initial_nodes:
for node in initial_nodes:
self.add_node(node)
def add_node(self, node: ServerNode) -> None:
with self._lock:
if any(n.name == node.name for n in self._nodes):
raise ValueError(f"Node '{node.name}' already exists.")
self._nodes.append(node)
def remove_node(self, name: str) -> None:
with self._lock:
self._nodes = [n for n in self._nodes if n.name != name]
if self._nodes:
self._cursor %= len(self._nodes)
else:
self._cursor = 0
def get_node(self) -> ServerNode:
with self._lock:
total_nodes = len(self._nodes)
if total_nodes == 0:
raise ServerUnavailableException("No servers registered in balancer pool.")
for step in range(total_nodes):
candidate_idx = (self._cursor + step) % total_nodes
node = self._nodes[candidate_idx]
if node.is_healthy():
self._cursor = (candidate_idx + 1) % total_nodes
return node
raise ServerUnavailableException("All servers in balancer pool are unhealthy.")
def _stable_hash(key: str) -> int:
"""Computes a 64-bit integer hash from MD5 bytes for deterministic placement."""
digest = hashlib.md5(key.encode('utf-8')).digest()
return int.from_bytes(digest[:8], byteorder='big')
class ConsistentHashBalancer:
def __init__(self, initial_nodes: Optional[List[ServerNode]] = None, vnodes_per_node: int = 100):
self._vnodes_per_node = vnodes_per_node
self._ring: List[int] = [] # Sorted list of virtual node hashes
self._vnode_map: Dict[int, ServerNode] = {} # vnode_hash -> ServerNode
self._nodes: Dict[str, ServerNode] = {} # node_name -> ServerNode
self._lock = threading.RLock()
if initial_nodes:
for node in initial_nodes:
self.add_node(node)
def add_node(self, node: ServerNode) -> None:
with self._lock:
if node.name in self._nodes:
raise ValueError(f"Node '{node.name}' already exists.")
self._nodes[node.name] = node
for v_idx in range(self._vnodes_per_node):
v_key = f"{node.name}#vnode-{v_idx}"
v_hash = _stable_hash(v_key)
# Insert keeping the ring sorted
idx = bisect.bisect_left(self._ring, v_hash)
if idx == len(self._ring) or self._ring[idx] != v_hash:
self._ring.insert(idx, v_hash)
self._vnode_map[v_hash] = node
def remove_node(self, name: str) -> None:
with self._lock:
if name not in self._nodes:
return
del self._nodes[name]
# Rebuild ring entries excluding target node
new_ring = []
new_vnode_map = {}
for v_hash in self._ring:
owner = self._vnode_map[v_hash]
if owner.name != name:
new_ring.append(v_hash)
new_vnode_map[v_hash] = owner
self._ring = new_ring
self._vnode_map = new_vnode_map
def get_node(self, key: str) -> ServerNode:
with self._lock:
if not self._ring:
raise ServerUnavailableException("Ring is empty.")
key_hash = _stable_hash(key)
start_idx = bisect.bisect_right(self._ring, key_hash) % len(self._ring)
visited_physical_nodes = set()
total_ring_len = len(self._ring)
for step in range(total_ring_len):
curr_idx = (start_idx + step) % total_ring_len
v_hash = self._ring[curr_idx]
target_node = self._vnode_map[v_hash]
if target_node.name in visited_physical_nodes:
continue
if target_node.is_healthy():
return target_node
visited_physical_nodes.add(target_node.name)
if len(visited_physical_nodes) == len(self._nodes):
break
raise ServerUnavailableException("All available physical nodes are unhealthy.")
Algorithmic & Trade-Off Comparison
1. Complexity Benchmark
Let $N$ represent physical servers, $V$ represent virtual tokens per server (typically 100–250), and $K$ represent total active keys.
| Dimension | Stateful Round-Robin | Consistent Hashing |
|---|---|---|
| Lookup Time (All Healthy) | $O(1)$ | $O(\log(N \cdot V))$ |
| Lookup Time (Degraded Pool) | $O(N)$ worst-case | $O(\log(N \cdot V) + V)$ clockwise walk |
| Node Addition | $O(1)$ amortized | $O(V \log(N \cdot V))$ sorted insertion |
| Node Removal | $O(N)$ list filtering | $O(N \cdot V)$ structure rebuild |
| Memory Consumption | $O(N)$ | $O(N \cdot V)$ |
2. Key Remapping and Rebalancing Behavior
- Standard Modulo Hashing ($hash(key) \pmod N$): Adding or removing a server changes $N \to N \pm 1$. This invalidates up to $100%$ of key routing assignments, causing severe cache eviction storms.
- Round-Robin: Zero affinity persistence. Subsequent calls for identical keys land on arbitrary nodes according to global request timing.
- Consistent Hashing: Adding or removing a node redistributes only $1/N$ of keys on average. The remaining $(N-1)/N$ keys retain their original target nodes.
3. Operational Characteristics
- Cache Affinity: Consistent hashing routes request keys (such as user IDs or URL paths) to identical backend servers consistently. This maximizes L1/L2 application cache hit ratios. Round-robin offers no cache locality.
- Hotspot Vulnerability:
- Round-Robin: Spreads traffic volume evenly regardless of data attributes. However, if backend request processing cost varies widely per request type, worker load can skew.
- Consistent Hashing: Key distribution relies heavily on hash uniformity. Non-uniform access patterns (e.g., high traffic for a viral key) will direct traffic spikes to a single physical node. Virtual nodes ($V \ge 100$) help balance total key capacity across machines, but single-key hotspots still require application-level caching or secondary distribution layers.
- Failure Resilience: Under dynamic node outages, consistent hashing cascades traffic from the failed server directly onto its adjacent downstream neighbor on the hash ring. Round-robin distributes failed node load evenly across all remaining healthy machines.
4. Real-World Applications
-
Round-Robin:
- Stateless REST APIs, microservices behind API Gateways (e.g., NGINX, Envoy).
- DNS-level round-robin balancing across multiple web server IP addresses.
- Workers pulling jobs off uniform task queues.
-
Consistent Hashing:
- Distributed Caching layers (e.g., Memcached clusters, Redis Cluster keyspace routing).
- Distributed Databases and Key-Value stores (e.g., Amazon DynamoDB, Apache Cassandra, Riak).
- WebRTC media routing servers keyed by conference call ID.