This question evaluates understanding of consistent hashing, virtual nodes, deterministic hash functions, and data structure design for efficient key-to-server mapping and dynamic membership changes.
Implement a class ConsistentHashRing that distributes keys across servers using a hash ring with virtual nodes.
Required API:
ConsistentHashRing(replicas_per_server: int)
add_server(server_id: str) -> None
remove_server(server_id: str) -> None
get_server(key: str) -> Optional[str]
Behavior:
replicas_per_server
virtual nodes at positions
hash(server_id + "#" + i)
for
i = 0..replicas_per_server-1
.
get_server(key)
computes
hash(key)
and returns the server owning the first virtual node found when moving clockwise around the ring.
hash(key)
, wrap around and return the server at the smallest position.
None
.
Target complexity:
add_server
/
remove_server
:
O(R log N)
where
R
is the number of replicas added or removed
get_server
:
O(log N)