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.
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
namehasreplicasvirtual nodes labelledname#0,name#1, …,name#(replicas-1); a node's position on the ring ishash32(label)(a number in0 … 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 fromhash32(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.
| Language | API |
|---|---|
| JS/TS | hash32(s), new HashRing(replicas), addNode, removeNode, getNode |
| Python | hash32(s), HashRing(replicas), add_node, remove_node, get_node |
| C# | HashRing.Hash32(s) (uint), new HashRing(replicas), AddNode, RemoveNode, GetNode |
| Java | HashRing.hash32(s) (long), new HashRing(replicas), addNode, removeNode, getNode |
| Go | Hash32(s) (uint32), NewHashRing(replicas), AddNode, RemoveNode, GetNode |
Example
Servers cache-a, cache-b, cache-c, replicas = 3. Virtual nodes sorted by position:
| Position | Label |
|---|---|
| 776,460,556 | cache-c#0 |
| 1,369,040,872 | cache-a#1 |
| 1,682,050,073 | cache-b#2 |
| … | … |
| 4,200,630,493 | cache-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,000getNodecalls 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.