Resilient Paginated API Client with Aggregation
SQL & DataModel answerLast updated
Build a robust script that authenticates against a paginated REST API, handles rate limits and bad records, and produces serialized output plus top-k category aggregates.
The Task
You have access to a REST API endpoint that returns JSON records representing real-time delivery events. Each record contains fields like trip_id, driver_id, latitude, longitude, and timestamp. Your job is to write a self-contained, runnable Python script — no third-party libraries, just the standard library — that fetches all records from the API and processes them end to end.
What the endpoint looks like
GET https://api.example.com/v1/deliveries
Authorization: Bearer <token>
A successful response looks like:
{
"data": [
{
"trip_id": "t-001",
"driver_id": "d-42",
"latitude": 37.7749,
"longitude": -122.4194,
"timestamp": "2024-06-01T12:00:00Z"
}
],
"next": "https://api.example.com/v1/deliveries?cursor=abc123"
}
When there are no more pages, "next" is null or absent.
What your script must do
-
Authenticate. Pass a bearer token, read from the environment variable
API_TOKEN. Never hard-code credentials. -
Fetch all pages. Follow
"next"links until they are exhausted. Guard against cycles and runaway pagination. -
Handle failures gracefully.
- Retry on
429and5xxresponses using exponential backoff with jitter. - Honor the
Retry-Afterheader when the server sends one. - Time out individual requests after 10 seconds.
- Skip and log malformed records — never crash the entire run because of one bad row.
- Retry on
-
Validate and transform each record. Coerce
latitudeandlongitudeto floats; reject values out of range (lat ∈ [-90, 90], lon ∈ [-180, 180]). Normalizetimestampto an ISO-8601 UTC string. Reject records missing required fields. -
Deduplicate. Records with the same
(trip_id, driver_id, timestamp)key should appear only once in the output. -
Output A — serialized records. Write the cleaned records to both a CSV file and a JSON file.
-
Output B — top-k aggregation. Count records per
driver_id. Print the topkdrivers (defaultk = 10). Break ties alphabetically so the output is deterministic. -
Tests. Include at least three unit tests covering the transform logic and the retry/backoff behavior. Tests must use only
unittestand must not make real network calls. -
Complexity analysis. In a comment block or docstring at the top of the file, state the time and space complexity of your solution and call out the dominant cost.
Constraints and edge cases to consider
kmay exceed the number of distinct drivers; return however many exist."data"may be an empty list or missing entirely on a valid page.latitudeandlongitudemay arrive as strings like"37.7"and should be coerced. Booleans must be rejected.timestampmay be epoch seconds (int/float), ISO-8601 withZ, or a tz-naive ISO string (treat as UTC).TrueandFalsemust be rejected.- Coordinates of exactly ±90 or ±180 are valid boundary values.
API_TOKENmissing from the environment should fail immediately with a clear message.
What is expected in your answer
Walk through your design decisions and trade-offs as you go. After presenting working code, explain:
- Why you structured the retry logic the way you did.
- How pagination is made safe against infinite loops.
- What you would change if you could use third-party libraries or if the data volume was 100× larger.
- The time and space complexity of the full pipeline.
Hints
Hint 1
Structure the program as a pipeline of small, independently testable functions: one for HTTP (with retries), one for pagination, one for record validation, and one orchestrator. Keeping them separate makes unit testing straightforward without touching real network code.
Hint 2
For retries, exponential backoff alone is not enough — add jitter (multiply the delay by a random factor between 0.5 and 1.0) to prevent synchronized retries from hammering the server. Always cap retries on non-transient errors like 401 or 404, which will never succeed no matter how many times you retry.
Hint 3
Top-k with a counter can be done in O(c log k) time using heapq.nsmallest instead of sorting the full counter. To make tie-breaking deterministic, sort by (-count, key) so alphabetical order resolves ties consistently.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to treat this as a streaming pipeline with five distinct stages: fetch one page, validate and transform records, deduplicate, serialize, and aggregate. Keeping each stage as its own function makes unit testing clean — you inject a fake HTTP function and never touch real network code in tests.
Design decisions and trade-offs
HTTP layer with retries. Exponential backoff with jitter handles the common case of a temporarily overloaded API. Without jitter, multiple workers waking up after the same delay create a thundering herd. The Retry-After header gets priority when present. Non-retryable errors — 401, 403, 404 — fail immediately with a clear message; retrying an auth failure just wastes time and burns quota.
Pagination safety. Following "next" links naively can loop forever if the server sends a cyclic cursor or never terminates. A seen set detects cycles; a max_pages cap catches runaway chains. Both are O(p) in space, which is negligible.
Record validation returning None. Rather than raising on bad records, transform returns None and logs the reason. The orchestrator counts skips and reports at the end. One malformed row must never abort a multi-hour run.
Deduplication key. Pages can overlap when the underlying dataset is modified mid-pagination. Using (trip_id, driver_id, timestamp) as a dedup key ensures the counter and output files stay consistent.
Top-k. heapq.nsmallest(k, counter.items(), key=lambda x: (-x[1], x[0])) is O(c log k) where c is the number of distinct drivers. If k ≥ c it returns all drivers, which satisfies the edge-case requirement. Sorting by (-count, key) makes ties alphabetically deterministic.
Complexity
Let n = total records, p = pages, c = distinct drivers, k = requested top-k.
- Time: O(n) to parse, transform, and deduplicate; O(c log k) for the heap. Network latency dominates wall-clock time.
- Space: O(n) for the dedup set and output list; O(c) for the counter. To reduce memory for very large datasets, write CSV rows as they arrive and replace in-memory dedup with an external key-value store or a sorted merge over sorted pages.
What changes at 100× scale
With requests and a Session (connection pooling), plus a ThreadPoolExecutor for parallel page fetches, throughput improves substantially. For true streaming at scale, replace in-memory dedup with a Redis SSET and write output incrementally to avoid materializing the full dataset.
Common mistakes
- Hard-coding the token or reading it inside a loop instead of once at startup.
- Retrying
401indefinitely instead of failing fast. - Forgetting that Python's
boolis a subclass ofint, soisinstance(True, int)isTrue— coordinates and timestamps need an explicitisinstance(v, bool)guard. - Using
sorted()on the full counter for top-k whenheapq.nsmallestis available and faster. - No cycle detection on pagination, which can loop forever against a buggy API.
Solution
"""
Delivery event API client — fetches, validates, deduplicates, and aggregates records.
Complexity:
Time: O(n) parse/transform/dedup + O(c log k) top-k aggregation
Network round-trips (p pages + retries) dominate wall-clock time.
Space: O(n) dedup set + output list; O(c) counter.
Usage:
API_TOKEN=<token> python3 solution.py --url https://api.example.com/v1/deliveries \
--out-csv records.csv --out-json records.json --top-k 10
"""
import argparse, csv, heapq, io, json, logging, math, os, random
import sys, time, unittest, urllib.error, urllib.request
from collections import Counter
from datetime import datetime, timezone
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger("delivery")
RETRYABLE_CODES = {429, 500, 502, 503, 504}
REQUIRED_FIELDS = ("trip_id", "driver_id", "latitude", "longitude", "timestamp")
class APIError(Exception):
pass
# ---------------------------------------------------------------------------
# HTTP layer
# ---------------------------------------------------------------------------
def http_get_json(
url, token,
timeout=10.0, max_retries=5, base_delay=0.5, max_delay=30.0,
opener=urllib.request.urlopen, sleep_fn=time.sleep,
):
"""GET *url* and return the parsed JSON body. Retries on transient errors."""
req = urllib.request.Request(
url,
headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
)
last_exc = None
for attempt in range(max_retries + 1):
# Compute backoff before the attempt so delay is available in except blocks.
raw_delay = min(max_delay, base_delay * (2 ** attempt))
delay = raw_delay * random.uniform(0.5, 1.0)
try:
with opener(req, timeout=timeout) as resp:
body = resp.read()
try:
return json.loads(body.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise APIError(f"invalid JSON body from {url}") from exc
except urllib.error.HTTPError as exc:
if exc.code not in RETRYABLE_CODES or attempt == max_retries:
raise APIError(f"HTTP {exc.code} from {url}") from exc
# Honor Retry-After when present.
ra = exc.headers.get("Retry-After") if exc.headers else None
if ra and str(ra).isdigit():
delay = min(max_delay, float(ra))
log.warning("HTTP %s; retry %d/%d in %.2fs", exc.code, attempt + 1, max_retries, delay)
last_exc = exc
except (urllib.error.URLError, TimeoutError, ConnectionError) as exc:
if attempt == max_retries:
raise APIError(f"network error for {url}: {exc}") from exc
log.warning("network error %s; retry %d/%d in %.2fs", exc, attempt + 1, max_retries, delay)
last_exc = exc
sleep_fn(delay)
raise APIError("exceeded retry budget") from last_exc # pragma: no cover
# ---------------------------------------------------------------------------
# Pagination
# ---------------------------------------------------------------------------
def iter_records(start_url, get_fn, max_pages=10_000):
"""Yield raw records from all pages, guarding against cycles and runaway chains."""
url = start_url
seen: set[str] = set()
while url:
if url in seen:
log.error("pagination cycle detected at %s; stopping", url)
break
if len(seen) >= max_pages:
log.error("reached max_pages=%d cap; stopping", max_pages)
break
seen.add(url)
page = get_fn(url)
if not isinstance(page, dict):
log.error("unexpected page type %s; stopping", type(page).__name__)
break
for rec in page.get("data") or []:
yield rec
url = page.get("next") or None
# ---------------------------------------------------------------------------
# Validation / transformation
# ---------------------------------------------------------------------------
def _parse_float_coord(v, name):
"""Coerce v to float, rejecting booleans and NaN."""
if isinstance(v, bool):
raise ValueError(f"{name} must not be boolean")
try:
f = float(v)
except (TypeError, ValueError) as exc:
raise ValueError(f"{name} not coercible to float: {v!r}") from exc
if math.isnan(f):
raise ValueError(f"{name} is NaN")
return f
def _parse_timestamp(v):
"""Return an ISO-8601 UTC string from epoch seconds, ISO string, or tz-naive ISO."""
if isinstance(v, bool) or v is None:
raise ValueError("timestamp must not be boolean or null")
if isinstance(v, (int, float)):
return datetime.fromtimestamp(float(v), tz=timezone.utc).isoformat().replace("+00:00", "Z")
s = str(v).strip().replace("Z", "+00:00")
dt = datetime.fromisoformat(s)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
else:
dt = dt.astimezone(timezone.utc)
return dt.isoformat().replace("+00:00", "Z")
def transform(raw):
"""
Validate and normalize a raw record dict.
Returns a clean dict on success, or None (logging the reason) on failure.
"""
if not isinstance(raw, dict):
log.debug("skipping non-dict record: %r", raw)
return None
try:
trip_id = raw.get("trip_id")
driver_id = raw.get("driver_id")
if not trip_id or not isinstance(trip_id, str):
raise ValueError("missing or invalid trip_id")
if not driver_id or not isinstance(driver_id, str):
raise ValueError("missing or invalid driver_id")
lat = _parse_float_coord(raw.get("latitude"), "latitude")
lon = _parse_float_coord(raw.get("longitude"), "longitude")
if not (-90.0 <= lat <= 90.0):
raise ValueError(f"latitude {lat} out of range")
if not (-180.0 <= lon <= 180.0):
raise ValueError(f"longitude {lon} out of range")
ts = _parse_timestamp(raw.get("timestamp"))
return {"trip_id": trip_id, "driver_id": driver_id,
"lat": lat, "lon": lon, "ts": ts}
except (ValueError, TypeError, KeyError) as exc:
log.debug("skipping record %r: %s", raw.get("trip_id", "?"), exc)
return None
# ---------------------------------------------------------------------------
# Aggregation
# ---------------------------------------------------------------------------
def top_k_drivers(records, k):
"""Return the top-k (driver_id, count) pairs by count, ties broken alphabetically."""
counts = Counter(r["driver_id"] for r in records)
return heapq.nsmallest(k, counts.items(), key=lambda x: (-x[1], x[0]))
# ---------------------------------------------------------------------------
# Serialization
# ---------------------------------------------------------------------------
def write_csv(records, path):
if not records:
log.warning("no records to write to %s", path)
return
with open(path, "w", newline="", encoding="utf-8") as fh:
writer = csv.DictWriter(fh, fieldnames=["trip_id", "driver_id", "lat", "lon", "ts"])
writer.writeheader()
writer.writerows(records)
def write_json(records, path):
with open(path, "w", encoding="utf-8") as fh:
json.dump(records, fh, indent=2)
# ---------------------------------------------------------------------------
# Orchestrator
# ---------------------------------------------------------------------------
def run(start_url, token, out_csv, out_json, top_k, get_fn=None):
if get_fn is None:
def get_fn(url):
return http_get_json(url, token)
seen_keys: set[tuple] = set()
clean, skipped = [], 0
for raw in iter_records(start_url, get_fn):
rec = transform(raw)
if rec is None:
skipped += 1
continue
key = (rec["trip_id"], rec["driver_id"], rec["ts"])
if key in seen_keys:
continue
seen_keys.add(key)
clean.append(rec)
log.info("fetched %d records, skipped %d malformed", len(clean), skipped)
write_csv(clean, out_csv)
write_json(clean, out_json)
log.info("wrote %s and %s", out_csv, out_json)
top = top_k_drivers(clean, top_k)
print(f"\nTop {top_k} drivers by record count:")
for rank, (driver_id, count) in enumerate(top, 1):
print(f" {rank:>3}. {driver_id} ({count} records)")
return clean, top
# ---------------------------------------------------------------------------
# Unit tests
# ---------------------------------------------------------------------------
class TestTransform(unittest.TestCase):
def _good(self):
return {"trip_id": "t1", "driver_id": "d1",
"latitude": 37.7, "longitude": -122.4, "timestamp": "2024-01-01T00:00:00Z"}
def test_valid_record(self):
r = transform(self._good())
self.assertIsNotNone(r)
self.assertAlmostEqual(r["lat"], 37.7)
self.assertEqual(r["ts"], "2024-01-01T00:00:00Z")
def test_boolean_coordinate_rejected(self):
raw = {**self._good(), "latitude": True}
self.assertIsNone(transform(raw))
def test_string_coordinate_coerced(self):
raw = {**self._good(), "latitude": "51.5"}
r = transform(raw)
self.assertIsNotNone(r)
self.assertAlmostEqual(r["lat"], 51.5)
def test_out_of_range_lat(self):
raw = {**self._good(), "latitude": 91.0}
self.assertIsNone(transform(raw))
def test_epoch_timestamp(self):
raw = {**self._good(), "timestamp": 0}
r = transform(raw)
self.assertEqual(r["ts"], "1970-01-01T00:00:00Z")
def test_missing_trip_id(self):
raw = {**self._good(), "trip_id": None}
self.assertIsNone(transform(raw))
class TestRetry(unittest.TestCase):
def test_retries_on_429_then_succeeds(self):
calls = []
class FakeHTTPError(urllib.error.HTTPError):
def __init__(self):
super().__init__("http://x", 429, "Too Many Requests", {}, None)
def fake_opener(req, timeout):
calls.append(1)
if len(calls) < 3:
raise FakeHTTPError()
return io.BytesIO(json.dumps({"data": [], "next": None}).encode())
fake_opener.__enter__ = fake_opener
fake_opener.__exit__ = lambda *a: None
result = http_get_json(
"http://example.com", "tok",
opener=fake_opener, sleep_fn=lambda _: None,
)
self.assertEqual(len(calls), 3)
self.assertEqual(result["data"], [])
def test_non_retryable_404_raises_immediately(self):
def fake_opener(req, timeout):
raise urllib.error.HTTPError("http://x", 404, "Not Found", {}, None)
with self.assertRaises(APIError):
http_get_json("http://example.com", "tok",
opener=fake_opener, sleep_fn=lambda _: None)
class TestTopK(unittest.TestCase):
def test_tie_breaking_is_alphabetical(self):
records = [{"driver_id": "b"}, {"driver_id": "a"},
{"driver_id": "b"}, {"driver_id": "a"}]
top = top_k_drivers(records, 2)
# Both have count 2; "a" < "b" alphabetically.
self.assertEqual(top[0][0], "a")
def test_k_larger_than_drivers(self):
records = [{"driver_id": "x"}, {"driver_id": "y"}]
top = top_k_drivers(records, 100)
self.assertEqual(len(top), 2)
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
if "--test" in sys.argv:
sys.argv.remove("--test")
unittest.main(exit=True)
parser = argparse.ArgumentParser()
parser.add_argument("--url", required=True)
parser.add_argument("--out-csv", default="records.csv")
parser.add_argument("--out-json", default="records.json")
parser.add_argument("--top-k", type=int, default=10)
args = parser.parse_args()
token = os.environ.get("API_TOKEN")
if not token:
sys.exit("API_TOKEN environment variable is not set")
run(args.url, token, args.out_csv, args.out_json, args.top_k)
Running it
# Run the full pipeline
API_TOKEN=my-secret python3 solution.py --url https://api.example.com/v1/deliveries
# Run the unit tests
python3 solution.py --test