Consistent Hashing
Sooner or later, every design that outgrows one machine has to answer a simple question: given a key, which server owns it? A cache cluster needs to know which node holds user:42. A sharded database needs to know where to write order 9f3a. A load balancer that wants sticky sessions needs to send the same user to the same backend every time.
The obvious answer, hash(key) % N, works until the day N changes. Then almost every key moves at once, caches go cold, databases start copying most of their data around, and the system falls over at exactly the moment you were trying to make it bigger. Consistent hashing is the family of techniques that fixes this: when a server joins or leaves, only a small, fair share of keys move.
It comes up constantly in interviews, sometimes as a direct question ("how would you distribute keys across cache nodes?") and more often as a detail inside a bigger design (a key-value store, a distributed cache, a rate limiter, a chat system's connection routing). We'll build it up in order:
- Why mod-N hashing breaks, with the arithmetic.
- The hash ring, how lookups work, and how to implement it.
- Virtual nodes, replication and capacity weighting.
- The alternatives you should know by name: rendezvous, jump, Maglev, fixed slots and bounded loads.
- What it doesn't solve, and how to talk about it in an interview.
The Problem with Mod-N
Say we have a cache cluster of 10 nodes and we place each key with node = hash(key) % 10. The hash spreads keys evenly, lookups are a single arithmetic operation, and every client computes the same answer without talking to anyone. It's a great scheme on a fixed cluster.
Now traffic grows and we add an eleventh node. Every key is now placed with hash(key) % 11. A key stays where it was only if hash(key) % 10 == hash(key) % 11, which happens for roughly 1 key in 11. About 91% of keys move.
In general, going from N to N + 1 nodes keeps only about 1 / (N + 1) of keys in place. The bigger the cluster, the worse it gets: going from 100 to 101 nodes moves about 99% of keys.
What does that mean in practice?
- For a cache, a moved key is a miss. Adding one node to absorb load turns a 95% hit rate into something close to 0% for a while, and the entire read load lands on the database behind it. That's a self-inflicted outage.
- For a database, a moved key is data that has to be copied. If each of 10 nodes holds 1 TB, adding a node means shuffling around 9 TB across the network instead of the roughly 0.9 TB the new node actually needs.
- For a failure, removing a node is just as bad. One machine dying should only affect the keys it held, not all of them.
The ideal is clear: when going from N to N + 1 nodes, only 1 / (N + 1) of the keys should move (exactly the share the new node will own), and they should all move to the new node. Nothing should move between the old nodes. That property is called minimal disruption, and it's what every scheme below is trying to achieve.
The Hash Ring
The classic consistent hashing scheme maps both keys and nodes onto the same circular space. Take a hash function with a large output, say 64 bits, and imagine its outputs 0 ... 2^64 - 1 bent into a circle so the largest value wraps around to zero.
- Each node is hashed (by its name or IP) to a point on the ring. That point is called its token or position.
- Each key is hashed to a point on the ring too.
- A key belongs to the first node clockwise from its position. Equivalently, each node owns the arc between the previous node's token and its own.
Now watch what happens when the cluster changes:
- Adding a node E between B and C: E takes over the arc between B and E, which used to belong to C. Only keys in that arc move, and they all move from C to E. A, B and D are untouched.
- Removing a node C: its arc merges into the next node clockwise. Only C's keys move, and they all go to D.
That's minimal disruption, at least on average. With N nodes placed at random, each owns an expected 1/N of the ring, so a new node takes an expected 1/(N+1) of the keys.
Implementing the Ring
The ring is just a sorted array of tokens and a binary search. Lookup is O(log T) for T tokens, which for a few thousand tokens is a handful of comparisons, well under a microsecond.
import bisect, hashlib
def h(s: str) -> int:
# Any well-mixed hash works; take 64 bits of MD5 for the example.
return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")
class Ring:
def __init__(self):
self.tokens = [] # sorted token positions
self.owner = {} # token -> node
def add(self, node: str):
t = h(node)
bisect.insort(self.tokens, t)
self.owner[t] = node
def remove(self, node: str):
t = h(node)
self.tokens.remove(t)
del self.owner[t]
def lookup(self, key: str) -> str:
# First token at or after the key's position, wrapping to the start.
i = bisect.bisect_left(self.tokens, h(key)) % len(self.tokens)
return self.owner[self.tokens[i]]
The hash function matters less than you'd think. It needs to be well distributed and identical on every client, so the fast non-cryptographic hashes (MurmurHash3, xxHash) are the usual choice. Cassandra's default partitioner uses Murmur3 over a 64-bit signed range. Don't use a language's built-in hash() if it's randomized per process, like Python's for strings, or two clients will disagree about where every key lives.
When you mention consistent hashing in an interview, say what it buys you in one sentence: "when we add or remove a node, only about 1/N of the keys move, instead of nearly all of them." That's the point. Drawing the ring without saying why is a mid-level answer; tying it to cache hit rate or rebalancing cost is a senior one.
Virtual Nodes
The basic ring has two real problems.
Uneven arcs. Placing a handful of points at random on a circle doesn't divide it evenly. With 10 nodes, the biggest arc is typically about twice the fair share, and the smallest can be tiny. The node with the biggest arc gets the most keys, the most traffic and the most disk, and it becomes the bottleneck for the whole cluster. As a rule of thumb, with N random points the largest arc is around ln N times the average.
Lumpy failover. When a node dies, its entire arc goes to one neighbor. If every node runs at 60% capacity and a node fails, its successor suddenly takes on double the keys and runs at 120%. It may fall over too, passing an even bigger arc to the next node. That's a cascading failure, and it's caused by the ring itself.
The fix for both is virtual nodes (vnodes): instead of putting each physical node on the ring once, put it on many times. Hash "A#0", "A#1", ... "A#127" to get 128 tokens for node A, and the same for every other node. Each token owns a small arc, and a physical node owns all the arcs of its tokens.
This changes the statistics a lot:
- Balance improves. A node's share is now the sum of many small, independent arcs, so the variation shrinks roughly with the square root of the vnode count. With 100 vnodes per node, the spread of load between nodes is on the order of 10%; with a few hundred, a few percent.
- Failover spreads out. When A dies, its 128 small arcs are each taken over by whichever node comes next on the ring, which is a different node for each arc. The load is shared across the whole cluster instead of dumped on one neighbor.
- Adding a node is fair. A new node with 128 tokens takes a small slice from many existing nodes, so the data it needs streams from all of them in parallel rather than from one.
- Heterogeneous hardware is easy. A machine with twice the RAM or disk gets twice the vnodes, and therefore about twice the keys.
The code barely changes: add inserts many tokens instead of one.
VNODES = 128
def add(self, node: str, weight: int = 1):
for i in range(VNODES * weight):
t = h(f"{node}#{i}")
bisect.insort(self.tokens, t)
self.owner[t] = node
The cost of vnodes is more metadata and more ranges. A 100-node cluster with 256 vnodes each has 25,600 ranges to track, gossip about and repair. Cassandra used to default to 256 vnodes per node and later lowered the default to 16, paired with a smarter token-allocation algorithm that picks tokens to balance load instead of choosing them at random. The lesson: random vnodes are a simple way to get balance, and a smarter placement gets the same balance with fewer of them.
Replication on the Ring
Real systems store each key on more than one node. The ring gives a natural way to choose replicas: walk clockwise from the key and take the first R distinct physical nodes. This ordered list is often called the key's preference list, a term from Amazon's Dynamo paper. The first node is the coordinator for that key, and the others hold copies.
def replicas(self, key: str, r: int) -> list[str]:
i = bisect.bisect_left(self.tokens, h(key))
out = []
for k in range(len(self.tokens)):
node = self.owner[self.tokens[(i + k) % len(self.tokens)]]
if node not in out: # skip extra vnodes of a node we already have
out.append(node)
if len(out) == r:
break
return out
Two details make this work in production:
- Skip duplicate physical nodes. With vnodes, the next three tokens might include two that belong to the same machine. Storing two "replicas" on one machine isn't replication, so the walk skips nodes already chosen.
- Spread across failure domains. Three replicas in the same rack die together when that rack's switch fails. Rack- and zone-aware placement keeps walking until it has nodes in different racks or availability zones. Cassandra's
NetworkTopologyStrategydoes this per datacenter.
Replication also smooths failures further: when a node dies, reads for its keys can go to the other replicas immediately, while the ring decides who takes over permanently. In Dynamo-style stores, a stand-in node can accept writes on the dead node's behalf and hand them back when it returns (hinted handoff). For more on how replicas stay in sync, see /system-design/sharding-replication.
Who Knows What the Ring Looks Like?
Consistent hashing tells you how to compute an owner from a ring. It doesn't tell you how every client and server gets the same ring. That's a membership problem, and there are three common answers:
- Static config. The list of nodes is in a config file or environment variable that every client reads. This is how a lot of memcached client libraries work: each application server has the node list and hashes locally. It's simple, but changing the cluster means rolling out new config, and during the rollout clients disagree.
- A coordination service. The ring lives in ZooKeeper or etcd. Clients watch it and update when it changes. This gives one source of truth, at the cost of another system to run. See /system-design/zookeeper-etcd.
- Gossip. Nodes tell each other about membership and tokens directly, and the ring converges within seconds without any central store. Cassandra and Riak work this way, and smart clients learn the ring from any node they connect to. See /system-design/gossip-protocol.
There's also the question of who does the routing. The client can compute the owner and go straight there (one hop, but every client needs the ring), or any node can accept a request and forward it (simpler clients, an extra hop). Many systems support both.
A subtle interview point: while the ring is changing, two clients can briefly disagree about who owns a key. For a cache, that's a few extra misses. For a database that needs strong consistency, it isn't acceptable, which is why systems that care either route through a single authoritative metadata service or use quorums that overlap across the old and new owners.
Alternatives to the Ring
The ring is the version everyone knows, but it's not the only way to get minimal disruption, and in some situations it's not the best. Knowing these by name, and what each is good at, is a strong signal.
Rendezvous Hashing (Highest Random Weight)
Rendezvous hashing skips the ring entirely. To place a key, compute a score for every node, score = hash(key, node), and pick the node with the highest score. For R replicas, pick the top R.
def owner(key: str, nodes: list[str]) -> str:
return max(nodes, key=lambda n: h(f"{key}|{n}"))
Why it works: when a node is removed, only keys for which it was the top scorer move, and each goes to its own second-best node, which is spread evenly across the cluster. When a node is added, it wins only the keys where its score beats the current winner, about 1/(N+1) of them. Balance is excellent without any vnodes, because every key independently picks from all nodes.
- Strengths: no ring to store or sync, just the node list. Perfect spread on failure. Weighting is easy with the formula
score = -weight / ln(u), whereuis the hash mapped into(0, 1). Replica selection is natural (top R). - Weakness: lookup is
O(N)hashes. For tens or a few hundred nodes, that's nothing. For thousands of nodes on a hot path, it adds up, though you can layer it (pick a group, then a node in the group).
It's a great default when the node count is modest, like choosing among 20 cache servers or picking which of 50 workers handles a tenant.
Jump Consistent Hash
Jump consistent hash is a short function, published by Google engineers, that maps a 64-bit key to one of N numbered buckets with essentially perfect balance, no memory at all, and O(log N) time:
def jump_hash(key: int, num_buckets: int) -> int:
b, j = -1, 0
while j < num_buckets:
b = j
key = (key * 2862933555777941757 + 1) & 0xFFFFFFFFFFFFFFFF
j = int((b + 1) * ((1 << 31) / ((key >> 33) + 1)))
return b
When num_buckets grows from N to N + 1, exactly the right 1/(N+1) of keys jump to the new bucket, and no others move. The catch is in the word "numbered": buckets are 0 ... N-1, and you can only add or remove at the end. You can't remove bucket 3 out of 10. That makes it a poor fit for a cache cluster where any machine can die, and a good fit for mapping keys to a set of logical shards that grows over time, where each shard is itself a replicated group that never disappears.
Maglev Hashing
Maglev hashing comes from Google's software load balancer of the same name. Each backend fills a fixed-size lookup table (a prime size like 65,537) using its own permutation of the slots, taking turns until the table is full. A lookup is then table[hash(key) % M]: one array access, O(1).
The table gives near-perfect balance, and when a backend is removed, most entries for other backends stay put, with only small additional disruption beyond the theoretical minimum. It's built for the load balancer case: millions of packets per second, each needing a backend in nanoseconds, with connections that should keep going to the same backend. Envoy offers both RING_HASH and MAGLEV load-balancing policies; Maglev is faster to look up and rebuild, while the ring is more flexible about weights.
Fixed Slots (Hash Partitions)
Many production systems take a simpler route: split the key space into a fixed, large number of slots up front, then assign slots to nodes with an explicit table.
- Redis Cluster has exactly 16,384 hash slots. A key's slot is
CRC16(key) % 16384, and the cluster keeps a map of which node owns which slot ranges. Adding a node means migrating some slots to it. - Kafka topics have a fixed number of partitions; keys hash to partitions, and partitions are assigned to brokers.
- Couchbase uses 1,024 vBuckets. Elasticsearch fixes the primary shard count at index creation and routes by
hash(routing) % shards.
This is mod-N hashing again, but with a twist: N is the slot count, which never changes. What changes is the slot-to-node table, and moving a slot moves exactly the keys in it, nothing else. You get minimal disruption by construction, perfect control over placement (move the hot slot to the idle node), and a tiny table to share (16,384 entries is a few kilobytes).
The trade-off is that you have to pick the slot count up front. Too few, and you can't spread over many nodes or rebalance finely; too many, and the per-slot overhead adds up. The usual guidance is to pick 10 to 100 times more slots than you ever expect to have nodes. Systems that started with too few partitions (an Elasticsearch index with 5 shards that now needs 50) end up reindexing everything.
If an interviewer asks "consistent hashing or fixed partitions?", a good answer is: fixed slots with a mapping table are simpler to operate and give explicit control over placement, so most modern databases use them; the hash ring shines when there's no central authority and nodes come and go freely, like a peer-to-peer store or client-side cache sharding.
Bounded Loads
All of the schemes above balance keys, not load. If some keys are much hotter than others, a node can be overloaded even with a perfectly even key count. Consistent hashing with bounded loads, also from Google research, adds a cap: no node may take more than c times the average load (say c = 1.25). If a key's owner is at the cap, the request moves clockwise to the next node that has room.
This keeps the stickiness of consistent hashing for most requests, while guaranteeing that no server goes beyond 125% of average. HAProxy supports it with hash-balance-factor, and it's a good fit for routing requests to caching proxies or video segment servers, where you want affinity but can't afford a hot server.
Choosing Between Them
| Scheme | Lookup cost | State to share | Balance | Removing an arbitrary node | Typical use |
|---|---|---|---|---|---|
| Mod-N | O(1) | Node count | Perfect | Moves almost everything | Fixed-size clusters only |
| Ring + vnodes | O(log T) | Token list | Good (more vnodes = better) | Yes, minimal movement | Cassandra, Riak, memcached clients |
| Rendezvous | O(N) | Node list | Excellent | Yes, minimal movement | Modest node counts, replica choice |
| Jump hash | O(log N) | Bucket count | Perfect | No, only the last bucket | Logical shard numbering |
| Maglev | O(1) | Lookup table | Near perfect | Yes, small extra movement | L4 load balancers |
| Fixed slots | O(1) | Slot table | Controlled | Yes, move its slots | Redis Cluster, Kafka, Couchbase |
What Consistent Hashing Doesn't Solve
Consistent hashing is about where keys live. Several problems sit next to it and are easy to confuse with it.
Hot keys. If one key gets 50,000 requests per second, it doesn't matter how evenly the other keys are spread: one node gets all of that key's traffic. The fixes live elsewhere. For reads, replicate the hot key to several nodes and pick one at random, or put a small local cache in front of the cluster. For writes, split the key into sub-keys (likes:post42:0 ... likes:post42:15) and sum them on read. The /system-design/likes-counter and /system-design/distributed-cache posts work through both.
Range queries. Hashing scatters adjacent keys. If you need "all events for user 42 between Monday and Friday," hashing by event ID puts them on every node. Either hash by user and keep events sorted within the partition (what Cassandra's partition key plus clustering key does), or use range partitioning instead, where each node owns a contiguous key range and ranges split as they grow (Bigtable, HBase, CockroachDB, Spanner). The trade-offs are in /system-design/sharding-replication.
Moving the data. The ring tells you which keys need to move, but something still has to copy them: stream the affected ranges from old owners to the new one, keep serving reads from the old owner until the copy catches up, then switch. A cache can skip this and accept misses; a database can't.
Cross-key operations. A transaction or join across keys on different nodes still needs coordination. Consistent hashing gives you no help, other than letting you choose a key (like user_id) so that related data hashes to the same place.
Consistent Hashing in an Interview
When to Bring It Up
- Distributed cache (memcached or Redis without cluster mode, client-side sharding). This is the textbook case: adding a cache node shouldn't wipe out your hit rate.
- A key-value store or Dynamo-style database you're designing from scratch. Consistent hashing with vnodes plus replication along the ring is the expected answer for partitioning. See /system-design/key-value-store.
- Sticky routing: sending each chat user's connection, each tenant's jobs or each URL's requests to the same server, so local state or caches stay warm. Rendezvous or ring hashing in the load balancer. See /system-design/load-balancer.
- Sharding a SQL database, where you can also say that fixed logical shards (say 1,024) mapped to physical hosts are easier to operate than a ring.
Don't force it in where it doesn't belong. A managed database like DynamoDB already partitions for you, so "DynamoDB, partitioned by user_id" is enough; you don't need to explain its internal hashing unless asked.
Common Follow-ups
- "What happens when a node is added?" Only keys between its predecessor and it move, about
1/(N+1)of the total. With vnodes, it takes small slices from many nodes, and data streams in parallel. - "How do you avoid an uneven split?" Virtual nodes (or a smarter token allocator), and weight vnodes by capacity.
- "What if one key is very hot?" Consistent hashing doesn't help. Replicate it for reads, shard the key for writes, add a local cache.
- "How do clients know the ring?" Static config, a coordination service like etcd, or gossip. Mention what happens while it's changing.
- "How do you pick replicas?" Walk clockwise to R distinct physical nodes in different racks or zones.
- "Why not just use mod-N?" Do the arithmetic: going from 10 to 11 nodes moves about 91% of keys.
A clean way to present partitioning in a design: "We hash
user_idinto 4,096 logical shards and keep a shard-to-node map in etcd. Adding capacity means moving some shards; each move is a bounded, observable operation." It shows you understand both the hashing and the operations around it.
Summary
Mod-N hashing places keys evenly but moves almost all of them when the node count changes, which empties caches and forces huge data copies. Consistent hashing fixes that by making placement depend on positions that don't shift when other nodes come and go. On the hash ring, keys go to the next node clockwise, so a join or leave moves only one arc's worth of keys. Virtual nodes even out arc sizes, spread failover load across the cluster and let you weight bigger machines, and walking the ring to distinct physical nodes in different zones gives replication.
The ring isn't the only option. Rendezvous hashing is simpler and better balanced for modest clusters. Jump hash is perfect for numbered shards that only grow. Maglev is built for fast load balancer lookups. Fixed slots with a mapping table, as in Redis Cluster and Kafka, are what most modern systems actually use. Bounded loads add a cap when key counts aren't the same as load. Whatever you pick, remember what it doesn't solve: hot keys, range queries, moving the data and cross-key transactions are separate problems with their own answers.