KatInterview

Fix a Broken Round-Robin Load Balancer

Data Structure DesignModel answer
MediumModel answerData Structure Designround-robinload-balancingdebugging

Last updated

Debug and repair a round-robin router that mis-assigns requests when servers are added, removed, or marked unhealthy, then write tests covering the edge cases.

Fix a Broken Round-Robin Load Balancer

You are handed a LoadBalancer class that is supposed to distribute incoming requests across a pool of backend servers in round-robin order. A suite of tests is already failing. Your job is to find the bug, fix it, and leave the codebase in a state you would be comfortable shipping.

What the router must do

  • Ordered rotation. Servers rotate in the order they were added. New servers are appended to the end.
  • Skip unhealthy, hold the slot. An unhealthy server is passed over but keeps its position. When it recovers, it rejoins the rotation at that same slot—no reshuffling.
  • Bounded scan. If no healthy server exists, return None. The method must never hang in an infinite loop.
  • Fairness. Every healthy server receives requests in strict cyclic order. No server should appear twice in a row while another healthy server is available, and no healthy server should be silently skipped.

Operations the router must support

MethodBehavior
add_server(name)Append a new healthy server.
remove_server(name)Remove the server; keep rotation consistent for the remaining ones.
set_health(name, healthy)Mark a server healthy or unhealthy.
next_server()Return the next healthy server, or None.

What you are expected to produce

  1. Identify the bug(s). Name the exact invariant that is violated and show how the failing tests expose it.
  2. Write a correct implementation. Your fix must handle add, remove, and health changes without corrupting the cursor.
  3. Write tests for at least: a single server, multiple servers with wraparound, removal at various cursor positions, health flapping, and the all-unhealthy case.
  4. Analyze complexity for each operation and discuss thread-safety.

You may use Python. Start by stating your assumptions and the invariant you intend to maintain before writing any code.

Hints

Hint 1

The cursor represents the index of the next candidate to examine, not the last server chosen. Ask yourself: after a healthy server at index i is returned, where should the cursor point so the next call picks up correctly?

Hint 2

Removing a server at index i shifts every server after it one position to the left. Work through the three cases—removal before the cursor, at the cursor, and after it—and decide what adjustment, if any, each case requires.

Hint 3

The scan that finds the next healthy server must be bounded by the length of the server list. If it runs len(servers) steps without finding a healthy one, return None immediately rather than continuing.