Skip to main content

Debug a Round-Robin Load Balancer

MediumPremium

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.

Starter code and solution
Python 3.11+ (standard library)
Download code

What's in the codebase

  • round_robin.py. RoundRobinBalancer with next_server, add_server, and remove_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. Prints PASS when 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.