Summary#
Consistent hashing assigns keys to nodes so that adding or removing a node moves only about 1/N of the keys, instead of nearly all of them as with hash(key) mod N. Nodes and keys are hashed onto the same circular space, the hash ring; each key belongs to the first node found clockwise. Virtual nodes (many ring positions per physical node) even out the load and spread a failed node's keys over many survivors. Replication stores each key on the next few distinct nodes clockwise. Alternatives: rendezvous (highest random weight) hashing and jump consistent hash. It is used in Dynamo-style databases (Cassandra, DynamoDB, Riak), distributed caches, CDNs and load balancers.
Why It Exists#
To spread keys over N cache or database nodes, the obvious approach is node = hash(key) mod N. It is fast and even, until N changes. Going from 4 to 5 nodes changes the result for about 80% of keys. For a cache, that means 80% of lookups suddenly miss and hit the database at once, which can take the database down. For a database, it means moving 80% of the data. Nodes join and fail all the time in large clusters, so we need a mapping where changes are local. This page builds on Partitioning and Sharding.
How It Works#
The problem with modulo hashing#
With mod N, a key keeps its node only if hash mod N equals hash mod (N+1). For 4 to 5 nodes, only about 1 in 5 keys stays put:
| Key hash | mod 4 | mod 5 | Moved? |
|---|---|---|---|
| 17 | 1 | 2 | yes |
| 20 | 0 | 0 | no |
| 33 | 1 | 3 | yes |
| 46 | 2 | 1 | yes |
| 58 | 2 | 3 | yes |
In general, going from N to N+1 nodes moves about N/(N+1) of all keys. The ideal is to move only the 1/(N+1) share that the new node should own.
Modulo hashing in depth#
A motivating example. Imagine a ticketing service that has outgrown one database. You split event data across three databases and route with db = hash(event_id) mod 3. Event 1234 hashes to a value whose remainder is 1, so it lives on database 1. Event 5678 lives on database 0, and event 9012 on database 2. The mapping is stateless, takes nanoseconds, and spreads events evenly. Then traffic grows and you add a fourth database. You change the code to mod 4, deploy, and every database's load spikes at once, not just the new one's. Event 1234's hash now has remainder 0 under mod 4, so the router looks for it on database 0, where it does not exist. Almost every event is in the "wrong" place. You must either move most of the data or serve errors and misses until it has moved.
Failures cause the same damage. Removing a node is just as bad as adding one. If database 2 dies and you switch from mod 3 to mod 2 to keep serving, a key keeps its location only if h mod 3 equals h mod 2. Over any run of 6 consecutive hash values, that holds for just two of them, so about two thirds of all keys move. The failure of one machine has turned into a reshuffle of the entire dataset, at the moment when the cluster is already short of capacity.
What it costs a cache. The damage is easiest to see with a cache. Suppose 10 cache nodes serve 1,000,000 reads per second with a 95% hit rate, so the database behind them sees 50,000 reads per second. Add an eleventh node with mod N and about 10/11, or 91%, of keys now map to a different node, where they are not cached. For the next few minutes the hit rate collapses toward 9%, and the database receives roughly 900,000 reads per second, 18 times its normal load. Few databases survive that, and the outage that follows is far worse than the capacity shortage that prompted the change. With consistent hashing, only the roughly 9% of keys that the new node takes over miss, and the database sees an extra 90,000 reads per second for a short time. That is a bump, not a stampede.
The properties we want. The 1997 paper that introduced consistent hashing (Karger, Lehman, Leighton, Panigrahy, Levine and Lewin, "Consistent Hashing and Random Trees", STOC 1997) framed the goal as a few properties of a mapping from items to buckets, where the set of buckets each client knows about may differ:
- Balance: each bucket gets about the same share of items.
- Monotonicity: when buckets are added, items move only to the new buckets, never between old ones.
- Spread: even if clients see slightly different sets of buckets, any one item is mapped to only a few distinct buckets across all clients.
- Load: no bucket is assigned too many items across all those differing views.
Modulo hashing has balance but fails monotonicity badly. The hash ring satisfies all four with high probability, which is why it became the default for caches and leaderless databases.
Choosing the hash function. Every consistent hashing scheme rests on a hash that is uniform, fast and identical in every client. Common choices are MurmurHash3 (Cassandra's default Murmur3Partitioner), xxHash, CRC16 (Redis Cluster, which takes CRC16 of the key modulo 16,384) and MD5 (the original ketama Memcached client). Cryptographic strength is unnecessary. What matters is uniformity, speed and determinism. Two traps catch teams in practice. The first is a language's built-in hash: Java's String.hashCode is poorly mixed for similar strings, and Python randomises hash() for strings per process unless PYTHONHASHSEED is fixed. Two Python services using hash(key) would therefore route the same key to different nodes. The second is changing the hash function or its seed during an upgrade, which silently remaps everything. Pin the algorithm and seed in a shared library, and test it across languages with known vectors.
The hash ring#
Map the hash output (say 0 to 2^32 - 1) onto a circle. Hash each node (by name or IP) to a position on the circle, and hash each key too. A key is owned by the first node clockwise from its position.
Worked example: adding a node. Ring positions run 0-9,999. Nodes A, B and C sit at 2,000, 5,000 and 8,000. A owns keys in (8,000, 2,000] (wrapping), B owns (2,000, 5,000], C owns (5,000, 8,000]. Now add D at 3,500:
- Keys in (2,000, 3,500] move from B to D.
- Keys in (3,500, 5,000] stay on B.
- A and C are untouched.
Only the range D took over moves, about a quarter of the keys with four evenly spaced nodes. Removing a node is the reverse: its keys move to the next node clockwise, and no other key moves.
Lookup is a binary search over the sorted node positions: O(log P) for P positions, microseconds even with thousands of positions.
The hash ring in depth#
A small ring, step by step. Use a toy ring with 100 positions, 0 to 99, and four databases placed at 0, 25, 50 and 75. A key that hashes to 37 walks clockwise and meets the database at 50 first, so it lives there. The database at 25 owns positions 1 to 25, the one at 50 owns 26 to 50, the one at 75 owns 51 to 75, and the one at 0 owns 76 to 99 plus 0 itself, because the ring wraps.
Adding a node. Place a fifth database at 90. Keys at 76 to 90 used to walk clockwise to DB1 at 0. Now they stop at 90. That is 15 of DB1's 25 positions, or 60% of DB1's data, and 15% of the whole dataset. Nothing else moves. Compare that with mod 4 to mod 5, which would move about 80% of everything. Removing a node works the same way in reverse. If DB2 at 25 fails, its range 1 to 25 falls to the next node clockwise, DB3 at 50, and everything else stays put. The catch is that DB3 now owns 50 positions while DB1 and DB4 own 25 each, so DB3 carries double load. Fixing that unevenness is the job of virtual nodes, described in the next section.
A real ring. Production rings use the full output of the hash: 0 to 2^32 - 1 for a 32-bit hash, or, in Cassandra's Murmur3 partitioner, the signed 64-bit range from -2^63 to 2^63 - 1. Node positions are called tokens, and each node owns the range ending at its token, written (previous token, my token]. Lookups use a sorted array of tokens and binary search, or a sorted map with a "ceiling" operation (Java's TreeMap.ceilingEntry, Go's sort.Search). With 1,000 nodes and 256 tokens each, the table has 256,000 entries, about 4 MB with node references. A lookup takes about 18 comparisons, well under a microsecond.
// Minimal ring lookup; tokens sorted ascending, owners aligned by index
function lookup(tokens: bigint[], owners: string[], keyHash: bigint): string {
let lo = 0, hi = tokens.length; // first token >= keyHash
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (tokens[mid] >= keyHash) hi = mid; else lo = mid + 1;
}
return owners[lo === tokens.length ? 0 : lo]; // wrap past the top
}Who knows the ring? Every client and node must agree on membership, or the same key goes to different places. There are two broad approaches. Centralised membership keeps the ring in a strongly consistent store such as ZooKeeper or etcd, versioned so that changes are atomic, and clients watch it for updates. Chat-server routers, many cache client libraries and Envoy's control plane work this way. Gossip-based membership, used by Cassandra, Riak and Dynamo, has each node periodically exchange its view with random peers, so changes reach everyone within seconds (see Failure Detection and Gossip). Gossip has no single point of failure, but views are briefly inconsistent. Leaderless systems tolerate that with mechanisms such as quorums, hinted handoff and read repair, so that a write sent to a slightly wrong set of replicas is still found later.
Membership versus liveness. A crucial distinction in Dynamo-style systems is that a node failing is not the same as a node leaving. If every short outage changed the ring, a 30-second network blip would trigger terabytes of streaming and then stream it all back. Dynamo and Cassandra therefore change ring membership only through explicit operator action (join, decommission, replace). Temporary failures are handled by routing around the down node and storing hints for it. A cache cluster can make the opposite choice and remove a dead node from the ring immediately, because "moving" cache data costs only some misses.
Virtual nodes#
With one position per node, the ring is uneven: random positions leave some nodes owning arcs several times larger than others. And when a node fails, its whole arc lands on one neighbour, which may then overload.
Virtual nodes (vnodes) fix both: each physical node takes many positions, such as A#0, A#1 ... A#255. With 100-256 vnodes per node, each node's total share is close to average (the standard deviation shrinks as vnodes grow). When a node fails, its many small arcs are spread across most of the other nodes. Vnodes also support heterogeneous hardware: a server with twice the capacity gets twice as many vnodes.
The cost is a bigger ring table (nodes × vnodes entries) and more, smaller ranges to track during repair and streaming.
ring = sorted list of (position, physical_node)
for node in nodes:
for i in 0 .. vnodes(node) - 1: # e.g. 128, scaled by capacity
ring.insert((hash(node.id + "#" + i), node))
lookup(key):
p = hash(key)
i = first index in ring with position >= p # binary search
if i == len(ring): i = 0 # wrap around
return ring[i].nodeVirtual nodes in depth#
How they spread a failure. Give each database several positions by hashing variations of its name: DB1-vn1, DB1-vn2, DB1-vn3 and so on. These land at scattered points, so the virtual nodes of all databases interleave around the ring. Now when DB2 fails, each of its small arcs falls to whichever virtual node comes next clockwise. The range of DB2-vn1 might go to DB1, that of DB2-vn2 to DB3, and that of DB2-vn3 to DB4. Instead of one neighbour doubling its load, every survivor takes a small, roughly equal share. With N nodes, each survivor's load rises by about 1/(N-1), which is 33% with 4 nodes and about 1% with 100.
How they spread a join. The same applies in reverse. A new node with one token takes load from only its clockwise neighbour, which helps that one node and nobody else. A new node with 128 tokens takes a sliver from almost every existing node, so the whole cluster gets lighter at once. In a database, that also means the new node can stream data in parallel from many peers during bootstrap, rather than reading everything from one neighbour whose disk and network become the bottleneck. Bootstrapping 2 TB from one peer at 200 MB/s takes about 3 hours. Pulling from 20 peers in parallel is limited by the new node's own disk and network, and is often several times faster.
How many? The arcs owned by one random token vary wildly. Their lengths behave like exponential random variables, so the largest of N arcs is about ln N times the average. With V tokens per node, a node's share is the sum of V such arcs, and its relative standard deviation falls roughly as 1/sqrt(V). For V = 16, that is about 25%. For V = 256 it is about 6%. Cassandra used 256 tokens per node by default for many years. Version 4.0 lowered the default to 16 and paired it with a token allocation algorithm (allocate_tokens_for_local_replication_factor) that chooses each new node's tokens deliberately, to balance ownership for the actual replication factor rather than relying on randomness. Sixteen well-placed tokens can then balance as well as hundreds of random ones.
Why not use thousands? More virtual nodes are not free. Each is a separate token range that must be tracked, repaired and streamed. Anti-entropy repair builds a Merkle tree per range, so 256 ranges per node means 256 trees to compare. There is a subtler availability cost too. With RF = 3 and many vnodes, almost every pair of nodes shares some range as replicas. If any two nodes are down at once, some ranges lose two of their three copies, so quorum reads and writes fail for those keys. With few tokens per node, most node pairs share no range, so a double failure is more likely to be harmless. Fewer, carefully placed tokens therefore improve both operational cost and availability under multiple failures, which was part of the reasoning behind Cassandra's change.
Weights. Virtual nodes give an easy way to handle mixed hardware. A server with twice the RAM or disk gets twice as many tokens and therefore about twice the share of keys. The same trick lets an operator drain a node gradually by lowering its weight, rather than removing it all at once.
Fixed partitions as an alternative. Some systems keep the ring idea but fix the number of slices. Riak divides the ring into a fixed number of equal partitions (64 by default, set at cluster creation) and assigns partitions to nodes. The Dynamo paper itself reports that this kind of scheme, with equal-sized partitions and tokens no longer tied to partition boundaries, gave the best balance and simplest bookkeeping of the strategies Amazon tried. Redis Cluster's 16,384 hash slots are the same idea with a different name. The trade-off is explicit: fixed slices make membership changes simple to plan and stream, but the slice count must be chosen up front. Kleppmann's Designing Data-Intensive Applications points out that the phrase "consistent hashing" is often applied loosely to these schemes. What they share is the goal of moving little data when membership changes, not the exact ring algorithm.
Keys versus traffic. Virtual nodes even out how many keys each node owns. They do nothing about how much traffic each key gets. If a ticketing system's hottest event, say a stadium tour going on sale, draws 100 times the reads of any other, its node is hot no matter how perfectly the keys are spread. That is the difference between structural imbalance (uneven key ownership, fixed by virtual nodes or token allocation) and workload imbalance (uneven popularity), which needs other tools:
- Read replicas for hot keys: replicate popular keys to several nodes and balance reads across them. This is the most common fix and comes for free in replicated stores if clients read from any replica.
- Key salting: write the hot key under several suffixed names (
event-42#0toevent-42#9) that hash to different nodes. Readers fan out and combine the results. - Adaptive rebalancing: monitor load and move or split specific ranges away from overloaded nodes. It is operationally complex to build, but managed services such as DynamoDB do it automatically.
- Bounded loads: cap each node's share and overflow keys to the next node, as described in the Deep Dive below.
Replication on the ring#
To store each key on R nodes, walk clockwise from the key and pick the first R distinct physical nodes (skipping vnodes that belong to a node already chosen). This list is the key's preference list in Dynamo terms. Placement can also be rack- or zone-aware: skip nodes in a rack or zone already used, so the R copies survive a whole rack or zone failure. Cassandra's NetworkTopologyStrategy does this per data centre. Adding a node then changes the replica sets only for the ranges it joins. See Quorums and Leaderless Replication.
Replication and data movement in depth#
Preference lists, concretely. With RF = 3 and nodes A to F holding interleaved virtual nodes, a key's replicas are found by walking clockwise from its hash and collecting the first three distinct physical nodes. Suppose the walk meets C#12, C#40 (skipped, because C is already chosen), A#7 and E#3. The preference list is then C, A, E. Dynamo adds a few extra nodes after these, so that if C is down, a write can be accepted by the fourth node in the list and handed back to C later. This is the sloppy quorum with hinted handoff. Zone awareness adds one more rule: also skip nodes whose zone already holds a copy. That way the three copies sit in three availability zones and survive the loss of a whole zone. Cassandra's NetworkTopologyStrategy applies this per data centre, with a separate replication factor for each data centre, such as {'us-east': 3, 'eu-west': 3}. Its older SimpleStrategy just takes the next RF nodes, which is acceptable only for single-zone test clusters.
Failures usually move no data. Consistent hashing tells you where data should live, but it does not teleport terabytes when a node dies. In a replicated store, a crashed node's keys already exist on other replicas, so the system keeps serving and no data moves at all:
- In Cassandra, each range lives on RF consecutive distinct nodes. If one is down, reads and writes at
QUORUMsucceed from the other two, coordinators store hints for the missed writes, and the node catches up from those hints, plus repair, when it returns. - In DynamoDB, each partition is replicated across three availability zones, and one replica acts as leader for writes. The 2022 USENIX ATC paper on DynamoDB describes the replicas as a Multi-Paxos group. If the leader fails, another replica is elected, and service continues without copying anything.
Data moves only during planned membership changes: adding capacity, decommissioning a node, or replacing a dead machine permanently to restore the replication factor. Even then, consistent hashing bounds the movement to the ranges that change owners, roughly 1/N of the data per node added or removed, not the whole dataset.
What happens when a node joins. The interesting part of a join is keeping the system correct while data is in flight:
While N is joining, its future ranges are pending. Coordinators send writes for those ranges to both the old owners and N, so nothing written during streaming is lost. Reads keep going to the old owners until N has all the data. Once streaming completes, N switches to normal and takes reads too. The old owners still hold copies of the moved data until an operator runs cleanup (nodetool cleanup in Cassandra). That is deliberately manual, so an aborted join does not leave data missing.
Removing a node. Removal is the mirror image. During decommission, the leaving node streams its ranges to the nodes that will inherit them before it goes away. If a node is simply dead and will not return, removenode (or replacing it with a new machine that takes over its tokens) rebuilds its data from the surviving replicas. That is slower, and it reduces redundancy until the rebuild finishes, so replacing a dead node promptly matters.
Caches are different. In a cache cluster there is no streaming. When a node joins, keys in its ranges simply miss and are refilled from the database. When a node leaves, its keys are lost and refilled elsewhere on demand. The cost is a temporary miss rate of about 1/N. To soften it, clients can warm the new node by reading from the old owner on a miss before falling back to the database, or add nodes during low-traffic periods.
Rendezvous hashing#
Rendezvous hashing (highest random weight, HRW) needs no ring. For each key, compute a score for every node, score = hash(key, node), and pick the node with the highest score (or the top R for replicas). When a node leaves, only keys for which it scored highest move, each to its own second-best node, so load spreads evenly without virtual nodes. When a node joins, it takes only the keys for which it now scores highest.
Lookup costs O(N) per key (one hash per node), fine for tens or hundreds of nodes, and weighting by capacity is easy. It is used in some load balancers and caches, and in systems that pick a few servers among a modest set.
Rendezvous hashing in depth#
Origin and idea. Rendezvous hashing was introduced by David Thaler and Chinya Ravishankar, who published it in IEEE/ACM Transactions on Networking in 1998 as a way for web proxies to agree on which proxy should cache each URL. Every client independently computes, for each candidate server, a pseudo-random score from the pair (key, server) and picks the server with the highest score. Clients that know the same server list therefore "meet" at the same server for each key without any coordination. Microsoft's Cache Array Routing Protocol (CARP) for proxy arrays used this highest-random-weight approach, and Apache Ignite's default affinity function for distributing cache partitions is named RendezvousAffinityFunction.
Why it moves so little. For each key, the scores define a ranking of all servers. Removing server S affects only the keys for which S ranked first. Each of those moves to its own second-ranked server, which is a uniformly random survivor, so S's load spreads evenly across all the others without any virtual nodes. Adding server T affects only keys for which T now ranks first, about 1/(N+1) of them, and each comes from whichever server previously held it. Every key's movement is minimal, and the balance is as good as the hash.
// Rendezvous (HRW) hashing with optional weights
function pickNode(key: string, nodes: { id: string; weight: number }[]): string {
let best = "", bestScore = -Infinity;
for (const n of nodes) {
const h = hash64ToUnitInterval(key + "|" + n.id); // uniform in (0, 1)
const score = -n.weight / Math.log(h); // weighted HRW score
if (score > bestScore) { bestScore = score; best = n.id; }
}
return best;
}
// For R replicas: sort nodes by score and take the top R.Weights done right. A naive weighting such as weight * hash does not give proportional shares. The standard formula is score = -weight / ln(h), where h is the hash mapped to the interval (0, 1). With it, a node of weight 2 wins exactly twice as often as a node of weight 1, and changing one node's weight moves only the keys that should move. This logarithmic method is the usual way to run weighted rendezvous hashing.
Replicas. Taking the top R scores gives R distinct servers directly, with no "skip duplicate vnodes" logic. When one of a key's R servers fails, the next-ranked server joins its replica set and the rest stay the same. To make replication zone-aware, pick the highest-scoring server in each of R different zones.
The cost and how to cut it. A lookup computes N hashes, so it costs O(N). At 50 servers and 20 nanoseconds per hash, that is about 1 microsecond, which is negligible for a proxy picking a backend. At 10,000 servers and millions of lookups per second it becomes significant. Two remedies exist. Cache the decision per key, or per hash bucket. Or use hierarchical (skeleton-based) rendezvous: arrange servers in a tree of groups, run rendezvous among the groups at each level, then among the servers in the chosen group. That brings the cost to about O(log N) while keeping most of the stability.
When to prefer it over a ring. Rendezvous is simpler to implement correctly, with no sorted structure to maintain, and it gives naturally even failover and easy weighting. That makes it a good choice for tens to hundreds of servers, for choosing R replicas, and for situations where many clients must agree on placement with minimal shared state, such as picking which of several workers owns a job or which cache node holds an object. Rings with virtual nodes remain the better fit when the node count is large and lookups are extremely hot, or when the system already works in terms of contiguous token ranges, as Cassandra's repair and streaming do.
Jump consistent hash (briefly)#
Jump consistent hash (Lamping and Veach, Google, 2014) maps a key to one of N numbered buckets with a short loop, no ring and no memory, in O(log N) time. Moving from N to N+1 buckets moves exactly the ideal 1/(N+1) fraction of keys. The limitation: buckets are numbered 0..N-1, so you can only add or remove at the end; it does not handle an arbitrary node failing in the middle. It suits mapping keys to shard numbers when shards are themselves replicated and never disappear.
Jump hash and other algorithms in depth#
How jump consistent hash works. John Lamping and Eric Veach described jump consistent hash in a 2014 paper from Google, "A Fast, Minimal Memory, Consistent Hash Algorithm". The key idea is to imagine growing the number of buckets one at a time, from 1 to N. When the count goes from j to j+1, a key should move to the new bucket with probability exactly 1/(j+1), which is the minimal movement. Simulating every step would take O(N). Instead, the algorithm uses the key as the seed of a pseudo-random generator and computes directly where the key next jumps, skipping all the steps in between. The expected number of jumps is about ln N, so the cost is O(log N). The whole algorithm fits in a few lines:
// Jump consistent hash (Lamping and Veach, 2014); key as 64-bit unsigned
function jumpHash(key: bigint, numBuckets: number): number {
let b = -1n, j = 0n;
const mask = (1n << 64n) - 1n;
while (j < BigInt(numBuckets)) {
b = j;
key = (key * 2862933555777941757n + 1n) & mask; // 64-bit LCG step
j = BigInt(Math.floor(Number(b + 1n) * (2 ** 31 / Number((key >> 33n) + 1n))));
}
return Number(b);
}It uses no memory beyond a few integers, and its balance is essentially perfect, with no variance from random token positions. The price is the one already noted: buckets are numbered 0 to N-1, and you can only add or remove bucket N-1. That fits a design where the "buckets" are logical shards, each itself a replicated group that never disappears. Jump hash picks the shard, and a separate layer maps shards to machines and handles failures. It does not fit a flat pool of cache servers where any one can die.
Maglev hashing. Google's Maglev load balancer (Eisenbud et al., NSDI 2016) needed to pick a backend for every packet at line rate, with even load and little disruption when backends change. Its answer is a precomputed lookup table of prime size M (the paper uses 65,537 in examples). Each backend derives an offset and a skip from two hashes of its name, which define its own permutation of the table slots. Backends then take turns claiming their next preferred empty slot until the table is full. Every backend ends up with almost exactly M/N slots, so balance is near perfect, and a packet's backend is just table[hash(5-tuple) mod M], a single memory read. When a backend is removed, most slots keep their owner, though not quite as few move as with a ring. Maglev accepts slightly more disruption in exchange for much better balance and constant-time lookup. To keep established connections stable anyway, it also keeps a connection-tracking table. Envoy offers a MAGLEV load-balancing policy built on the same idea.
Multi-probe consistent hashing. Ben Appleton and Michael O'Reilly (Google, 2015) proposed hashing each key several times instead of giving each node many positions. A node has one point on the ring, and the key is assigned to the closest node over, for example, 21 probes. This gives balance comparable to many virtual nodes with only N ring entries, at the cost of more hashing per lookup.
Choosing among them. The decision usually reduces to a few questions:
- Must any node be removable at any time? Then use the ring with virtual nodes, rendezvous or Maglev, not jump hash.
- Are lookups so hot that every nanosecond counts? Maglev's table or jump hash.
- Is the node count small, with weights and replicas needed? Rendezvous.
- Do you want explicit control of what moves? Fixed slots or logical shards with a map.
Comparison#
| Modulo | Ring + vnodes | Rendezvous | Jump hash | |
|---|---|---|---|---|
| Keys moved on change | ~all | ~1/N | ~1/N | exactly 1/N |
| Lookup cost | O(1) | O(log P) | O(N) | O(log N) |
| Memory | None | Ring table | Node list | None |
| Arbitrary node removal | Bad | Yes | Yes | Only last bucket |
| Weighted nodes | No | vnode counts | Weighted scores | No |
Where it is used#
- Dynamo-style databases: Amazon's Dynamo paper (2007) popularised the ring with virtual nodes and preference lists. Cassandra places token ranges on a ring with vnodes; Riak used a ring of fixed partitions.
- Distributed caches: Memcached clients such as ketama use consistent hashing so adding a cache server does not invalidate most of the cache. See Distributed Caching.
- CDNs: the original consistent hashing paper (Karger et al., 1997) came from work on web caching that led to Akamai; CDNs still map URLs to cache servers within a site this way, so each object is cached on few servers.
- Load balancers: hashing on a client or connection key keeps sessions sticky to backends even as the pool changes. Maglev (Google's software load balancer) uses its own consistent hashing table; HAProxy and Envoy offer ring hash and Maglev balancing. See Load Balancing.
Redis Cluster takes a related approach: 16,384 fixed hash slots assigned to nodes; moving slots moves only their keys.
Real-world uses in depth#
Memcached clients. Memcached servers know nothing about each other, so all distribution happens in the client. The ketama algorithm, first published by Last.fm in 2007, became the de facto standard. Each server gets about 160 points on a 32-bit ring, derived from MD5 hashes of strings like "10.0.0.5:11211-0". Keys go to the next point clockwise. Because every client library that implements ketama the same way produces the same mapping, a PHP front end and a Java back end share cache entries correctly. The same idea appears in nginx's hash $request_uri consistent; upstream directive, which uses a ketama-compatible ring to pin each URL to one upstream cache, and in Twemproxy (nutcracker) for Redis and Memcached pools.
Fixed hash slots: Redis Cluster. Redis Cluster deliberately does not use a ring. It computes CRC16(key) mod 16384 to pick one of 16,384 hash slots and assigns ranges of slots to primaries. To rebalance, an operator or tool migrates individual slots, and only that slot's keys move. Keys can be forced into the same slot with a hash tag: only the part inside braces is hashed, so user:{42}:profile and user:{42}:cart share a slot and can be used together in multi-key commands and transactions. Compared with a ring, the slot map is explicit and small (16,384 entries), and moves are easy to reason about. The cost is that rebalancing needs coordination: someone must decide which slots move where, and clients must follow MOVED redirects while it happens. Choosing between a ring and fixed slots is a genuine design trade-off worth naming in an interview.
Databases. Cassandra and ScyllaDB use the token ring directly, with virtual nodes. ScyllaDB has since moved to "tablets", smaller units of data that can be moved and split independently, which is another step toward fixed or dynamic partitions over raw tokens. DynamoDB uses hash partitioning of the partition key under the hood. Partitions are split as they grow and placed by the service, so users never see a ring. Riak used a ring of fixed partitions. The Dynamo paper (DeCandia et al., SOSP 2007) is the reference point for all of these: it combined consistent hashing with virtual nodes, preference lists, sloppy quorums, hinted handoff and Merkle-tree anti-entropy into one design.
CDNs and web caches. The original consistent hashing work at MIT grew out of the problem of spreading web content across many caches without every cache needing to know every other's state, and it led to the founding of Akamai. Inside a CDN point of presence, a request for a URL is hashed to pick which of dozens of servers caches that object. Each object is then stored once or twice per site rather than on every server, which multiplies effective cache capacity, and adding a server disturbs only its share of objects.
Load balancers. When a backend keeps per-client state, such as a local cache, a WebSocket session or an in-memory shopping cart, hashing on a client key gives stickiness that survives pool changes. Envoy supports RING_HASH and MAGLEV policies. HAProxy offers hash-type consistent, along with a hash-balance-factor setting that implements bounded loads. nginx supports consistent hash. Google's Maglev and similar L4 balancers use consistent hashing so that a balancer added or lost mid-flow still sends a connection's packets to the same backend.
Chat and connection routing. A WhatsApp-style chat system must deliver a message to whichever server holds the recipient's live connection. One design assigns users to chat servers by consistent hashing of user ID. A registry in ZooKeeper or etcd records the servers and which segments of the hash space each owns. A client connects to the server that owns its user ID, and a server delivering a message computes the recipient's owner and forwards the message there directly, with no lookup table of connections. The design works, but it raises problems you must address:
- Every chat server must be able to reach every other, so the cluster wants fewer, larger servers rather than many small ones.
- Adding servers moves ownership of some users. Those users must be disconnected and reconnect to their new owner. If that is done all at once, it causes a thundering herd of reconnects, so drain gradually with jittered reconnect delays.
- During the move, a message might be routed to the old owner while the user is mid-reconnect. Sending events to both old and new owners for a short window, or buffering undelivered messages, prevents loss.
An alternative is a pub/sub layer (Redis pub/sub or a message broker) where each server subscribes to the users it currently holds. That decouples connection placement from routing, at the cost of an extra hop. See Real-time Updates.
Stateful services in general. Any service that benefits from affinity, such as a per-user rate limiter, a per-document collaboration server or a per-tenant aggregator, can use consistent hashing so that one instance owns each key and keeps its state in memory. Ownership changes when instances scale. That needs a hand-off protocol (drain, transfer state, or rebuild it from a durable log), and this is where most of the real engineering effort goes.
A worked design: sharding a cache tier#
Requirements. A product catalogue serves 2,000,000 reads per second at peak with a p99 target of 5 ms. The hot working set is about 1 TB. The source of truth is a PostgreSQL cluster that can absorb at most about 100,000 reads per second. So the cache must keep a hit rate above 95% at all times, including while nodes are being added or replaced.
Sizing. With 64 GB of usable memory per cache node, 1 TB needs 16 nodes. Allowing 25% headroom for growth and for the loss of a node gives 20 nodes. Each serves about 100,000 reads per second, which is comfortable for Redis or Memcached on modern hardware.
Placement. Each node gets 128 virtual nodes on a 64-bit ring built from xxHash of "host:port#i". From the 1/sqrt(V) rule, the busiest node owns about 9% more keys than average, which the headroom covers. The ring lives in etcd as a single versioned document. A shared client library, the same in Go, Java and TypeScript and tested against common hash vectors, watches it. Every client therefore applies a change within about a second of it being written.
Adding a node. Going from 20 to 21 nodes moves about 1/21, or 4.8%, of keys. Those keys miss once, adding roughly 2,000,000 × 0.048 = 96,000 reads per second to the database for the time it takes to refill them, typically tens of seconds for hot keys. That is close to the database's limit, so two refinements keep it safe. First, the new node's virtual nodes are activated in four steps of 32 a few minutes apart, so each step causes only about 24,000 extra database reads per second. Second, on a miss the client first asks the key's previous owner, which still holds the value, before falling back to the database. Nearly all of the movement is then absorbed by the cache tier itself.
Losing a node. If cache-14 dies, its 5% of keys spread over the 19 survivors, each taking on about 0.26% of the total key space, roughly 5% more than it held before. The misses mostly reach the database, adding about 100,000 reads per second at peak. That is at the edge of its capacity, so the cache client protects it with request coalescing: only one in-flight database read per key at a time, with other callers waiting for that result. Because hot keys are requested many times per second, coalescing removes most of the duplicate load. The dead node is removed from the ring after a 10-second confirmation window, rather than on the first failed health check, so a brief network blip does not cause a reshuffle. Either way, a replacement node takes over the old node's virtual nodes, so when it returns, only that range refills.
Hot keys. A flash sale makes one product page 3% of all reads, or 60,000 reads per second for one key. On top of its normal 100,000, that would push the owning node to 160% of its usual load. Clients sample 1% of requests and report the top keys. A key above 0.5% of traffic is marked "replicated" in the ring document. Clients then write it to its owner and the next two distinct nodes clockwise, and spread reads randomly across the three. As a second layer, the hottest few hundred keys are also held for 1-2 seconds in each app server's in-process cache, which absorbs the rest.
What this shows. Consistent hashing did the core job of keeping movement proportional to change. Almost everything else in the design is about the traffic consequences of movement: staged activation, reading from the previous owner, coalescing, careful failure detection and hot-key replication. In production, that is where most of the engineering effort lies.
When to Use It#
- Distributing keys across a changing set of cache or storage nodes.
- Client-side sharding of caches (Memcached, Redis without Cluster).
- Sticky load balancing where sessions or caches benefit from affinity.
- Leaderless databases that place replicas without a central directory.
When NOT to Use It#
- Small, fixed sets of shards: a lookup table of logical shards is simpler and easier to reason about.
- When you need range scans by key: hashing destroys order; use range partitioning.
- When a central directory already exists (a coordinator assigns partitions, as in Kafka), extra hashing adds nothing.
How to Implement It#
- Use a good, fast hash (MurmurHash3, xxHash); it need not be cryptographic, but it must be uniform.
- Choose vnodes per node (64-256), scaled by node capacity.
- Store the ring membership in a consistent store or spread it via gossip; all clients must agree.
- For replication, pick the next R distinct physical nodes, rack- or zone-aware.
- On membership change, stream only the affected ranges; for caches, accept misses for the moved keys.
- Monitor per-node load; consistent hashing balances keys, not traffic: hot keys still need caching or splitting.
| Technology | Fits when |
|---|---|
| Cassandra, ScyllaDB (token ring with vnodes) | Leaderless database partitioning |
| ketama-style Memcached clients | Client-side cache sharding |
| Envoy / HAProxy ring hash, Maglev | Consistent load balancing |
| Redis Cluster hash slots | Fixed-slot alternative for Redis |
Trade-offs#
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| Ring, few positions | Simple | Uneven load; failover onto one neighbour | Rarely; prefer vnodes |
| Ring + vnodes | Even load, spread failover, weights | Larger metadata, more ranges | General purpose |
| Rendezvous | No ring, even spread, easy weights | O(N) lookup | Tens to hundreds of nodes |
| Jump hash | No memory, perfect balance | Only grow or shrink at the end | Numbered, replicated shards |
| Fixed slots / logical shards | Explicit, easy to move | Need slot map management | Databases and Redis Cluster |
| Maglev table | Near-perfect balance, O(1) lookup | More disruption on change, table rebuild | High-rate L4 load balancing |
| Bounded loads | Caps hot-node load at a set factor | Some keys leave their natural owner | Caches and balancers with skewed traffic |
| Gossip membership | No central dependency | Briefly inconsistent views | Leaderless databases with quorums and repair |
| Central membership (etcd) | One agreed ring version | Extra dependency to run and watch | Caches, chat routing, stateful services |
Common Pitfalls#
- Using
mod Nfor caches and causing a stampede to the database when a node is added. - Too few virtual nodes, leaving some nodes with twice the average load.
- Clients disagreeing on ring membership, so the same key goes to different nodes.
- Forgetting that consistent hashing does not fix hot keys.
- Hashing with a language's default or randomised hash, so different services route the same key differently.
- Treating every transient node failure as a membership change and streaming data back and forth.
- Assuming more virtual nodes is always better, ignoring repair cost and multi-failure availability.
- Moving chat or session ownership all at once and causing a reconnect thundering herd.
Real-World Examples#
Amazon's Dynamo paper describes partitioning with consistent hashing and virtual nodes, and replicating each key to the next N nodes on the ring.
Google's Maglev paper (2016) describes a consistent hashing scheme designed for software load balancers, giving even load and minimal disruption when backends change.
Cassandra 4.0 changed its default from 256 random tokens per node to 16 tokens chosen by an allocation algorithm, citing better balance, cheaper repair and better availability when several nodes fail. Vimeo described adding consistent hashing with bounded loads to HAProxy so that popular videos no longer overloaded single cache servers.
In the Interview#
Handling consistent hashing in an interview#
Know when to go deep. In most product-design interviews (a feed, a booking system, a URL shortener), you will use DynamoDB, Cassandra, Redis Cluster or a managed cache that already distributes data for you. One sentence is enough: "DynamoDB hash-partitions by event_id and rebalances itself" or "the cache tier uses consistent hashing, so adding a node moves only about 1/N of keys". Spending ten minutes drawing a ring there wastes time the interviewer wanted spent on the product's hard parts.
When it is the main topic. Infrastructure interviews are different. "Design a distributed cache", "design a key-value store" and "design a message broker" all expect you to build the distribution layer yourself. Be ready to explain, in order:
- Why not modulo: changing N remaps nearly every key, with a worked number such as 10 to 11 nodes moving about 91% of keys.
- The ring: keys go to the first node clockwise, and a join or leave affects only the neighbouring range.
- Virtual nodes: they give even ownership, spread failover and allow weighting, at the cost of more ranges to track.
- Failures versus membership changes: replicas serve while a node is down, and data streams only on planned changes, bounded to the affected ranges.
- Hot spots: virtual nodes fix structural imbalance, while replication, salting or bounded loads fix workload imbalance.
- Replication on the ring: the next R distinct nodes, spread across zones.
A strong answer sounds like this: "Each cache node gets 128 virtual nodes on a 64-bit Murmur3 ring, with membership in etcd. Clients cache the ring and watch for changes. Adding one node to 20 moves about 5% of keys, so the database sees a brief 5% miss bump instead of a stampede. Hot keys such as a trending event are detected from client-side sampling and replicated to three nodes, with reads spread between them."
Red flags to avoid: claiming consistent hashing balances traffic; forgetting that every client must see the same membership; and proposing to remove a node from the ring on every transient failure, which causes needless data movement.
Deep Dive: Load balance maths and bounded loadsShow
Imbalance with few positions. With one random position per node, the largest arc is expected to be about ln(N) times the average: with 100 nodes, the busiest owns roughly 4-5x average. With V vnodes per node, the spread narrows roughly as 1/√V; 100-200 vnodes gets most nodes within about ±10% of average.
Consistent hashing with bounded loads. A variant (Mirrokni, Thorup and Zadimoghaddam, Google, 2016) caps each node at, for example, 1.25x average load; if the natural owner is full, the key goes to the next node clockwise. This protects against skew while keeping most of the stability. Google described using it in Cloud Pub/Sub, and HAProxy supports a bounded-load option.
Fixed partitions vs moving tokens. Riak and Redis Cluster split the space into a fixed number of partitions and move whole partitions between nodes. This makes membership changes explicit and simpler to stream than recomputing token ranges, at the cost of choosing the partition count up front.
Deep Dive: Why only 1/N moves, and the cost of balanceShow
Expected movement, proved in one line. Hash N nodes to uniformly random points and add node N+1. By symmetry, every one of the N+1 nodes is equally likely to own any given key, so the new node owns a 1/(N+1) fraction in expectation. Only those keys change owner, because every other key's first-clockwise node is unchanged. That is monotonicity. Movement is therefore exactly the minimum needed to give the new node a fair share. Modulo hashing moves N/(N+1) of keys, which is N times more than necessary.
Arc lengths and imbalance. N random points on a circle of circumference 1 cut it into N arcs. Their lengths behave like independent exponential variables with mean 1/N, normalised to sum to 1. The longest is about (ln N)/N and the shortest about 1/N^2. With N = 100, the busiest node owns about 4.6 times its fair share and some nodes own almost nothing, which is the imbalance that virtual nodes fix. With V virtual nodes per node, a node's share is a sum of V such arcs. Its mean stays 1/N and its standard deviation falls to about 1/(N sqrt(V)), so the relative spread is about 1/sqrt(V). Ten percent spread needs about 100 virtual nodes, and 5% needs about 400.
Load, not keys: bounded loads. Mirrokni, Thorup and Zadimoghaddam ("Consistent Hashing with Bounded Loads", SODA 2018) cap each server at (1 + ε) times the average load. A key that would land on a full server continues clockwise to the next one with room. They show that the expected number of keys moved per server change stays bounded by a function of ε alone, so stability survives. With ε = 0.25, no server ever carries more than 125% of the average, however skewed the requests are. Vimeo's engineering team described implementing this in HAProxy for their video cache tier, where it is exposed as hash-balance-factor, and Google has described using the algorithm in production load balancing.
Monotonicity versus balance. There is a real tension between balance and minimal movement. Perfect balance with arbitrary removals, as Maglev aims for, requires more keys to move when membership changes than the theoretical minimum. Minimal movement with no memory, as in jump hash, requires restricting which bucket can be removed. Rings with virtual nodes and rendezvous hashing sit in the middle: near-minimal movement, good but probabilistic balance, and memory or CPU proportional to the node count. Every production choice is a point on this triangle of balance, movement and lookup cost.
The Dynamo paper's evolution. DeCandia et al. (SOSP 2007) report that Amazon first assigned random tokens to nodes, then found that random tokens made partition ranges uneven. Bootstrapping a node required scanning other nodes' data to find what to transfer, and archiving was awkward because ranges kept changing. They moved to dividing the hash space into Q equal-sized partitions and having each of S nodes hold Q/S of them. This decouples partitioning (fixed, equal slices) from placement (which node holds which slice). That is the same separation Riak, Redis Cluster and logical-shard designs use, and a good mental model for any system that claims to use consistent hashing.
Key Takeaways#
hash mod Nremaps nearly every key when N changes; consistent hashing moves only about 1/N.- Keys belong to the first node clockwise on the hash ring; adding or removing a node affects only its neighbouring range.
- Virtual nodes give even load, spread failover and allow weighting by capacity.
- Replicas go to the next distinct physical nodes clockwise, ideally in different racks or zones.
- Rendezvous and jump hash are ringless alternatives; the technique underpins Dynamo, Cassandra, caches, CDNs and load balancers.
- Distinguish structural imbalance (fixed by virtual nodes or token allocation) from workload imbalance (fixed by replication, salting or bounded loads).
- Failures normally move no data in a replicated store. Only planned membership changes stream ranges, and pending ranges receive writes during a join.
- Pin the hash function and seed across all clients, and keep membership agreed, through a consistent store or gossip plus repair.
- Rendezvous hashing is the simplest correct choice for small pools and replica selection. Maglev suits packet-rate balancing, and jump hash suits numbered logical shards.