Consistent hashing in system design

Consistent hashing maps keys to servers so that adding or removing a server moves only the keys that server gains or loses, about 1/N of them, instead of reshuffling almost everything as hash(key) mod N does. Servers and keys are hashed onto the same ring, and each key belongs to the next server clockwise. Virtual nodes, many ring positions per server, keep the load even and spread a failed server's keys across the survivors.

By Published 8 min read

1. What consistent hashing is

Any distributed cache or partitioned store has to answer one question for every request: which machine holds this key? The obvious answer, hash the key and take it modulo the number of machines, works until the number of machines changes. Consistent hashing, introduced in a 1997 paper by Karger and colleagues for web caching, is a mapping that stays mostly stable when machines come and go. It shows up in distributed caches, Dynamo-style databases, load balancers that need affinity, and peer-to-peer systems.

2. Why interviewers ask about it

It is the standard answer to "how do you add a cache node without a cold-cache meltdown?" and "how does this store rebalance?". Interviewers use it to check whether you understand the cost of moving data, not just the picture of a circle. Strong answers mention virtual nodes, replica placement and hot keys without being asked; weak answers stop at "put the servers on a ring".

3. Why hash mod N breaks

With server = hash(key) mod N, a key stays on the same server after N changes only if its hash gives the same remainder under both counts. Going from 4 to 5 servers, that holds for one key in five, so roughly 80% of keys move. For a cache, that means 80% misses at once, all landing on the database. For a store, it means copying most of the data across the network. In our run of 100,000 keys, mod N moved 79.9% of them.

4. The ring, step by step

  1. Pick a hash spaceFor example, 64-bit integers, treated as a circle so the largest value wraps to zero.
  2. Place serversHash each server's ID (or several IDs per server, see virtual nodes) to positions on the ring.
  3. Place keysHash each key with the same function.
  4. Walk clockwiseA key belongs to the first server position at or after its own. Past the top, wrap to the start.
  5. Add a serverIt takes over only the arc between its position and the previous server's. Every moved key goes to the new server; no other key moves.
  6. Remove a serverIts arc passes to the next server clockwise. Only its keys move.
import bisect, hashlib

def h(s: str) -> int:
    # 64-bit ring position from a stable hash (not Python's built-in hash())
    return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")

class Ring:
    def __init__(self, vnodes: int = 100):
        self.vnodes = vnodes
        self.points = []   # sorted ring positions
        self.owner = {}    # position -> node name

    def add(self, node: str) -> None:
        for i in range(self.vnodes):
            p = h(f"{node}#{i}")
            bisect.insort(self.points, p)
            self.owner[p] = node

    def remove(self, node: str) -> None:
        for i in range(self.vnodes):
            p = h(f"{node}#{i}")
            self.points.remove(p)
            del self.owner[p]

    def lookup(self, key: str) -> str:
        i = bisect.bisect_right(self.points, h(key))
        if i == len(self.points):   # wrap around the top of the ring
            i = 0
        return self.owner[self.points[i]]

ring = Ring(vnodes=100)
for n in ["A", "B", "C", "D"]:
    ring.add(n)
keys = [f"user:{i}" for i in range(100_000)]
before = {k: ring.lookup(k) for k in keys}
ring.add("E")
after = {k: ring.lookup(k) for k in keys}
moved = [k for k in keys if before[k] != after[k]]
print(f"moved {len(moved) / len(keys):.1%}, all to E: {all(after[k] == 'E' for k in moved)}")
# moved 19.6%, all to E: True
A minimal ring with virtual nodes (run with python3; output shown at the end)

Lookups are a binary search over the sorted positions, so O(log V) where V is the total number of virtual nodes. Ties between positions are possible in principle with a weak hash; a 64-bit hash makes them vanishingly rare, and production code breaks ties deterministically.

5. Virtual nodes and load balance

With one position per server, the arcs are random lengths, so some servers own far more of the ring than others. Giving each server many positions averages that out. In our test with four servers and 100,000 keys, averaged over five runs with different hash salts, the busiest server held this multiple of the average load:

Busiest server's load relative to the mean, 4 servers, 100,000 keys (average of 5 runs; single runs vary)
Virtual nodes per serverBusiest server vs average
1about 1.9 times (single runs ranged 1.4 to 2.5)
10about 1.3 times
100about 1.08 times
1,000about 1.03 times
Busiest server's load relative to the mean, 4 servers, 100,000 keys (average of 5 runs; single runs vary). Scroll sideways on a small screen.
  • Spreading failures. When a server with many positions dies, its arcs pass to many different neighbors, so no single survivor takes the whole load.
  • Weighting. A machine with twice the memory can take twice the virtual nodes.
  • Cost. More positions mean a bigger routing table and slower membership changes. Hundreds per server is a common middle ground.

6. Replication, hot keys and bounded loads

Replicas on the ring. Dynamo-style stores keep N copies of each key on the first N distinct physical servers clockwise from it, skipping extra virtual nodes of a server already chosen. Placement across racks or zones needs one more rule: skip servers in a zone that already holds a copy. Our consistency and CAP guide covers how reads and writes then use those replicas, and database replication covers how the copies stay in step.

Hot keys. Consistent hashing balances the number of keys, not the traffic per key. One celebrity profile or one viral URL still lands on one server. Fixes sit above the ring: cache the hot key locally in the app tier, replicate it to several servers and read from any, or split the key (key#1 to key#8) and merge on read.

Bounded loads. A refinement by Mirrokni, Thorup and Zadimoghaddam, consistent hashing with bounded loads, caps each server at a small factor above the average; if a key's server is full, the key goes to the next server clockwise with room. It trades a little stability for a hard limit on imbalance, which helps load balancers that route sessions.

7. Alternatives worth naming

Other ways to get small movement when the server count changes
MethodHow it worksStrengthWeakness
Rendezvous (highest random weight)Score every server with hash(server, key); the highest score winsNo ring to store; even load without virtual nodes; easy weightingLookup is O(N) servers, fine for tens of servers, slow for thousands
Jump consistent hashA short loop maps a key to bucket 0..n-1 using no stored stateTiny, fast, near-perfect balanceBuckets are numbered, so you can only add or remove at the end; no arbitrary server removal
Fixed logical partitionsHash into a fixed number of partitions (thousands); a table maps partitions to serversSimple rebalancing: move whole partitions; easy to reason aboutPartition count chosen up front; the table must be stored and kept consistent
Other ways to get small movement when the server count changes. Scroll sideways on a small screen.
def rendezvous(key: str, nodes: list[str]) -> str:
    return max(nodes, key=lambda n: h(f"{n}|{key}"))

def jump_hash(key: int, buckets: int) -> int:
    # Lamping and Veach's jump consistent hash; buckets numbered 0..n-1
    b, j = -1, 0
    while j < buckets:
        b = j
        key = (key * 2862933555777941757 + 1) & 0xFFFFFFFFFFFFFFFF
        j = int((b + 1) * (1 << 31) / ((key >> 33) + 1))
    return b
Rendezvous and jump hash, reusing h() from above (run: both moved 20.1% of keys going from 4 to 5 servers, all to the new one)

8. How it shows up in common prompts

Where a stable key-to-server mapping matters
PromptWhat is hashedWhy consistent hashing
Caching layer for any read-heavy designCache keys to cache nodesAdding a node must not empty most of the cache
Rate limiterUser or API key to counter shardAll of one user's requests must hit the same counter
Web crawlerHostname to crawler workerPoliteness per host needs one worker per host
Sharding a key-value storePartition key to storage nodeRebalancing should copy as little data as possible
Load balancing with affinitySession or user ID to backendKeep a user's local state warm while backends change
Where a stable key-to-server mapping matters. Scroll sideways on a small screen.

9. Mistakes to avoid

  • Using a language's built-in hash. Some are randomized per process, so two app servers would disagree about the ring. Use a stable hash such as MD5, xxHash or MurmurHash.
  • One position per server. Load can be twice the average or worse on the unlucky server.
  • Claiming it fixes hot keys. It balances key counts, not request rates.
  • Forgetting the data move. The keys that move still have to be copied or warmed; plan a background transfer and serve from the old owner until it finishes.
  • Ignoring membership. Every client must see the same ring. Say where membership lives (a config store, gossip) and what happens while it changes.

10. How to talk about it in the interview

  • Say why mod N fails with a number: about 80% of keys move going from 4 to 5 servers.
  • Describe the ring in two sentences, then add virtual nodes unprompted.
  • Explain replica placement and zone awareness if the design stores data.
  • Name the hot key limit and your fix.
  • Mention fixed partitions as the common alternative and why you picked one or the other.

Fictional example

Scaling a session cache
Interviewer
Your session cache has eight nodes and you need a ninth before a sales event. What happens?
Candidate
I map session IDs with consistent hashing, about 200 virtual nodes per server. Adding the ninth moves roughly one ninth of sessions, all to the new node, so the other eight keep their hit rate.
Interviewer
Those moved sessions still miss, right?
Candidate
Yes, so for a short window the client checks the new owner first and falls back to the old one, and the new node fills as it goes. For sessions I could also replicate each key to the next node clockwise so a failed node doesn't log people out.
Interviewer
And one very busy key?
Candidate
The ring won't help with that. I'd cache it in the app servers for a few seconds or copy it to several nodes.

Practicing with Natively

Consistent hashing is easy to draw and harder to defend when an interviewer asks about the second-order effects. During a mock session, Natively transcribes both voices as you talk and can offer talking points on each follow-up, which makes it obvious afterwards if you never mentioned virtual nodes or data movement. Capture a screenshot of a ring diagram or a prompt and it can walk you through it. The transcript and notes stay available for review once the practice ends.

Questions people ask

What is consistent hashing?

A way to map keys to servers so that adding or removing a server moves only about 1/N of the keys. Servers and keys are hashed onto the same ring, and each key belongs to the first server clockwise from its position.

Why are virtual nodes used in consistent hashing?

With one ring position per server, arcs have random sizes and some servers get far more keys than others. Giving each server many positions evens out the load, lets bigger machines take more positions, and spreads a failed server's keys across many survivors.

Does consistent hashing solve hot keys?

No. It balances how many keys each server owns, not how much traffic each key gets. A single very popular key still lands on one server; fix that with local caching, replicating the key or splitting it into sub-keys.

What is the difference between consistent hashing and rendezvous hashing?

Rendezvous hashing scores every server for each key and picks the highest score. It needs no ring or virtual nodes and balances well, but a lookup checks every server, so it suits small pools. Both move only the keys of the server that changed.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP