Add nodes without remapping everything
Modulo hashing (key % N) remaps almost every key when N changes.
Say it like this
I partition the cache with consistent hashing and virtual nodes, so adding or losing a node remaps about one-Nth of the keys instead of nearly all of them.
Basic solution
Place nodes and keys on a hash ring; a key belongs to the next node clockwise. Adding a node moves only about 1/N of the keys. Virtual nodes smooth the load.
Keys and virtual nodes on the ring
Two physical nodes each own several positions. A key belongs to the first position clockwise. Adding a node inserts new positions and moves only the keys just before each of them.
How it works
- Hash each node's id onto a ring of 2 to the power 32 positions. For virtual nodes, hash the id with a replica number appended (node-7#0, node-7#1, and so on) so each physical node gets many positions. Keep all positions in one sorted array.
- To find which node owns a key, hash the key to a position on the same ring, then walk clockwise (search the sorted array for the first position greater than or equal to it). The node tagged on that position owns the key. If the key's position is past the last entry, wrap around to the first.
- Adding a node inserts its positions into the array. Each inserted position takes over only the keys between it and the previous position, so across all its positions the new node receives about 1/N of the keys and every other node gives up a small slice.
- Removing a node deletes its positions, and each slice it owned falls to the next position clockwise. Because its positions were interleaved with everyone else's, its keys spread over many neighbours rather than landing on one.
- With 100 to 200 virtual positions per physical node, the random gaps between positions average out, and each node ends up with a share of the ring within a few percent of equal.
Who holds the ring
- Either every client keeps a copy of the ring and learns about changes from a config service, or a proxy layer keeps the ring and clients talk to the proxy. Either way the ring carries a version number so a client that still has an old ring can be told to refresh.
Worked example
Distributed cache for the news feed
- 50 cache nodes hold 800 GB of timelines and post bodies. With plain modulo hashing (key mod number of nodes), growing to 51 nodes changes the answer for 50/51, about 98%, of keys: the entire cache misses at once and the database takes 6K feed reads/s plus hydration, which is a cold-start incident.
- With consistent hashing, adding node 51 moves about 1/51, 2%, of keys: about 16 GB migrates and the miss rate rises by about 2% for a few minutes, which the database absorbs without anyone noticing.
- Load balance: with one position per node, the largest slice of the ring is often 3 to 4 times the average, so one node does several times the work of another. With 150 virtual nodes each, the spread drops to roughly plus or minus 5%.
- Node failure: node 17's 2% of keys spill to the next positions clockwise. With virtual nodes that 2% is split across many neighbours, so no single node takes the whole hit.
- Hot keys: a celebrity post body cached on one node is still one node's problem, because hashing places each key on exactly one node. Consistent hashing does nothing for that, so the hot key is replicated under suffixed names instead.
Variants and when each wins
Classic ring with virtual nodes
- Nodes and keys share one ring, each node holds many positions. It is the general tool for caches and partitioned stores where nodes join and leave.
Rendezvous (highest random weight) hashing
- For each key, compute hash(key, node) for every node and pick the highest score. There is no ring to store and the spread is perfectly even; it wins for a handful of nodes, because every lookup costs one hash per node.
Jump consistent hash
- A tiny function maps a key to a bucket number with no state at all. It wins for fixed-size, numbered shards, because it only supports adding or removing the last bucket.
Range partitioning with a directory
- Split the key space into ranges and keep a table of which node owns each range. It wins when you need ordered scans or want to split hot ranges by hand, and it needs that directory to be consistent and always available.
Recommendation: ring with 100 to 200 virtual nodes for caches; rendezvous for a handful of nodes; range partitioning when you need ordered scans.
Failure modes
Clients with a stale ring
- You notice values vanish: a write succeeds and the next read misses. It happens because a client with an old copy of the ring sent the write to the old owner while another client with the new ring read from the new owner. Fix it by versioning the ring, having nodes reject requests that carry an old version, and refreshing clients from the config service.
Uneven load without virtual nodes
- You notice one node handling three times the traffic of another. It happens because each node has only one position and the random gaps between positions are very unequal. Fix it with 100 to 200 virtual positions per node, giving bigger machines more positions.
Cascading failure
- You notice one node fails, its neighbour takes the extra load and fails too, and the failures march around the ring. It happens because there was no spare capacity and the failed node's keys all landed on one neighbour. Fix it with virtual nodes so the spill spreads across many nodes, 30% headroom on every node, and load shedding before a node tips over.
Hot key
- You notice one node saturated by a single key. It happens because hashing places each key on exactly one node and cannot split it. Fix it with an in-process cache in each app server, or by storing the key under several suffixed names and reading a random copy.
Rebalance storm
- You notice a burst of cache misses and migration traffic during a scale-up. It happens because several nodes were added at once, moving a large share of keys in a short time. Fix it by adding nodes one at a time and warming each new node by reading from both old and new owners for a period.
Interviewer follow-ups
Answer out loud before you open each one.
How many virtual nodes per physical node and why?
Around 100 to 200. With one position per node the slice sizes vary several-fold; with a few hundred positions the law of large numbers evens the slices to within a few percent. More than that costs lookup memory and ring-update time for little gain.
How does a client learn that the ring has changed?
A cluster manager publishes a new ring version to a config service that clients watch, and each node tags responses with the version it believes is current. A client that sends a stale version gets a redirect or refresh hint and reloads the ring.
Does consistent hashing help with a hot key?
No. It places keys evenly but each key still lives on one node, so a single very popular key saturates its owner. Fix it with client-side caching or by replicating that key under several suffixed names.
What is the difference between consistent hashing and sharding by range?
Hashing spreads keys uniformly but destroys order, so range scans must fan out to every node. Range partitioning keeps order for scans and lets you split hot ranges by hand, but needs a directory and tends to hot-spot on sequential keys.
Connections
- In study paths
- Splitting the data
- Built on
- Consistent hash ring
- Pairs with
- Partition the data · Spread a hot key · Find services and config at runtime · Survive losing a node
- Pulls against
- Fix a hot shard
- Used in
- Distributed Key-Value Cache (Redis / Memcached-like)