Consistent hashing and virtual nodes
The trouble with changing N
Section titled “The trouble with changing N”Hash mod N is the simplest hash placement: a key goes to shard hash(key) mod N. It stores nothing and spreads keys well, and it breaks when N changes. A key stays only if its hash gives the same remainder for the old and the new number of shards. Take 4 shards becoming 5. Of the 20 possible pairs of remainders, only 4 are equal, so one key in five stays and N / (N + 1) of them move: 80% in theory. The load balancing module does the same arithmetic, and the lab agrees with it.
Each key goes to the shard given by its hash mod N. Add a shard and count the keys that move.
What the last change did
Add or remove a shard, change the strategy, the virtual nodes or the traffic, or press Rebalance. This panel says how many keys the change moved.
- Hottest shard
- 25%Shard 1: 1× the fair share of 25%
- Keys moved by the last change
- —No change yet
- Keys per shard
- 2,500 most, 2,500 fewest10,000 keys on 4 shards
- Placement metadata
- NoneThe hash decides, so there is no table.
fair share 25%
Keys arriving
A sample of the requests, and the shard that serves each key under the current layout. The chart and the table hold the figures.
- user:7539Shard 1
- user:4900Shard 4
- user:9833Shard 4
- user:5352Shard 4
- user:8588Shard 4
- user:7741Shard 2
- user:4536Shard 3
- user:7331Shard 3
Look up a key
user:1234 is on Shard 1.
| Shard | Keys held | Share of requests | Keys moved in | Keys moved out |
|---|---|---|---|---|
| Shard 1 | 2,500 (25%) | 25% | 0 | 0 |
| Shard 2 | 2,500 (25%) | 25% | 0 | 0 |
| Shard 3 | 2,500 (25%) | 25% | 0 | 0 |
| Shard 4 | 2,500 (25%) | 25% | 0 | 0 |
Shards are numbered from 1 here. In the C# example the same shards are node-0, node-1 and so on. The keys moved in and out are those of the last change.
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- The lab counts 10,000 keys, user:0 to user:9999, the same keys as the C# example. A key moves when the shard that holds it changes, and every key counts the same, whatever it holds.
- The hash is FNV-1a over the text of the key, and a virtual node sits at the hash of its number, a # and the name of its shard. This is the definition the C# example uses, so the same keys move. It is not a cryptographic hash.
- A shard's load is the share of requests that reach its keys, worked out from how popular each key is. It is what a very long stream converges to, not a measurement of a run. The stream shown beside it is a sample.
- Hot keys are neighbouring numbers, starting at user:3400, like a burst of new ids or one customer's records. The rest of the requests choose any key with equal chance.
Simplifications
- No data is copied and nothing takes time: a resize or a rebalance is instant. In a real system, moving keys copies data, competes with the traffic, and can take hours.
- Range and directory follow simple rules: split the busiest range, move the hottest keys first. Real systems choose when to split and move, and limit how much moves at once.
- FNV-1a puts labels that differ only in their last character close together, so with a few virtual nodes this ring is more lopsided than points placed at random would be. With 100 or more, the two agree more closely.
- Cross-shard queries, replicas and the cost of looking up a directory are not modelled: the lab counts where keys live and what changing that costs.
Parameter values are illustrative. They are not benchmarks of any real product.
Press Add a shard and read Keys moved by the last change: 8,006 of 10,000 keys (80.1%) change shard, against a theory of 80%. Almost every key has to be copied to another machine because one machine was added. For a store that holds data, that is a long migration, and a cache that held those keys is cold.
Mental model. Put the shards and the keys on the same circle. A key belongs to the first shard clockwise from it. A shard that joins takes only the keys between itself and the shard before it. A shard that leaves hands its keys to the next one. Nothing else moves.
The ring
Section titled “The ring”That circle is consistent hashing. Hash each key to a position on a circle of 2^32 points. Give each shard one or more positions on the same circle, found by hashing the shard’s name together with a number. A key belongs to the shard that owns the first position at or after the key’s, going round the circle and wrapping past the end.
When a shard joins, its positions take over the arcs just before them, and only the keys on those arcs change owner, all of them to the new shard. When a shard leaves, its keys go to the owners of the next positions. Every other key stays where it is. Dynamo’s paper describes this as the main advantage of consistent hashing: the departure or arrival of a node affects only its immediate neighbours, and other nodes remain unaffected.
Keys sit on a ring, and every shard has virtual nodes on it. Add a shard and count the keys that move.
What the last change did
Add or remove a shard, change the strategy, the virtual nodes or the traffic, or press Rebalance. This panel says how many keys the change moved.
- Hottest shard
- 28.6%Shard 4: 1.1× the fair share of 25%
- Keys moved by the last change
- —No change yet
- Keys per shard
- 2,858 most, 2,255 fewest10,000 keys on 4 shards
- Placement metadata
- 400 entries4 shards with 100 virtual nodes each on the ring.
fair share 25% Hottest shard
Keys arriving
A sample of the requests, and the shard that serves each key under the current layout. The chart and the table hold the figures.
- user:7539Shard 3
- user:4900Shard 4
- user:9833Shard 2
- user:5352Shard 2
- user:8588Shard 2
- user:7741Shard 2
- user:4536Shard 3
- user:7331Shard 2
Look up a key
user:1234 is on Shard 1.
| Shard | Keys held | Share of requests | Keys moved in | Keys moved out |
|---|---|---|---|---|
| Shard 1 | 2,338 (23.4%) | 23.4% | 0 | 0 |
| Shard 2 | 2,549 (25.5%) | 25.5% | 0 | 0 |
| Shard 3 | 2,255 (22.6%) | 22.5% | 0 | 0 |
| Shard 4 · hottest | 2,858 (28.6%) | 28.6% | 0 | 0 |
Shards are numbered from 1 here. In the C# example the same shards are node-0, node-1 and so on. The keys moved in and out are those of the last change.
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- The lab counts 10,000 keys, user:0 to user:9999, the same keys as the C# example. A key moves when the shard that holds it changes, and every key counts the same, whatever it holds.
- The hash is FNV-1a over the text of the key, and a virtual node sits at the hash of its number, a # and the name of its shard. This is the definition the C# example uses, so the same keys move. It is not a cryptographic hash.
- A shard's load is the share of requests that reach its keys, worked out from how popular each key is. It is what a very long stream converges to, not a measurement of a run. The stream shown beside it is a sample.
- Hot keys are neighbouring numbers, starting at user:3400, like a burst of new ids or one customer's records. The rest of the requests choose any key with equal chance.
Simplifications
- No data is copied and nothing takes time: a resize or a rebalance is instant. In a real system, moving keys copies data, competes with the traffic, and can take hours.
- Range and directory follow simple rules: split the busiest range, move the hottest keys first. Real systems choose when to split and move, and limit how much moves at once.
- FNV-1a puts labels that differ only in their last character close together, so with a few virtual nodes this ring is more lopsided than points placed at random would be. With 100 or more, the two agree more closely.
- Cross-shard queries, replicas and the cost of looking up a directory are not modelled: the lab counts where keys live and what changing that costs.
Parameter values are illustrative. They are not benchmarks of any real product.
Press Add a shard here. With 100 virtual nodes for each shard, 1,988 keys (19.9%) move, against a theory of 1 / (N + 1), which is 20%. Look at Keys moved in in the table: all 1,988 went to Shard 5, and none moved between the old shards. Hash mod N moved four times as many keys, and spread them over every shard.
The load balancing module has a ring too, but its lab uses another hash function and its own keys, and quotes 80% and about 21% for the same two cases. Both agree with the theory, not with each other to the key, so read each lesson’s numbers against its own lab.
Virtual nodes
Section titled “Virtual nodes”A ring with one position for each shard is lopsided, because positions fall unevenly. Dynamo’s paper says that the random position assignment of each node leads to non-uniform data and load distribution, and that the basic algorithm ignores differences in the capacity of nodes. Its answer is virtual nodes: each node is assigned multiple positions, which it calls tokens. The paper lists the benefits: when a node becomes unavailable its load is dispersed evenly across the others, a new node accepts a roughly equal amount of load from each of the others, and the number of virtual nodes of a node can follow its capacity.
The lab shows the effect. It opens on a ring with one virtual node for each shard.
A ring with one virtual node for each shard. Raise the number of virtual nodes and watch the keys even out across the shards.
What the last change did
Add or remove a shard, change the strategy, the virtual nodes or the traffic, or press Rebalance. This panel says how many keys the change moved.
- Hottest shard
- 99%Shard 4: 4× the fair share of 25%
- Keys moved by the last change
- —No change yet
- Keys per shard
- 9,896 most, 34 fewest10,000 keys on 4 shards
- Placement metadata
- 4 entries4 shards with 1 virtual nodes each on the ring.
fair share 25% Hottest shard
Keys arriving
A sample of the requests, and the shard that serves each key under the current layout. The chart and the table hold the figures.
- user:7539Shard 4
- user:4900Shard 4
- user:9833Shard 4
- user:5352Shard 4
- user:8588Shard 4
- user:7741Shard 4
- user:4536Shard 4
- user:7331Shard 4
Look up a key
user:1234 is on Shard 4.
| Shard | Keys held | Share of requests | Keys moved in | Keys moved out |
|---|---|---|---|---|
| Shard 1 | 35 (0.4%) | 0.3% | 0 | 0 |
| Shard 2 | 34 (0.3%) | 0.3% | 0 | 0 |
| Shard 3 | 35 (0.4%) | 0.3% | 0 | 0 |
| Shard 4 · hottest | 9,896 (99%) | 99% | 0 | 0 |
Shards are numbered from 1 here. In the C# example the same shards are node-0, node-1 and so on. The keys moved in and out are those of the last change.
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- The lab counts 10,000 keys, user:0 to user:9999, the same keys as the C# example. A key moves when the shard that holds it changes, and every key counts the same, whatever it holds.
- The hash is FNV-1a over the text of the key, and a virtual node sits at the hash of its number, a # and the name of its shard. This is the definition the C# example uses, so the same keys move. It is not a cryptographic hash.
- A shard's load is the share of requests that reach its keys, worked out from how popular each key is. It is what a very long stream converges to, not a measurement of a run. The stream shown beside it is a sample.
- Hot keys are neighbouring numbers, starting at user:3400, like a burst of new ids or one customer's records. The rest of the requests choose any key with equal chance.
Simplifications
- No data is copied and nothing takes time: a resize or a rebalance is instant. In a real system, moving keys copies data, competes with the traffic, and can take hours.
- Range and directory follow simple rules: split the busiest range, move the hottest keys first. Real systems choose when to split and move, and limit how much moves at once.
- FNV-1a puts labels that differ only in their last character close together, so with a few virtual nodes this ring is more lopsided than points placed at random would be. With 100 or more, the two agree more closely.
- Cross-shard queries, replicas and the cost of looking up a directory are not modelled: the lab counts where keys live and what changing that costs.
Parameter values are illustrative. They are not benchmarks of any real product.
Read Keys per shard: with 1 virtual node one shard holds 9,896 keys and the others 35, 34 and 35. Now raise Virtual nodes per shard and watch Keys per shard even out. For each setting, press Reset to go back to four shards, choose the number of virtual nodes, press Add a shard, and read Keys moved by the last change:
| Virtual nodes per shard | Keys moved, 4 to 5 shards |
|---|---|
| 1 | 9,864 |
| 3 | 6,549 |
| 10 | 3,732 |
| 30 | 4,245 |
| 100 | 1,988 |
| 300 | 1,822 |
| 1,000 | 1,932 |
Fewer virtual nodes do not move fewer keys. With few of them, the new shard’s positions can fall in a stretch that held most of the keys, and it then takes most of them. From 100 virtual nodes up the count is within about 200 keys of the theory, 2,000. The spread tells the same story. With 10 virtual nodes the busiest of four shards holds 37.2% of the keys and the quietest 16.1%. With 100 it is 28.6% and 22.6%. More virtual nodes cost memory for a bigger ring, and a lookup in a bigger table, which the lab shows as a larger Placement metadata.
The same thing in code
Section titled “The same thing in code”The C# example builds the same ring with the same hash and the same 10,000 keys, so its counts are the lab’s. It also checks the two properties that matter: that every key which moves when node-4 joins goes to node-4, and that removing node-1 from five nodes moves exactly the 2,050 keys it held. The page’s code is never run in the browser: the output below was produced by a CI run of the same file.
// Consistent hashing with virtual nodes, next to `hash mod N`: how many keys move when a node joins or leaves?//// The construction, so that any other implementation gives the same answers:// hash FNV-1a, 32 bits, over the UTF-8 bytes of the text (offset basis 2166136261, prime 16777619)// position virtual node i of a node sits at hash("{i}#{node}"), for i = 0 .. V-1// key belongs to the first virtual node at or after hash(key), going round the ring;// past the last one, it wraps to the first// tie two virtual nodes at the same position: the node name in ordinal order comes first// mod hash(key) % N picks "node-{k}"; going from N to N+1 nodes adds node-N// The replica number goes first in the label: with "{node}#{i}", which differs only at the end,// this hash clumps the virtual nodes together and the ring comes out lopsided (checked with these keys).using System.Globalization;using System.Text;
const int virtualNodes = 100;var keys = Enumerable.Range(0, 10_000).Select(i => $"user:{i}").ToArray();Console.WriteLine($"{keys.Length} keys over 4 nodes");
// How even is the split? Few virtual nodes leave big gaps on the ring; many smooth them out.foreach (var count in new[] { 10, virtualNodes }){ var spread = new HashRing(count); for (var i = 0; i < 4; i++) spread.Add($"node-{i}"); var owners = keys.Select(spread.Owner).ToArray(); var perNode = Enumerable.Range(0, 4).Select(i => owners.Count(o => o == $"node-{i}")).ToArray(); Console.WriteLine($"{count,3} virtual nodes each: busiest node {Percent(perNode.Max())}, quietest {Percent(perNode.Min())}");}
string ModOwner(string key, int nodes) => $"node-{Fnv1a.Hash(key) % nodes}";string Percent(int part) => (100.0 * part / keys.Length).ToString("0.0", CultureInfo.InvariantCulture) + "%";void Report(string label, string[] before, string[] after){ var moved = before.Zip(after).Count(pair => pair.First != pair.Second); Console.WriteLine($"{label,-26} {moved,4} of {keys.Length} keys moved ({Percent(moved)})");}
var ring = new HashRing(virtualNodes);for (var i = 0; i < 4; i++) ring.Add($"node-{i}");var ringWith4 = keys.Select(ring.Owner).ToArray();var modWith4 = keys.Select(k => ModOwner(k, 4)).ToArray();
// A fifth node joins.ring.Add("node-4");var ringWith5 = keys.Select(ring.Owner).ToArray();Report("hash mod N, 4 -> 5 nodes", modWith4, keys.Select(k => ModOwner(k, 5)).ToArray());Report("hash ring, add node-4", ringWith4, ringWith5);Console.WriteLine($" moved anywhere but to node-4: {ringWith4.Zip(ringWith5).Count(p => p.First != p.Second && p.Second != "node-4")}");
// node-1 leaves.ring.Remove("node-1");Report("hash ring, remove node-1", ringWith5, keys.Select(ring.Owner).ToArray());Console.WriteLine($" keys that were on node-1: {ringWith5.Count(o => o == "node-1")}");
static class Fnv1a{ public static uint Hash(string text) { var hash = 2166136261u; foreach (var b in Encoding.UTF8.GetBytes(text)) hash = (hash ^ b) * 16777619u; return hash; }}
class HashRing(int virtualNodes){ private (uint Position, string Node)[] _points = []; private uint[] _positions = [];
public void Add(string node) => Set(_points.Concat(Enumerable.Range(0, virtualNodes).Select(i => (Fnv1a.Hash($"{i}#{node}"), node))));
public void Remove(string node) => Set(_points.Where(p => p.Node != node));
public string Owner(string key) { var i = Array.BinarySearch(_positions, Fnv1a.Hash(key)); if (i < 0) i = ~i; // no point exactly here: take the next one along return _points[i % _points.Length].Node; // past the last point, wrap round to the first }
private void Set(IEnumerable<(uint Position, string Node)> points) { _points = points.OrderBy(p => p.Position).ThenBy(p => p.Node, StringComparer.Ordinal).ToArray(); _positions = _points.Select(p => p.Position).ToArray(); }}10000 keys over 4 nodes 10 virtual nodes each: busiest node 37.2%, quietest 16.1%100 virtual nodes each: busiest node 28.6%, quietest 22.6%hash mod N, 4 -> 5 nodes 8006 of 10000 keys moved (80.1%)hash ring, add node-4 1988 of 10000 keys moved (19.9%) moved anywhere but to node-4: 0hash ring, remove node-1 2050 of 10000 keys moved (20.5%) keys that were on node-1: 2050This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.
What happens if a shard leaves the ring?
Section titled “What happens if a shard leaves the ring?”Remove a shard from a ring of five with 100 virtual nodes each. The shard held 2,050 keys, and those are exactly the keys that move, 20.5% of the 10,000. They do not all go to one neighbour, because the shard’s 100 positions sit among everyone else’s, so each of the four others takes a part. The other 7,950 keys do not move. With hash mod N the same removal would change the remainder of most keys.
A ring is still a hash. It balances keys, and it cannot see load: one key with 30% of the traffic sits where its hash puts it, whatever the number of virtual nodes. And a ring cannot move one key to relieve one shard, because a key lives where the ring puts it. The next lesson deals with hot shards, and with the layouts that can move one key or one range.
Redis Cluster offers another way to keep placement stable. It does not hash to a node. It hashes each key to one of 16,384 slots, with CRC16, and assigns slots to nodes. Adding a node means moving some slots to it, and the hash of a key never changes. The unit of movement is the slot, and the table of slots is small.
- Hash mod N moves
N / (N + 1)of the keys when a shard is added: 8,006 of 10,000 (80.1%) going from 4 shards to 5. - A ring puts shards and keys on one circle. A key belongs to the first shard position clockwise from it, so a new shard takes keys only from the arcs next to its positions: 1,988 keys (19.9%), all of them to the new shard.
- A shard that leaves moves exactly its own keys: 2,050 of 10,000 when one of five leaves.
- Virtual nodes give each shard many positions. With 10 per shard the busiest of four holds 37.2% of the keys and the quietest 16.1%. With 100 it is 28.6% and 22.6%. The keys moved also come near the theory from about 100.
- A ring balances keys, not load, and cannot move one key. Fixed hash slots, as in Redis Cluster, keep placement stable in another way.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.