KatInterview

Build Stateful Round-Robin and Consistent Hash Load Balancers

Data Structure DesignModel answer
MediumModel answerData Structure Designload-balancerconsistent-hashinground-robin

Last updated

Implement thread-safe Round-Robin and Consistent Hashing balancers supporting health checks and dynamic nodes, then analyze their performance.

Design and write thread-safe load balancer implementations in Python (or your preferred language) for two distinct algorithms:

  1. Stateful Round-Robin Balancer:

    • Maintains an ordered set of server nodes, where each node has a health status (HEALTHY or UNHEALTHY).
    • Cycles through available servers sequentially to handle request delegation.
    • Bypasses UNHEALTHY servers cleanly without resetting or corrupting the sequence for standard nodes.
    • Correctly updates its internal state across concurrent calls, safely handles adding/removing servers dynamically, and throws a custom exception if zero operational nodes remain.
  2. Consistent-Hashing Balancer:

    • Assigns request keys to nodes situated on a dynamic hash ring utilizing virtual nodes (vnodes) for each physical backend server.
    • Routes incoming keys to the nearest clockwise operational node on the ring.
    • Allows dynamically registering or unregistering physical nodes while minimizing data re-mapping (re-keying) across remaining cluster members.
    • Handles offline nodes by continuing clockwise past inactive virtual nodes until reaching an operational server.

Following your implementations, provide a theoretical comparison that covers:

  • Time and space complexity for request lookup, server registration, and node removal.
  • Key migration characteristics under cluster topology shifts.
  • Cache affinity, load distribution uniformness (hotspot prevention), and fault tolerance.
  • Concrete real-world production cases suited to each approach.

Hints

Hint 1

Use an explicit Enum for health status to prevent string-matching bugs, and ensure state variables like index counters survive across function invocations.

Hint 2

When removing nodes during active operation, ensure index pointer recalculation prevents out-of-bounds access or skipped elements.

Hint 3

Ensure hashing is deterministic across executions; avoid standard Python hash() which uses per-process random seeds.