Databases and storage

Consistent hashing

How to spread keys over a changing set of servers so that adding or losing one moves only a small share of the data.

Lesson12 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

In the late 1990s the web had a caching problem. A popular page could be served from a pool of cache servers, and the obvious way to decide which server held which page was hash(url) mod N, where N is the number of servers. It is one line of code, it spreads keys evenly, and every client that knows N agrees on the answer.

It works until N changes, and N always changes. A machine dies at 3 a.m. You add capacity before a sale. Each time, the formula quietly gives a different answer for almost every key. The data is still in the cluster, on servers where nobody will look for it again. Every cache effectively empties at once, and the database behind it takes the full read load with no warning.

Why hash mod N breaks when the cluster changes size7 components: App servers, Database, Cache A, Cache B, Cache C, Cache D, Cache E. Connections: App servers to Cache A; App servers to Cache B; App servers to Cache C; App servers to Cache D; App servers to Cache E; App servers to Database (on a miss).App serversDatabase5% of readsCache Aslot 0Cache Bslot 1Cache Cslot 2Cache Dslot 3Cache Eslot 4not in the pool yeton a miss

Step 1 of 6

Four cache servers sit in front of the database. The app picks one with hash(key) mod 4, so every key has exactly one home and about 95% of reads are cache hits.

Read the steps as text
  1. Four cache servers sit in front of the database. The app picks one with hash(key) mod 4, so every key has exactly one home and about 95% of reads are cache hits.
  2. A read for the key user:42 hashes to slot 2. Cache C has it, so the database never hears about this request.
  3. Traffic grows, so you add a fifth server. The formula becomes hash(key) mod 5. Nothing was deleted, and nothing looks wrong yet.
  4. The same key now gets a different answer. user:42 maps to slot 0, and Cache A has never seen it. The value is still sitting on Cache C, where nobody will look for it again.
  5. A key keeps its server only if its hash gives the same remainder for 4 and for 5, which is true for 1 key in 5. The other 80% miss at the same moment and fall through to the database.
  6. Consistent hashing changes the mapping so that adding a server moves only the keys that server takes over, about one fifth here. The other four fifths stay where they are and keep hitting.
Why hash mod N breaks when the cluster changes size

Engineers tried the workarounds you would expect. Some doubled the cluster each time, which halves the damage but means buying twice the hardware you need. Some kept a lookup table from key to server, which is flexible but puts a large, hot piece of state in front of every request. Some scheduled resizes for the quietest hour and warmed the cache by replaying traffic.

In 1997 David Karger and colleagues at MIT published a different formula, which they called consistent hashing. It became the basis of Akamai’s content network, and a decade later Amazon’s Dynamo paper made it the standard way to partition a distributed key-value store.

The idea: hash the servers too

Take the output range of a hash function, say 0 to 232 - 1, and bend it into a circle. Then:

  1. Hash each server (its name or address) to a point on the ring.
  2. Hash each key to a point on the same ring.
  3. A key belongs to the first server you meet moving clockwise from the key.

Each server therefore owns the arc between itself and the previous server. In code, the ring is a sorted array of server positions and a lookup is a binary search, so it costs O(log N) with no network call.

Now watch what happens when the cluster changes:

  • A server joins. It lands at one point and takes over part of one arc, the keys between its predecessor and itself. Every other key keeps its owner.
  • A server leaves. Its arc passes to the next server clockwise. Every other key keeps its owner.

With N servers, a change moves about 1/N of the keys on average. That is the minimum possible, since the new server has to get its share from somewhere.

Consistent hashing ring

Open full screen
CBADkeys sit inside,nodes on the ring

Keys per node (a fair share is 40)

  • A35
  • B20
  • C97
  • D8

Add or remove a node. Keys that change owner are outlined. Then raise the virtual nodes and compare how evenly the keys spread.

Nodes
4
Busiest node
97
Quietest node
8
Moved by last change
none yet
Would move with mod N
none yet

Virtual nodes

The basic ring has two flaws you will notice as soon as you try it with a few servers.

First, random points do not divide a circle evenly. With four servers it is common for one to own 40% of the ring and another 10%. Second, when a server dies its whole arc lands on one neighbour, which may then be overloaded and die too.

The fix is to give each physical server many positions on the ring, called virtual nodes or vnodes. Hash server-a#1, server-a#2 and so on up to a few hundred. Each server now owns many small arcs scattered around the ring, and three useful things follow:

  • Load evens out. The share each server owns is an average over many arcs. With around 100 to 200 virtual nodes per server, the spread between the busiest and quietest server typically falls to within about 10%.
  • Failure spreads. A dead server’s arcs are adjacent to many different servers, so each survivor absorbs a small slice.
  • Capacity can differ. A machine with twice the memory gets twice the virtual nodes.

The cost is a larger ring to keep in memory and to gossip around the cluster, and more ranges to track during repair and rebalancing.

Replication on the ring

A ring also gives you a rule for where copies go. To store R replicas of a key, walk clockwise from the key and take the next R distinct physical servers, skipping virtual nodes that belong to a server you already picked. Dynamo calls this list the key’s preference list.

Production systems add placement constraints to that walk, such as “no two replicas in the same rack or availability zone”, so that one failure domain cannot hold every copy.

What it does not solve

Consistent hashing spreads keys evenly. It does not spread load evenly if the keys themselves are uneven. One celebrity account or one viral URL is a single key on a single server, and no arrangement of the ring changes that. Hot keys need a different tool: a local cache in front, key splitting, or dedicated capacity.

It also does not move the data for you. When ownership of an arc changes, something has to stream those keys to the new owner (for a database) or accept that they will miss once and be refilled (for a cache).

Alternatives worth knowing

Approach How a key finds its node Good fit
Hash ring with virtual nodes Binary search on ring positions Dynamo-style stores, client-side cache sharding
Fixed slots with a table hash mod 16384, then look up the slot’s owner Redis Cluster, systems that want explicit, operator-driven rebalancing
Rendezvous hashing Score every node for the key, pick the highest Small node counts, no ring state to maintain
Jump consistent hash A short loop that maps a key to a bucket number Numbered shards that only grow at the end
Range partitioning Sorted key ranges that split when large Range scans, as in HBase, Spanner and CockroachDB

All of these keep movement small when the cluster changes. What separates them is whether you need range scans, whether nodes can leave from the middle, and how much routing state you want to manage.

In the interview

Reach for consistent hashing when your design has a set of interchangeable nodes that will change size and a cost to moving keys: a distributed cache, a sharded key-value store, sticky routing of users to WebSocket servers.

A strong answer takes about a minute. Say why mod N fails (nearly every key moves), describe the ring (first server clockwise), add virtual nodes for balance and replicas for durability, and then name what it does not fix (hot keys). If the interviewer pushes further, compare it with a slot table and say which you would pick for this system and why.

Key takeaways

  • hash(key) mod N remaps almost every key when N changes; consistent hashing remaps about 1/N of them.
  • Servers and keys are hashed onto the same ring, and a key belongs to the first server clockwise from it.
  • Virtual nodes (many ring positions per server) even out load and let a bigger machine take a bigger share.
  • Replicas are the next distinct physical servers clockwise, which is how Dynamo-style stores build a preference list.
  • It is one of several answers. Fixed slot tables, rendezvous hashing and range partitioning solve the same problem with different trade-offs.

Try it

Check yourself

1. A cache cluster grows from 4 to 5 servers using hash(key) mod N. Roughly what share of keys now map to a different server?
2. With consistent hashing and no virtual nodes, what is the main practical problem?
3. A server on the ring dies. Which keys need a new home?
4. Redis Cluster assigns each key to one of 16,384 hash slots and stores a slot-to-node table. Why might a team prefer this over a hash ring?

0 of 4 answered

Flashcards

These 5 cards are in your review deck. Tap a card to see the answer.

What problem does consistent hashing solve?

Mapping keys to servers so that when a server joins or leaves, only about 1/N of keys change owner, instead of nearly all of them as with hash mod N.

On a hash ring, which server owns a key?

The first server position found moving clockwise from the key's hash. Lookup is a binary search over the sorted positions.

What are virtual nodes and why use them?

Each physical server is placed on the ring many times (often 100 or more). This evens out load, spreads a failed server's keys over many survivors, and lets larger servers take more positions.

How are replicas chosen on a ring?

Walk clockwise from the key and take the next R distinct physical servers, skipping extra virtual nodes of a server already chosen. Dynamo calls this the preference list.

Name two alternatives to a hash ring that also limit key movement.

A fixed number of hash slots with a slot-to-node table (Redis Cluster), and rendezvous (highest random weight) hashing. Range partitioning with splits is a third.

Review the deck