KatInterview

Fan-Out Aggregation, Retry Logic, and Load Balancer Repair

System DesignModel answer
MediumModel answerSystem Designfault-toleranceload-balancingretry-logic

Last updated

Implement a fault-tolerant multi-source data aggregator with retry handling, then find and fix bugs in a load balancer and extend it with round-robin and consistent hashing.

The Problem

You have two independent exercises. Both test the same underlying skill: writing code that stays correct when dependencies fail or scale changes.


Part 1: Fault-Tolerant Data Aggregator

You are building a service that assembles a single response from three separate internal APIs: a trip API, a rider API, and a driver API. Each API exposes a .get(id) method.

Implement a method get_trip_summary(trip_id) that:

  1. Fetches the trip record (required — if this fails, the whole call fails).
  2. Uses IDs from the trip record to fetch the rider and driver in parallel or sequence.
  3. Returns a single nested dict in exactly this shape:
{
    "trip_id": "t1",
    "status": "COMPLETED",
    "rider": {"id": "r1", "name": "Jordan"},
    "driver": {"id": "d1", "name": "Casey"},
    "waypoints": [{"lat": 40.7, "lng": -74.0}],
    "errors": []
}
  1. Handles two error types: TransientError (network blip — worth retrying) and PermanentError (bad ID, validation failure — do not retry).
  2. Retries transient failures up to 3 total attempts with exponential backoff. After all attempts are exhausted for an optional source (rider, driver), degrade gracefully: set that field to None and append an entry to "errors". If the required source (trip) exhausts retries, raise the error to the caller.
  3. Accepts an injectable sleep function so tests run without real delays.

Write tests covering:

  • All sources succeed on the first attempt (verify the full output dict and that each API was called exactly once).
  • One optional source fails once then succeeds (verify recovery, call count = 2, one backoff recorded).
  • One optional source fails on every attempt (verify graceful degradation, call count = 3, two backoffs recorded, correct errors entry).
  • The required source fails on every attempt (verify the exception propagates, call count = 3).

Part 2: Debug and Extend a Load Balancer

Below is a load balancer with several bugs. Your tasks:

  1. Identify and fix every bug. For each one, name what the bug is and what breaks because of it.
  2. Add round-robin routing. Requests should cycle across healthy servers in a deterministic order.
  3. Describe (no code required) how you would extend the design to support consistent hashing — cover the data structure, how a server addition or removal affects key mapping, and the role of virtual nodes.
# Buggy implementation — do not use as-is
class LoadBalancer:
    def __init__(self, servers):
        self.servers = servers   # list of {"id": str, "healthy": bool}
        self.index = 0

    def get_server(self):
        server = self.servers[self.index]   # (A)
        self.index += 1                     # (B)
        if not server["healthy"]:           # (C)
            return self.get_server()
        return server

Three bugs are marked with comments; there may be more. Assume the balancer is called from multiple threads.

Hints

Hint 1

For the aggregator, decide which sources are required and which are optional before writing a single line — that decision drives everything else. The retry wrapper should be reusable for both cases; only what you do with a final failure differs.

Hint 2

When fixing the load balancer, work through failure modes one by one: what happens when the pool is empty? when all servers are unhealthy? when two threads call get_server() at the same time? Each question points to a distinct bug.

Hint 3

Consistent hashing uses a ring (sorted array of hash positions). To look up a key, hash it and find the next clockwise position in the ring. Virtual nodes make each real server occupy multiple positions, which smooths out uneven load distribution.