System DesignOct 6, 2026⏱️ 3 min read
Design Consistent Hashing: Virtual Nodes, Hash Rings & Partition Balancing

Design Consistent Hashing: Virtual Nodes, Hash Rings & Partition Balancing

The Problem with Modulo Hashing (hash(key) % N)

Suppose you distribute cache keys across $N = 4$ Redis servers using: $$\text{serverIndex} = \text{hash}(\text{key}) \bmod N$$
This works until Server 3 crashes or you add Server 5 for peak traffic ($N$ becomes $3$ or $5$). Almost every single key maps to a new server index ($\sim 75%$ to $80%$ of keys shift!). All cache lookups suddenly miss simultaneously, slamming your backing database.
Consistent Hashing guarantees that when cluster size changes from $N$ to $N \pm 1$, on average only $K / N$ keys need to move (where $K$ is total keys).
Consistent Hashing Ring Diagram

Consistent Hashing Ring Diagram


1. How the Hash Ring Works

  1. 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$.
  2. Place Servers on the Ring: Hash each server's IP or stable ID (hash("cache-node-01")) onto ring positions.
  3. 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

With just 4 physical servers placed directly on a circle, random hash distribution creates two critical problems:
  1. Uneven Partitions: One node might accidentally own 45% of the ring while another owns 8%.
  2. Cascading Load on Failure: If a node dies, 100% of its traffic shifts onto a single neighbor, potentially overloading and toppling that neighbor too.
Virtual Nodes (vnodes) fix both issues:
  • Instead of placing Server A once on the ring, place Server 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 A fails, its keys redistribute evenly across all remaining physical hosts rather than one unlucky neighbor.
  • Heterogeneous Hardware: A 64 GB node can receive 200 vnodes while a 32 GB node receives 100 vnodes.

3. Clean Python Implementation with bisect

python
import 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.

Share this article

Comments