GOAT EngineerPreparing your learning space…

System Design · Concept Library · Free article

Consistent Hashing — Add a Node Without Moving the World

Why adding one server to a cluster should not force almost all of your data to move — and the ring that makes it so. From naive hash % N tying every key to the node count, up through the hash ring, clockwise ownership, the ~1/N rebalance, virtual nodes for an even load, and the cascading failure they prevent — for interns through principal engineers.

Consistent hashing maps both your keys and your nodes onto one fixed ring, so a key is owned by the first node clockwise from where it lands — which means adding or removing a node moves only ~1/N of the keys instead of nearly all of them. The problem it solves is hash(key) % N: because the shard is computed from the node count, changing that count (adding one machine) re-homes almost every key at once, a data-movement storm that takes the cluster down. The ring breaks that link — a key’s position never changes, only which node happens to be next around the circle — so growing the cluster moves just the slice the new node claims. The catch is that a hash scatters nodes unevenly, so a plain ring runs one node hot and, when a node dies, dumps its whole arc onto a single neighbour (a cascade). The fix is virtual nodes: give each physical machine many positions around the ring, so load spreads evenly and a dead node’s work disperses across all the survivors. It is the backbone of Dynamo, Cassandra, Redis Cluster, and every CDN — and it is still only one copy per node, which is where replication comes in next.

Adding one node moved almost everything

The pager goes off at 7:04 a.m. Hatch’s four-shard Postgres cluster has been climbing toward full for weeks, and last night it crossed 88% disk. The plan was routine: add a fifth shard before the morning rush, spread the load, buy another year of runway. So the on-call flips the router from four shards to five — a one-line change, hash(key) % 4 becomes hash(key) % 5 — and the cluster detonates. Within seconds 80% of the 12 TB dataset starts copying across the network at once, every switch saturates, the disks pin, and the API goes dark under the same 120,000 writes per second it was serving fine a minute ago. The incident channel fills up: "why did adding one machine try to move the entire database?"

You have met this storm before — it is the exact open wound the database sharding chapter left you with. Splitting the data across four machines worked beautifully right up until the day you needed a fifth, and then the very rule that placed each row turned adding a node into a full-cluster migration. That is not a bug in the disks or the network; it is baked into the routing math. This page is the fix — and it is one of the genuinely beautiful ideas in distributed systems. By the end you will be able to add a shard to a live cluster and move only a thin sliver of the data, leaving the rest exactly where it sits.

Why hash % N ties every key to the node count

To fix the storm you have to see exactly why it happens, because the culprit is not the one people first blame. The natural way to spread keys across four machines is to hash the key to a big number and take the remainder: shard = hash(key) % 4. It is fast, it needs no lookup table, and it spreads keys evenly — a hash scrambles order, so the four shards each end up with roughly a quarter of the keys. For a fixed cluster it is close to perfect. The trouble is hiding in that innocent % 4.

Look at what the remainder actually depends on: the total number of shards. A key’s home is hash(key) % N, and N is the node count. So the moment you change the count — from 4 to 5 — you change the divisor for every key at once, and a different divisor produces a different remainder for almost all of them. A key that lived on shard 2 under % 4 now computes to shard 4 under % 5; its neighbour jumps from shard 1 to shard 0. Nobody moved the data on purpose — the formula re-addressed nearly the whole keyspace in a single stroke, and the cluster dutifully started shipping rows to match. Going 4 → 5 remaps roughly 80% of the keys, not the 20% that should have moved.

The hash ring — give every key a fixed home

Here is the move, and it is smaller than its reputation. Instead of hashing a key down to one of N slots, hash it to a position on a huge fixed number line — say 0 up to 2³² — that never changes no matter how many nodes you own. Now bend that line into a circle so the top wraps back to the bottom: pass the largest value and you land back at zero. That circle is the hash ring. Every key hashes to a permanent point on it, and — this is the part that surprises people the first time — the nodes get hashed onto the very same ring. Each shard runs its own name or id through the same hash function and takes a position on the circle, sitting right there among the keys.

With both keys and nodes on one circle, ownership needs a rule, and the rule is a single sentence: a key belongs to the first node you reach travelling clockwise from where the key lands. Drop a key at position 172; walk clockwise until you bump into a node; that node owns the key. That is the entire assignment scheme. Notice what just happened to the coupling from the last section — a key’s position is fixed forever, computed from the key alone, and the only thing that decides its owner is which node happens to be sitting next around the ring. Play with it below: drag the key around and watch ownership hand off from one shard to the next exactly at each shard’s position.

The interactive version of this example is available when JavaScript loads.

Add or remove a node — and move only ~1/N of the keys

Now watch the storm evaporate. When you add a fifth shard, it hashes to one position on the ring and slots in between two existing nodes. Ask which keys have to move, and the answer is delightfully small: only the keys in the arc between the new node and the node just counter-clockwise of it — the slice the newcomer now sits in front of. Every other key on the ring still meets the same node clockwise it always did, so its owner is unchanged and it does not move a byte. The new node lifts only its own fair share off the one neighbour whose arc it split. Adding one node to N moves about 1/(N+1) of the keys, not 80% of them.

Removing a node is the mirror image and just as gentle. When a shard leaves — you scale down, or it dies — the keys it owned simply flow to the next node clockwise, because that is now the first node they meet. Only that departed node’s arc moves; the rest of the ring never notices. Compare the two schemes head-to-head below: grow the cluster and watch the ring shift only the new nodes’ slices while naive hash % N re-homes almost everything for the same growth.

The interactive version of this example is available when JavaScript loads.

So the ring has kept its promise: add a node, move a sliver. But there is a crack in it we glossed over, and it is the thing that separates a whiteboard drawing from a system that survives. We drew the four nodes tidily spaced around the circle — evenly, a quarter-turn apart. Nothing guarantees that. The nodes are placed by hashing their names, and a hash does not lay things out neatly; it drops them wherever it likes. Some arcs come out huge and some tiny, which means some nodes own far more of the ring — and far more of the load — than others. That lumpiness, and the nasty failure it triggers when a node dies, is the next thing to fix.

The lumpy ring — even keys, uneven nodes

Here is the crack in full. The ring spreads your keys beautifully, because there are millions of them and a hash scatters millions of things almost perfectly evenly. But the nodes are a different story: you have only a handful of them — four, five, maybe a dozen — and a hash does not space a handful of points evenly around a circle. Throw five points at a ring by hashing their names and you do not get five tidy 72-degree slices; you get one node sitting far from the node counter-clockwise of it, owning a huge arc, and another two nodes crammed close together owning slivers. And remember the ownership rule: a node owns everything in the arc behind it. A big arc means a big share of the keys, and a big share of the traffic.

So one node quietly ends up owning 40-something percent of the ring while a fair share would be 20%, and it runs hot while its neighbours coast — not because it is doing anything special, but because the hash happened to drop it in a lonely spot. Reseed the placement below a few times and watch the hotspot jump around: it is pure luck of the draw, and every fresh layout is a new gamble.

The interactive version of this example is available when JavaScript loads.

Virtual nodes — scatter each machine everywhere at once

The lumpiness came from having too few points on the ring, so the fix is almost insultingly direct: put more points on the ring. Instead of giving each physical machine one position, give it many — a hundred, two hundred — each one just another hashed position that happens to carry the same machine’s name. These extra positions are called virtual nodes (or vnodes). Physically there are still only five machines; on the ring there are now five hundred or a thousand points, and each machine owns not one fat arc but a hundred tiny scattered slivers spread all the way around the circle.

And now the statistics flip in your favour. Averaging one arc is a coin toss; averaging a hundred arcs is the law of large numbers, and the law of large numbers is relentless — the more slivers each machine owns, the closer its total creeps to a perfectly even share. The lonely-node lottery disappears, because every machine has points in every neighbourhood of the ring. Drag the vnode count below from one up toward a couple hundred and watch the load spread — its standard deviation — collapse toward zero:

The interactive version of this example is available when JavaScript loads.

The cascade a lumpy ring hides

Even load is the visible win of virtual nodes. The one that actually saves you at 3 a.m. is subtler, and it only shows up when a node dies. Think through what happens on a plain one-point-per-node ring when a machine fails. Its keys do not vanish into thin air — they flow to the next node clockwise, because that node is now the first one they meet. Which sounds fine, until you notice the word the: one node inherits the entire dead node’s arc, all at once. That heir was already carrying its own load; now it is carrying its load plus a whole dead machine’s worth on top. It tips past its capacity, falls over, and dumps everything — its own keys and the ones it just inherited — onto the next node clockwise, which now tips even faster. That is a cascading failure: one death triggers the next, the next triggers the one after, and the whole ring goes down like dominoes. Kill a shard below with vnodes off and step through the collapse:

The interactive version of this example is available when JavaScript loads.

Now flip virtual nodes on and kill a node again. Because that machine’s positions were scattered into a hundred little arcs all around the ring, its hundred slivers each have a different clockwise neighbour — so its load does not fall on one victim, it disperses across all the survivors at once. Four machines each pick up a quarter of a dead node’s work, a small bump nobody chokes on, and the ring simply keeps serving. Vnodes turned a fatal single-heir dump into a gentle everyone-shares. This is the same instinct as edge load shedding from earlier — the art of not letting one failure concentrate into the next one — just achieved by spreading the load instead of dropping it.

Measuring and operating a real ring

Here is the part the tutorials wave away, and it is exactly where "I read about consistent hashing" turns into "I have run it." A ring hides its problems in the average, the same way a sharded cluster does. Your dashboard says "cluster load: 40%" and everything looks calm — but that is the mean across the machines, and it is perfectly consistent with one node pinned while others coast. The first rule of operating a ring is the same as operating any cluster: never trust an aggregate — chart every metric per node. Only then does an imbalance jump off the screen.

What to watch on a live ring

  • Per-node share, on two axes — how much of the keyspace each node owns (are the vnodes balanced?) and how much traffic it actually serves. Track the imbalance ratio (busiest ÷ average); a healthy ring with 150 vnodes sits near 1.0, and a drift upward means your vnode count is too low or a node’s vnodes clumped.
  • Data moved per topology change — when you add or drop a node, measure the bytes that actually streamed. It should be ~1/N of the dataset; if it is far more, something is re-hashing on the node count (a modulo leak) instead of the ring.
  • Cache-miss rate right after a change — the slice that moved arrives cold on its new owner, so expect a miss spike for exactly that ~1/N. A miss storm bigger than the slice you moved is the tell that too many keys re-homed.
  • Ring agreement across clients — every client (or proxy) must share the same view of where the nodes sit. If two clients disagree about the ring, they route the same key to different nodes — silent misses and split writes. This is the failure mode people forget.
  • The hot key that the ring cannot fix — consistent hashing balances keys, not per-key load. One viral key still lands on one vnode on one node, and no vnode count spreads a single key. Watch for a lone node hot while the keyspace looks balanced — that is a hot key, not a ring problem, and it needs the hot-key ladder, not more vnodes.

The cost, and when NOT to reach for it

Consistent hashing is close to magic for the problem it solves, but the senior move is knowing it is not free and not always the answer. It carries real costs: the ring map is P × V entries (five machines × 200 vnodes = a thousand positions to store and keep in sync), a lookup is a binary search over that sorted map on every request (cheap, but not free), and you now have the coordination problem from the last section — everyone must agree on the ring. It also does not solve two things people expect it to: it does nothing for a hot key (one key, one node, always), and it gives you no copies — a dead node’s data is still gone until you add replication on top.

When plain modulo (or something else) is the better call

  • A small, fixed cluster you rarely resize. If you have three nodes and will not touch them for a year, hash % 3 is simpler, needs no ring map, and the resize storm never happens because you never resize. Do not pay for a ring you never grow.
  • When you need ordered range scans. Any hashing — modulo or ring — scatters order, so "give me last Tuesday’s rows" becomes a broadcast. If ordered scans dominate, that is a shard-key decision (range partitioning), not a consistent-hashing one — see database sharding.
  • When a managed system already does it. You rarely hand-roll a ring. Cassandra, DynamoDB, and Redis Cluster bake it in; your job is to understand it, pick a good partition key, and set the vnode count — not to build the ring yourself.
  • When even ~1/N is too much data to move live. ~1/N of a petabyte is still a lot. The ring bounds which keys move, but you still need online streaming (copy-while-serving, then cut over) so the move does not saturate the network — the same tooling sharded systems use to reshard.

Where consistent hashing actually runs

You have been using consistent hashing for years without seeing it — it is quietly holding up a huge share of the infrastructure you touch daily. The idea traces back to a 1997 MIT paper (built for web caching) and then Amazon’s 2007 Dynamo paper, which popularised the ring-plus-vnodes design that most systems copied. Here is where it lives now:

The consistent-hashing landscape — data stores, caches, and the load-balancing cousin. Most large systems live in one of these rows.
SystemWhat it isHow it uses the ring
Amazon Dynamo / DynamoDBThe key-value store that popularised the designKeys and nodes on a ring; ~128 virtual nodes per machine; a key’s replicas are the next nodes clockwise
Apache CassandraWide-column store, sharded from the ground upA token ring with vnodes (256 historically, 16 by default now) — you cannot not use it
RiakDynamo-style key-value storeA 160-bit SHA-1 ring split into fixed partitions handed to nodes
Redis ClusterSharded RedisA slot variant — 16,384 fixed hash slots assigned to nodes, not a per-key vnode ring
memcached (client-side)Distributed cacheClients ring-hash keys across servers (the "ketama" algorithm) so one server dying only cold-misses its slice
CDNs & L7 load balancersEdge caches and request routersConsistent / rendezvous hashing routes a key to the same edge or backend for cache affinity (e.g. Google’s Maglev)

That last row is worth a beat, because you have already met it from the other side. On the load balancing page, consistent hashing showed up as a balancing algorithm — a way to keep the same client or cache key hitting the same backend so a sticky session or a warm cache survives. That is the very same ring, used for request routing instead of data partitioning. Here you learned the data-partitioning angle: which node owns a key. There it was the routing angle: which backend serves a request. One idea, two jobs — and naming that connection is a small flex that shows you see the whole board.

Show me the code

The whole thing is smaller than its reputation — a sorted array and a binary search. Here is the shape in words you can turn into any language. The only rule that matters: hash with a stable function (md5, murmur, xxhash — not the language’s built-in string hash, which can change between versions and silently re-home your whole ring).

  1. Build the ring once: for each node, hash nodeId + ":" + i for i in 0..vnodeCount and store each result as a point: ring.push({ pos: hash(id + ":" + i), node: id }). Then ring.sort((a, b) => a.pos - b.pos) — a sorted array of vnode positions.
  2. Look up a key’s owner with a binary search for the first position >= hash(key): let i = lowerBound(ring, hash(key)); if (i === ring.length) i = 0; return ring[i].node. The i === length → 0 line is the wrap-around that closes the circle.
  3. Add a node by inserting its vnodes and re-sorting: for (i in 0..vnodeCount) insertSorted(ring, { pos: hash(newId + ":" + i), node: newId }). Only the keys in the arcs those new points split have to move — everyone else’s binary search still lands where it did.
  4. Remove a node by deleting its vnodes: ring = ring.filter(p => p.node !== deadId). The keys it owned now binary-search to the next point clockwise — again, only its slice moves.
  5. Keep the node list (and vnode count) in config, distributed to every client or proxy, and change it through a controlled rollout — because the moment two clients disagree on the ring, they route the same key two different ways.

Pitfalls that bite in production

  • A plain ring with one point per node. The textbook version nobody ships — it is lumpy, runs a node hot, and cascades on failure. Always use virtual nodes; "consistent hashing" in practice means consistent hashing with vnodes.
  • Too few vnodes. A handful of vnodes per node barely improves the variance. Aim for ~100–200 (or whatever your system defaults to) so the load spread drops under ~5%.
  • Expecting it to fix a hot key. The ring balances keys, not per-key load. One viral key still melts one node — that is the hot-key problem, and more vnodes will not touch it.
  • Forgetting replication. A balanced ring still keeps one copy per node; a dead node loses its slice. Consistent hashing is placement, not durability — you still need replicas.
  • An unstable hash function. Using a language’s built-in string hash (which can change across versions or runtimes) re-homes your entire ring on an upgrade. Pin a stable hash like murmur or md5.
  • Ring drift between clients. Different clients holding different node lists route the same key to different nodes — silent misses and split writes. Distribute the ring from one source of truth and converge fast.
  • Charting cluster averages. The one hot or clumped node hides in the mean. Chart per-node keyspace and traffic, and alert on the imbalance ratio.

Best practices

  • Always run virtual nodes, ~100–200 per machine (or your system’s default), so both steady-state load and failure load spread evenly.
  • Weight vnodes by capacity — give a machine with twice the resources twice the vnodes, and heterogeneous hardware balances itself.
  • Pin a stable, well-distributed hash (murmur / md5 / xxhash), never the runtime’s built-in string hash.
  • Distribute the ring from one source of truth (a coordinator or gossip) and make membership changes converge fast, so clients never route on a stale ring.
  • Layer replication on top — the ring places data; replicas keep it alive. Store each key on the next N nodes clockwise so a death does not lose its slice.
  • Instrument per node — keyspace share, traffic share, data-moved-per-change, and post-change miss rate — and alert on the imbalance ratio, not the average.
  • Reach for it only when you actually resize — a tiny fixed cluster is fine on plain modulo; the ring earns its keep the day you grow.

The interview deck — intern to principal

What problem does consistent hashing solve? (intern)
Naive hash(key) % N ties a key’s home to the node count, so adding or removing a node changes the divisor and re-homes almost every key at once — a data-movement storm. Consistent hashing lets you add or remove a node while moving only ~1/N of the keys.
How does the ring actually work? (intern → SDE2)
Hash both keys and nodes onto one fixed circle. A key is owned by the first node you reach travelling clockwise from where it lands; past the last node you wrap to the first. Because a key’s position never depends on how many nodes exist, changing the node count only affects the keys in the changed node’s arc.
Why do you need virtual nodes? (SDE2 → senior)
With one point per node there are too few points to space evenly, so one node owns a big arc and runs hot. Give each machine ~100–200 virtual positions and the load averages out. Vnodes do two jobs: even steady-state load, and — when a node dies — dispersing its load across all survivors instead of dumping it on one neighbour.
What happens to load when a node dies, with and without vnodes? (senior)
Without vnodes, the dead node’s entire arc falls on its single clockwise neighbour, which can tip over capacity and cascade. With vnodes, its scattered arcs hand off to many different neighbours, so the load spreads thinly across the whole cluster and nobody chokes.
Does consistent hashing solve hot keys? (senior → staff)
No. It balances keys across nodes, not load per key. One viral key lands on one vnode on one node, and no vnode count splits a single key. That is the hot-key problem — you fix it with caching, key-splitting, or a dedicated node, not with the ring.
How do all the clients agree on the ring, and what breaks if they don’t? (staff)
Membership is distributed by a coordinator (ZooKeeper/etcd), by gossip (Cassandra/Dynamo), or computed client-side from a shared node list. If two clients hold different rings during a change, they route the same key to different nodes — silent cache misses and split writes — so changes must converge fast and ideally atomically.
When would you NOT use consistent hashing? (principal)
A small fixed cluster you never resize — plain hash % N is simpler and the storm never happens. Or when ordered range scans dominate (any hashing destroys order). Also know the cousins: rendezvous hashing (no ring, O(N) lookup), jump hash (no memory, but only removes the last bucket), and Redis Cluster’s fixed 16,384 slots — all reaching the same goal by different roads.

The one thing to carry

The whole chapter collapses to a single sentence: never tie a key’s home to how many nodes exist — put keys and nodes on a shared ring, own each key by the next node clockwise, and scatter each machine with virtual nodes so both load and failure spread evenly. That is what turns "add a shard" from a full-cluster detonation into a quiet operation that moves a sliver. Modulo re-homes everyone because it depends on the count; the ring re-homes only the changed node’s arc because it does not. And virtual nodes are non-negotiable — they are what make the ring both balanced in the steady state and safe when a node dies.

By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.