Retrieve and rank teams from a paginated REST API
SQL & DataModel answerLast updated
Build a client that fetches all pages of team records, handles retries and rate limits, then returns the top n teams sorted by wins descending and name ascending.
You are building a client for a sports analytics API that returns team statistics across multiple pages.
Write a function getTopTeams(baseUrl, n) that:
- Fetches team data from a paginated JSON API. Each successful response is a JSON array of team objects:
[{"name": "string", "wins": integer}, ...] - Requests pages sequentially by appending
&page=<number>to the base URL (or?page=<number>if no query string exists). Page numbers start at 1. - Stops when a page returns an empty array, null, an empty response body, or HTTP 404.
- Aggregates all retrieved teams, then sorts them by wins (descending), breaking ties by name (ascending, lexicographic).
- Returns an array of the top
nteam names.
Your implementation must handle:
- Transient failures: connection errors, timeouts, HTTP 5xx, and malformed JSON should trigger retries with exponential backoff.
- Rate limiting: HTTP 429 responses should respect the
Retry-Afterheader (in seconds) when present; otherwise back off exponentially. - Permanent errors: HTTP 4xx responses other than 404 and 429 should fail immediately without retrying.
- Invalid records: skip any record missing
nameorwins, or wherewinsis not an integer, ornameis not a non-empty string. - Duplicate names: if the same team name appears on multiple pages, keep the record with the highest
winsvalue.
If n ≤ 0, return an empty array. If fewer than n teams exist, return all of them.
Assume a maximum of 3 retry attempts per page, a base backoff delay of 0.5 seconds, a maximum delay cap of 30 seconds, and a request timeout of 10 seconds. Add random jitter to backoff delays to avoid thundering herd.
Impose a safety limit of 1000 pages to guard against infinite pagination.
Hints
Hint 1
Separate the retry logic into a helper that returns either a list of records or None when pagination ends.
Hint 2
Use a dictionary to track the best wins value for each team name as you merge pages.
Hint 3
Sort by the tuple (-wins, name) to get wins descending and names ascending in one pass.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What this problem tests
This is a production-readiness question disguised as data aggregation. Sorting by (wins desc, name asc) is straightforward; the real challenge is writing a resilient client that doesn't fail silently, crash on bad data, or hammer a rate-limited endpoint.
Strong candidates clarify edge cases before coding and structure the solution in testable layers.
Clarify first
State these assumptions aloud. If the interviewer doesn't correct you, document your choices in comments.
- Pagination end signal: stop on empty array
[],null, empty body, or 404. - URL construction: if
baseUrlalready has a query string, append&page=N; otherwise use?page=N. - Retryable vs permanent: retry connection errors, timeouts, 5xx, and unparseable JSON. Fail immediately on 4xx other than 404 and 429.
- Rate limit handling: honor
Retry-Afterwhen present (capped at max delay); otherwise use exponential backoff. - Record validation: require a dict with a string
name(non-empty after stripping) and an integerwins. Python'sboolis anintsubclass, so explicitly reject booleans. - Duplicate handling: keep the maximum
winsfor each name. (Alternative: sum wins if records represent individual games—ask which applies.) - Edge cases for
n: return[]ifn ≤ 0; return all teams ifnexceeds the count.
Approach
Split the work into three layers:
1. Page fetcher with retry logic
_fetch_page(url, ...) returns either a list of raw records or None (meaning "no more data"). It handles:
- Transient errors (network, timeout, 5xx, malformed JSON) → retry with backoff
- Rate limits (429) → respect
Retry-Afteror back off - End signals (404, empty body,
null) → returnNone - Permanent errors (other 4xx) → raise immediately
Backoff formula: min(max_delay, base_delay × 2^attempt) + jitter, where jitter is a small random value to desynchronize concurrent clients.
2. Pagination loop
Request page 1, 2, 3, … until _fetch_page returns None or an empty list. A max_pages cap (1000) prevents runaway loops if the API never terminates.
3. Aggregation and ranking
- Validate each record: skip if
nameorwinsis missing/invalid. - Merge into a
name → winsdictionary, keeping the max wins per name. - Sort by
(-wins, name)and take the topnnames.
Using heapq.nsmallest with key (-wins, name) is more efficient than a full sort when n is small.
Why this works
- Correctness: each page increments strictly, so we visit each page at most once. Retries are bounded per page. The sort key
(-wins, name)produces the required order. - No silent failures: if retries exhaust, the function raises an exception rather than returning a partial leaderboard. Silent data loss is worse than a clear error.
- Robustness: invalid records are filtered before aggregation, so a malformed record can't cause a runtime error during the sort.
Complexity
Let P = number of pages, T = total records across all pages, U = unique team names.
- Time: O(T) to parse and merge, O(U log n) to extract top n with a heap. Network latency and backoff dominate wall-clock time.
- Space: O(U) for the aggregation dict, O(page_size) per page in flight.
Edge cases
| Scenario | Handling |
|---|---|
| Page 1 is empty or 404 | Return [] |
n = 0 or n < 0 | Return [] |
n exceeds team count | Return all teams |
wins is a string, float, boolean, or null | Skip record |
name is missing, empty, or not a string | Skip record |
Body is {"data": [...]} wrapper | Unwrap if data is a list |
| Truncated JSON response | Treated as transient, retried |
429 with large Retry-After | Capped at max_delay |
| Same team on multiple pages | Keep highest wins |
| Endless pagination | Stopped at 1000 pages |
Python implementation
import heapq
import json
import random
import socket
import time
import urllib.error
import urllib.request
class FetchError(Exception):
"""Raised when a page cannot be fetched after retries or on permanent failure."""
def _build_page_url(base_url: str, page: int) -> str:
"""Append page parameter to base URL."""
if base_url.endswith(("?", "&")):
return f"{base_url}page={page}"
separator = "&" if "?" in base_url else "?"
return f"{base_url}{separator}page={page}"
def _exponential_backoff(attempt: int, base: float, cap: float) -> float:
"""Return backoff delay with jitter."""
delay = min(cap, base * (2 ** attempt))
jitter = random.uniform(0, base * 0.1)
return delay + jitter
def _http_get(url: str, timeout: float):
"""Fetch URL and return (status, headers, body_text)."""
req = urllib.request.Request(url, headers={"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=timeout) as response:
return response.status, dict(response.headers), response.read().decode("utf-8")
def _fetch_page(url, http_client, max_retries, base_delay, max_delay, timeout, sleep_fn):
"""
Fetch one page with retry logic.
Returns a list of raw records, or None if pagination ends.
Raises FetchError on permanent failure.
"""
last_exception = None
for attempt in range(max_retries + 1):
retry_delay = None
try:
status, headers, body = http_client(url, timeout)
body = (body or "").strip()
if not body:
return None
data = json.loads(body)
if data is None:
return None
# Some APIs wrap results in {"data": [...]}
if isinstance(data, dict) and "data" in data:
if isinstance(data["data"], list):
data = data["data"]
else:
raise FetchError(f"Unexpected 'data' type: {type(data['data'])}")
if not isinstance(data, list):
raise FetchError(f"Expected list, got {type(data).__name__}")
return data
except urllib.error.HTTPError as e:
if e.code == 404:
return None
if e.code == 429 or 500 <= e.code < 600:
# Check for Retry-After header
retry_after = e.headers.get("Retry-After") if e.headers else None
if retry_after and retry_after.strip().isdigit():
retry_delay = min(max_delay, float(retry_after))
last_exception = e
else:
# Permanent 4xx error
raise FetchError(f"HTTP {e.code} at {url}") from e
except (urllib.error.URLError, socket.timeout, TimeoutError,
ConnectionError, json.JSONDecodeError) as e:
# Transient errors - will retry
last_exception = e
# If we've exhausted retries, give up
if attempt == max_retries:
raise FetchError(
f"Failed to fetch {url} after {max_retries + 1} attempts"
) from last_exception
# Sleep before retrying
delay = retry_delay if retry_delay is not None else _exponential_backoff(
attempt, base_delay, max_delay
)
sleep_fn(delay)
return None # Unreachable but satisfies type checker
def _is_valid_record(record):
"""Validate and return (name, wins) tuple or None."""
if not isinstance(record, dict):
return None
name = record.get("name")
wins = record.get("wins")
# Validate name: must be non-empty string
if not isinstance(name, str) or not name.strip():
return None
# Validate wins: must be integer but not boolean
if not isinstance(wins, int) or isinstance(wins, bool):
return None
return (name.strip(), wins)
def getTopTeams(
baseUrl: str,
n: int,
max_retries: int = 3,
base_delay: float = 0.5,
max_delay: float = 30.0,
timeout: float = 10.0,
max_pages: int = 1000,
http_client=None,
sleep_fn=None
) -> list:
"""
Fetch all paginated team data and return top n team names.
Args:
baseUrl: API endpoint base URL
n: Number of top teams to return
max_retries: Maximum retry attempts per page
base_delay: Base backoff delay in seconds
max_delay: Maximum backoff delay cap
timeout: Request timeout in seconds
max_pages: Safety limit on pagination
http_client: Injection point for testing (uses _http_get by default)
sleep_fn: Injection point for testing (uses time.sleep by default)
Returns:
List of top n team names sorted by wins desc, name asc
"""
if n <= 0:
return []
http_client = http_client or _http_get
sleep_fn = sleep_fn or time.sleep
# Dictionary to track best wins per team
team_wins = {}
page = 1
while page <= max_pages:
url = _build_page_url(baseUrl, page)
records = _fetch_page(
url, http_client, max_retries, base_delay, max_delay, timeout, sleep_fn
)
# None or empty list signals end of pagination
if records is None or len(records) == 0:
break
# Validate and merge records
for record in records:
validated = _is_valid_record(record)
if validated:
name, wins = validated
# Keep maximum wins for each team
if name not in team_wins or wins > team_wins[name]:
team_wins[name] = wins
page += 1
if not team_wins:
return []
# Sort by (-wins, name) and extract top n names
# Using heap is more efficient when n << len(team_wins)
top_teams = heapq.nsmallest(
n,
team_wins.items(),
key=lambda item: (-item[1], item[0])
)
return [name for name, wins in top_teams]
Testing strategy
- Mock the HTTP client to return predefined responses without hitting a real network.
- Mock sleep to avoid waiting during tests.
- Test empty pages, malformed JSON, 404, 429 with and without
Retry-After, duplicate team names, and edge values ofn.
This structure makes the function testable, maintainable, and production-ready.