18. Consistent Hashing
Distribute keys across servers so adding or removing a node barely shuffles anything
You have a million cached objects and four servers. The obvious approach is
server = hash(key) % 4. It works beautifully -- until you add a fifth server.
Suddenly almost every key maps to a different server. Your cache hit rate
drops to near zero, your database gets slammed, and you're paged at 3 a.m.
Consistent hashing solves this by ensuring that when you add or remove a server, only a small fraction of keys need to move. It was introduced by Karger et al. in 1997 and is now a cornerstone of distributed systems.
The Problem: Modular Hashing
With hash(key) % N, every key's assignment depends on N. Change
N and nearly every key lands on a different server.
Example: 6 keys, 3 servers → 4 servers
Key hash(key) % 3 % 4
─────────────────────────────────
"user:1" 17 2 1 ← moved
"user:2" 42 0 2 ← moved
"user:3" 89 2 1 ← moved
"user:4" 123 0 3 ← moved
"user:5" 56 2 0 ← moved
"user:6" 71 2 3 ← moved
Result: 6 out of 6 keys moved (100%)
On average, going from N to N+1 servers reshuffles K × (N−1) / N keys -- that's roughly 75% of all keys when going from 3 to 4 servers.
The Key Idea: A Hash Ring
Consistent hashing in one sentence
Arrange the entire hash space as a ring (from 0 to 232−1, wrapping around), place servers at hashed positions on the ring, and assign each key to the next server clockwise.
Because key assignment depends only on nearby servers on the ring -- not on the total count of servers -- adding or removing a server disturbs only the keys in one arc of the ring.
How It Works
-
Hash the servers onto the ring
For each server, compute
hash(server_id)to get a position on the ring (an integer from 0 to 232−1). Place the server at that position. -
Hash each key onto the ring
Compute
hash(key)the same way. The key lands at some position on the ring. -
Walk clockwise to the next server
Starting from the key's position, walk clockwise around the ring. The first server you encounter is responsible for that key.
Worked Example: 3 Servers, 6 Keys
Initial ring with servers A, B, C
Ring positions (0 to 2^32-1, shown as 0-999 for clarity):
Server A → position 150
Server B → position 450
Server C → position 750
Key assignments (walk clockwise to next server):
"user:1" → pos 80 → Server A (next server clockwise)
"user:2" → pos 200 → Server B
"user:3" → pos 350 → Server B
"user:4" → pos 500 → Server C
"user:5" → pos 650 → Server C
"user:6" → pos 900 → Server A (wraps around past 999)
Distribution: A=2, B=2, C=2
Adding Server D at position 600
After adding Server D
Server A → 150, Server B → 450, Server D → 600, Server C → 750
Key assignments:
"user:1" → pos 80 → Server A (unchanged)
"user:2" → pos 200 → Server B (unchanged)
"user:3" → pos 350 → Server B (unchanged)
"user:4" → pos 500 → Server D ← MOVED (was C, now D)
"user:5" → pos 650 → Server C (unchanged)
"user:6" → pos 900 → Server A (unchanged)
Only 1 out of 6 keys moved! Specifically, only keys between D's predecessor (B at 450) and D itself (600) are affected -- they now point to D instead of C.
Removing a Server
When a server is removed, only its keys need to move -- they simply fall through to the next server clockwise. If server B (at 450) goes down, "user:2" and "user:3" move to server D (at 600). All other keys stay put.
Virtual Nodes
With only 3 physical servers, the ring is divided into just 3 arcs. By random chance, those arcs can be wildly uneven -- one server might own 60% of the key space while another owns 10%.
The fix: virtual nodes (vnodes)
Instead of placing each physical server at one position on the ring, place it at many positions. Each position is a "virtual node." A physical server with 150 virtual nodes has 150 points scattered around the ring. Keys still walk clockwise to the nearest point -- but now the load is spread much more evenly.
Effect of virtual nodes on distribution
Physical servers: 3, Total keys: 10,000
Vnodes per server Std dev of load Max/min ratio
───────────────────────────────────────────────────────
1 ~40% 5.2x
10 ~12% 1.8x
50 ~5% 1.3x
150 ~2% 1.1x
500 ~1% 1.05x
With 150 virtual nodes per server, each server handles roughly its fair share (33 ± 1%) of the keys. The ring becomes nearly uniform.
The tradeoff: more virtual nodes means more entries in the ring data structure, consuming more memory and making lookups marginally slower. In practice, 100-200 virtual nodes per server is a sweet spot.
The Math: How Many Keys Move?
When a new server is added to a ring of N servers:
Keys moved on node addition
Consistent hashing: on average, K / (N+1) keys move -- only
the keys that now map to the new server. With K = 1,000,000 and N = 3, that's ~250,000 keys.
Modular hashing: on average, K × N / (N+1) keys move.
With the same numbers, that's ~750,000 keys.
As N grows, the advantage becomes more dramatic. Going from 99 to 100 servers: consistent hashing moves ~1% of keys, modular hashing moves ~99%.
Pseudocode
Ring Construction
class ConsistentHashRing:
ring = sorted map (position → server_id)
vnodes_per_server = 150
function add_server(server_id):
for i from 0 to vnodes_per_server - 1:
position = hash(server_id + ":" + i)
ring[position] = server_id
function remove_server(server_id):
for i from 0 to vnodes_per_server - 1:
position = hash(server_id + ":" + i)
ring.delete(position)
Key Lookup
function get_server(key):
if ring is empty: return null
position = hash(key)
// Find the first server position >= key position
server_pos = ring.ceiling(position)
// If we've gone past the end, wrap around to the first entry
if server_pos is null:
server_pos = ring.first()
return ring[server_pos]
Node Addition / Removal
function add_server_and_migrate(new_server_id):
add_server(new_server_id)
// For each key currently stored:
for key in all_keys:
new_owner = get_server(key)
if new_owner != current_owner(key):
migrate(key, from: current_owner, to: new_owner)
function remove_server_and_migrate(server_id):
// First find all keys owned by this server
keys_to_move = get_keys_for_server(server_id)
remove_server(server_id)
// Reassign orphaned keys to their new owners
for key in keys_to_move:
new_owner = get_server(key)
migrate(key, from: server_id, to: new_owner)
Modular Hashing vs Consistent Hashing
| Property | Modular Hashing | Consistent Hashing |
|---|---|---|
| Assignment rule | hash(key) % N |
Walk clockwise on ring |
| Keys moved on add | ~K × N / (N+1) | ~K / (N+1) |
| Keys moved (3→4) | ~75% of keys | ~25% of keys |
| Keys moved (99→100) | ~99% of keys | ~1% of keys |
| Distribution evenness | Perfectly uniform | Nearly uniform (with vnodes) |
| Implementation | Single modulo operation | Sorted ring + binary search |
| Lookup time | O(1) | O(log V) where V = total vnodes |
| Best for | Fixed-size clusters | Elastic, dynamic clusters |
Where Consistent Hashing Is Used
| System | How it uses consistent hashing |
|---|---|
| Amazon DynamoDB | Partitions data across storage nodes; virtual nodes ensure balanced load during scaling |
| Apache Cassandra | Each node owns a range of the token ring; adding nodes splits token ranges automatically |
| Memcached | Client libraries use consistent hashing to route cache keys to servers, minimizing misses during scaling |
| Akamai CDN | Routes web requests to edge servers; consistent hashing was originally developed at Akamai |
| Discord | Distributes guild (server) data across database nodes with consistent hashing for rebalancing |
| Riak | Uses a 160-bit ring partitioned into vnodes to distribute and replicate key-value data |
Key Takeaways
- Modular hashing (
hash % N) reshuffles nearly all keys when N changes -- catastrophic for caches and distributed storage - Consistent hashing arranges the hash space as a ring and assigns each key to the next server clockwise
- Adding or removing a server only affects keys in one arc of the ring -- on average K/(N+1) instead of K×N/(N+1)
- Virtual nodes (multiple ring positions per physical server) fix the uneven distribution problem
- With 150 vnodes per server, load distribution becomes nearly uniform (±2%)
- It's the foundation of DynamoDB, Cassandra, Memcached, Akamai CDN, and many other distributed systems
Try It Yourself -- Consistent Hash Ring
Add and remove servers and keys on the ring. Watch which keys move and compare the distribution to modular hashing.
Key Assignments
Add some servers and keys to get started.
Distribution Comparison
Move Log
No changes yet.
Consistent hashing is one of those algorithms that makes distributed systems possible at scale. Without it, every scaling event would be a catastrophe of cache misses and data migrations. The hash ring is a simple, beautiful idea -- and once you see it, you'll notice it behind nearly every large-scale distributed system.