KatInterview

Build a Weighted Consistent Hash Ring

Data Structure DesignModel answer
MediumModel answerData Structure Designhashingdistributed-systemsdata-structures

Last updated

Design and code a hash ring that maps keys to servers with virtual nodes, supporting weighted capacity and minimal key movement on topology changes.

You're building a distributed cache router. Design a consistent hash ring that assigns keys to servers while minimizing how many keys get reassigned when servers are added or removed.

Implement a ConsistentHashRing class with these methods:

  • add_node(node_id, weight=1.0) — register a server with the given capacity weight
  • remove_node(node_id) — unregister a server; return True if it existed, False otherwise
  • get_node(key) — return which server owns this key, or None if the ring is empty

Requirements:

  • Use virtual nodes (vnodes) to distribute load evenly. A server with weight w should receive roughly w / total_weight of all keys.
  • When a server joins or leaves, only keys directly affected by that change should move—keys should not shift between unchanged servers.
  • Handle hash collisions deterministically so all clients agree on ownership.
  • Support re-weighting: calling add_node on an existing server updates its weight.

Explain your design choices:

  • Which hash function and why
  • How you handle collisions
  • How you choose the number of virtual nodes
  • Time and space complexity
  • How this compares to simple modulo hashing (key % num_servers)

Hints

Hint 1

Think about representing the ring as a sorted structure where both keys and servers live in the same hash space.

Hint 2

Virtual nodes are copies of the same physical server placed at different hash positions—more copies mean smoother distribution.

Hint 3

A deterministic tie-breaker (like including the node ID in the sort key) ensures all clients see the same ring even if hash values collide.