Polski

Consistent hashing ring

Spread cache keys over servers so that adding or removing a server moves only a small share of keys. A ring with virtual nodes and binary search.

hard · typescript · javascript · python · csharp · java · go · 40 XP

A cache cluster has a few servers. Naive hash(key) % serverCount moves almost all keys when one server is added – the cache is suddenly empty and the database gets an avalanche of queries. Consistent hashing (Dynamo, Cassandra, Memcached, load balancers) moves only the keys that have to move.

Task

A class HashRing(replicas):

  • every server name has replicas virtual nodes labelled name#0, name#1, …, name#(replicas-1); a node's position on the ring is hash32(label) (a number in 0 … 2³² − 1),
  • addNode(name) adds a server (adding an existing one changes nothing), removeNode(name) removes it (removing a missing one changes nothing),
  • getNode(key) returns the server of the first virtual node clockwise from hash32(key): the one with the smallest position ≥ hash32(key), or, if there is none, the first node of the ring (wrap-around); for equal positions the smaller label wins; an empty ring → null / None / "" (Go).

The hash32 function (FNV-1a over UTF-8 bytes with a final bit mix) is ready in the starter code – no need to change it.

LanguageAPI
JS/TShash32(s), new HashRing(replicas), addNode, removeNode, getNode
Pythonhash32(s), HashRing(replicas), add_node, remove_node, get_node
C#HashRing.Hash32(s) (uint), new HashRing(replicas), AddNode, RemoveNode, GetNode
JavaHashRing.hash32(s) (long), new HashRing(replicas), addNode, removeNode, getNode
GoHash32(s) (uint32), NewHashRing(replicas), AddNode, RemoveNode, GetNode

Example

Servers cache-a, cache-b, cache-c, replicas = 3. Virtual nodes sorted by position:

PositionLabel
776,460,556cache-c#0
1,369,040,872cache-a#1
1,682,050,073cache-b#2
……
4,200,630,493cache-b#0

hash32("user:1") = 1,763,983,599 → the first node not smaller is cache-b#1 (1,901,845,678) → cache-b. hash32("key-10") = 4,216,627,689 is larger than every position → wrap-around to cache-c#0 → cache-c.

Constraints

  • Up to 100 servers, 1 ≤ replicas ≤ 200, up to 50,000 getNode calls per test.

Expected complexity

getNode: O(log(N · R)) for N servers and R replicas. addNode / removeNode: O(N · R · log(N · R)) (rebuilding the sorted array) or better with a tree structure.