Fan-Out Aggregation, Retry Logic, and Load Balancer Repair
System DesignModel answerLast 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:
- Fetches the trip record (required — if this fails, the whole call fails).
- Uses IDs from the trip record to fetch the rider and driver in parallel or sequence.
- 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": []
}
- Handles two error types:
TransientError(network blip — worth retrying) andPermanentError(bad ID, validation failure — do not retry). - 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
Noneand append an entry to"errors". If the required source (trip) exhausts retries, raise the error to the caller. - Accepts an injectable
sleepfunction 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
errorsentry). - 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:
- Identify and fix every bug. For each one, name what the bug is and what breaks because of it.
- Add round-robin routing. Requests should cycle across healthy servers in a deterministic order.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both exercises share a core theme: code that stays correct under adversarial conditions. For the aggregator that means failed dependencies; for the load balancer it means empty pools, unhealthy servers, and concurrent callers. Solve the correctness problem first, then talk about performance improvements.
Part 1: Fault-Tolerant Aggregator
Design decisions before writing code
- The trip record is the root object. Without it you cannot determine which rider or driver to fetch, so failure there must propagate immediately.
- The rider and driver are optional in the sense that a degraded response (with
Noneand an error entry) is more useful to the caller than a hard failure. TransientErroris the only type that warrants a retry. Retrying aPermanentError(wrong ID, schema mismatch) just burns latency for a guaranteed failure.- Inject
sleepso tests assert the backoff schedule without real delays.
Implementation
import time
from dataclasses import dataclass, field
class TransientError(Exception): ...
class PermanentError(Exception): ...
@dataclass
class RetryPolicy:
max_attempts: int = 3
base_delay: float = 0.05
sleep: callable = time.sleep # injectable for tests
def call(self, fn, *args):
for attempt in range(1, self.max_attempts + 1):
try:
return fn(*args)
except TransientError:
if attempt == self.max_attempts:
raise
self.sleep(self.base_delay * 2 ** (attempt - 1))
# unreachable, but satisfies type checkers
raise RuntimeError("retry loop exited unexpectedly")
class TripAggregator:
def __init__(self, trip_api, rider_api, driver_api, retry=None):
self.trip_api = trip_api
self.rider_api = rider_api
self.driver_api = driver_api
self.retry = retry or RetryPolicy()
def _optional(self, name, fn, arg, errors):
"""Call fn(arg) with retries; on final failure, record the error and return None."""
try:
return self.retry.call(fn, arg)
except (TransientError, PermanentError) as exc:
errors.append({"source": name, "error": type(exc).__name__})
return None
def get_trip_summary(self, trip_id):
# Required: raises if exhausted
trip = self.retry.call(self.trip_api.get, trip_id)
errors = []
rider = self._optional("rider", self.rider_api.get, trip["rider_id"], errors)
driver = self._optional("driver", self.driver_api.get, trip["driver_id"], errors)
return {
"trip_id": trip["id"],
"status": trip["status"],
"rider": None if rider is None else {"id": rider["id"], "name": rider["name"]},
"driver": None if driver is None else {"id": driver["id"], "name": driver["name"]},
"waypoints": [{"lat": w["lat"], "lng": w["lng"]} for w in trip["waypoints"]],
"errors": errors,
}
The output is built field-by-field from known keys. Schema drift in a downstream API cannot leak through silently — it either maps correctly or raises a KeyError that becomes visible immediately.
Complexity: O(k · r) calls and latency (k sources, r max attempts) with sequential fetching. In production, fan out the independent rider and driver calls with asyncio.gather or a thread pool; latency drops from the sum of source latencies to the maximum. Always add a per-call timeout and an overall deadline so retries cannot blow past the caller's SLA.
Tests
import unittest
class Flaky:
"""Test double that fails a given number of times before returning data."""
def __init__(self, data, failures=0, exc=TransientError):
self.data = data
self.failures = failures
self.exc = exc
self.calls = 0
def get(self, key):
self.calls += 1
if self.calls <= self.failures:
raise self.exc("simulated failure")
return self.data[key]
TRIP_DATA = {"t1": {"id": "t1", "status": "COMPLETED", "rider_id": "r1",
"driver_id": "d1", "waypoints": [{"lat": 40.7, "lng": -74.0}]}}
RIDER_DATA = {"r1": {"id": "r1", "name": "Jordan"}}
DRIVER_DATA = {"d1": {"id": "d1", "name": "Casey"}}
FULL_RESULT = {
"trip_id": "t1", "status": "COMPLETED",
"rider": {"id": "r1", "name": "Jordan"},
"driver": {"id": "d1", "name": "Casey"},
"waypoints": [{"lat": 40.7, "lng": -74.0}],
"errors": [],
}
def make_svc(trip_f=0, rider_f=0, driver_f=0):
sleeps = []
apis = (Flaky(TRIP_DATA, trip_f), Flaky(RIDER_DATA, rider_f), Flaky(DRIVER_DATA, driver_f))
svc = TripAggregator(*apis, RetryPolicy(max_attempts=3, base_delay=0.01, sleep=sleeps.append))
return svc, apis, sleeps
class AggregatorTests(unittest.TestCase):
def test_all_succeed_first_try(self):
svc, apis, sleeps = make_svc()
self.assertEqual(svc.get_trip_summary("t1"), FULL_RESULT)
self.assertEqual([a.calls for a in apis], [1, 1, 1])
self.assertEqual(sleeps, [])
def test_transient_failure_recovers(self):
svc, apis, sleeps = make_svc(rider_f=1)
self.assertEqual(svc.get_trip_summary("t1"), FULL_RESULT)
self.assertEqual(apis[1].calls, 2)
self.assertEqual(sleeps, [0.01])
def test_optional_exhausted_degrades_gracefully(self):
svc, apis, sleeps = make_svc(driver_f=5)
expected = dict(FULL_RESULT, driver=None,
errors=[{"source": "driver", "error": "TransientError"}])
self.assertEqual(svc.get_trip_summary("t1"), expected)
self.assertEqual(apis[2].calls, 3)
self.assertEqual(sleeps, [0.01, 0.02])
def test_required_exhausted_raises(self):
svc, apis, _ = make_svc(trip_f=5)
with self.assertRaises(TransientError):
svc.get_trip_summary("t1")
self.assertEqual(apis[0].calls, 3)
Each test checks three things: the full output dict, call counts (proving retries are bounded), and the backoff schedule.
Part 2: Load Balancer Bugs and Extensions
Bug inventory
| Location | Bug | Consequence |
|---|---|---|
| Line A | No bounds check before indexing | IndexError on an empty pool |
| Line B | Index increments but never wraps | IndexError once index >= len(servers) |
| Line C | Recursive skip with no depth limit | Infinite recursion / stack overflow if all servers are unhealthy |
| Implicit | No lock around index reads and writes | Race condition: two threads can read the same index and both use the same server, breaking round-robin distribution |
Fixed implementation
import threading
class NoHealthyServer(Exception): ...
class LoadBalancer:
def __init__(self, servers):
self.servers = servers # list of {"id": str, "healthy": bool}
self._index = 0
self._lock = threading.Lock()
def get_server(self):
with self._lock:
n = len(self.servers)
if n == 0:
raise NoHealthyServer("server pool is empty")
for _ in range(n):
server = self.servers[self._index]
self._index = (self._index + 1) % n
if server["healthy"]:
return server
raise NoHealthyServer("no healthy servers available")
The loop scans at most n servers, so it terminates even when every server is unhealthy. The lock is held for the entire read-modify-write cycle on _index, eliminating the race.
Consistent hashing extension
Replace the round-robin cursor with a sorted ring of hash positions.
Data structure: Hash each server ID to one or more positions on a 0–2³²−1 integer ring. Store those positions in a sorted array (or a sorted dict mapping position → server). To route a request, hash the request key, then binary-search for the next position clockwise (i.e., bisect_right); wrap around to position 0 if the key hash exceeds every entry.
Server addition: The new server claims the arc between itself and its predecessor. Only keys in that arc remap — typically 1/n of the keyspace. Every other key is unaffected.
Server removal: Its arc transfers to the next server clockwise. Again only 1/n of keys move.
Virtual nodes: A single hash per server tends to produce uneven arc sizes, concentrating load. Assigning each real server v virtual positions (e.g., hash("server-1#0"), hash("server-1#1"), …, hash("server-1#v-1")) distributes load much more evenly. v = 100–200 is a common production default. The tradeoff is memory: the ring grows by v entries per server, which is negligible at typical cluster sizes.
When to prefer consistent hashing over round-robin: When requests carry a key (user ID, session token, cache shard) and you want the same server to handle all requests for that key — for cache locality or stateful session affinity. Round-robin is simpler and fine when requests are stateless.