Consistent hashing is a way to decide which server owns a key so that adding or removing a server moves only a small share of the keys. Keys and servers are hashed onto a circle called the hash ring, and each key belongs to the first server found clockwise from its position.

In this article we follow one example the whole way: the session cache of an online exam platform in Hyderabad. Millions of student sessions live on a few cache servers, and the cluster must grow on exam day without losing every cached session. You will see why the usual hash(key) % N breaks, how the ring fixes it, and how virtual nodes, replicas and hot keys work. Every idea comes with runnable Java code plus Python and C++, and real measured numbers.

Key takeaways

  • With hash(key) % N, going from 6 to 7 servers moved 85.8% of 50,000 keys; from 99 to 100 servers it moved 99.0%.

  • On a hash ring, adding a server moved only the keys in one arc (8.0% in our test), and every moved key went to the new server.

  • One position per server gives uneven load (the busiest server held 1.65x the average). 500 virtual nodes per server brought it to 1.07x.

  • Replicas must be walked clockwise to distinct servers; a naive "next three positions" repeated a server for 40.3% of keys.

  • Rendezvous hashing and jump hash are simpler alternatives for some clusters; the ring is the right choice when you need weights, replicas and many servers.

  • Consistent hashing decides placement. It does not move data, copy replicas or keep clients in agreement; those are separate jobs.

1. What Is Consistent Hashing?

A big system spreads data over many machines. A request for one key must find the machine that holds it, and it must find the same machine every time. The mapping from key to machine is a routing function. Consistent hashing is a routing function that stays almost the same when machines come and go.

It was introduced by Karger and colleagues at MIT in 1997 to spread web-cache traffic. Today it sits inside cache clients, sharded databases and load balancers. If you have read about scalability, this is how the data tier scales horizontally without a mass reshuffle.

Two questions explain why it matters. Why is consistent hashing used? Because servers are added for traffic peaks and replaced after failures, and each change must not make the whole cache cold. What does it guarantee? With N well-balanced servers, adding one moves about 1/(N+1) of the keys, instead of nearly all of them.

2. The Exam Platform We Will Use

Imagine an exam platform with one login service and a cluster of cache servers named cache-1, cache-2, .... When a student signs in, the platform stores their session (profile, current test, time left) in the cache under a key such as student:101. Every later request reads that key first and only goes to the database on a miss.

EventWhat the platform needsWhat goes wrong with a bad routing rule
Exam day traffic spikeAdd cache servers quicklyMost sessions move; the cache goes cold in the middle of an exam
A cache server crashesKeep serving everyone elseEvery key may change server, not just the dead one's keys
A server is replacedSwap one machineDatabase is flooded by cache misses
One test paper is opened by everyoneServe one key very fastOne server melts while the others sit idle

All the experiments use key names such as student:0, student:1, student:2 and servers called cache-N. A small hash function (MurmurHash3, 32 bits) turns every key and server name into a number from 0 to 4,294,967,295, and it gives the same answer in Java, Python and C++.

3. Why Modulo Hashing Fails When Servers Change

The simplest rule is server = hash(key) % N, where N is the number of servers. It is fast, needs no memory and balances load well. It has one fatal weakness: N is part of the formula, so changing N changes the answer for almost every key.

Output

== Five sessions, 6 servers then 7 servers ==
  student:101 -> cache-1 with 6 servers, cache-3 with 7 servers
  student:102 -> cache-5 with 6 servers, cache-0 with 7 servers
  student:103 -> cache-3 with 6 servers, cache-4 with 7 servers
  student:104 -> cache-2 with 6 servers, cache-1 with 7 servers
  student:105 -> cache-2 with 6 servers, cache-6 with 7 servers
== Keys that change server out of 50000 ==
  6 -> 7 servers: 42885 moved (85.8%)
  7 -> 6 servers: 42885 moved (85.8%)
  11 -> 12 servers: 45766 moved (91.5%)
  99 -> 100 servers: 49514 moved (99.0%)

Dry run. Look at student:101. With 6 servers its hash modulo 6 is 1, so it lives on cache-1. After a 7th server joins, the same hash modulo 7 is 3, so the platform now looks on cache-3, where nothing is stored. Over 50,000 keys, going from 6 to 7 servers sends 42,885 keys (85.8%) to a different server. Removing a server from 7 to 6 moves exactly the same keys back. The bigger the cluster, the worse it gets: 11 to 12 servers moves 91.5% and 99 to 100 servers moves 99.0%. The share that stays put is about 1/(N+1), so adding a server to a big cluster is almost the same as clearing the whole cache.

For a cache, a moved key is a cache miss: the data is still sitting on the old server, but nobody will look there, so every request goes to the database. This is the cache stampede that takes systems down on exam day.

4. The Hash Ring

Consistent hashing removes N from the formula. Imagine all hash values from 0 to 4,294,967,295 written around a circle, so the largest value joins back to 0. This circle is the hash ring.

  1. Place each server on the ring by hashing its name (or IP address): position = hash("cache-1").

  2. Place each key on the ring with the same hash function: position = hash("student:2").

  3. Find the owner by walking clockwise from the key until you meet a server. That server owns the key.

These are the real positions our hash gives. cache-1 sits at 0x26b891cd, cache-2 at 0x402922ff, cache-5 at 0xb2212b44, cache-4 at 0xbddbf959, cache-6 at 0xe8ebe31b and cache-3 at 0xee02d202. The key student:2 hashes to 0x40a866fc, so walking clockwise the first server it meets is cache-5. The key student:14 hashes to 0xf5646c8b, which is past the last server, so the walk wraps around the end of the ring and lands on cache-1.

Each server therefore owns an arc: all positions between the previous server and itself. When the number of servers changes, only the arcs next to the change are affected.

5. How the Owner of a Key Is Found

You do not need a real circle in code. Keep the server positions in a sorted structure, and for each key find the smallest position that is greater than or equal to the key's hash. In Java this is a TreeMap and the call ceilingEntry(hash); in Python it is bisect_left on a sorted list; in C++ it is std::map::lower_bound. If nothing is found, the key is past the last server, so wrap to the first entry.

A lookup costs O(log V), where V is the number of positions on the ring, and a membership change costs O(R log V), where R is the number of positions that server owns. Both are tiny compared with a network call to the cache.

6. Adding and Removing a Server

This is the whole point of the ring. When cache-7 is added, it is placed at its own hash position and takes over only the arc between its predecessor and itself. Keys everywhere else keep their owner. When a server is removed, only the keys it owned move, to the next server clockwise.

Output

== Ring positions (one per server) ==
  26b891cd  cache-1
  402922ff  cache-2
  b2212b44  cache-5
  bddbf959  cache-4
  e8ebe31b  cache-6
  ee02d202  cache-3
== Load with 6 servers (50000 keys) ==
  cache-1: 11005 keys (22.0%)
  cache-2: 4994 keys (10.0%)
  cache-3: 1050 keys (2.1%)
  cache-4: 2241 keys (4.5%)
  cache-5: 22292 keys (44.6%)
  cache-6: 8418 keys (16.8%)
== Add cache-7 ==
  keys moved: 4000 (8.0%), of which to cache-7: 4000
== Remove cache-4 ==
  cache-4 held 2241 keys; keys moved: 2241, all of them from cache-4: true

Dry run. With 6 servers the ring positions in clockwise order are cache-1, cache-2, cache-5, cache-4, cache-6 and cache-3. The 50,000 keys are split as 11,005, 4,994, 1,050, 2,241, 22,292 and 8,418 for cache-1 to cache-6. Now cache-7 is hashed to 0xd2309e8d, between cache-4 (0xbddbf959) and cache-6 (0xe8ebe31b). 4,000 keys (8.0%) change owner, and the program checks that all 4,000 went to cache-7: no key moved between two old servers. Then cache-4, which holds 2,241 keys, is retired: exactly 2,241 keys move, and every one of them was owned by cache-4. Compare this with 42,885 moves from the modulo rule.

Notice what the numbers also reveal. With six servers and one position each, the load is very uneven: cache-3 holds only 2.1% of the keys and cache-5 holds 44.6%. Only 8.0% of the keys moved when the seventh server joined instead of the ideal 14.3% (1/7), because the new server landed in a short arc. This is the weakness we fix next.

7. How Many Keys Move?

When servers are balanced, adding the (N+1)th server to a cluster of N moves about 1/(N+1) of the keys. Going from 12 to 13 servers should move about 7.7% of them, and from 99 to 100 servers about 1%. Compare this with modulo hashing, where the same changes moved 92.5% and 99.0%.

The number is an average, and a ring with a single position per server can be far from it. In the later comparison, the same 12 to 13 change on a one-position ring moved 14.2% of the keys (almost twice the ideal), and one server held 2.00x the average load. Moving few keys is good only if the load is also even, which is what virtual nodes provide.

8. Uneven Load and Virtual Nodes

Hashing a server name once gives it one random point on the ring, and random points are rarely evenly spaced. One server can end up owning a very long arc and another a tiny one. This is the hot spot problem.

What are virtual nodes in consistent hashing? Instead of one position per server, give each server many positions by hashing cache-1/v0, cache-1/v1, cache-1/v2 and so on. Every position points back to the same physical server. The lookup rule does not change; the server just owns many small arcs that average out.

Output

== Balance with 6 servers, 50000 keys (average 8333 per server) ==
    1 positions per server: busiest 13785 (1.65x), quietest 5725 (0.69x)
   10 positions per server: busiest 15095 (1.81x), quietest 4517 (0.54x)
  100 positions per server: busiest 9335 (1.12x), quietest 7182 (0.86x)
  500 positions per server: busiest 8889 (1.07x), quietest 7643 (0.92x)
== cache-4 fails (100 positions per server): 7182 keys move ==
  cache-1 receives 1676 (23.3%)
  cache-2 receives 905 (12.6%)
  cache-3 receives 1482 (20.6%)
  cache-5 receives 2214 (30.8%)
  cache-6 receives 905 (12.6%)

Dry run. With 6 servers and 50,000 keys the average is 8,333 keys per server. With 1 position per server, the busiest server holds 13,785 keys (1.65x the average) and the quietest 5,725 (0.69x). With 10 positions the range is 1.81x to 0.54x: with so few points luck still dominates, and this run was even worse than with one position. With 100 positions it is 1.12x to 0.86x, and with 500 positions it is 1.07x to 0.92x, which is nearly flat. More positions give better balance, but each position costs memory and a little work when the membership changes, so real systems pick a number from tens to a few hundred and then measure.

Virtual nodes also allow weights. A machine with twice the memory can be given twice as many positions and will receive about twice as many keys.

9. How Consistent Hashing Handles Node Failure

When a server fails, its keys must go somewhere. With one position per server, the entire arc goes to the single next server, which suddenly carries its own load plus the dead server's load and may fail too. This is how one crash turns into a chain of crashes.

The second half of the CH3 output shows this. When cache-4 fails with 100 positions per server, 7,182 keys move (14.4% of the 50,000; a perfectly even ring would give 16.7%). They are shared among the five survivors: cache-1 receives 1,676 (23.3%), cache-2 receives 905 (12.6%), cache-3 receives 1,482 (20.6%), cache-5 receives 2,214 (30.8%) and cache-6 receives 905 (12.6%). No single server absorbs the whole failure. The split is not perfectly even, which is another reason to use enough virtual nodes and to keep some headroom on every server.

10. Replication on the Ring

A cache can lose data and refill it, but a store that keeps the only copy needs replicas. The ring gives a simple way to choose them: after the key's owner, keep walking clockwise and take the next servers. The set of servers chosen for one key is called its preference list.

There is a trap. Because every server has many virtual positions, the next position on the ring is often the same server again, and storing a second copy on the same machine does not protect you from losing that machine. The walk must skip servers it has already chosen, and in a real data centre it should also skip servers in a zone that already holds a copy, so that one zone outage (power or network) cannot remove all copies.

Output

== Replica lists (3 copies, one per zone) ==
  student:101 -> cache-2 (zone-1), cache-4 (zone-2), cache-6 (zone-3)
  student:102 -> cache-6 (zone-3), cache-1 (zone-1), cache-4 (zone-2)
  student:103 -> cache-1 (zone-1), cache-4 (zone-2), cache-5 (zone-3)
  student:104 -> cache-5 (zone-3), cache-3 (zone-2), cache-2 (zone-1)
  student:105 -> cache-3 (zone-2), cache-2 (zone-1), cache-5 (zone-3)
== Check over 20000 keys ==
  naive next-3-positions repeats a server: 8063 keys (40.3%)
  zone-aware lists with 3 servers in 3 zones: 20000 of 20000
== cache-5 fails ==
  keys whose replica list changes: 10517 (52.6%)
  fewest copies a changed key keeps in place: 2

Dry run. The cluster has 6 servers in 3 zones (cache-1 and cache-2 in zone-1, cache-3 and cache-4 in zone-2, cache-5 and cache-6 in zone-3), with 100 positions each. The key student:101 gets cache-2 (zone-1), cache-4 (zone-2) and cache-6 (zone-3): three servers in three zones. Across 20,000 keys, the naive rule "take the next 3 positions" picked the same server twice for 8,063 keys (40.3%), while the walk that skips repeats gave three servers in three zones for all 20,000. When cache-5 fails, 10,517 keys (52.6%) get a new list, because each server appears in the lists of about 3 out of 6 keys. But every changed key still keeps at least 2 of its 3 copies in place, so only one copy per key has to be rebuilt.

The ring only chooses where replicas live. Copying the data, deciding when a write is acknowledged and repairing missing copies is the job of the replication protocol; see Consistency Models (quorums) and the CAP theorem. Dynamo-style stores such as Cassandra use exactly this ring-plus-preference-list design.

11. Consistent Hashing vs Rendezvous Hashing, Jump Hash and Fixed Partitions

The ring is not the only way to get stable routing. Three other techniques are worth knowing, and interviewers like to ask when you would pick each one.

  • Rendezvous hashing (highest random weight, Thaler and Ravishankar, 1996): for each key, compute a score for every server and pick the highest. No ring and no virtual nodes; the cost is one hash per server per lookup.

  • Jump consistent hash (Lamping and Veach, 2014): a few lines of arithmetic that map a key to a bucket number from 0 to N-1 using no memory. Buckets can only be added or removed at the end, so it suits numbered shards, not servers that fail in the middle. Google Guava ships it as Hashing.consistentHash.

  • Fixed partitions: hash the key to one of a fixed number of partitions (for example 16,384 in Redis Cluster), and keep a table that maps partitions to servers. Modulo is fine here because the partition count never changes; only the table does.

Output

== 12 -> 13 servers, 10000 keys (ideal: 7.7% move) ==
  method             moved   busiest/avg at 12 servers
  modulo              92.5%        1.05x
  ring, 1 position    14.2%        2.00x
  ring, 100 positions   7.6%        1.15x
  rendezvous           7.8%        1.06x
  jump hash            7.7%        1.03x

Dry run. The program routes the same 10,000 keys with each method and measures two things: how many keys move when the cluster grows from 12 to 13 servers, and how uneven the load is at 12 servers. The ideal move is 7.7%.

MethodKeys moved (12 to 13)Busiest server vs averageMemory and work per lookup
Modulo92.5%1.05xNone; one hash
Ring, 1 position per server14.2%2.00xSmall ring; one hash and a search
Ring, 100 positions per server7.6%1.15x1,200 ring entries; one hash and a search
Rendezvous hashing7.8%1.06xNone; one hash per server
Jump hash7.7%1.03xNone; a short loop

Read the table in three steps. First, modulo is the only method that fails the move test: 92.5% of the keys moved against an ideal 7.7%. Second, a ring with a single position is the least balanced (2.00x) and also moves almost twice the ideal share. Third, the ring with 100 positions, rendezvous and jump hash all land close to the ideal move, and rendezvous and jump hash are a little more even (1.06x and 1.03x against 1.15x) and need no state, so for a small, simple cluster they are often a better answer than a ring. The ring wins when the cluster is large (rendezvous must score every server), when servers fail anywhere in the middle (jump hash cannot do that), and when you need weights and replica lists.

12. Hot Keys and Bounded Loads

Consistent hashing spreads keys evenly. It does not spread requests evenly. If one key is read far more than the others, such as the live leaderboard during an exam, the single server that owns it takes all that traffic. Two techniques help.

  • Bounded loads. Give every server a cap (for example 1.10 times the average). If the owner is full, pass the key clockwise to the next server that still has room. The balance becomes a guarantee and not just a statistical hope.

  • Hot key copies. Store the hot key under several names (leaderboard/copy0 to leaderboard/copy3) and let each request pick one at random. The reads spread over the servers that own those names.

Output

== Bounded loads: 20000 keys, 6 servers, cap = 1.10 x average = 3667 ==
  plain ring  : cache-1=3529, cache-2=3271, cache-3=3290, cache-4=2800, cache-5=2757, cache-6=4353
  bounded ring: cache-1=3667, cache-2=3273, cache-3=3370, cache-4=3082, cache-5=2941, cache-6=3667; keys passed to a later server: 796 (4.0%)
== One hot key: 10000 reads of the live leaderboard ==
  one copy        : cache-5=10000
  4 salted copies : cache-2=5000, cache-3=2500, cache-6=2500

Dry run. With 6 servers, only 20 positions each and 20,000 keys, the plain ring puts 4,353 keys on cache-6 against an average of 3,333. With a cap of 3,667 (1.10 x average) the same keys end up as 3,667, 3,273, 3,370, 3,082, 2,941 and 3,667: nothing is above the cap, and only 796 keys (4.0%) were passed on to another server. For the hot key, 10,000 reads of one name all hit cache-5. Spreading them over 4 salted names split the reads as cache-2 5,000, cache-3 2,500 and cache-6 2,500. Notice that two of the four copies landed on cache-2, so it still serves twice as much as the others. Salted names are random servers; if you need guaranteed spread, place the copies with the distinct-server walk from the replication section.

13. Keeping Every Client on the Same Ring

Every client that routes keys must have the same server list and the same hash function. If two application servers hold different versions of the ring, the same key goes to two different cache servers, the cache stops behaving like one cache, and bugs appear that are very hard to reproduce.

Common ways to avoid this are to keep the ring in a configuration service (ZooKeeper, etcd or a database table) with a version number, to have clients check the version regularly, and to let a server answer "I am not the owner" so the client refreshes its ring. Gossip protocols spread membership between the nodes themselves in Dynamo-style stores. In Java, keep the ring in an immutable object and swap it atomically (a volatile reference to a new TreeMap), so a lookup never sees a half-built ring.

14. Cache or Database: Who Moves the Data?

Consistent hashing changes who owns a key. It does not move the data. What you do next depends on what the servers hold.

  • Cache: do nothing. The missing keys are loaded from the database on demand. You may warm the new server first so that exam-day traffic does not hit a cold node.

  • Database or any store that holds the only copy: before switching the ring version, copy the affected key ranges from the old owner to the new one, check them, and only then change the routing. Otherwise the new owner answers "not found" for data that exists.

15. Consistent Hashing in Real Systems

SystemHow it routes keysNotes
Amazon Dynamo and Apache CassandraToken ring with virtual nodes and preference listsReplicas are the next distinct nodes clockwise
Memcached clients (ketama style)Client-side consistent hashing over cache serversThe client holds the ring, so all clients must agree
Envoy and NGINX load balancersRing hash and Maglev (Envoy), "hash ... consistent" (NGINX)Sticky routing by a key such as user or session id
Redis ClusterFixed 16,384 hash slots mapped to serversFixed partitions, not a ring
Apache Kafka producershash(key) modulo the number of partitionsAdding partitions changes where a key goes
Content delivery networksThe original use: map web objects to cache serversWhere the idea came from (1997)

Common Mistakes

  • Using one position per server. It looks fine in a diagram and gives 2.00x load on one server in practice; use virtual nodes.

  • Replicating to the next position instead of the next distinct server. Copies land on the same machine (40.3% of keys in our test).

  • Assuming the ring moves data. It only changes ownership; plan the data transfer for stores that hold the only copy.

  • Letting clients disagree about membership. Version the ring and refresh it.

  • Using a poor hash function. A hash that clusters values (such as plain String.hashCode() without mixing) makes the ring uneven. Use MurmurHash3 (as in our code) or xxHash.

  • Ignoring hot keys. Even placement of keys does not mean even traffic.

Best Practices

  • Give each server at least 100 virtual nodes, then measure the real balance and adjust.

  • Use a stable, well-mixed, non-cryptographic hash, and use the same one in every client.

  • Handle two virtual nodes with the same hash with a fixed rule so every client resolves it the same way.

  • Keep spare capacity on each server so that a failure does not overload the survivors.

  • Store the ring as an immutable, versioned object and replace it atomically.

  • For small clusters, compare with rendezvous hashing before you build a ring.

Interview Questions

  • What is consistent hashing and why is it used? It maps keys and servers onto a ring so that adding or removing a server moves only about 1/N of the keys, which keeps caches warm and limits data movement.

  • Why does modulo hashing fail when a server is added? N is in the formula, so changing N changes the server for most keys (85.8% going from 6 to 7 servers in our test).

  • What are virtual nodes? Many ring positions per physical server. They even out the arcs, spread a failed server's load across many servers and let you weight bigger machines.

  • How are replicas placed on the ring? Walk clockwise from the key and take the next distinct servers, preferably in different zones.

  • What is the time complexity of a lookup? O(log V) with a sorted structure and binary search, where V is the number of virtual nodes.

  • Consistent hashing vs rendezvous hashing? Rendezvous scores every server per key and needs no ring, which is simple and very even for small clusters; the ring scales better to many servers and supports replica lists.

  • Does consistent hashing solve hot keys? No. It balances keys, not traffic; use key copies, caching in front, or bounded loads.

  • Does consistent hashing move the data? No. It decides ownership; a separate process must transfer data for stores that hold the only copy.

Summary

IdeaWhat to remember
Modulo hashingChanging N moves almost every key (85.8% for 6 to 7 servers)
Hash ringKeys go to the first server clockwise; a change affects only one arc
Virtual nodesMany positions per server give even load and shared failure impact
ReplicationWalk clockwise to distinct servers in distinct zones
AlternativesRendezvous and jump hash are simple and even; fixed partitions move whole slots
LimitsIt does not move data, share traffic of hot keys or keep clients in agreement
  • Consistent hashing removes the server count from the routing formula, so a cluster change moves only a small share of the keys.

  • Use virtual nodes to fix uneven arcs and to spread the load of a failed server.

  • Choose replicas as distinct servers (and zones) clockwise on the ring.

  • Pick the routing technique that fits the cluster: ring for large and changing clusters, rendezvous or jump hash for small or numbered ones.

  • Handle hot keys, ring versions and data transfer separately.

Previous topic: Consistency Models. Next: Single Point of Failure.

Further reading