Consistent hashing maps both keys and servers onto the same circular hash space, and assigns each key to the first server found by walking clockwise. When a server joins or leaves, only the keys on one arc of the circle move, about K/N of them, instead of nearly all of them. It is the placement scheme behind Amazon Dynamo, Cassandra, many distributed caches, CDNs and load balancers.
Think of it like
Bus stops on a ring road
Houses sit along a circular road and each household walks clockwise to the next bus stop. If the city adds a new stop, only the houses between the new stop and the previous one change their stop; everyone else keeps walking to the same place. If a stop closes, only its households walk a little further to the next one. Compare that with renumbering every house's stop whenever the number of stops changes.
The problem with mod-N hashing
The obvious way to spread keys over N servers is server = hash(key) mod N. It balances well and needs no lookup table. It breaks the moment N changes, because almost every key's remainder changes too.
| Key | hash(key) | mod 4 (4 servers) | mod 5 (5 servers) | Moved? |
|---|---|---|---|---|
user:1 | 15 | 3 | 0 | yes |
user:2 | 22 | 2 | 2 | no |
user:3 | 37 | 1 | 2 | yes |
user:4 | 40 | 0 | 0 | no |
user:5 | 53 | 1 | 3 | yes |
user:6 | 66 | 2 | 1 | yes |
user:7 | 71 | 3 | 1 | yes |
user:8 | 84 | 0 | 4 | yes |
Cached keys
100M
spread across 10 cache servers
Add 1 server, mod-N
~90.9M
keys remapped (10/11 of them)
Add 1 server, ring
~9.1M
keys remapped (1/11 of them)
Difference
10×
fewer misses hitting the database
The hash ring
Take the output range of a hash function, for example 0 to 2³² − 1, and bend it into a circle so that the largest value is followed by 0. Hash each server (by name or address) to a point on the circle, and hash each key to a point with the same function. A key belongs to the first server at or after its position, moving clockwise, wrapping past the top if needed.
- 1
Place the servers
Compute
hash("cache-a"),hash("cache-b"), ... and mark each point on the ring. - 2
Hash the key
Compute
hash("user:42")to get the key's position. - 3
Walk clockwise
The first server position greater than or equal to the key's position owns the key (its successor).
- 4
Wrap around
If no server lies after the key, wrap to the server with the smallest position.
For readability, use a ring of size 100. Servers A, B and C hash to positions 10, 40 and 75. Each server owns the arc that ends at its position: A owns (75, 10], B owns (10, 40] and C owns (40, 75].
| Key | Position | Owner | Reason |
|---|---|---|---|
| k1 | 5 | A | First server clockwise from 5 is A at 10 |
| k2 | 25 | B | Next server after 25 is B at 40 |
| k3 | 60 | C | Next server after 60 is C at 75 |
| k4 | 90 | A | Nothing after 90, so wrap around to A at 10 |
Add server D at position 55
- D takes over the arc (40, 55], previously part of C's arc
- Only keys in that arc move, all of them from C to D
- A and B are untouched; k3 at 60 stays on C
Remove server B
- B's arc (10, 40] is absorbed by its successor C
- Only B's keys move (k2 goes to C)
- A's keys stay exactly where they were
Try it in the simulation above: add and remove nodes and notice that only the keys on one arc change color each time.
Why only about K/N keys move
With K keys and N servers placed uniformly, each server owns about 1/N of the ring and so about K/N keys. A new server lands inside one existing arc and takes part of it; in expectation it ends up owning 1/(N+1) of the ring, so about K/(N+1) keys move, all from a single neighbor. Removing a server hands its K/N keys to its successor. This is the minimum possible: any scheme that stays balanced must move at least that many keys to the new server.
Virtual nodes
With only a few servers, random positions are lumpy. For N servers placed at random, the largest arc is expected to be about ln N times the fair share: with 10 servers the unluckiest one owns roughly 29% of the ring instead of 10%. And when a server dies, its entire load lands on a single successor, which may then tip over too.
The fix is to give each physical server many positions, called virtual nodes or tokens: hash "cache-a#0", "cache-a#1", ... "cache-a#99". Each server now owns many small arcs scattered around the ring, and the law of large numbers evens out its total share.
- Balance: the spread of load shrinks roughly like
1/√Vfor V virtual nodes per server: about 10% standard deviation with 100 vnodes, about 3% with 1,000. - Graceful failure: a dead server's many small arcs are absorbed by many different successors, so its load spreads across the cluster instead of doubling one neighbor.
- Heterogeneous capacity: give a server with twice the RAM twice as many vnodes and it receives about twice the keys.
- Cost: the ring has N × V entries to store, gossip and search, and replication must track more, smaller ranges.
Replication on the ring
To store each key on R servers, walk clockwise from the key and take the first R distinct physical servers. This ordered list is the key's preference list. Virtual nodes belonging to a server already chosen are skipped, and production systems also skip nodes in the same rack or availability zone so a single failure cannot take out every replica (Cassandra's NetworkTopologyStrategy).
Implementing the ring
The ring is just a sorted array (or sorted map) of vnode positions, each pointing to its physical server. A lookup is a binary search for the first position at or after the key's hash, with wrap-around to index 0. See the implementations below in Python, TypeScript and Java.
- Use a well-mixed hash (MD5, MurmurHash3, xxHash). Language built-ins such as Python's
hash()are randomized per process and must never be used for placement. - Keep vnode names deterministic (
node#i) so every client builds an identical ring. - Rebuild or copy-on-write the ring when membership changes so readers never see a half-updated structure.
Where consistent hashing is used
| System | How it uses consistent hashing |
|---|---|
| Amazon Dynamo / DynamoDB | The 2007 Dynamo paper popularized the ring with virtual nodes, preference lists, sloppy quorums and hinted handoff. |
| Apache Cassandra, ScyllaDB, Riak | A token ring (Murmur3 partitioner) decides which nodes own each partition key; replicas are the next nodes clockwise, respecting racks and data centers. |
| Discord | Routes each guild (server) to the Elixir node that owns its process with a consistent hash ring, so membership changes move few guilds. |
| CDNs | Karger et al. invented consistent hashing in 1997 to assign URLs to web caches; Akamai was founded on it. Within a cluster, each object maps to a few cache servers so it is not duplicated everywhere. |
| Load balancers | NGINX hash ... consistent (ketama), HAProxy hash-type consistent, Envoy's ring hash and Maglev policies, and Google's Maglev keep connections sticky to backends as the pool changes. |
| Memcached clients | The ketama algorithm (from Last.fm) in client libraries spreads keys across a memcached pool. |
Alternatives
Rendezvous (highest random weight) hashing
For each key, score every server with hash(server, key) and pick the highest score. Removing a server only moves the keys for which it was the winner, and taking the top R scores gives a replica list for free. Balance is excellent without virtual nodes, but each lookup is O(N), which is fine for tens of servers. GitHub's load balancer (GLB) uses a rendezvous variant to build its forwarding tables.
Jump consistent hash
Google's jump hash (Lamping and Veach, 2014) maps a 64-bit key to a bucket number in [0, N) with a few lines of arithmetic, no memory and near-perfect balance, in O(log N) time. The catch: buckets are numbered, and you can only add or remove the last bucket. That suits sharded storage with numbered shards, not a cache pool where any server can fail.
import hashlib
def _h(s: str) -> int:
return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")
def rendezvous(key: str, nodes: list[str]) -> str:
# Highest random weight: every node bids, the highest bid wins.
return max(nodes, key=lambda n: _h(f"{n}:{key}"))
def jump_hash(key: int, num_buckets: int) -> int:
# Lamping & Veach (2014). key is a 64-bit integer.
b, j = -1, 0
while j < num_buckets:
b = j
key = (key * 2862933555777941757 + 1) & 0xFFFFFFFFFFFFFFFF
j = int((b + 1) * ((1 << 31) / ((key >> 33) + 1)))
return b| Scheme | Lookup | Memory | Balance | Remove any node? | Weights |
|---|---|---|---|---|---|
| Ring + virtual nodes | O(log(N·V)) | O(N·V) | Good with enough vnodes | Yes | Vary vnode count |
| Rendezvous (HRW) | O(N) | O(N) | Excellent | Yes | Weighted variants |
| Jump hash | O(log N) | O(1) | Near perfect | No, only the last bucket | No |
| Maglev | O(1) table lookup | O(table size) | Near perfect | Yes, small disruption | Yes |
Complexity
| Operation | Time | Notes |
|---|---|---|
| Lookup a key | O(log(N·V)) | Binary search over N·V sorted vnode positions |
| Add a node | O(V log(N·V)) | Insert V positions into a balanced tree (a sorted array costs O(N·V) per insert) |
| Remove a node | O(V log(N·V)) | Delete its V positions |
| Keys moved per change | O(K/N) | Only the arcs adjacent to the changed node's positions |
| Replica list of size R | O(log(N·V) + walk) | Walk clockwise until R distinct physical nodes are found |
N = physical nodes, V = virtual nodes per physical node, K = keys.
Implementation
A sorted structure of vnode positions plus binary search. `getNodes` returns the preference list of distinct physical nodes for replication.
import bisect
import hashlib
def _hash(key: str) -> int:
"""Map a string to a 64-bit position on the ring."""
return int.from_bytes(hashlib.md5(key.encode()).digest()[:8], "big")
class ConsistentHashRing:
def __init__(self, vnodes: int = 100):
self.vnodes = vnodes
self._ring: list[int] = [] # sorted vnode positions
self._owner: dict[int, str] = {} # position -> physical node
def add_node(self, node: str, weight: int = 1) -> None:
for i in range(self.vnodes * weight):
pos = _hash(f"{node}#{i}")
if pos in self._owner: # astronomically rare collision: skip
continue
bisect.insort(self._ring, pos)
self._owner[pos] = node
def remove_node(self, node: str) -> None:
self._ring = [p for p in self._ring if self._owner[p] != node]
self._owner = {p: n for p, n in self._owner.items() if n != node}
def get_node(self, key: str) -> str:
if not self._ring:
raise LookupError("ring is empty")
idx = bisect.bisect_left(self._ring, _hash(key)) # first position >= hash
if idx == len(self._ring): # wrap around
idx = 0
return self._owner[self._ring[idx]]
def get_nodes(self, key: str, n: int) -> list[str]:
"""Preference list: the next n distinct physical nodes clockwise."""
result: list[str] = []
if not self._ring:
return result
start = bisect.bisect_left(self._ring, _hash(key))
for step in range(len(self._ring)):
node = self._owner[self._ring[(start + step) % len(self._ring)]]
if node not in result:
result.append(node)
if len(result) == n:
break
return result
ring = ConsistentHashRing(vnodes=100)
for name in ["cache-a", "cache-b", "cache-c"]:
ring.add_node(name)
ring.add_node("cache-big", weight=2) # twice the capacity, twice the vnodes
print(ring.get_node("user:42"))
print(ring.get_nodes("user:42", 3)) # three distinct replicasKey takeaways
hash(key) mod Nremaps about N/(N+1) of all keys when one server is added; consistent hashing remaps only about 1/(N+1).- Servers and keys share one circular hash space; a key belongs to the first server clockwise from it.
- Adding or removing a node only affects the arc next to it, so only its neighbors exchange data.
- Virtual nodes smooth out uneven arcs, spread a failed node's load across many peers and support weighted capacity.
- Replicas go to the next R distinct physical nodes clockwise (the preference list), ideally in different racks or zones.
- Rendezvous hashing and jump hash are simpler alternatives with different trade-offs on lookup cost and flexibility.
Common pitfalls
- Using few or no virtual nodes, leaving one server with two or three times its fair share.
- Hashing with a per-process randomized function (Python's
hash(), Java'sObject.hashCodeof mutable objects) so clients disagree on placement. - Counting virtual nodes instead of physical nodes when choosing replicas, putting two copies on one machine.
- Assuming consistent hashing fixes hot keys: one very popular key still lives on one server.
- Forgetting the wrap-around case when the key hashes past the last server position.
Interview tips
- Open with the mod-N failure and a concrete number (10 to 11 servers moves about 91% of keys).
- Draw the ring, place three servers and a few keys, then add a server and show which keys move.
- Mention virtual nodes unprompted, and explain both balance and failure spreading.
- Connect it to replication, quorums and hinted handoff if the conversation is about a key-value store.
Real-world applications
- Partition placement in Dynamo-style databases: Cassandra, ScyllaDB, Riak, DynamoDB.
- Client-side sharding of memcached and Redis caches.
- Sticky routing in load balancers (Maglev, Envoy ring hash, NGINX consistent hash).
- Assigning objects to cache servers inside CDN points of presence.
- Routing actors or sessions to nodes (Discord guilds, Akka cluster sharding).
Test yourself
A cache cluster grows from 10 to 11 servers using hash(key) mod N. About what share of keys now map to a different server?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.