Consistent hash ring
A hash ring with virtual nodes: add a node, remove a node and look up the owner of a key, so that a membership change moves only the keys of the node that changed.
Statement
A cache tier picks a node for each key. With hash(key) mod N, changing N moves almost every key. Implement HashRing(vnodes=100) with add_node(node), remove_node(node) and get_node(key), so that adding or removing one node moves only the keys that node gains or loses.
Positions come from position(text): the first 8 bytes of the SHA-256 of the UTF-8 text, read as a big-endian integer. It is given in the starter and must not change, so that every process agrees. A node owns vnodes points, at position(f"{node}#{i}") for i from 0 to vnodes − 1. A key belongs to the node whose point is the first at or after position(key); past the highest point it wraps round to the lowest point on the ring.
get_node returns None on an empty ring. Adding a node that is already on the ring, or removing one that is not, changes nothing.
Examples
vnodes = 100
ring = HashRing(100)
ring.get_node("user:5") → None # empty ring
add cache-a, cache-b, cache-c
ring.get_node("user:5") → "cache-b"
ring.get_node("user:6") → "cache-b"
ring.get_node("user:8") → "cache-a"
ring.remove_node("cache-b")
ring.get_node("user:5") → "cache-a" # moved off cache-b
ring.get_node("user:6") → "cache-c" # moved off cache-b
ring.get_node("user:8") → "cache-a" # did not moveConstraints
Up to 50 nodes with 100 virtual nodes each and 10⁵ lookups, so get_node must be O(log(N × V)). Node names and keys are non-empty strings. Two points on the same position do not occur in the tests. Python's built-in hash() is salted per process for strings, so it cannot be used here.