InterviewDryRun
Lesson 32 · 22 min video · free

Design Consistent Hashing

A cluster of cache servers must split millions of keys between them, and adding or removing one server should move as few keys as possible. This lesson builds consistent hashing from first principles: why modulo hashing fails, the hash ring, virtual nodes for even load, replicas around the ring, a binary-search lookup, how every client agrees on the ring, moving data without losing it, and the alternatives an interviewer may ask about.

The video is on its wayIt goes up on the InterviewDryRun YouTube channel shortly. The full written lesson is below.

What you will learn

  • Hash modulo N moves almost every key when N changes; consistent hashing moves only about one Nth.
  • Put servers and keys on the same ring; a key belongs to the first server clockwise from it.
  • Virtual nodes, many points per server, even out the load and spread a failed server's keys across all the others.
  • Replicate a key to the next few distinct servers clockwise.
  • Lookups are a binary search over a sorted array of ring points: fast and tiny in memory.
  • Every client must agree on the ring: publish it from one source of truth with a version number.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The naive approach, and why it fails
  5. Step 4: The hash ring
  6. Step 5: Adding and removing servers
  7. Step 6: Virtual nodes
  8. Step 7: The lookup in code
  9. Step 8: Replication around the ring
  10. Step 9: Who owns the ring?
  11. Step 10: Moving data safely
  12. Step 11: Hot keys and bounded load
  13. Step 12: Alternatives worth knowing
  14. Step 13: The follow-up questions
  15. Step 14: The parts people forget
  16. Recap
Practice this question with Max

The question

Welcome to lesson thirty-two of the system design course. Today's question is a short one to say and a deep one to answer. The interviewer says: design consistent hashing for a cluster of cache servers, so that adding or removing a server moves as few keys as possible.

Unlike most lessons in this course, this is not a product. It is a building block, and it shows up inside many of the other designs we have done: the distributed cache in lesson five, the key value store in lesson four, the sharded database in lesson thirty-one, object storage, the content delivery network. Whenever data is split across machines that come and go, someone has to decide which machine owns which key.

Interviewers like this question for two reasons. First, it has a clear wrong answer that almost everyone gives first, and they want to see whether you notice why it is wrong. Second, it is mathematical enough that you can be precise: how many keys move, how uneven the load is, how much memory the lookup takes. Precision is what separates a good answer from a great one.

We will go step by step: the requirements, the naive approach and why it fails, the hash ring, virtual nodes, replication, the lookup code, who keeps the ring and how changes spread, moving data safely, hot keys, the alternatives, and the follow-up questions. Let us start.

Step 1: Clarify the requirements

Requirements
  1. 01
    Map key → serverany client, locally, in microseconds
  2. 02
    Even loadeach server gets about its fair share
  3. 03
    Minimal movementadding or removing a server moves ~1/N of keys
  4. 04
    Agreementall clients map a key to the same server
  5. 05
    Heterogeneous serversbigger machines take more keys
  6. 06
    Replicationoptionally, copies on several servers

Start by pinning down the setting. We have a cluster of cache servers, say twenty of them, holding a few hundred million keys between them. Many application servers read and write keys. Every application server must be able to work out, on its own and quickly, which cache server owns a given key.

Functional requirements. Given a key, return the server that owns it. That function must be deterministic, so every client gets the same answer, and it must be fast, because it runs on every single cache request.

Non-functional requirements. Even load: each server should hold close to its fair share of keys and traffic. Minimal disruption: when a server joins or leaves, only a small fraction of keys should change owner, ideally about one Nth, where N is the number of servers, because that is the unavoidable minimum. Everything else is wasted movement.

Ask a few questions. Are servers the same size? If not, we need weights. Is this a pure cache, where losing a key just means a miss, or a store, where moving a key means copying data? Do we need replicas? Does the client compute the mapping, or a proxy in the middle? The answers change the details, so ask them out loud.

Step 2: Back-of-the-envelope estimates

The cluster
Servers20
Keys300 million~15M per server
Reads500,000/s~25,000/s per server
Cache hit rate95%database sees 25,000/s
Database capacity~40,000/sbefore it struggles

A few numbers make the stakes concrete. Say twenty cache servers, three hundred million keys, and five hundred thousand cache reads a second across the cluster.

At a ninety-five per cent hit rate, the database behind the cache sees five per cent of the traffic: twenty-five thousand reads a second. Say the database can survive about forty thousand. That margin is the whole story of this question.

Now imagine that adding one server causes most keys to change owner. Those keys are now looked up on servers that do not have them. The hit rate drops from ninety-five per cent to near zero for a while, the database suddenly sees hundreds of thousands of reads a second instead of twenty-five thousand, and it falls over. Adding capacity to the cache took the whole site down.

So minimal movement is not a nice-to-have. With a cache, every moved key is a miss, and a burst of misses is an outage. With a store, every moved key is data copied over the network. Either way, we want to move as close to one twentieth of the keys as possible when we go from twenty servers to twenty-one.

Step 3: The naive approach, and why it fails

Modulo hashing
def server_for(key, servers):
    h = hash64(key)               # stable hash, e.g. 64 bits
    return servers[h % len(servers)]

# 20 servers: key 'user:42' → h % 20 = 7  → server 7
# 21 servers: key 'user:42' → h % 21 = 13 → server 13 (moved!)

The answer everyone reaches for first is simple. Hash the key to a big number, then take it modulo the number of servers. Server equals hash of key, mod N. It is fast, it is deterministic, and with a good hash function the load is very even.

A note on the hash function: it must be stable across machines and languages, so every client agrees. A language's built-in hash is often randomised per process, so use a defined function, such as a fast non-cryptographic sixty-four bit hash, or a cryptographic one if speed is not a concern.

Keys that move with modulo hashing
ChangeIdeal movementModulo moves
20 → 21 servers~5%~95%
20 → 19 servers~5%~95%
100 → 101 servers~1%~99%

Now the problem. Change N from twenty to twenty-one. A key stays on the same server only if its hash mod twenty equals its hash mod twenty-one, which is true for only about one key in twenty-one. So roughly ninety-five per cent of keys move. Exactly the disaster we just estimated.

Removing a server is just as bad, and removing one is not always planned: a server crashes, N drops to nineteen, and the whole cache is suddenly cold. With more servers it only gets worse: going from a hundred to a hundred and one moves about ninety-nine per cent of keys.

Say this clearly in the interview, with the number. Modulo hashing gives perfect balance but terrible stability. What we want is a scheme where changing N moves only the keys that have to move. That scheme is consistent hashing.

Step 4: The hash ring

The hash ring
clockwiseclockwisewraps past 0EDGE0 / 2^64SERVICEServer Aat 12%SERVICEServer Bat 45%SERVICEServer Cat 78%CLIENTkey xat 30%CLIENTkey yat 60%CLIENTkey zat 95%

Here is the idea. Take the output range of the hash function, say zero to two to the sixty-four minus one, and bend it into a circle, so the largest value wraps around to zero. Call it the ring.

Now hash each server, for example its name or address, onto the ring. Server A lands at twelve per cent of the way round, server B at forty-five, server C at seventy-eight.

Then hash each key onto the same ring. The rule: a key belongs to the first server you meet walking clockwise from the key's position. Key x at thirty per cent walks clockwise and meets server B at forty-five. Key y at sixty per cent meets server C. Key z at ninety-five per cent walks past the top, wraps round to zero, and meets server A.

So each server owns an arc: the stretch of ring between the previous server and itself. Server B owns everything from twelve per cent up to forty-five. That is the whole algorithm. It looks almost too simple, so let us see why it solves our problem.

Step 5: Adding and removing servers

Adding server D at 35%
Ring segmentOwner beforeOwner after
78% → 12% (wrap)AA
12% → 35%BD (moved)
35% → 45%BB
45% → 78%CC

Add a server D, which hashes to thirty-five per cent, between A at twelve and B at forty-five. Which keys change owner? Only the keys between twelve and thirty-five per cent. They used to walk clockwise to B; now they meet D first. Every other key on the ring is untouched.

And all the moved keys came from one place, server B. On average, a new server takes about one Nth of all keys, which is exactly the minimum we said was unavoidable. Compare that to ninety-five per cent with modulo hashing.

What consistent hashing guarantees
  1. 01
    Joinnew server takes keys only from its clockwise neighbour
  2. 02
    Leaveits keys go only to its clockwise neighbour
  3. 03
    Movement~1/N of keys on average
  4. 04
    Everyone elseuntouched, cache stays warm

Removing a server is the mirror image. If B crashes, the keys in its arc, twelve to forty-five per cent, now walk further clockwise and land on C. Nothing else moves. In a cache, those keys miss once and are refilled from the database. The rest of the cache stays warm.

But look again at that last example, because an interviewer will. When B fails, all of its keys land on one server, C. C suddenly has double the load. And even before any failure, our three servers sat at twelve, forty-five and seventy-eight per cent, so their arcs were thirty-three, thirty-three and thirty-four per cent. That was lucky. With random positions, arcs are usually very uneven. Both problems have the same fix.

Step 6: Virtual nodes

Load spread vs points per server
1 point per serverlargest ≈ 3–4× smallestvery uneven
10 points± ~30%
100 points± ~10%common choice
1,000 points± ~3%more memory, still small

With only one point per server, positions are random, and random points on a circle leave very uneven gaps. With ten servers, it is normal for the biggest arc to be three or four times the smallest. One server holding three times its share of keys gets three times the traffic, and it is the one that runs out of memory first.

Virtual nodes on the ring
SERVICEA·0WORKERB·0STOREC·0SERVICEA·1WORKERB·1STOREC·1SERVICEA·2WORKERB·2

The fix is virtual nodes. Instead of putting each server on the ring once, put it on the ring many times, say a hundred or two hundred times, by hashing server A hash zero, server A hash one, and so on. Each of those points is a virtual node, and each owns a small arc. A key still walks clockwise to the first point, and that point says which real server it belongs to.

Two things improve. First, balance. Each server's share is now the sum of many small arcs, and sums of many random pieces are much more even than a single random piece. With a hundred virtual nodes per server, shares are typically within about ten per cent of fair.

Second, failure spreads out. When server B dies, its hundred small arcs are each taken over by whatever point comes next, which is a different server each time. So B's load is spread roughly evenly across all the survivors, instead of doubling one neighbour. Likewise, a new server takes a little from everyone, instead of a lot from one.

Weights through virtual nodes
ServerMemoryVirtual nodesShare of keys
A64 GB100~20%
B64 GB100~20%
C128 GB200~40%
D (draining)64 GB100 → 50 → 0~20% → 0

Virtual nodes also give us weights for free. A server with twice the memory gets twice as many virtual nodes, and so about twice the keys. Retiring a server gently is possible too: reduce its virtual nodes step by step, so its keys drain away gradually instead of all at once.

The cost is memory and ring-building time, and both are small. Twenty servers with two hundred points each is four thousand entries. Even a thousand servers with two hundred points is two hundred thousand entries, a few megabytes, which every client can hold easily.

Step 7: The lookup in code

Ring lookup
class Ring:
    def __init__(self, servers, vnodes=200):
        pts = [(hash64(f'{s}#{i}'), s)
               for s in servers for i in range(vnodes * s.weight)]
        pts.sort()
        self.hashes = [h for h, _ in pts]
        self.owners = [s for _, s in pts]

    def owner(self, key):
        i = bisect_left(self.hashes, hash64(key))
        return self.owners[i % len(self.hashes)]   # wrap past top

How does a client find the owner fast? Store the ring as a sorted array of point positions, each with its server. To find a key's owner, hash the key and binary search for the first point greater than or equal to the hash. If you run off the end, wrap around to the first point.

A binary search over four thousand points takes about twelve comparisons. Even over two hundred thousand points, it is about eighteen. That is well under a microsecond, cheap enough to run on every request.

Building the ring means hashing every virtual node and sorting, a few milliseconds. We rebuild it only when membership changes, which is rare, and swap the new ring in atomically, so lookups never see half a ring.

Two small details worth mentioning. If two points ever collide on the same hash, break the tie deterministically, for example by server name, so every client agrees. And make sure the same server never appears twice in a row when you choose replicas, which brings us to replication.

Step 8: Replication around the ring

Replicas clockwise
first pointnext pointnext distinctnext distinctCLIENTkey xSERVICEServer B1st: ownerWORKERB againskip duplicateSERVICEServer D2nd replicaSERVICEServer A3rd replica

For a cache, one copy is often enough: losing a server means some misses. For a key value store, or a cache that must stay hot, we keep several copies. The ring gives us a natural place to put them.

Walk clockwise from the key, and take the first three distinct physical servers you meet. The first is the owner; the next two hold replicas. With virtual nodes, the next point might belong to the same server again, so skip any server you already have.

Go one step further in a real deployment: skip servers in the same rack or availability zone as one you have already chosen. Then a single rack failure or zone failure cannot take out every copy of a key. This list of servers for a key is often called its preference list.

The ring also tells us exactly what to repair after a failure. If server B dies, every key that had B in its preference list now takes the next distinct server clockwise as its new replica, and that server copies those keys from the surviving replicas. Because of virtual nodes, that repair work is spread across the whole cluster.

Step 9: Who owns the ring?

Where the mapping lives
OptionHowTrade-off
Client libraryevery client builds the ringfastest; every client must agree
Proxy tierclients talk to a proxy that routesone place to change; extra hop
Server redirectany server answers 'ask server C'simple clients; extra round trip on miss

Here is a subtle point that strong candidates raise without being asked. Consistent hashing only works if every client has the same ring. If one application server thinks there are twenty cache servers and another thinks there are twenty-one, they send the same key to different servers, and you get misses at best and inconsistent data at worst.

First decide where the mapping lives. Client side, every application server holds the ring and talks straight to the right cache server. That is the fastest, with no extra hop, but every client must be updated. A proxy tier puts the ring in a few proxies, so only they need to agree, at the cost of an extra network hop. Or servers can redirect: ask any server, and it tells you who owns the key.

Spreading ring changes
  1. 01
    Source of truthconfig service with a versioned server list
  2. 02
    Clients watchrebuild ring, swap atomically
  3. 03
    Version on requestsserver can reject a stale ring
  4. 04
    Health checksremove dead servers deliberately, not on one timeout
  5. 05
    Peer gossipalternative for large peer-to-peer stores

Then decide how membership changes spread. The usual answer: a small, strongly consistent configuration service holds the list of servers and their weights, with a version number. Clients watch it. When the list changes, every client rebuilds its ring and swaps it in, usually within a second or two.

For a few seconds, some clients have the old ring and some the new one. For a cache, that just causes a few extra misses. For a store, include the ring version in requests, so a server can reply: you have an old ring, refresh and retry.

And be careful about removing servers automatically. If a server is slow for one second and every client drops it from the ring, its keys move, then it comes back and they move again. Flapping like that is worse than the slowness. Require several failed health checks, or a human, before changing the ring. Large peer-to-peer stores sometimes spread membership by gossip between servers instead of a central service; mention it as an alternative.

Step 10: Moving data safely

Adding a server to a data store
  1. 01
    1. Join as pendingreceives copies of its future keys
  2. 02
    2. Stream datafrom current owners, throttled
  3. 03
    3. Dual writenew writes go to old and new owner
  4. 04
    4. Switch readspublish new ring version
  5. 05
    5. Clean upold owner deletes keys it no longer owns

For a pure cache, a new server simply starts empty, and its keys miss and refill. Even so, about one Nth of keys missing at once can hurt the database, so add cache servers one at a time, at quiet hours, and let each warm up before the next.

For a data store, a moved key without its data is lost data, so the new server joins in stages. First, it joins as pending: it is in the next version of the ring, but clients still use the current one.

The current owners stream the keys that will move to the new server, throttled so they do not starve live traffic. Meanwhile, writes to those keys go to both the old and the new owner, so nothing written during the copy is missed.

When the copy has caught up, publish the new ring version. Reads and writes now go to the new owner. Finally, the old owners delete the keys they no longer own, after a safety delay. Removing a server deliberately is the same process in reverse.

Thanks to virtual nodes, the new server pulls a small slice from every existing server in parallel, so the copy finishes quickly and no single server is overloaded by the migration.

Step 11: Hot keys and bounded load

Handling hot keys
  1. 01
    Local cacheclients cache hot keys for a second or two
  2. 02
    Key splittingpost:9#0 … post:9#7 spread across servers
  3. 03
    Read replicasread hot keys from any replica
  4. 04
    Bounded loadscap each server at ~1.25× average; overflow walks on

Consistent hashing balances keys, not traffic. If one key is wildly popular, say a viral post read a hundred thousand times a second, it lives on one server, and no amount of virtual nodes helps, because the ring maps that key to exactly one place.

Fixes, in order of simplicity. A small local cache in each client for the hottest keys, valid for a second or two, absorbs most of the load. Or split the key: store eight copies under eight suffixed names, which hash to different servers, and have readers pick one at random. Or, with replication, read hot keys from any replica, not just the owner.

There is also a neat variant called consistent hashing with bounded loads. Give every server a capacity of, say, one and a quarter times the average load. When a key's owner is full, the key keeps walking clockwise to the next server with room. Balance becomes guaranteed, at the cost of a little extra movement. Mentioning it shows depth.

Step 12: Alternatives worth knowing

Three ways to pick a server
SchemeHowStrengthsWeaknesses
Ring + vnodesfirst point clockwiseflexible, weights, replicasmemory for points, some imbalance
Rendezvous (HRW)score every server with hash(key, server); highest winssimple, even, no ringO(N) per lookup
Jump hashtiny arithmetic loop → bucket 0..N-1no memory, perfectly evenonly add/remove at the end

The ring is not the only way to get minimal movement. Two alternatives come up in interviews, and knowing them shows you understand the problem rather than one solution.

Rendezvous hashing, also called highest random weight. For each key, compute a score for every server, hash of key and server together, and pick the server with the highest score. When a server leaves, only its keys move, to their second-highest server. It is very simple and very even, but each lookup touches every server, which is fine for tens of servers and slow for thousands.

Jump consistent hashing is a few lines of arithmetic that map a key to a bucket number from zero to N minus one, with perfect balance and no memory at all. Its limitation: buckets are numbered, so you can only add or remove the last one. That suits storage shards with numbers, not cache servers that fail at random.

Recommend the ring with virtual nodes for a cluster of servers that come and go, mention rendezvous for small clusters, and jump hashing for numbered shards. Being able to compare them is exactly the kind of judgement this question rewards.

Step 13: The follow-up questions

Follow-up questions
  1. 01
    How many virtual nodes?
  2. 02
    Prove the movement
  3. 03
    Range queries
  4. 04
    Ring vs fixed partitions
  5. 05
    Monitoring

Now the follow-up questions. Here is Max, our AI interviewer, with the kind of thing an interviewer asks after this answer.

Max asks

“How do you choose the number of virtual nodes?”

Balance improves roughly with the square root of the number of points, so going from ten to a hundred points per server helps a lot, and going from a thousand to ten thousand helps a little. A hundred to two hundred per server is a common choice. Measure the actual spread of keys per server in a simulation with your real server count, and pick the smallest number that keeps every server within about ten per cent of fair.

Max asks

“Why does adding one server move only about one Nth of the keys?”

A new server's virtual nodes take over the arcs just before them on the ring. With N plus one servers and evenly spread points, the new server ends up owning about one in N plus one of the ring, and only those keys change owner. Every other key still walks clockwise to the same point it did before, so it does not move at all.

Max asks

“Can you do range queries over keys with consistent hashing?”

Not efficiently, because hashing scatters neighbouring keys across the ring on purpose. If you need ranges, partition by key range instead: split the sorted key space into ranges, assign ranges to servers, and split or move ranges as they grow. Many databases do exactly that. Consistent hashing is for point lookups.

Max asks

“Why not just use a fixed number of partitions, say a thousand, and assign them to servers?”

That is a very good alternative, and many systems use it. Hash keys into a thousand fixed partitions, and keep a small table mapping partitions to servers. Adding a server means moving some whole partitions to it. Movement is minimal and fully controlled, and the table is easy to reason about. It is really a hand-managed version of virtual nodes. The trade-off is that the table must be stored and updated centrally, and the partition count must be chosen large enough up front.

Max asks

“How would you know the hashing is working well in production?”

Track keys, memory and requests per second per server, and alert when any server is more than, say, twenty-five per cent above average. Track the cache hit rate during every membership change, which shows how much movement really happened. And log the ring version every client uses, so you can spot a client stuck on an old ring.

Step 14: The parts people forget

Often forgotten
  1. 01
    Stable hash functionsame output in every language and process
  2. 02
    Agreementall clients on the same ring version
  3. 03
    Flappingdon't remove a server on one timeout
  4. 04
    Cold startadd cache servers one at a time
  5. 05
    Traffic ≠ keyshot keys need their own fix

A few points that candidates often miss.

The hash function must be stable across every client language and process. A per-process randomised hash silently breaks the whole design, because two clients disagree about every key.

Clients must agree on the ring, so it comes from one versioned source of truth, not from each client's own view of which servers responded recently.

Membership changes must be deliberate. Removing a server on a single timeout causes flapping, and every flap moves keys twice.

Adding cache capacity is itself a load event, because moved keys miss. Add one server at a time, at a quiet hour, and watch the database.

And balanced keys do not mean balanced traffic. A single hot key needs local caching, splitting or replica reads, whatever the ring looks like.

Recap

Recap
  1. 01
    Modulo fails~95% of keys move on any change
  2. 02
    The ringfirst server clockwise owns the key
  3. 03
    Virtual nodeseven load, weights, failures spread out
  4. 04
    Replicasnext distinct servers, different racks
  5. 05
    Lookupbinary search over sorted points
  6. 06
    Agreementversioned ring from one source
  7. 07
    Migrationstream, dual write, switch, clean up
  8. 08
    Alternativesrendezvous, jump hash, fixed partitions

Let us recap. Hash modulo N balances well but moves almost every key when N changes, which empties a cache and floods the database. Consistent hashing puts servers and keys on one ring, and each key belongs to the first server clockwise, so a change moves only about one Nth of the keys.

Virtual nodes even out the load, give weights for free and spread a failed server's keys across everyone. Replicas go to the next distinct servers clockwise, in different racks. Lookups are a binary search over a small sorted array.

Every client must use the same ring, published from one versioned source of truth. Data stores move keys in stages: stream, dual write, switch, clean up. And know the alternatives: rendezvous hashing, jump hashing and fixed partitions.

In a forty-five minute interview: five minutes on requirements and the cost of moving keys, ten minutes on why modulo fails and the ring, fifteen on virtual nodes, replication and lookups, and the rest on membership, migration and follow-ups. The moment that wins it is putting a number on the failure: ninety-five per cent of keys move, the cache goes cold, the database falls over.

Practice saying exactly that, out loud, with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson thirty-three, where we design a pastebin.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.