Consistent Hashing in Distributed Systems
Consistent hashing is a technique for distributing keys across a pool of servers so that adding or removing a server only remaps a tiny fraction of keys (~K / N on average) instead of reshuffling nearly the entire dataset. It is the backbone of distributed caching, sharded databases, and sticky load balancers.
Why Naive Modulo Hashing (hash(key) % N) Fails
The simplest way to pick a server from N nodes is serverIndex = hash(key) % N. That works fine while N never changes — and breaks catastrophically the moment a server crashes or you scale out:
- Suppose you have
N = 4cache nodes and 1 node goes down (N = 3). - Because the divisor changed from
4to3, almost every key hashes to a different remainder (~75%of keys remap, and with 100 nodes,~99%remap!). - In a distributed cache, a 99% remapping triggers an instant cache miss storm that can knock over your primary database.
How the Consistent Hash Ring Works
Consistent hashing decouples key placement from the total node count N by mapping both servers and keys onto the same fixed circular hash space (shown below as 0..359 for clarity; in production, typically 0 to 2^32 - 1):
- Place servers on the ring: Hash each server’s identifier (e.g., IP address or hostname) to a position on the circle — here
Server A (0),Server B (120), andServer C (240). - Place keys on the ring: Hash each lookup key using the same hash function — here
k1 (40),k2 (170), andk3 (300). - Walk clockwise to find the owner: Starting at a key’s position, move clockwise until you hit the first server:
k1 (40)→Server B (120)k2 (170)→Server C (240)k3 (300)→ wraps past359 → 0toServer A (0)
Now look at the After panel when the cluster changes:
- Adding
Server Dat position80: Only keys falling in the arc(0..80]— here justk1 (40)— move fromServer BtoServer D. Bothk2 (170)andk3 (300)keep their exact same owners (Server CandServer A), whereashash(key) % Nwould have reshuffled~75%of all keys. - Removing a node (e.g.,
Server Bcrashes): OnlyServer B’s keys shift clockwise toServer C. All other nodes keep 100% of their keys.
Virtual Nodes (Vnodes) for Even Distribution
With only a few physical nodes on a ring, random hashing often creates lopsided arcs — one node might end up owning 60% of the ring while another owns 10%. And if one node fails, its single clockwise neighbor suddenly absorbs 100% of its traffic.
Virtual nodes (vnodes) fix both issues:
- Instead of placing
Node Aonce on the ring, place 100–200 virtual replicas (Node A#1,Node A#2, …,Node A#150) scattered randomly around the circle. - Keys spread far more evenly across physical servers (standard deviation drops sharply as vnode count rises).
- When a physical node fails, its keys are spread cleanly across all remaining servers instead of overloading one neighbor.
- Powerful machines can be assigned more vnodes than smaller machines for natural weighted load distribution.
Modulo Hashing vs. Consistent Hashing
| Dimension | Naive Modulo (hash % N) |
Consistent Hashing (with Vnodes) |
|---|---|---|
| Keys moved when adding/removing 1 node | ~((N - 1) / N) (nearly 100% at scale) |
~1 / N (theoretical minimum) |
| Lookup complexity | O(1) |
O(log(N × V)) via binary search on sorted ring |
| Heterogeneous hardware support | Hard | Easy — assign more virtual nodes to larger servers |
| Cache miss storm on node failure | Severe | Minimal — only failed node’s slice remaps |
Where Consistent Hashing Is Used in Production
- Distributed Caches: Memcached clients and Redis routing proxies use consistent hashing so losing one cache shard doesn’t flush the whole cluster.
- Distributed Databases: Apache Cassandra and Amazon DynamoDB partition data and pick replica owners by walking clockwise across the ring (pairing directly with CAP theorem tunable quorums and database sharding).
- CDNs & Load Balancers: CDN edge clusters and Layer 7 load balancers (NGINX, Envoy, HAProxy) use consistent hashing to keep hot objects pinned to the same cache node.
- Distributed Rate Limiters: Sharding per-user token buckets across Redis nodes with minimal counter loss during cluster resizes.
FAQs
Does consistent hashing eliminate hot keys (celebrity keys)?
No. Consistent hashing balances how many keys each node owns, not how much traffic a single key receives. If one key (like a viral post) gets 50% of all traffic, its single owner node still gets hammered — solve hot keys with local in-process caching, read replicas, or key salting.How many virtual nodes per physical server should I use?
Most production systems use 100 to 200 virtual nodes per physical server. Below ~50, key distribution can still skew noticeably; above ~500, ring metadata memory and binary-search overhead grow with diminishing balance gains.How is consistent hashing implemented in code?
Store all virtual node hash positions in a sorted array (or balanced BST / TreeMap) mappinghashPosition → nodeId. To look up a key, compute h = hash(key) (e.g., MurmurHash3 or xxHash), binary-search for the first position >= h, and wrap around to index 0 if h is larger than the last node on the ring.How does consistent hashing work with replication?
To storeR = 3 replicas of a key, walk clockwise from hash(key) and pick the first 3 distinct physical nodes (skipping duplicate virtual nodes belonging to the same physical machine).