Design Consistent Hashing: Virtual Nodes, Hash Rings & Partition Balancing
The Problem with Modulo Hashing (hash(key) % N)
Consistent Hashing Ring Diagram
1. How the Hash Ring Works
- Choose a Fixed Hash Space: Map a cryptographically uniform hash function (e.g., SHA-1, MurmurHash3, xxHash) onto a circular ring from $0$ to $2^{32} - 1$.
- Place Servers on the Ring: Hash each server's IP or stable ID (
hash("cache-node-01")) onto ring positions. - Place Keys & Walk Clockwise: Hash each key (
hash("user:42")), place it on the ring, and walk clockwise until hitting the first server node.
Adding or Removing a Server
- Add a Server: Only keys in the arc immediately counter-clockwise to the new node move from its clockwise neighbor to the new node. All other $N-1$ arcs remain untouched.
- Remove a Server: Only keys owned by the failed node roll forward to the next clockwise node.
2. Why Virtual Nodes Are Mandatory in Production
- Uneven Partitions: One node might accidentally own 45% of the ring while another owns 8%.
- Cascading Load on Failure: If a node dies, 100% of its traffic shifts onto a single neighbor, potentially overloading and toppling that neighbor too.
- Instead of placing
Server Aonce on the ring, placeServer A#0,Server A#1, ...,Server A#199(100–200 virtual positions per host). - Result: Standard deviation of partition sizes drops below ~5%, and if
Server Afails, its keys redistribute evenly across all remaining physical hosts rather than one unlucky neighbor. - Heterogeneous Hardware: A 64 GB node can receive
200vnodes while a 32 GB node receives100vnodes.
3. Clean Python Implementation with bisect
pythonimport bisect import hashlib class ConsistentHashRing: def __init__(self, vnodes_per_node: int = 150): self.vnodes = vnodes_per_node self.ring = {} # hash_int -> physical_node self.sorted_keys = [] # sorted ring positions @staticmethod def _hash(key: str) -> int: return int(hashlib.md5(key.encode("utf-8")).hexdigest()[:8], 16) def add_node(self, node: str): for i in range(self.vnodes): vnode_hash = self._hash(f"{node}#{i}") if vnode_hash not in self.ring: self.ring[vnode_hash] = node bisect.insort(self.sorted_keys, vnode_hash) def remove_node(self, node: str): for i in range(self.vnodes): vnode_hash = self._hash(f"{node}#{i}") if vnode_hash in self.ring: del self.ring[vnode_hash] idx = bisect.bisect_left(self.sorted_keys, vnode_hash) if idx < len(self.sorted_keys) and self.sorted_keys[idx] == vnode_hash: self.sorted_keys.pop(idx) def get_node(self, key: str) -> str | None: if not self.sorted_keys: return None key_hash = self._hash(key) idx = bisect.bisect_right(self.sorted_keys, key_hash) # Wrap around the circle if past the last node if idx == len(self.sorted_keys): idx = 0 return self.ring[self.sorted_keys[idx]]
4. Real-World Systems Using Consistent Hashing
- Amazon DynamoDB & Apache Cassandra: Data partitioning across storage rings.
- Discord: Routing guild/chat state across Elixir processes.
- Google Maglev / Envoy: Connection-preserving L4 load balancing.
- CDNs (Akamai, Cloudflare): Routing specific URLs to edge cache nodes for maximum cache hit ratio.