Designing Dynamic Load Balancers: Round-Robin and Consistent Hashing
Data Structure DesignModel answerLast updated
Implement a resilient round-robin request balancer that handles dynamic server membership, followed by a consistent hashing router to maintain key affinity.
You are tasked with building the core request-routing component for an API gateway. The task consists of two parts: building a robust round-robin load balancer, and implementing a consistent hashing router to preserve key affinity.
Part 1: Dynamic Round-Robin Balancer
Implement a data structure that routes requests among an active pool of servers using a round-robin strategy. Your implementation must support the following methods:
add_server(server_id: str): Adds a server to the available pool.remove_server(server_id: str): Removes a server from the available pool.get_next_server() -> str: Returns the identifier of the next server in sequence.
Requirements & Edge Cases:
- Thread Safety: Multiple threads will invoke
get_next_server(),add_server(), andremove_server()concurrently. - Empty Pool: If no servers are available,
get_next_server()should returnNone(or raise a clear exception). - Dynamic Membership Modifications: Removing or adding a server mid-rotation must not cause out-of-bounds errors, race conditions, or skip/repeat servers unnecessarily.
- Defect Analysis: List common defects found in naive round-robin implementations (such as index drift or concurrency issues) and explain how to test for them deterministically.
Part 2: Consistent Hashing Router
To support stateful routing (e.g., sticky user sessions or distributed caches), implement a consistent hashing router. The router maps both servers and request keys onto a unified hash ring.
Implement a class supporting the following interface:
add_server(server_id: str): Hashes and places the server (and its virtual nodes) on the ring.remove_server(server_id: str): Removes the server and its virtual nodes from the ring.get_server(key: str) -> str: Hashes the given key and routes it to the nearest server clockwise on the ring.
Requirements:
- Virtual Nodes (Replicas): Support a parameter
num_replicas(e.g., 100 to 200) per physical server to ensure balanced distribution. - Deterministic Lookup:
get_server(key)must returnNoneif the ring is empty. - Minimal Key Movement: Demonstrate or explain why adding/removing a server reassigns only a fraction ($1/N$) of keys on average.
- Complexity: State the time and space complexity of
add_server,remove_server, andget_server.
Hints
Hint 1
For Part 1, storing current position as a simple integer index combined with array length operations like `idx % len(servers)` can fail if the array shrinks during execution.
Hint 2
For Part 2, standard Python dictionary lookups won't preserve sorted ring order. Consider maintaining a sorted list of hash values along with a map from hash to server ID.
Hint 3
Use `bisect.bisect_right` or `bisect.bisect_left` to efficiently locate the first node with a hash value greater than or equal to the key's hash value, wrapping around to the first element if necessary.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Architecture
Part 1: Thread-Safe Dynamic Round-Robin
A naive round-robin implementation often maintains a list of servers and a global index integer incremented on every get_next_server() call via index % len(servers). This approach breaks down under dynamic changes and concurrency:
- Race Conditions: Reading and updating the index across threads without mutual exclusion leads to duplicate choices or skipped turns.
- Index-Out-Of-Bounds Drift: If
remove_server()shrinks the list whileindexpoints near the end, a concurrent read can trigger an index error. - Off-by-One Delays: Modifying the array while iterating causes shifts in server position.
To address these issues, we can protect state modifications and reads using a thread lock. When removing a server before or at the current pointer position, we adjust the internal pointer backward to preserve smooth rotation.
Part 2: Consistent Hashing Router
Consistent hashing assigns both servers and keys to points on a circular space (typically $0$ to $2^{32}-1$).
- Hash Ring Construction: We map each server ID into multiple "virtual nodes" (e.g.,
server_1#0,server_1#1, ...server_1#V-1) using a uniform hash function like MD5 or SHA-256. Virtual nodes prevent hot-spotting and ensure even load distribution across nodes. - Sorted Array & Binary Search: We store the hash values of all active virtual nodes in a sorted array
ringand maintain a mappingring_map: hash_value -> server_id. - Lookup (
get_server): We computehash(key)and use binary search (bisect_rightorbisect_left) to locate the first node hash $\ge \text{hash}(key)$. If the key's hash exceeds all node hashes on the ring, it wraps around to index0.
Python Implementation
import hashlib
import bisect
import threading
from typing import Optional, List
# ==========================================
# Part 1: Thread-Safe Round-Robin Load Balancer
# ==========================================
class RoundRobinLoadBalancer:
def __init__(self, servers: Optional[List[str]] = None):
self._lock = threading.Lock()
self._servers: List[str] = list(servers) if servers else []
self._index: int = 0
def add_server(self, server_id: str) -> None:
with self._lock:
if server_id not in self._servers:
self._servers.append(server_id)
def remove_server(self, server_id: str) -> None:
with self._lock:
if server_id not in self._servers:
return
idx = self._servers.index(server_id)
self._servers.pop(idx)
# Adjust index to prevent skipping elements or going out of bounds
if len(self._servers) == 0:
self._index = 0
elif idx < self._index or self._index >= len(self._servers):
self._index %= len(self._servers)
def get_next_server(self) -> Optional[str]:
with self._lock:
if not self._servers:
return None
server = self._servers[self._index]
self._index = (self._index + 1) % len(self._servers)
return server
# ==========================================
# Part 2: Consistent Hashing Router
# ==========================================
class ConsistentHashingRouter:
def __init__(self, num_replicas: int = 100):
self.num_replicas = num_replicas
self._ring: List[int] = [] # Sorted list of virtual node hashes
self._ring_map: dict[int, str] = {} # hash -> physical server_id
self._lock = threading.Lock()
def _hash(self, key: str) -> int:
"""Returns a 32-bit integer hash for uniform distribution."""
digest = hashlib.md5(key.encode('utf-8')).digest()
return int.from_bytes(digest[:4], byteorder='big')
def add_server(self, server_id: str) -> None:
with self._lock:
for i in range(self.num_replicas):
vnode_key = f"{server_id}#vnode{i}"
h = self._hash(vnode_key)
if h not in self._ring_map:
bisect.insort(self._ring, h)
self._ring_map[h] = server_id
def remove_server(self, server_id: str) -> None:
with self._lock:
for i in range(self.num_replicas):
vnode_key = f"{server_id}#vnode{i}"
h = self._hash(vnode_key)
if h in self._ring_map:
idx = bisect.bisect_left(self._ring, h)
if idx < len(self._ring) and self._ring[idx] == h:
self._ring.pop(idx)
del self._ring_map[h]
def get_server(self, key: str) -> Optional[str]:
with self._lock:
if not self._ring:
return None
h = self._hash(key)
idx = bisect.bisect_right(self._ring, h)
# Wraparound to first element if hash exceeds all entries in ring
if idx == len(self._ring):
idx = 0
return self._ring_map[self._ring[idx]]
Defect Analysis & Verification for Round-Robin
To prove the robustness of the Round-Robin component, we test against three common implementation bugs:
- Unsynchronized Pointer Race Condition:
- Symptom: Concurrent calls return the same server multiple times out of order.
- Test: Spawn 10 threads calling
get_next_server()1,000 times simultaneously on a pool of 3 servers. Assert that the frequency distribution of returned server IDs is equal ($\pm 1$).
- Index Out-of-Bounds on Shrink:
- Symptom:
IndexErrorthrown whenremove_servershrinks the list while_indexis atlen(servers) - 1. - Test: Set up servers
["A", "B", "C"]. Callget_next_server()3 times (_indexbecomes 0). Callget_next_server()2 times (_indexbecomes 2, pointing to "C"). Callremove_server("C"). Callget_next_server()—it should cleanly return "A" without throwing an exception.
- Symptom:
Complexity Analysis
Let $N$ be the total number of physical servers and $V$ be num_replicas (virtual nodes per server). The total number of nodes on the hash ring is $M = N \times V$.
| Operation | Round-Robin | Consistent Hashing |
|---|---|---|
get_next_server / get_server | $\mathcal{O}(1)$ | $\mathcal{O}(\log(N \cdot V))$ |
add_server | $\mathcal{O}(1)$ | $\mathcal{O}(V \cdot \log(N \cdot V) + V \cdot N \cdot V)$ * |
remove_server | $\mathcal{O}(N)$ (list search) | $\mathcal{O}(V \cdot \log(N \cdot V) + V \cdot N \cdot V)$ * |
| Space Complexity | $\mathcal{O}(N)$ | $\mathcal{O}(N \cdot V)$ |
*Note: Array insertion/deletion via bisect.insort or pop inside a Python list takes $\mathcal{O}(M)$ shift operations per replica. If node additions/removals are frequent, replacing the array with a balanced binary search tree (like a Red-Black Tree or Treap) lowers modification costs to $\mathcal{O}(V \log M)$.
Minimal Key Movement Guarantee
In traditional hash routing (hash(key) % N), changing $N$ to $N+1$ causes almost all keys ($\sim \frac{N}{N+1}$) to re-hash to new positions.
With Consistent Hashing, adding or removing a server affects only the range between the added/removed node and its immediate counter-clockwise predecessor. As a result, only $\approx \frac{1}{N}$ of total keys are re-mapped to different servers, minimizing disruption to cached state across the system.