Fix a Broken Round-Robin Load Balancer
Data Structure DesignModel answerLast 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
| Method | Behavior |
|---|---|
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
- Identify the bug(s). Name the exact invariant that is violated and show how the failing tests expose it.
- Write a correct implementation. Your fix must handle add, remove, and health changes without corrupting the cursor.
- Write tests for at least: a single server, multiple servers with wraparound, removal at various cursor positions, health flapping, and the all-unhealthy case.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Before touching code, pin down the one invariant everything else depends on:
cursoris the index of the next candidate to examine, and0 <= cursor < len(servers)whenever the list is non-empty.
All bugs in broken round-robin routers trace back to a moment where this invariant is silently broken.
The Common Bugs
1. Advancing from the wrong position.
self.cursor = (self.cursor + 1) % n # incremented first
while not healthy[servers[self.cursor]]:
self.cursor = (self.cursor + 1) % n
return servers[self.cursor]
The cursor is left pointing just past the chosen server—which is correct—but only when no unhealthy servers were skipped. When skipping does occur, the cursor ends up one step too far, causing the following call to repeat a server or skip one entirely.
2. Pre-increment on the first request. Incrementing before reading means servers[0] is never returned on lap one.
3. Off-by-one on removal. Using if cursor > len(servers) instead of >= len(servers) leaves a stale out-of-range index after the last element is removed.
4. Cursor not adjusted after removal. Deleting element i shifts everything at index > i left by one. If the cursor pointed past i, it now points to the wrong server. If the cursor equals the new length, it is out of bounds.
5. Unbounded scan. A while True loop with only a health check for the exit condition hangs when all servers are unhealthy.
The Fix
Scan at most n positions in cyclic order starting from cursor. When a healthy server is found at index i, set cursor = (i + 1) % n—advancing past the chosen server, not past any skipped ones.
For removal at index i:
i < cursor: shift the cursor left by one (cursor -= 1) because everything before the cursor moved.i == cursorori > cursor: no shift needed; the cursor still points to the right relative position.- In all cases, if
cursor >= len(servers)after the deletion, wrap it to0.
Implementation
import threading
from typing import Iterable, Optional
class LoadBalancer:
def __init__(self, servers: Iterable[str] = ()):
self._servers: list[str] = []
self._healthy: dict[str, bool] = {}
self._cursor = 0 # index of next candidate to examine
self._lock = threading.Lock()
for s in servers:
self.add_server(s)
def add_server(self, name: str, healthy: bool = True) -> None:
with self._lock:
if name in self._healthy:
raise ValueError(f"duplicate server {name!r}")
self._servers.append(name) # append: no existing index shifts
self._healthy[name] = healthy
def remove_server(self, name: str) -> None:
with self._lock:
i = self._servers.index(name) # raises ValueError if absent
del self._servers[i]
del self._healthy[name]
# Adjust cursor for the left-shift caused by deletion
if i < self._cursor:
self._cursor -= 1
# Guard against out-of-bounds (also handles empty list)
if self._servers and self._cursor >= len(self._servers):
self._cursor = 0
def set_health(self, name: str, healthy: bool) -> None:
with self._lock:
if name not in self._healthy:
raise KeyError(name)
self._healthy[name] = healthy # position unchanged, cursor unaffected
def next_server(self) -> Optional[str]:
with self._lock:
n = len(self._servers)
for step in range(n): # bounded: terminates even if all unhealthy
i = (self._cursor + step) % n
name = self._servers[i]
if self._healthy[name]:
self._cursor = (i + 1) % n # advance past the chosen server
return name
return None
Tests
def route(lb, k):
return [lb.next_server() for _ in range(k)]
def test_single_server():
lb = LoadBalancer(["A"])
assert route(lb, 3) == ["A", "A", "A"]
def test_empty_returns_none():
assert LoadBalancer().next_server() is None
def test_all_unhealthy_returns_none():
lb = LoadBalancer(["A", "B"])
lb.set_health("A", False)
lb.set_health("B", False)
assert lb.next_server() is None
def test_fair_wraparound():
lb = LoadBalancer(["A", "B", "C"])
assert route(lb, 7) == ["A", "B", "C", "A", "B", "C", "A"]
def test_remove_before_cursor():
lb = LoadBalancer(["A", "B", "C"])
assert route(lb, 2) == ["A", "B"] # cursor now at index 2 → C
lb.remove_server("A") # shifts B→0, C→1; cursor adjusts to 1
assert route(lb, 3) == ["C", "B", "C"]
def test_remove_at_cursor():
lb = LoadBalancer(["A", "B", "C"])
assert route(lb, 1) == ["A"] # cursor at 1 → B
lb.remove_server("B") # cursor stays at 1 → C
assert route(lb, 2) == ["C", "A"]
def test_remove_last_element_wraps_cursor():
lb = LoadBalancer(["A", "B", "C"])
route(lb, 2) # cursor at index 2 → C
lb.remove_server("C") # cursor 2 >= len 2, wraps to 0
assert route(lb, 2) == ["A", "B"]
def test_add_during_routing():
lb = LoadBalancer(["A", "B"])
route(lb, 1) # cursor at 1 → B
lb.add_server("C")
assert route(lb, 3) == ["B", "C", "A"]
def test_health_flapping_no_duplicate_no_skip():
lb = LoadBalancer(["A", "B", "C"])
assert lb.next_server() == "A"
lb.set_health("B", False)
assert route(lb, 2) == ["C", "A"] # B skipped; no duplicate A
lb.set_health("B", True)
assert route(lb, 3) == ["B", "C", "A"] # B rejoins in original slot
Complexity and Thread-Safety
| Operation | Time | Notes |
|---|---|---|
add_server | O(1) amortized | List append |
remove_server | O(n) | List scan + left-shift |
set_health | O(1) | Dict update |
next_server | O(n) worst case | Bounded scan; O(1) when all servers healthy |
Space is O(n) for the server list and health map.
A single threading.Lock around every method is the simplest correct approach. It serializes all operations, which is fine for moderate request rates. At higher throughput you could replace the lock with a threading.RWLock (readers-writer lock): next_server and set_health take a read lock while add_server and remove_server take a write lock. For extreme scale, a lock-free design using atomic cursor updates is possible, but only worthwhile once profiling shows the lock is actually the bottleneck.
The most common mistake candidates make is forgetting to adjust the cursor after removal, which surfaces only in tests that advance the cursor before removing—exactly why the removal tests above are structured the way they are.