Build a Scalable Memory-Constrained API Ingestion Pipeline
Data Structure DesignModel answerLast 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
- Complete Traversal: Iteratively retrieve every page starting from
page = 1throughtotal_pages. Readtotal_pagesdynamically from every page response to accommodate changes during execution. - Schema Normalization: Map raw order objects into a 5-element tuple adhering to:
id: stringcreated_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: stringcustomer_email: string
- 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. HonorRetry-Afterheaders when provided. - Fail immediately on non-retryable status codes (e.g., 400, 401, 403, 404).
- Filtering: Support an optional
sincefilter parameter (accepting ISO strings ordatetimeobjects) to filter out records wherecreated_at < since. - Memory & Ordering Constraints:
- Output rows must be sorted chronologically by
created_atascending, breaking ties byidascending. - 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.
- Output rows must be sorted chronologically by
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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Architecture & Key Concepts
Ingesting paginated endpoints reliably at scale requires solving four main engineering challenges:
- Rate Limiting & Retries: Respecting server call limits while handling intermittent failures using full jitter backoff.
- Schema Normalization: Handling variations in JSON representations and avoiding binary floating-point inaccuracies when working with currency.
- Memory Management (External Sort): Reading datasets larger than RAM by leveraging disk-backed buffer flushing and N-way streaming merge.
- Offset Drift Mitigation: Removing identical records caused by dynamic database changes during deep pagination runs.
Technical Details
1. Accurate Currency Processing
Converting floating-point representation (49.99) using naïve operations like int(val * 100) introduces floating-point drift (e.g., 49.99 * 100 evaluating to 4998.999999999999). Utilizing decimal.Decimal with explicit rounding (ROUND_HALF_UP) guarantees exact integer cent values.
2. Lexicographical Sorting via UTC Strings
Converting all incoming timestamp variations to fixed-width UTC strings (YYYY-MM-DDTHH:MM:SS.fffZ) ensures that standard lexicographical string comparisons accurately reflect chronological order. This simplifies both filtering (created_at >= since) and external sorting operations.
3. External Merge Sort Pipeline
To maintain an $O(1)$ spatial overhead relative to total dataset size:
- Accumulate parsed records in a memory buffer up to
chunk_size(e.g., 50,000 records). - Sort the buffer in place by
(created_at, id). - Write sorted runs to temporary files on disk.
- Stream and merge runs into
out_streamusingheapq.merge, dropping duplicate entries as they are processed.
Python Implementation
import csv
import heapq
import random
import tempfile
import time
from datetime import datetime, timezone
from decimal import Decimal, ROUND_HALF_UP
import unittest
from unittest.mock import MagicMock
import requests
FIELDS = ["id", "created_at", "amount_cents", "customer_id", "customer_email"]
RETRYABLE_STATUSES = {429} | set(range(500, 600))
class IngestionError(Exception):
"""Raised when request attempts exhaust retries or encounter fatal status codes."""
pass
class TokenBucketRateLimiter:
"""Controls request timing to ensure a max execution rate per second."""
def __init__(self, rate_per_sec=10.0, clock=time.monotonic, sleep=time.sleep):
self.interval = 1.0 / rate_per_sec
self.clock = clock
self.sleep = sleep
self.next_allowed_time = float("-inf")
def acquire(self):
now = self.clock()
if now < self.next_allowed_time:
self.sleep(self.next_allowed_time - now)
now = self.next_allowed_time
self.next_allowed_time = now + self.interval
def parse_to_utc_iso(val) -> str:
"""Parses timestamps into fixed-length UTC ISO 8601 strings."""
if isinstance(val, datetime):
dt = val
elif isinstance(val, (int, float)) and not isinstance(val, bool):
dt = datetime.fromtimestamp(val, tz=timezone.utc)
else:
s = str(val).strip()
if s.endswith("Z"):
s = s[:-1] + "+00:00"
dt = datetime.fromisoformat(s)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
dt_utc = dt.astimezone(timezone.utc)
return dt_utc.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
def extract_amount_cents(raw_record: dict) -> int:
"""Converts raw numerical monetary representation into integer cents safely."""
if "amount_cents" in raw_record and raw_record["amount_cents"] is not None:
dec = Decimal(str(raw_record["amount_cents"]))
if dec != dec.to_integral_value():
raise ValueError(f"Invalid non-integer amount_cents: {dec}")
return int(dec)
if "amount" in raw_record and raw_record["amount"] is not None:
dec = Decimal(str(raw_record["amount"]))
return int((dec * Decimal("100")).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
raise ValueError("Missing 'amount' or 'amount_cents' key in payload.")
def normalize_record(raw_record: dict) -> tuple:
"""Transforms raw dictionary into standardized 5-element tuple schema."""
rec_id = raw_record.get("id")
created_at = raw_record.get("created_at")
customer = raw_record.get("customer") or {}
cust_id = customer.get("id") or raw_record.get("customer_id")
cust_email = customer.get("email") or raw_record.get("customer_email") or ""
if not rec_id or not created_at or not cust_id:
raise ValueError(f"Malformed record structure: {raw_record}")
return (
str(rec_id),
parse_to_utc_iso(created_at),
extract_amount_cents(raw_record),
str(cust_id),
str(cust_email).strip(),
)
def execute_request_with_retry(
session,
url,
params,
limiter,
max_retries,
sleep_fn,
rand_fn,
base_delay=0.5,
max_delay=30.0,
):
for attempt in range(max_retries + 1):
limiter.acquire()
retry_after_val = None
try:
response = session.get(url, params=params, timeout=10.0)
if response.status_code == 200:
return response.json()
if response.status_code not in RETRYABLE_STATUSES:
raise IngestionError(f"Unrecoverable HTTP {response.status_code} for URL {url}")
error_msg = f"HTTP {response.status_code}"
retry_after_val = response.headers.get("Retry-After")
except (requests.ConnectionError, requests.Timeout) as exc:
error_msg = f"Network Exception: {exc}"
if attempt == max_retries:
raise IngestionError(f"Exhausted retries ({max_retries}). Final error: {error_msg}")
# Exponential backoff with full jitter
backoff_cap = min(max_delay, base_delay * (2 ** attempt))
delay = rand_fn() * backoff_cap
if retry_after_val:
try:
delay = max(delay, float(retry_after_val))
except ValueError:
pass
sleep_fn(delay)
def flush_buffer_to_temp_file(buffer: list) -> tempfile.TemporaryFile:
"""Sorts buffer chunk by (created_at, id) and writes to disk."""
buffer.sort(key=lambda row: (row[1], row[0]))
temp_file = tempfile.TemporaryFile(mode="w+", newline="", encoding="utf-8")
writer = csv.writer(temp_file)
writer.writerows(buffer)
temp_file.seek(0)
buffer.clear()
return temp_file
def parse_temp_file_stream(temp_file):
"""Generator that yields rows from a temporary CSV file with proper types."""
reader = csv.reader(temp_file)
for row in reader:
yield (row[0], row[1], int(row[2]), row[3], row[4])
def fetch_all_orders(
base_url,
limit,
out_stream,
since=None,
*,
max_retries=5,
session=None,
sleep_fn=time.sleep,
clock_fn=time.monotonic,
rand_fn=random.random,
chunk_size=50000,
rate_limit=10.0,
):
session = session or requests.Session()
limiter = TokenBucketRateLimiter(rate_limit, clock_fn, sleep_fn)
since_iso = parse_to_utc_iso(since) if since is not None else None
url = f"{base_url.rstrip('/')}/orders"
memory_buffer = []
temp_files = []
try:
current_page = 1
total_pages = 1
while current_page <= total_pages:
payload = execute_request_with_retry(
session,
url,
{"page": current_page, "limit": limit},
limiter,
max_retries,
sleep_fn,
rand_fn,
)
total_pages = int(payload.get("total_pages", 0))
raw_data = payload.get("data") or []
for raw_record in raw_data:
normalized = normalize_record(raw_record)
# Filter out old records if since threshold provided
if since_iso and normalized[1] < since_iso:
continue
memory_buffer.append(normalized)
if len(memory_buffer) >= chunk_size:
temp_files.append(flush_buffer_to_temp_file(memory_buffer))
current_page += 1
if memory_buffer:
temp_files.append(flush_buffer_to_temp_file(memory_buffer))
# Stream merged runs out to destination CSV
csv_writer = csv.writer(out_stream)
csv_writer.writerow(FIELDS)
if temp_files:
file_streams = [parse_temp_file_stream(tf) for tf in temp_files]
merged_stream = heapq.merge(
*file_streams, key=lambda row: (row[1], row[0])
)
last_written_key = None
for row in merged_stream:
row_key = (row[1], row[0])
if row_key != last_written_key:
csv_writer.writerow(row)
last_written_key = row_key
finally:
for tf in temp_files:
tf.close()
Unit Testing
class TestIngestionPipeline(unittest.TestCase):
def test_normalize_record_currency_and_time(self):
raw = {
"id": "ord_101",
"created_at": "2024-03-15T10:00:00Z",
"amount": 19.99,
"customer": {"id": "cust_1", "email": "[email protected]"},
}
res = normalize_record(raw)
self.assertEqual(res, ("ord_101", "2024-03-15T10:00:00.000Z", 1999, "cust_1", "[email protected]"))
def test_rate_limiter_spacing(self):
mock_sleep = MagicMock()
mock_clock = MagicMock(side_effect=[0.0, 0.02, 0.2])
limiter = TokenBucketRateLimiter(rate_per_sec=10.0, clock=mock_clock, sleep=mock_sleep)
limiter.acquire()
limiter.acquire() # Should trigger sleep of 0.08s
mock_sleep.assert_called_once_with(0.1 - 0.02)
def test_retry_mechanism_on_500(self):
mock_session = MagicMock()
resp_500 = MagicMock(status_code=500)
resp_200 = MagicMock(status_code=200)
resp_200.json.return_value = {"page": 1, "total_pages": 1, "data": []}
mock_session.get.side_effect = [resp_500, resp_200]
limiter = TokenBucketRateLimiter(rate_per_sec=100.0, sleep=lambda x: None)
data = execute_request_with_retry(
mock_session, "http://api.test", {}, limiter, max_retries=3,
sleep_fn=lambda x: None, rand_fn=lambda: 0.5
)
self.assertEqual(data["page"], 1)
self.assertEqual(mock_session.get.call_count, 2)
Complexity Analysis
-
Time Complexity:
- Fetching & Schema Parsing: $O(N)$ where $N$ is the total count of order records.
- Sorting In-Memory Chunks: $O(N \log K)$ where $K$ is the configured
chunk_size. - Heap Merging: Splitting dataset into $M = \lceil N / K \rceil$ temporary file runs yields an N-way merge cost of $O(N \log M)$.
- Total Time Complexity: $\mathcal{O}(N \log M)$ (dominated by the external merge step).
-
Space Complexity:
- RAM Overhead: bounded by $\mathcal{O}(K)$ where $K$ is the
chunk_size. Memory usage remains constant relative to dataset size $N$. - Disk Overhead: $\mathcal{O}(N)$ temporary disk storage for intermediate runs, which are safely cleaned up via the
finallyblock.
- RAM Overhead: bounded by $\mathcal{O}(K)$ where $K$ is the
Architectural Follow-Up: Cursor-Based Pagination
If the API transitions from offset-based (page=N) to cursor-based pagination (e.g., passing starting_after=order_id or returning an opaque token next_cursor in response metadata):
- Sequential Loop State: Update request parameters dynamically using the returned
next_cursorinstead of incrementingpage. - Termination Logic: Break loop execution when
next_cursorreturnsnullor is missing from response body instead of checkingcurrent_page > total_pages. - Offset Drift Elimination: Cursor-based approaches naturally eliminate pagination drift (duplicate or missing items caused by insertions/deletions mid-crawl) at the API source. However, keeping duplicate handling in the merge phase provides defense-in-depth against upstream database duplication.