What Is Consistent Hashing - and When a Plain Modulo Is Fine
What is consistent hashing? It is a way of assigning keys to nodes so that when the number of nodes changes, only a small fraction of keys has to move. That is the whole point, and everything else about it is machinery in service of that one property.
The problem it exists to solve shows up the first time you shard anything with hash(key) % N. That works perfectly until N changes. Add one node to a cluster of ten and nearly every key now maps somewhere new: your cache is cold, your shard router points at the wrong box, and your rebalance moves almost the entire dataset across the network at once.
Consistent hashing replaces the dependency on N with a dependency on which positions are occupied on a ring. Nodes and keys are both hashed into the same circular space, and each key belongs to the next node clockwise. Remove a node and only its own arc of keys reassigns, to its clockwise neighbour. Everything else stays where it was.
This page covers the mechanism, the two problems the naive ring has, and the cases where you should keep the modulo and go do something more useful with your week.
| Concept | Consistent Hashing |
|---|---|
| Where it sits | Distributed systems - sits in the routing/placement layer, between a client and a set of interchangeable nodes |
| In one sentence | A key-to-node mapping where adding or removing one node reassigns roughly 1/N of the keys instead of nearly all of them. |
The 60-Second Answer
What it does: hashes both keys and nodes into one circular keyspace; a key is owned by the first node clockwise from it.
The one problem it solves: membership churn. Scaling a cluster, or losing a node, moves only the keys in the affected arc rather than remapping the whole keyspace.
The one cost it adds: every client now needs a shared, agreed view of ring membership. That is a consensus or gossip problem, plus virtual nodes to keep the arcs balanced, plus the operational burden of diagnosing why this key landed on that node.
If your node count is fixed and you can tolerate a full rebalance during a maintenance window, hash(key) % N is the correct answer.
How It Actually Works
The mechanism, step by step
- 1. Hash keys and nodes into the same circular keyspace
- 2. A key belongs to the first node clockwise from its position
- 3. Removing a node hands its arc to its clockwise neighbour
- 4. Virtual nodes fix the uneven-arc problem
- 5. Weighted nodes come from token counts, not from the hash
- 6. Every client needs the same ring, or it reads from the wrong node
- 7. Replication walks the ring to pick the next N owners
- 8. Bounded-load variants cap how hot one node can get
1. Hash keys and nodes into the same circular keyspace
One number line, joined end to end
Take a hash function with a fixed output width and treat its range as a circle: the value after the maximum wraps to zero. Hash your keys into it, and hash your node identities into it too - that second part is the trick. Both now live as positions on the same ring.
ring_pos = hash(identity) % 2**32 # nodes and keys use the same function
Nothing about a key's position depends on how many nodes exist. That decoupling is the entire source of the stability property.
⚠️ In production — The hash must spread node identities evenly, so use a general-purpose non-cryptographic hash (or a cryptographic one truncated), not something that clusters on similar inputs. Node names like cache-01, cache-02, cache-03 differ in one character - a weak hash will place them close together on the ring and hand one of them a huge arc.
2. A key belongs to the first node clockwise from its position
Successor lookup defines ownership
To route a key, hash it, then walk clockwise until you hit a node position. That node owns the key. In practice you keep node positions in a sorted array and do a binary search for the first position greater than the key's, wrapping to index 0 if you fall off the end.
This makes ownership a local property. Each node implicitly owns the arc between its predecessor's position and its own, and nothing outside that arc cares about it.
⚠️ In production — The wraparound case is where the bugs live. If you forget it, keys hashing above the highest node position get no owner, and you will see a thin band of keys failing while the other 99% work fine - which looks like data corruption rather than an off-by-one.
3. Removing a node hands its arc to its clockwise neighbour
Only one arc reassigns
Delete a node's position from the ring and its arc merges into the successor's arc. Keys in that arc now resolve one step further clockwise. Keys anywhere else on the ring resolve exactly as before, because their successor did not change.
Adding a node is the mirror image: it inserts a position and steals the portion of its successor's arc that now falls behind it. One donor, one recipient, one slice of data in motion.
⚠️ In production — The successor inherits the departed node's traffic on top of its own, instantly. If your nodes run near capacity, losing one does not spread its load across the cluster - it dumps all of it on a single neighbour, which can then fall over and dump a double arc on the next one. Virtual nodes are what prevent this cascade, not the basic ring.
4. Virtual nodes fix the uneven-arc problem
Each physical node gets many positions
With a handful of real nodes hashed onto a huge ring, arc sizes come out badly lopsided by luck alone. The fix is to place each physical node at many positions - commonly by hashing node-name#i for a range of i - and treat every one of those positions as a token owned by that node.
for i in range(vnodes_per_node):
ring[hash(f"{node}#{i}")] = node
More tokens means the law of large numbers works in your favour: arc totals converge toward even, and when a node leaves, its many small arcs scatter across many different successors instead of landing on one.
⚠️ In production — Token count is a real tradeoff, not a free dial. More tokens means a larger ring structure to hold, ship around, and diff on every membership change; fewer means worse balance and nastier failover concentration. Pick a number, measure actual key distribution against it, and leave it alone - changing it later is a full reshuffle, which is exactly what you adopted this to avoid.
5. Weighted nodes come from token counts, not from the hash
Heterogeneous hardware, same ring
If some machines have twice the memory or disk of others, give them proportionally more tokens. Share of the keyspace is just share of total tokens, so capacity ratios translate directly into token ratios without touching the lookup logic.
This is how a cluster absorbs a hardware generation change gracefully: new, larger nodes join with more tokens, old ones are drained by removing their tokens, and routing never needs to learn about machine types.
⚠️ In production — Draining a node by yanking all its tokens at once is the same event as a hard failure, with the same thundering reassignment. Remove tokens in batches and let replication or cache refill settle between batches.
6. Every client needs the same ring, or it reads from the wrong node
Membership is now a distributed problem
The ring is only useful if everyone computing a lookup agrees on which positions exist. That agreement has to be distributed somehow: a coordination service holding authoritative membership, a gossip protocol between nodes, or a control plane pushing ring versions out to clients.
During a membership change, clients converge at different times. For a window, two clients hash the same key and reach different nodes.
⚠️ In production — This is the cost people underestimate. For a cache, a split view is a miss and some duplicated entries - annoying, survivable. For a store of record, it is two writers on one key with no coordination between them. If the data matters, the ring must pair with replication and a version or quorum scheme; consistent hashing decides placement and says nothing at all about consistency, despite the name.
7. Replication walks the ring to pick the next N owners
Successor list, skipping same-host tokens
To keep R copies of a key, continue clockwise past the primary owner and take the next R-1 distinct nodes. The same lookup that chose the primary produces the replica set, so no separate placement system is needed.
With virtual nodes you must skip tokens belonging to a node already in the set, and in a multi-rack or multi-zone deployment you also skip nodes sharing a failure domain - otherwise all three copies can land behind one power feed.
⚠️ In production — Failure-domain-aware walking makes arc sizes uneven again, because skipped tokens push load onto whoever is eligible. Balanced placement and fault-isolated placement pull against each other; you choose a point between them, and you should know which one you chose.
8. Bounded-load variants cap how hot one node can get
Overflow to the next node
A balanced keyspace does not mean balanced traffic. One key can be requested far more than its neighbours, and the ring will dutifully send every one of those requests to a single node.
The standard refinement is a load cap: if the clockwise owner is already above some multiple of average load, the request overflows to the next node instead. Keys stay mostly stable, but a hot arc can spill rather than melt.
⚠️ In production — Overflow means a key's location is now a function of live load, so a key can be served by different nodes at different times. That is fine for a read-through cache and actively harmful if you assumed single ownership for locking, sequencing, or write serialisation on that key.
## Where You Meet It
- A read-through cache tier in front of a database, with clients sharding across cache nodes. This is the canonical case: a modulo mapping means every deploy that changes node count empties the cache and sends the full read load to the database, which is how a routine scale-up turns into an outage. Consistent hashing confines the cold slice to the arc that actually moved.
- A distributed key-value store that places data by key rather than by a lookup table. The ring picks both the primary owner and the replica set by walking clockwise, so nodes can join or leave by claiming or releasing tokens, with data transfer proportional to the tokens that changed hands rather than to the size of the cluster.
- A layer-7 load balancer doing session affinity without a session store. Hashing a session cookie or user ID onto a ring of backends keeps a given user on one backend for cache locality, and a backend's removal breaks affinity for that backend's users only - not for everyone.
- A stream processing or job-sharding system where each worker owns a subset of partitions. Workers hash their identity onto a ring and claim the partitions in their arc, so an autoscaler adding workers triggers a partial handoff instead of a global stop-the-world reassignment.
- A multi-tenant service pinning each tenant to a node for warm per-tenant state - compiled rules, loaded models, open connections. Tenants are weighted by giving big ones more consideration in placement, and a node replacement rewarms only the tenants that moved.
When You Actually Need It
- Your node count changes during normal operation - autoscaling, rolling replacement, spot instance churn - rather than only in planned maintenance windows.
- The cost of a key moving is real: a cache miss that hits a loaded database, or a data transfer measured in a meaningful fraction of a node's disk.
- A full rebalance would exceed what your network or backing store can absorb at once, so you need movement proportional to the membership change rather than to cluster size.
- Nodes are interchangeable for the work in question - any node can serve any key given the data - so placement is genuinely free to be chosen by a hash.
- You need replica placement to fall out of the same mapping as primary placement, rather than maintaining a separate placement table that can disagree with routing.
- Hardware is heterogeneous and you need capacity-proportional shares without a hand-maintained shard map.
When You Don't
- Your node count is fixed and changes only during maintenance. Three nodes that have been three nodes for two years, with a scheduled window for the rare change, do not need a ring. Use
hash(key) % N, accept the one-time reshuffle, and keep a mapping you can compute in your head during an incident. - A single node still fits the workload. If one instance holds your whole cache or dataset with headroom, sharding is the premature step and consistent hashing is premature twice over. Scale the box, add a read replica, and revisit when you have actual numbers showing one node is the ceiling.
- You have fewer than a handful of nodes. Below roughly five or ten, hash-based balance is poor enough that you need many virtual nodes to compensate, and at that size an explicit shard map in config is more predictable and far easier to debug. Consistent hashing starts paying for itself when the cluster is large enough that hand-maintaining placement is the bigger risk.
- Your access pattern is dominated by a few hot keys. The ring balances keyspace, not traffic, and will happily route a disproportionate share of requests to one node. Fix the hotspot first - key splitting, a local cache in front, request coalescing - or you will ship a ring and still have the same overloaded node.
- Queries are not single-key lookups. Range scans, secondary-index reads, joins, and
ORDER BYacross shards all suffer when keys are scattered by hash, because every query becomes a scatter-gather. If range locality matters, use range partitioning with a partition map and accept the rebalancing work. - Your datastore or proxy already does placement for you. Managed caches, sharded databases, and partitioned message systems have their own placement scheme, usually with the membership and rebalancing machinery already built and tested. Implementing a second ring in your application layer on top of theirs gives you two mappings that can disagree, which is worse than either alone.
What People Get Wrong
"Consistent hashing gives you consistency."
The name refers to the mapping being stable across membership changes, not to data consistency. It decides where a key lives and makes no statement about reads and writes agreeing. Consistency comes from replication protocols, quorums, and versioning layered on top.
"It balances load across the cluster."
It balances the keyspace, assuming a good hash and enough virtual nodes. Request load follows key popularity, which the ring knows nothing about. One hot key can saturate one node in a perfectly balanced ring, which is why bounded-load variants exist.
"Adding a node means no keys move."
Roughly 1/N of keys move - that is the guarantee, and it is a good one. The claim is that movement is proportional to the change, not that it is zero. Those keys still need to be transferred or refetched, and that transfer is a real operational event.
"More virtual nodes is strictly better balance, so use a lot."
Balance improves with token count but with diminishing returns, while the cost of holding, distributing, and diffing ring state grows with it. Past a point you are paying membership-propagation cost for balance you cannot measure.
Why It Was Built This Way
The constraint that forced the design is that there is no central authority you can afford to ask on every request. If you could consult a shard map on each lookup, you would not need a hash at all - you would keep an explicit table mapping each key or key-range to a node, move entries one at a time, and have perfect control over placement. That is exactly what range-partitioned systems with a partition service do, and it gives better balance and range locality than any ring.
What it costs is a lookup hop, a service that must be available for every request, and a table that grows with your keyspace. Consistent hashing trades that away for a mapping any client can compute locally from a small amount of membership state. The hash function is the shard map - it just has to be derivable from the node list alone, which is why node identities get hashed into the same space as keys. Once both live on one ring, ownership is a comparison, and no one has to be asked.
The price of that trade is visible in everything awkward about the technique. You lose the ability to choose placement, so you need virtual nodes to patch up the balance that randomness gave you. You lose range locality, so cross-key queries become scatter-gather. You lose a single authoritative answer to "where is this key", so you get windows where clients disagree, and you need replication and versioning to make that survivable. And a key's owner is now computed rather than recorded, which makes debugging placement an exercise in reproducing someone's ring version rather than reading a row from a table.
Understanding that trade is what tells you when to reach for it. Consistent hashing is the right answer when membership churn is frequent and a lookup service on the request path is unacceptable. When neither of those holds - when nodes are stable, or you can afford to ask - the simpler mapping is not a compromise. It is the better engineering choice.
Related Briefs
What to Read Next
- rendezvous hashing vs consistent hashing
- what is a distributed hash table
- range partitioning vs hash partitioning
- what is quorum consistency in distributed systems
Consistent hashing buys you one thing: movement proportional to the membership change rather than to the size of the cluster. Reach for it when nodes join and leave as a matter of routine and a central lookup on every request is off the table. If your cluster is small and stable, the modulo is not a shortcut - it is the mapping you can still reason about at 3am, and that is worth more than the property you are not using.
댓글
댓글 쓰기