Sharding with consistent hashing

Spread keys over many database or cache nodes so that adding a node moves only a small share of keys.

Time O(log n) lookupSpace O(n·v) ring pointsCode C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Place nodes and keys on the same circle of hash values. A key belongs to the first node clockwise from it. When a node joins, it only takes keys from its neighbour; with hash mod N, almost every key would move. Many virtual points per node keep the load even.

Code

class HashRing
{
    readonly SortedDictionary<uint, string> _ring = new();
    public void Add(string node)
    {
        for (int v = 0; v < 100; v++) _ring[Hash($"{node}#{v}")] = node;
    }
    public string NodeFor(string key)
    {
        uint h = Hash(key);
        foreach (var (point, node) in _ring)
            if (point >= h) return node;
        return _ring.First().Value; // wrap around the ring
    }
}

Tips

In the .NET library

In .NET you would keep the ring in a sorted structure and binary search it; SortedDictionary with a linear walk keeps the example short.