KatInterview

Resilient Paginated API Client with Aggregation

SQL & DataModel answer
MediumModel answerSQL & Datapythonrest-apipagination

Last 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

  1. Authenticate. Pass a bearer token, read from the environment variable API_TOKEN. Never hard-code credentials.

  2. Fetch all pages. Follow "next" links until they are exhausted. Guard against cycles and runaway pagination.

  3. Handle failures gracefully.

    • Retry on 429 and 5xx responses using exponential backoff with jitter.
    • Honor the Retry-After header 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.
  4. Validate and transform each record. Coerce latitude and longitude to floats; reject values out of range (lat ∈ [-90, 90], lon ∈ [-180, 180]). Normalize timestamp to an ISO-8601 UTC string. Reject records missing required fields.

  5. Deduplicate. Records with the same (trip_id, driver_id, timestamp) key should appear only once in the output.

  6. Output A — serialized records. Write the cleaned records to both a CSV file and a JSON file.

  7. Output B — top-k aggregation. Count records per driver_id. Print the top k drivers (default k = 10). Break ties alphabetically so the output is deterministic.

  8. Tests. Include at least three unit tests covering the transform logic and the retry/backoff behavior. Tests must use only unittest and must not make real network calls.

  9. 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

  • k may exceed the number of distinct drivers; return however many exist.
  • "data" may be an empty list or missing entirely on a valid page.
  • latitude and longitude may arrive as strings like "37.7" and should be coerced. Booleans must be rejected.
  • timestamp may be epoch seconds (int/float), ISO-8601 with Z, or a tz-naive ISO string (treat as UTC). True and False must be rejected.
  • Coordinates of exactly ±90 or ±180 are valid boundary values.
  • API_TOKEN missing 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.