KatInterview

Retrieve and rank teams from a paginated REST API

SQL & DataModel answer
MediumModel answerSQL & Datapaginationapierror-handling

Last 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:

  1. Fetches team data from a paginated JSON API. Each successful response is a JSON array of team objects: [{"name": "string", "wins": integer}, ...]
  2. Requests pages sequentially by appending &page=<number> to the base URL (or ?page=<number> if no query string exists). Page numbers start at 1.
  3. Stops when a page returns an empty array, null, an empty response body, or HTTP 404.
  4. Aggregates all retrieved teams, then sorts them by wins (descending), breaking ties by name (ascending, lexicographic).
  5. Returns an array of the top n team 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-After header (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 name or wins, or where wins is not an integer, or name is not a non-empty string.
  • Duplicate names: if the same team name appears on multiple pages, keep the record with the highest wins value.

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.