Skip to content
Katabench
Try free
9 min read The Katabench team

Consistent hashing measured on a million keys

Consistent hashing measured on a million keys: adding an 11th node moved 90.97% of keys under modulo and 9.76% on a ring with 100 virtual nodes per node.

Take a cache fleet of ten nodes that routes each key with hash(key) % 10. Add an eleventh to get about 10% more capacity. In the simulation behind this post, 909,650 of 1,000,000 keys changed owner the moment the eleventh node appeared. If those keys all miss, a cache with a 95% hit rate drops to about 8.6% (95% x 9.03% of keys that stayed), and the database behind it takes roughly eighteen times its normal read load (91.4% misses against 5%). A database sized for a 95% hit rate has no headroom for that.

Consistent hashing exists to make that number small. The load balancing post introduces it as one strategy among several, and sharding vs partitioning names it as a way out of the resharding trap. This post measures it: what the ring costs, how badly it behaves without virtual nodes, what replication changes, and where it stops helping.

All numbers below come from one C# program we ran: 1,000,000 keys named user:0 onward, hashed with the first 8 bytes of SHA-256, one fixed run with no random seed. A different hash or node naming would shift the figures a little.

Why modulo moves nearly everything

A key stays put only when h % 10 equals h % 11. For a well-mixed hash that happens about once in eleven tries, because the two remainders line up only for the small values of h in each repeating cycle of 110. So the fraction that moves is about 1 - 1/(N+1), and it gets worse as the fleet grows:

Text
modulo, keys that change node
10 -> 11:    909,650 of 1,000,000 = 90.97%
10 -> 9:     900,090 of 1,000,000 = 90.01%
100 -> 101:  989,965 of 1,000,000 = 99.00%

The ring

Karger and colleagues' 1997 paper introduced consistent hashing to relieve hot spots across a changing set of web caches. Hash both nodes and keys into the same large number space and treat it as a circle. A key belongs to the first node at or after its own hash, wrapping past the top. A new node claims only the stretch between itself and its predecessor, so everything else keeps its owner.

Adding an 11th node: what has to move

  • hash mod N 90.97% of keys move
  • Ring, 100 virtual nodes 9.76% of keys move

Grey dots are existing nodes and the green dot is the new one. Keys on the green arc change owner. Every other key stays where it was.

The ideal for one new node out of 11 is 1/11, or 9.09%. Real rings use many points per node, so the new node takes small arcs from all over the ring.

The lookup is a binary search over sorted points:

C#
using System.Security.Cryptography;
using System.Text;

public sealed class HashRing
{
    private readonly ulong[] _points;
    private readonly string[] _owners;

    public HashRing(IEnumerable<string> nodes, int virtualNodes)
    {
        var entries = nodes
            .SelectMany(node => Enumerable.Range(0, virtualNodes)
                .Select(i => (Point: Hash($"{node}#{i}"), Node: node)))
            .OrderBy(entry => entry.Point)
            .ToArray();

        _points = entries.Select(entry => entry.Point).ToArray();
        _owners = entries.Select(entry => entry.Node).ToArray();
    }

    public string Owner(ulong keyHash) => _owners[FirstAtOrAfter(keyHash)];

    // Walk clockwise, skipping points owned by a node already chosen.
    public string[] Replicas(ulong keyHash, int count)
    {
        var replicas = new List<string>(count);
        var start = FirstAtOrAfter(keyHash);

        for (var i = 0; i < _owners.Length && replicas.Count < count; i++)
        {
            var node = _owners[(start + i) % _owners.Length];
            if (!replicas.Contains(node))
            {
                replicas.Add(node);
            }
        }

        return [.. replicas];
    }

    private int FirstAtOrAfter(ulong keyHash)
    {
        var index = Array.BinarySearch(_points, keyHash);
        if (index < 0)
        {
            index = ~index;
        }

        return index == _points.Length ? 0 : index; // past the last point: wrap around
    }

    public static ulong Hash(string value) =>
        BitConverter.ToUInt64(SHA256.HashData(Encoding.UTF8.GetBytes(value)));
}

Hash with something stable. .NET's string.GetHashCode is randomized per process, so two instances would disagree about the ring.

One point per node is not enough

The textbook drawing gives each node one point. Here is what that does, growing from 10 nodes to 11 at four settings. The max, min and stddev columns describe the 10-node ring: the fullest and emptiest nodes relative to a fair share, and the spread of load. The last column is the share of keys that moved, where the ideal is 1/11, or 9.09%.

Text
vnodes  max/mean  min/mean  stddev   moved
     1      2.18      0.08   74.7%   5.91%
    10      1.51      0.50   35.4%  14.40%
   100      1.18      0.87   11.5%   9.76%
  1000      1.05      0.94    3.3%   9.14%

With one point per node, the unluckiest node held 2.18 times its share and another held 8% of it. Point placement is effectively random, so arcs come in very unequal lengths. The moved figure swings for the same reason: 5.91% at one point per node, all taken from a single neighbor, and 14.40% at ten. Only at higher settings does the new node's share settle near the ideal. The deviation roughly tracks 1/sqrt(v), so 100 points gets you about 10% and 1,000 about 3%.

At one point per node, the fullest node held 2.18 times its fair share and the emptiest held 8% of it. At 1,000 points per node, those figures were 1.05 times and 94%.

Removal shows the second benefit. Taking node-3 out of the ring moved only keys it owned, zero others, in both configurations below. Where they went differs:

Text
1 vnode:     node-5=131,259
100 vnodes:  node-0=8,943  node-1=7,287  node-2=9,089  node-4=9,721  node-5=6,770
             node-6=15,955 node-7=9,155  node-8=4,329  node-9=19,603

With one point per node, a failure hands all of its load to one neighbor, which can then fail too. With many points, nine nodes share it, though not equally at this setting. The Dynamo paper gives the same reasons for virtual nodes, non-uniform load from random placement and a failed node's load needing to disperse, and adds a third: assign more points to bigger machines so load follows capacity.

The cost is memory and rebuild work on every router. A thousand points across ten nodes is 10,000 sorted entries, which is small. Across a thousand nodes it is a million entries that must change whenever membership does, so the setting becomes a real trade-off on large fleets.

Replicas walk the ring

Replication usually stores a key on its owner plus the next nodes clockwise. With virtual nodes, the next three points on the ring often belong to the same machine. In our run at 100 points per node, taking the next three points without a check gave 25.94% of keys fewer than three distinct nodes, so a quarter of the data would have less protection than configured. Dynamo's preference list skips positions to ensure "only distinct physical nodes", which is what Replicas above does. Cassandra's documentation describes the same skip and says replication strategies may also skip nodes in the same failure domain, such as a rack or datacenter.

Replication also widens what a membership change touches, without widening what it costs:

Text
replication factor 3, 100 vnodes, 10 -> 11 nodes
keys with a changed replica set:  26.93%
new copies to stream:             269,337 of 3,000,000 (8.98%)
primary changed:                  9.76%

More than a quarter of keys have a new replica in their set, which is close to the 3/11 you would expect, yet only about one stored copy in eleven has to move. For a database that is the number that sizes the rebalance. For a read path it means requests can reach a node whose copy is still streaming, so routers need to know which nodes are ready rather than only which nodes exist.

Hot keys ignore the ring

Hashing balances keys. Traffic follows a different distribution. We replayed the same ring at 1,000 points per node, with key popularity following a Zipf distribution (s = 1), a common stand-in for skewed access:

Text
rank-1 key share of traffic: 6.95%    top 10 keys: 20.35%

node-5   keys 10.41%   traffic 15.24%     <- owns the rank-1 key
node-1   keys 10.54%   traffic 13.63%     <- owns the rank-2 key
node-3   keys  9.92%   traffic 11.45%
...
node-7   keys  9.76%   traffic  7.36%

Key counts stay within about 0.6 of a percentage point of 10%, and the busiest node still takes double the traffic of the quietest. More virtual nodes cannot help, because one key is one point. Fixes work at a different layer. Read a hot key from any replica rather than only its primary. Put a short-lived in-process cache in front of it. Split a known hot key into suffixed copies and read a random one. Or cap each node: consistent hashing with bounded loads keeps every server at or below a chosen factor above the average load, while still bounding how many clients move on each membership change.

When a ring is the wrong tool

Rings suit fleets where nodes come and go by name. If you can number buckets sequentially, jump consistent hash needs no stored state at all. The paper gives up arbitrary removal on purpose, arguing that a storage shard cannot simply vanish the way a cache server can. Redis Cluster takes a third route. Its specification maps every key with CRC16(key) mod 16384 and then assigns those slots to nodes. Modulo over a fixed number never reshuffles, and rebalancing becomes moving named slots, which you can see and throttle. That is the virtual-bucket design the sharding post describes.

Whichever you pick, membership agreement is the part that fails in production. Two routers holding different node lists send the same key to different owners. For a cache that is an extra miss. For a database it is a write to the wrong place, so the map needs a version, and moving a range means copying first, then flipping the pointer.

Routing the keys you just measured

A rebalance that moves 9.76% of keys still goes wrong if routers disagree about where those keys went, so the routing tier is where a partitioned design gets tested. The System Design Studio has challenges that start there, one on a dataset that outgrew its biggest machine and one on crawl frontier ownership split across private regions, and hash versus range stays your call. The tracks overview shows where those challenges sit beside the code tracks.

Practice what you just read

  • System Design Studio Hard Katabench Pro

    Shard the Database

    The dataset outgrew the biggest machine you can rent and one database can't hold it. Split the data across shards and route each key to the shard that owns it.

    Open the Pro kata: Shard the Database
  • System Design Studio Hard Katabench Pro

    Partition Crawl Ownership

    Route every host to one durable frontier shard so crawl state can scale out without two partitions attacking the same origin.

    Open the Pro kata: Partition Crawl Ownership

More like this: System Design Studio →

Get new puzzles and .NET tips in your inbox

A short note when fresh kata land, plus the C# and performance tricks behind the grading. No spam, unsubscribe anytime.