KatInterview

Build a Weighted Hash Ring for Sharding Keys Across Servers

Data Structure DesignModel answer
MediumModel answerData Structure Designconsistent-hashingvirtual-nodesbinary-search

Last updated

Design a hash ring with weighted virtual nodes that assigns keys to servers, supports adding and removing servers with little key movement, and handles collisions and concurrency.

Weighted Hash Ring

You are building the routing layer of a sharded storage service. Design a class that decides which backend server owns each key, so that when servers join or leave, as few keys as possible change owners.

Operations

  1. add_node(node_id, weight) registers a physical server. Its weight controls how many virtual nodes (points on the ring) it receives, so a heavier server owns a larger share of the key space.
  2. remove_node(node_id) deletes a server together with every virtual node it contributed.
  3. get_node(key) returns the node_id responsible for key.

Requirements

  • Map both servers and keys into a fixed integer space such as 0 .. 2^32 - 1 using a hash that gives the same result in every process and across restarts.
  • get_node must run in O(log V) time, where V is the total number of virtual nodes.
  • Every virtual node must be traceable back to the physical server that owns it.

Example

ring = ConsistentHashRing()
ring.add_node("Server_A", weight=2)
# Server_A might occupy positions such as [100, 500] on the ring

ring.get_node("order_123")   # -> "Server_A"

Edge cases you must address

  • Two virtual nodes hash to the same position. Define a deterministic tie-break.
  • The ring contains no servers.
  • Many threads call get_node while others add or remove servers.

What to deliver

Explain your data structure and ownership rule, then give working code. State the complexity of each operation, justify why few keys move on membership changes, and describe how you handle the edge cases above. Be ready to discuss how you would extend the design to support replication and to react to overloaded servers.

Hints

Hint 1

Picture the hash space as a circle. A key belongs to the first virtual node found at or after its hash when moving clockwise, and if none exists you wrap to the smallest position.

Hint 2

Keep one sorted list of (position, node_id, replica_index) entries. Storing the physical node_id inside each entry removes the need for a second lookup table, and tuple ordering gives you a deterministic tie-break for equal positions.

Hint 3

Avoid Python's built-in hash() because it is randomized per process. For concurrency, think copy-on-write: writers hold a lock and publish a freshly built list, while readers take one reference to the current list and never lock.