Sharding with consistent hashing
Spread keys over many database or cache nodes so that adding a node moves only a small share of keys.
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
- Say the number: with N nodes, adding one moves about 1/(N+1) of keys instead of nearly all of them.
- Virtual nodes (many points per server) smooth out uneven gaps and let bigger machines take more points.
- Used by DynamoDB, Cassandra, and client-side sharding in Redis clients.
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.