KatInterview

Build a Scalable Memory-Constrained API Ingestion Pipeline

Data Structure DesignModel answer
HardModel answerData Structure Designpaginationrate-limitingexternal-sort

Last updated

Ingest, normalize, filter, and stream-sort paginated API data under memory constraints with exponential backoff and rate limiting.

You are tasked with writing a robust data collection pipeline for a platform's transactional data store. The platform exposes a REST endpoint GET /orders?page=N&limit=M returning JSON output formatted as:

{
  "page": 1,
  "per_page": 100,
  "total_pages": 45,
  "data": [
    {
      "id": "ord_10293",
      "created_at": "2024-03-15T14:22:10Z",
      "amount": 49.99,
      "customer": {
        "id": "cust_883",
        "email": "[email protected]"
      }
    }
  ]
}

Design and implement a Python module to pull all order records across every page, apply transformation logic, and stream the results to an output stream out_stream in CSV format.

Requirements

  1. Complete Traversal: Iteratively retrieve every page starting from page = 1 through total_pages. Read total_pages dynamically from every page response to accommodate changes during execution.
  2. Schema Normalization: Map raw order objects into a 5-element tuple adhering to:
    • id: string
    • created_at: string formatted as UTC ISO 8601 with millisecond precision (YYYY-MM-DDTHH:MM:SS.fffZ)
    • amount_cents: integer (accurately mapping float amounts or pre-calculated integer values without rounding errors)
    • customer_id: string
    • customer_email: string
  3. Resilience & Rate Limiting:
    • Throttle execution to a maximum rate of 10 requests per second.
    • Retry transient HTTP status codes (HTTP 429 and HTTP 5xx) and network-level timeouts using exponential backoff with full jitter up to max_retries. Honor Retry-After headers when provided.
    • Fail immediately on non-retryable status codes (e.g., 400, 401, 403, 404).
  4. Filtering: Support an optional since filter parameter (accepting ISO strings or datetime objects) to filter out records where created_at < since.
  5. Memory & Ordering Constraints:
    • Output rows must be sorted chronologically by created_at ascending, breaking ties by id ascending.
    • Deduplicate repeated records that arise from pagination drift (new insertions shifting offsets).
    • Do not store all records in main memory at once; streaming and external sorting must be employed for large volume processing.

Provide comprehensive unit testing, analyze the algorithmic complexities, and explain how the system should handle cursor-based pagination.

Hints

Hint 1

Standardizing timestamps to fixed-length UTC ISO strings makes chronological sorting and string comparison identical.

Hint 2

When memory usage must remain bounded, buffer records into fixed chunks, sort each chunk, write to temporary disk storage, and merge streams using heapq.merge.

Hint 3

Decouple time and HTTP requests via dependency injection to write fast, non-flaky unit tests.