KatInterview

Designing Dynamic Load Balancers: Round-Robin and Consistent Hashing

Data Structure DesignModel answer
MediumModel answerData Structure Designdesign-dshashingconcurrency

Last updated

Implement a resilient round-robin request balancer that handles dynamic server membership, followed by a consistent hashing router to maintain key affinity.

You are tasked with building the core request-routing component for an API gateway. The task consists of two parts: building a robust round-robin load balancer, and implementing a consistent hashing router to preserve key affinity.

Part 1: Dynamic Round-Robin Balancer

Implement a data structure that routes requests among an active pool of servers using a round-robin strategy. Your implementation must support the following methods:

  • add_server(server_id: str): Adds a server to the available pool.
  • remove_server(server_id: str): Removes a server from the available pool.
  • get_next_server() -> str: Returns the identifier of the next server in sequence.

Requirements & Edge Cases:

  1. Thread Safety: Multiple threads will invoke get_next_server(), add_server(), and remove_server() concurrently.
  2. Empty Pool: If no servers are available, get_next_server() should return None (or raise a clear exception).
  3. Dynamic Membership Modifications: Removing or adding a server mid-rotation must not cause out-of-bounds errors, race conditions, or skip/repeat servers unnecessarily.
  4. Defect Analysis: List common defects found in naive round-robin implementations (such as index drift or concurrency issues) and explain how to test for them deterministically.

Part 2: Consistent Hashing Router

To support stateful routing (e.g., sticky user sessions or distributed caches), implement a consistent hashing router. The router maps both servers and request keys onto a unified hash ring.

Implement a class supporting the following interface:

  • add_server(server_id: str): Hashes and places the server (and its virtual nodes) on the ring.
  • remove_server(server_id: str): Removes the server and its virtual nodes from the ring.
  • get_server(key: str) -> str: Hashes the given key and routes it to the nearest server clockwise on the ring.

Requirements:

  1. Virtual Nodes (Replicas): Support a parameter num_replicas (e.g., 100 to 200) per physical server to ensure balanced distribution.
  2. Deterministic Lookup: get_server(key) must return None if the ring is empty.
  3. Minimal Key Movement: Demonstrate or explain why adding/removing a server reassigns only a fraction ($1/N$) of keys on average.
  4. Complexity: State the time and space complexity of add_server, remove_server, and get_server.

Hints

Hint 1

For Part 1, storing current position as a simple integer index combined with array length operations like `idx % len(servers)` can fail if the array shrinks during execution.

Hint 2

For Part 2, standard Python dictionary lookups won't preserve sorted ring order. Consider maintaining a sorted list of hash values along with a map from hash to server ID.

Hint 3

Use `bisect.bisect_right` or `bisect.bisect_left` to efficiently locate the first node with a hash value greater than or equal to the key's hash value, wrapping around to the first element if necessary.