Debug a Round-Robin Load Balancer
You're on an infrastructure team, and a small service spreads incoming requests across servers in rotation: A, B, C, A, B, C. The file is short, the tests are provided, and the service is broken. Run the tests, find the bugs, and fix each one where it is.
What's in the codebase
round_robin.py.RoundRobinBalancerwithnext_server,add_server, andremove_server. The module docstring is the spec. This is the only file you change.test_round_robin.py. Fourteen tests covering rotation order, adding and removing servers, rotation after a removal, error cases, and list ownership.scenarios.py. Prints six picks, removes a server, and prints three more. PrintsPASSwhen both lists match.README.md. Run commands and ground rules.
Out of the box, three tests pass and eleven fail. scenarios.py crashes with IndexError on the fourth pick.
Your task
The file has four bugs. Fix them so all 14 tests pass, without changing the class, method names, or signatures.
The balancer keeps its own copy of the server list, so changes on either side never leak to the other. next_server cycles through the servers starting with the first and raises ValueError when there are none. add_server appends to the rotation. remove_server raises ValueError for an unknown server, and after a removal the next call returns the server that would have come next in the old order.
["A", "B", "C"], 6 picks -> A, B, C, A, B, C ["A", "B"], pick, add "C", 3 picks -> A, then B, C, A ["A", "B", "C"], pick, remove "B", 2 picks -> A, then C, A ["A", "B", "C"], 2 picks, remove "A", 3 picks -> A, B, then C, B, C ["A", "B", "C"], 2 picks, remove "C", 2 picks -> A, B, then A, B ["A", "B"], remove "C" -> ValueError [], next_server() -> ValueError
You're done when all 14 tests pass and python3 scenarios.py prints PASS.
The consistent hashing follow-up
Once the balancer works, the interviewer asks you to convert it to consistent hashing, so a given request key keeps landing on the same server. Explain where servers sit on the ring, how a key finds its server, which keys move when a server joins or leaves, and how you'd even out the load.
Using AI on this problem
This round usually allows AI for lookups, such as what list.remove returns. Don't paste the failures in and ask for a fix: reading the tracebacks and tracing the index on paper are what the interviewer is watching. If you use AI for the consistent hashing follow-up, decide the ring design yourself first and use it only to check syntax.
Why the starter is broken
The four bugs, in the order the tests surface them:
- The wrap is off by one.
next_serveradvances with% (len(self.servers) + 1), so after the last server the index lands one past the end. That's theIndexErroron the fourth pick. list.removereturnsNone.self.servers = self.servers.remove(server)replaces the list withNone. The next call tonext_serversees a falsy list and raisesValueError: no servers available, which looks like an empty balancer rather than a crash.- The constructor shares the caller's list.
self.servers = serversbinds a second name to the same list, soadd_servermutates the caller's list and the caller's later appends change the rotation. - Removal never adjusts the index. Removing a server before the current position shifts every later server down one place, so the index now skips a server. Removing the server at the end can leave the index past the end of the list.
Bugs 1 and 4 are indexing bugs. Bugs 2 and 3 are list-assignment bugs.
Approach
- Run the tests and read the first traceback. The
IndexErrorpoints at the wrap. - Fix one bug at a time and rerun. Each fix exposes the next set of failures.
- For removal, find the position first, delete it, then repair the index: shift it down when the removed server sat before it, and wrap to 0 when it runs past the end.
Pythonclass RoundRobinBalancer:
def __init__(self, servers: list) -> None:
self.servers = list(servers)
self._index = 0
def next_server(self) -> str:
if not self.servers:
raise ValueError("no servers available")
server = self.servers[self._index]
self._index = (self._index + 1) % len(self.servers)
return server
def add_server(self, server: str) -> None:
self.servers.append(server)
def remove_server(self, server: str) -> None:
position = self.servers.index(server)
del self.servers[position]
if position < self._index:
self._index -= 1
if self._index >= len(self.servers):
self._index = 0
list.index raises ValueError for an unknown server, which is the behavior the spec asks for. The copy goes in the constructor, so add_server and remove_server only ever touch the balancer's own list.
All 14 tests pass and scenarios.py prints PASS. If you fix only the first three bugs, two tests still fail: removing a server before the current position, and removing the server the index points to at the end.
What to focus on
- Read the failure before the code. The traceback names the line. An
IndexErrorinnext_serveris the wrap. AValueErrorthat says there are no servers after a removal means the list becameNone. - Fix in place. Each bug is a one- or two-line change. Rewriting around
itertools.cyclehides whether you understood the failures, and a cycle can't remove servers anyway. - Separate returning from mutating, and binding from copying.
list.removemutates and returnsNone. Assignment binds a name and copies nothing. Two of the four bugs are those two confusions. - Draw the index for removal. Write out the list, the index, and the removed position for each case. Guessing usually breaks the case where the removed server was last.
The consistent hashing follow-up
Round-robin remembers nothing about which key went where, so any add or remove reassigns nearly every key. Consistent hashing places each server on a ring at the hash of its name, and a request goes to the first server at or after the hash of its key, wrapping around. When a server joins or leaves, only the keys in its arc move.
One position per server makes the arcs uneven, so each server takes many positions, called virtual nodes. More virtual nodes means more even load and a bigger ring to maintain. Lookup is a binary search over the sorted ring positions.
With three servers and 1,000 keys, removing one server moves only the keys that server owned, about a third, and every other key stays put. Be ready to discuss what happens to requests already running on a server that's leaving: drain them, or retry them on the new owner with an idempotency key so nothing runs twice.