Resilient Paginated REST Ingestion and Aggregation
Medium · Data Manipulation (SQL/Python) · Software Engineer · Onsite
Problem Statement
Implement a standard-library Python client and data-cleaning pipeline that pulls courier GPS pings from an authenticated HTTP GET endpoint, normalizes and deduplicates valid events, serializes the cleaned stream to CSV and JSON, and ranks the top-k couriers by distinct orders handled.
Using the public types, constants, and signatures in starter.py, implement the following components:
-
HTTP transport & retry client (
urllib_transport,parse_retry_after,ApiClient):urllib_transport(url, headers, timeout)executes aGETrequest viaurllib.requestwithtimeoutseconds. Return anHttpResponse(status, body, headers)with lowercased header names and UTF-8 decoded text (errors="replace") for both2xxand4xx/5xxHTTP responses (closing error streams and preserving status and headers with an empty body if reading an error stream fails mid-transfer). Raise anOSErrorsubclass on network errors or low-level HTTP framing failures.parse_retry_after(value)parses aRetry-Afterheader string into a finite float>= 0representing seconds, returningNonewhen missing, negative, non-finite, or non-numeric (such as an HTTP-date).ApiClient.backoff_delay(attempt, retry_after)returnsretry_afterif provided; otherwisemin(self.max_delay, self.base_delay * (2 ** attempt))for 0-basedattempt.ApiClient.get_json(url)sendsAuthorization: Bearer <token>andAccept: application/json. RetryOSError, invalid JSON in2xxresponses, and statuses inRETRYABLE_STATUSES = {408, 429, 500, 502, 503, 504}up toself.max_retriestimes, sleepingbackoff_delay(...)between attempts (passing parsedretry-afteron retryable HTTP statuses). RaiseApiErrorimmediately on non-retryable HTTP statuses (such as400,401,403,404) or once allmax_retriesretries fail (without sleeping after the final failed attempt).
-
Cursor pagination (
with_query,iter_pages):with_query(url, params)mergesparamsintourl's query string, replacing existing values for keys present inparamswhile keeping other existing query parameters intact.iter_pages(client, url, page_size=100, max_pages=10_000)requestslimit=<page_size>on the first request and addscursor=<cursor>on subsequent pages. If a response is a bare JSONlist, yield it once and stop. Otherwise expect{"data": [...], "next_cursor": ...}, yielddata, and stop whennext_cursorisNoneor"". Acceptstrorintcursors (rejectingboolor containers); raiseApiErroron malformed page envelopes, repeated cursors, or exceedingmax_pages.
-
Record normalization & deduplication (
parse_timestamp,parse_record,fetch_records):parse_timestamp(value)converts Unix epoch seconds (abs(value) < 10^11), Unix epoch milliseconds (abs(value) >= 10^11), or ISO 8601 strings (treating offset-free strings as UTC) into UTC millisecond format'YYYY-MM-DDTHH:MM:SS.sssZ', returningNonefor booleans, non-finite values, or unparsable inputs.parse_record(raw)converts a rawdictinto the fiveFIELDS(["order_id", "courier_id", "latitude", "longitude", "timestamp"]):order_idandcourier_idbecome trimmed non-empty strings (intallowed,boolrejected);latitudein[-90, 90]andlongitudein[-180, 180]become finitefloats (int,float, or numericstrallowed,boolrejected);timestampusesparse_timestamp. ReturnNoneifrawis not adictor any field fails validation.fetch_records(client, url, page_size=100)iterates through all pages, skips malformed records (incrementingFetchResult.malformed), drops subsequent records matching a previously kept(order_id, courier_id, timestamp)tuple after normalization (incrementingFetchResult.duplicates), countsFetchResult.pages, and preserves first-seen API order.
-
Serialization, leaderboard & CLI (
records_to_csv,records_to_json,orders_per_courier,top_k,main):records_to_csv(records)returns CSV text with headerFIELDSand\nline terminators;records_to_json(records)returns a JSON array string.orders_per_courier(records)maps eachcourier_idto its count of distinctorder_ids.top_k(counts, k)returns thekhighest(courier_id, count)pairs ordered bycountdescending, thencourier_idascending ([]ifk <= 0).main(argv)readsAPI_TOKENfromos.environ(returning exit code2if missing,1onApiError,0on success), writes the CSV and JSON files, and printscourier_id\tcountlines for the top-kcouriers.
Examples
Example 1
Input:
Paginated endpoint https://fleet.example.org/v2/pings called with page_size = 2 and k = 2:
- Request 1 (?limit=2) -> HTTP 200:
json
{
"data": [
{"order_id": 501, "courier_id": " drv-b ", "latitude": "40.7128", "longitude": -74.006, "timestamp": 1704067200},
{"order_id": 502, "courier_id": "", "latitude": 40.75, "longitude": -73.99, "timestamp": 1704067260}
],
"next_cursor": "tok_2"
}
- Request 2 (?limit=2&cursor=tok_2) -> first returns HTTP 429 with header {"retry-after": "2"}, then on retry returns HTTP 200:
json
{
"data": [
{"order_id": "501", "courier_id": "drv-b", "latitude": 40.7128, "longitude": -74.006, "timestamp": "2024-01-01T00:00:00Z"},
{"order_id": "503", "courier_id": "drv-a", "latitude": 40.7306, "longitude": -73.9352, "timestamp": 1704067260500}
],
"next_cursor": null
}
Output:
FetchResult:
pages = 2, malformed = 1, duplicates = 1
records = [
{"order_id": "501", "courier_id": "drv-b", "latitude": 40.7128, "longitude": -74.006, "timestamp": "2024-01-01T00:00:00.000Z"},
{"order_id": "503", "courier_id": "drv-a", "latitude": 40.7306, "longitude": -73.9352, "timestamp": "2024-01-01T00:01:00.500Z"}
]
top_k(orders_per_courier(records), 2) = [("drv-a", 1), ("drv-b", 1)]
Explanation:
On page 1, order 501 normalizes to ("501", "drv-b", "2024-01-01T00:00:00.000Z") while order 502 has an empty courier_id (malformed = 1). Fetching tok_2 hits a 429, sleeps 2.0 seconds per Retry-After, and retries ?limit=2&cursor=tok_2. On page 2, "2024-01-01T00:00:00Z" normalizes to "2024-01-01T00:00:00.000Z" and is dropped as a duplicate of order 501 (duplicates = 1), while millisecond epoch 1704067260500 becomes "2024-01-01T00:01:00.500Z". Both couriers have 1 distinct order, so "drv-a" sorts ahead of "drv-b" alphabetically.
Example 2
Input: Cleaned records:
records = [
{"order_id": "ord-10", "courier_id": "rider-2", "latitude": 51.5074, "longitude": -0.1278, "timestamp": "2024-03-15T08:30:00.000Z"},
{"order_id": "ord-10", "courier_id": "rider-2", "latitude": 51.5080, "longitude": -0.1285, "timestamp": "2024-03-15T08:31:00.000Z"},
{"order_id": "ord,11", "courier_id": "rider-1", "latitude": 51.5090, "longitude": -0.1300, "timestamp": "2024-03-15T08:32:00.000Z"},
{"order_id": "ord-12", "courier_id": "rider-1", "latitude": 51.5100, "longitude": -0.1310, "timestamp": "2024-03-15T08:33:00.000Z"},
]
Output:
orders_per_courier(records) = {"rider-2": 1, "rider-1": 2}
top_k(orders_per_courier(records), 1) = [("rider-1", 2)]
records_to_csv(records):
order_id,courier_id,latitude,longitude,timestamp
ord-10,rider-2,51.5074,-0.1278,2024-03-15T08:30:00.000Z
ord-10,rider-2,51.508,-0.1285,2024-03-15T08:31:00.000Z
"ord,11",rider-1,51.509,-0.13,2024-03-15T08:32:00.000Z
ord-12,rider-1,51.51,-0.131,2024-03-15T08:33:00.000Z
Explanation:
rider-2 emitted two valid GPS pings along the same delivery "ord-10" at different timestamps, so both pings remain in the CSV output while orders_per_courier counts "ord-10" once (1 distinct order). rider-1 handled two distinct orders ("ord,11" and "ord-12"), taking first place, and records_to_csv quotes "ord,11" so its embedded comma does not split columns.
Constraints
- Use only the Python standard library (no third-party HTTP or data libraries).
latitudemust be finite and satisfy-90.0 <= latitude <= 90.0;longitudemust be finite and satisfy-180.0 <= longitude <= 180.0.- Numeric timestamps with
abs(value) >= 100_000_000_000(10^11) represent Unix epoch milliseconds (preserving exact millisecond digits for largeintvalues); smaller magnitudes represent Unix epoch seconds. RETRYABLE_STATUSES = {408, 429, 500, 502, 503, 504}; non-retryable4xxresponses fail immediately without sleeping.iter_pagesstops withApiErrorif any cursor repeats or total fetched pages exceedmax_pages.
Step-by-step walkthrough
Pin down the contract and data pipeline
Start by organizing the pipeline into small, single-purpose functions with explicit contracts:
- Authentication: read a bearer token (a secret credential sent in the HTTP header
Authorization: Bearer <token>) from theAPI_TOKENenvironment variable rather than a command-line flag, keeping secrets out of shell history andpslistings. - Pagination shape:
GET <url>?limit=100[&cursor=...]returns{"data": [...], "next_cursor": "tok_2" or null}(or a bare JSON list[...]for an unpaginated endpoint). - Target schema: normalize
order_idandcourier_idto trimmed non-empty strings,latitudein[-90, 90]andlongitudein[-180, 180]to finite floats, andtimestamp(Unix seconds, Unix milliseconds>= 10^11, or ISO 8601 text) to UTCYYYY-MM-DDTHH:MM:SS.sssZ. - Fault isolation & outputs: skip and count malformed or duplicate pings without aborting the run, serialize valid records to CSV and JSON, and report the top-
kcouriers by distinctorder_idcount (breaking ties alphabetically bycourier_id).
REST Endpoint --> [urllib_transport + ApiClient] (auth, timeout, retry + backoff) | v [iter_pages] (follow next_cursor, block loops) | v [parse_record] (clean fields or return None) | v [fetch_records] (drop normalized duplicates, count stats) / \ v v [records_to_csv / json] [orders_per_courier -> top_k]Sticking strictly to Python's standard library (
urllib,json,csv,heapq,logging) keeps the pipeline zero-dependency and immediately testable.- Authentication: read a bearer token (a secret credential sent in the HTTP header
Isolate network I/O behind a pluggable transport
Calling
urllib.request.urlopendirectly inside pagination or retry code makes unit tests slow and dependent on live network sockets. Injecting a transport callable(url, headers, timeout) -> HttpResponse(plus asleepcallable) lets production traffic useurllib_transportwhile tests pass an instant in-memory fake.@dataclass class HttpResponse: """One HTTP answer. Header names are lower-case.""" status: int body: str headers: Dict[str, str] = field(default_factory=dict) class ApiError(Exception): """A request failed for good: a non-retryable status, retries used up, or an unexpected payload.""" # Transport: callable (url, headers, timeout_seconds) -> HttpResponse; raises OSError on network failure. Transport = Callable[[str, Dict[str, str], float], HttpResponse] def urllib_transport(url: str, headers: Dict[str, str], timeout: float) -> HttpResponse: """A real GET with the standard library.""" request = urllib.request.Request(url, headers=headers, method="GET") try: # Phase 1: Send the GET request with a per-socket-operation timeout. with urllib.request.urlopen(request, timeout=timeout) as response: status = response.status raw_headers = response.headers body = response.read() except urllib.error.HTTPError as error: # urllib raises HTTPError on 4xx/5xx, so convert it back to HttpResponse for uniform status handling. try: status = error.code raw_headers = error.headers or {} try: body = error.read() except (http.client.HTTPException, OSError): # If an error body drops mid-stream, keep status and headers so 429/5xx can still retry. body = b"" finally: # Close the underlying socket stream so repeated HTTP errors do not leak connections. error.close() except http.client.HTTPException as error: # Normalize low-level HTTP framing drops (such as IncompleteRead) into an OSError subclass. raise ConnectionError(str(error)) from error # normalized_headers: dict mapping lower-case header name -> value (e.g. {"retry-after": "3"}). normalized_headers = {} for name, value in raw_headers.items(): normalized_headers[name.lower()] = value decoded_body = body.decode("utf-8", errors="replace") return HttpResponse(status, decoded_body, normalized_headers)Three defensive details protect
urllib_transportin real deployments: 1.urlopenraisesHTTPErroron4xxand5xxstatuses; converting that intoHttpResponselets one status table govern retries, anderror.close()prevents socket leaks. 2. When a503error body drops mid-stream (IncompleteRead), keepingstatus = 503andraw_headers(includingRetry-After) preserves retry behavior instead of crashing while reading an error page. 3. Lowercasing header names makes"Retry-After"and"retry-after"identical at lookup time.Add timeouts, retries, and exponential backoff
Separate transient server/network hiccups from permanent client errors:
Outcome Retry? Why --------------------------------------+--------+--------------------------------------------- 2xx + valid JSON No Success — return parsed payload immediately 2xx + truncated / non-JSON body Yes Dropped stream or gateway HTML error page 408, 429, 500, 502, 503, 504 Yes Rate limit, timeout, or transient server bug Other 4xx (400, 401, 403, 404) No Bad URL or invalid token — fail immediately Socket timeout / DNS / refused (OSError) Yes Temporary network glitchBetween retries, exponential backoff doubles the wait after each failed attempt (
base_delay * 2^attempt, capped atmax_delay), unless the server supplies a numericRetry-Afterheader specifying exact seconds to wait. Withbase_delay = 0.5andmax_retries = 4, the four waits are0.5s, 1.0s, 2.0s, 4.0sacross5total attempts:def parse_retry_after(value: Optional[str]) -> Optional[float]: """Seconds from a Retry-After header, or None if it is missing or not a number of seconds.""" if value is None: return None try: seconds = float(value) except ValueError: # HTTP-date strings (like "Wed, 21 Oct 2015 07:28:00 GMT") return None to fall back to backoff. return None # Reject NaN, infinity, and negative durations because time.sleep rejects negative numbers. if not math.isfinite(seconds) or seconds < 0: return None return seconds class ApiClient: """GET + JSON with bearer-token auth, a per-request timeout and retries with exponential backoff.""" def __init__(self, token: str, transport: Transport = urllib_transport, sleep: Callable[[float], None] = time.sleep, timeout: float = 10.0, max_retries: int = 4, base_delay: float = 0.5, max_delay: float = 30.0) -> None: self.token = token self.transport = transport self.sleep = sleep self.timeout = timeout self.max_retries = max_retries self.base_delay = base_delay self.max_delay = max_delay def backoff_delay(self, attempt: int, retry_after: Optional[float]) -> float: """Seconds to wait after failed attempt number `attempt` (0-based).""" # Honor an explicit server Retry-After header when present. if retry_after is not None: return retry_after exponential_wait = self.base_delay * (2 ** attempt) return min(self.max_delay, exponential_wait) def get_json(self, url: str) -> Any: """The parsed JSON body of a GET to url. Raises ApiError when it cannot succeed.""" # Send the secret token in the Authorization header rather than the URL query string. headers = {"Authorization": f"Bearer {self.token}", "Accept": "application/json"} # Run 1 initial attempt (attempt = 0) plus up to max_retries retry attempts. for attempt in range(self.max_retries + 1): retry_after = None try: response = self.transport(url, headers, self.timeout) except OSError as error: problem = f"network error ({error})" else: if 200 <= response.status < 300: try: return json.loads(response.body) except ValueError: # A 200 body cut off mid-transfer or replaced by proxy HTML is worth retrying. problem = "response body is not valid JSON" elif response.status in RETRYABLE_STATUSES: problem = f"HTTP {response.status}" retry_after = parse_retry_after(response.headers.get("retry-after")) else: # Non-retryable client errors (400, 401, 403, 404) will never succeed; fail immediately. raise ApiError(f"HTTP {response.status} from {url}: {response.body[:200]}") # Stop immediately once all retries are exhausted so we do not sleep one extra time. if attempt == self.max_retries: raise ApiError(f"giving up on {url} after {attempt + 1} attempts; last problem: {problem}") delay = self.backoff_delay(attempt, retry_after) logger.warning("%s; retry %d of %d in %.1f s", problem, attempt + 1, self.max_retries, delay) self.sleep(delay)Notice
logger.warningrecords only the failure summary and delay, neverheaders, keeping the bearer token out of log files.Page through cursors and guard against server loops
Cursor pagination walks through a feed one slice at a time using an opaque bookmark (
next_cursor) returned by the prior page, avoiding the skipped or duplicated rows that happen with numericoffset=when fresh GPS pings arrive mid-run:GET /v2/pings?limit=2 --> {"data": [r1, r2], "next_cursor": "tok_2"} GET /v2/pings?limit=2&cursor=tok_2 --> {"data": [r3, r4], "next_cursor": null} (stop!)Three checks guard against broken servers: 1. Store requested cursors in
seen_cursorsand raiseApiErrorif any cursor comes back twice. 2. Bound total iterations bymax_pagesin case a faulty server invents fresh cursors endlessly. 3. Validate envelope shape (datamust be alist, and non-emptynext_cursormust be astrorint, neverboolor a container).def with_query(url: str, params: Dict[str, Any]) -> str: """url with params added to its query string, replacing existing values for the same keys.""" parts = urllib.parse.urlsplit(url) # merged_pairs: list of (key, value) query tuples keeping existing keys not overridden by params. merged_pairs = [] for key, value in urllib.parse.parse_qsl(parts.query, keep_blank_values=True): if key not in params: merged_pairs.append((key, value)) for key, value in params.items(): merged_pairs.append((key, str(value))) encoded_query = urllib.parse.urlencode(merged_pairs) updated_parts = parts._replace(query=encoded_query) return urllib.parse.urlunsplit(updated_parts) def iter_pages(client: ApiClient, url: str, page_size: int = 100, max_pages: int = 10_000) -> Iterator[List[Any]]: """Yield each page's list of raw records, following next_cursor until it is null or empty. Expected payload: {"data": [...], "next_cursor": "abc" or null}. A bare JSON list is a single page. """ cursor = None # seen_cursors: set of str cursor tokens already requested (e.g. {"p2", "p3"}) to detect infinite loops. seen_cursors = set() for _ in range(max_pages): params: Dict[str, Any] = {"limit": page_size} if cursor is not None: params["cursor"] = cursor page_url = with_query(url, params) payload = client.get_json(page_url) # A bare JSON array means the endpoint is unpaginated; yield it once and stop. if isinstance(payload, list): yield payload return if not isinstance(payload, dict) or not isinstance(payload.get("data"), list): raise ApiError("unexpected payload: expected a list or an object with a 'data' list") yield payload["data"] next_cursor = payload.get("next_cursor") if next_cursor is None or next_cursor == "": return # Reject booleans or nested containers so a broken "next_cursor": false does not become "?cursor=False". if isinstance(next_cursor, bool) or not isinstance(next_cursor, (str, int)): raise ApiError("unexpected payload: 'next_cursor' must be a string, integer, or null") cursor = str(next_cursor) if cursor in seen_cursors: raise ApiError(f"pagination loop: cursor {cursor!r} came back twice") seen_cursors.add(cursor) raise ApiError(f"stopped after {max_pages} pages")In Example 1, when
?limit=2&cursor=tok_2hitsHTTP 429withRetry-After: 2,client.get_jsonsleeps2.0s, re-requests that exact cursor URL, and yields page 2 cleanly.Normalize and validate each field without crashing
Give each field a dedicated helper returning either a cleaned value or
None, keeping a record only when all five fields succeed:- Identifiers (
_parse_id): accept trimmed non-empty strings and integers (501 -> "501"), rejectingbool(isinstance(True, int)isTruein Python). - Coordinates (
_parse_coordinate): accept numbers or numeric strings inside[-90, 90]and[-180, 180], catching bothValueErrorandOverflowError(e.g. 400-digit JSON integers) and rejectingNaN/infviamath.isfinite. - Timestamps (
parse_timestamp): normalize epoch seconds (1704067200), epoch milliseconds (1704067260500 >= 10^11), and ISO 8601 strings to UTCYYYY-MM-DDTHH:MM:SS.sssZ, using integerdivmod(value, 1000)so large millisecond integers never lose1 msto float rounding.
EPOCH_MS_THRESHOLD = 100_000_000_000 def parse_timestamp(value: Any) -> Optional[str]: """ISO 8601 UTC with milliseconds, like '2023-11-14T22:13:20.000Z', or None if unusable. Numbers are Unix epoch seconds, or milliseconds when at least EPOCH_MS_THRESHOLD. Strings are ISO 8601; a string without a UTC offset is taken as UTC. """ # Reject bool first because isinstance(True, int) is True in Python. if isinstance(value, bool): return None try: if isinstance(value, int): if abs(value) >= EPOCH_MS_THRESHOLD: # Use integer divmod so large millisecond timestamps never lose 1 ms to float rounding. whole_seconds, rem_ms = divmod(value, 1000) moment = datetime.fromtimestamp(whole_seconds, tz=timezone.utc) moment = moment.replace(microsecond=rem_ms * 1000) else: moment = datetime.fromtimestamp(value, tz=timezone.utc) elif isinstance(value, float): if not math.isfinite(value): return None seconds = value / 1000.0 if abs(value) >= EPOCH_MS_THRESHOLD else value moment = datetime.fromtimestamp(seconds, tz=timezone.utc) elif isinstance(value, str): text = value.strip() # Replace trailing Z/z with +00:00 so datetime.fromisoformat works across Python 3 versions. if text.endswith("Z") or text.endswith("z"): text = text[:-1] + "+00:00" moment = datetime.fromisoformat(text) if moment.tzinfo is None: moment = moment.replace(tzinfo=timezone.utc) else: return None utc_moment = moment.astimezone(timezone.utc) except (ValueError, OverflowError, OSError): # Catches unparsable text, huge ints exceeding time_t, and out-of-range years. return None return utc_moment.isoformat(timespec="milliseconds").replace("+00:00", "Z") def _parse_id(value: Any) -> Optional[str]: """A non-empty identifier as a string. Integers are accepted; bools are not.""" if isinstance(value, bool): return None if isinstance(value, int): return str(value) if isinstance(value, str) and value.strip(): return value.strip() return None def _parse_coordinate(value: Any, limit: float) -> Optional[float]: """value as a finite float in [-limit, limit], or None. Numeric strings are accepted.""" if isinstance(value, bool) or not isinstance(value, (int, float, str)): return None try: number = float(value) except (ValueError, OverflowError): # OverflowError happens when json.loads parses a 400-digit integer that cannot fit in float64. return None # Reject NaN, +inf, -inf, and out-of-bounds GPS degrees (latitude +-90, longitude +-180). if not math.isfinite(number) or abs(number) > limit: return None return number def parse_record(raw: Any) -> Optional[Dict[str, Any]]: """Map one raw API record to the target schema (the FIELDS keys), or None if it is malformed.""" if not isinstance(raw, dict): return None order_id = _parse_id(raw.get("order_id")) courier_id = _parse_id(raw.get("courier_id")) latitude = _parse_coordinate(raw.get("latitude"), 90.0) longitude = _parse_coordinate(raw.get("longitude"), 180.0) timestamp = parse_timestamp(raw.get("timestamp")) # Keep the record only if every required field parsed cleanly. if None in (order_id, courier_id, latitude, longitude, timestamp): return None return { "order_id": order_id, "courier_id": courier_id, "latitude": latitude, "longitude": longitude, "timestamp": timestamp, }- Identifiers (
Deduplicate normalized records and track health counts
Paginated feeds often repeat boundary events across adjacent pages. Deduplicating on
(order_id, courier_id, timestamp)after normalization ensures that(501, " drv-b ", 1704067200)on Page 1 and("501", "drv-b", "2024-01-01T00:00:00Z")on Page 2 collide on("501", "drv-b", "2024-01-01T00:00:00.000Z"). Individual bad rows log atDEBUG, with oneINFOhealth summary at completion:@dataclass class FetchResult: """The clean records in API order, plus counts for the log.""" records: List[Dict[str, Any]] malformed: int = 0 duplicates: int = 0 pages: int = 0 def fetch_records(client: ApiClient, url: str, page_size: int = 100) -> FetchResult: """Fetch every page, keep the valid records in API order and drop exact duplicates.""" result = FetchResult(records=[]) # seen_keys: set of (order_id, courier_id, normalized_timestamp) tuples already kept. seen_keys = set() for page in iter_pages(client, url, page_size): result.pages += 1 for raw in page: record = parse_record(raw) if record is None: result.malformed += 1 logger.debug("skipping malformed record: %r", raw) continue # Deduplicate after normalization so epoch 1704067200 and "2024-01-01T00:00:00Z" match. dedupe_key = (record["order_id"], record["courier_id"], record["timestamp"]) if dedupe_key in seen_keys: result.duplicates += 1 continue seen_keys.add(dedupe_key) result.records.append(record) logger.info("fetched %d pages: kept %d records, skipped %d malformed and %d duplicates", result.pages, len(result.records), result.malformed, result.duplicates) return resultSerialize to CSV/JSON and compute deterministic top-k
For serialized output,
csv.DictWriterquotes fields containing commas or quotes (ord,11->"ord,11"), whereas manual string joining would corrupt CSV columns.For aggregation, a single delivery emits multiple GPS pings over time (as in Example 2, where
rider-2reports"ord-10"at08:30and08:31), so grouping distinctorder_ids percourier_idvia sets counts actual deliveries. Finally,heapq.nsmallest(k, counts.items(), key=_rank)with(-count, name)extracts thekleaders inO(C log k)time and breaks ties alphabetically:def records_to_csv(records: List[Dict[str, Any]]) -> str: """CSV text with a header row and the columns in FIELDS order.""" buffer = io.StringIO() # csv.DictWriter automatically quotes values containing commas, quotes, or newlines. writer = csv.DictWriter(buffer, fieldnames=FIELDS, lineterminator="\n") writer.writeheader() for record in records: writer.writerow(record) return buffer.getvalue() def records_to_json(records: List[Dict[str, Any]]) -> str: """The records as a JSON array.""" return json.dumps(records, indent=2) def orders_per_courier(records: List[Dict[str, Any]]) -> Dict[str, int]: """Number of distinct order_ids per courier_id.""" # orders_by_courier: dict mapping courier_id -> set of distinct order_ids (e.g. {"c1": {"o1", "o2"}}). orders_by_courier: Dict[str, set] = {} for record in records: courier_id = record["courier_id"] if courier_id not in orders_by_courier: orders_by_courier[courier_id] = set() orders_by_courier[courier_id].add(record["order_id"]) # counts: dict mapping courier_id -> distinct order count. counts: Dict[str, int] = {} for courier_id, order_ids in orders_by_courier.items(): counts[courier_id] = len(order_ids) return counts def _rank(item: Tuple[str, int]) -> Tuple[int, str]: # Negate count so largest counts sort first; break ties alphabetically by courier name. name, count = item return (-count, name) def top_k(counts: Dict[str, int], k: int) -> List[Tuple[str, int]]: """The k (name, count) pairs with the highest counts, ties broken by name ascending.""" if k <= 0: return [] return heapq.nsmallest(k, counts.items(), key=_rank)Mini-trace on Example 2:
rider-2has pings("ord-10", "ord-10")->1distinct order, andrider-1has("ord,11", "ord-12")->2distinct orders, sotop_k(counts, 1)returns[("rider-1", 2)]. On Example 1 ({"drv-b": 1, "drv-a": 1}), rank keys(-1, "drv-a") < (-1, "drv-b")break the tie to return[("drv-a", 1), ("drv-b", 1)].Wire up the CLI entry point
Configure
logging.basicConfiginsidemainrather than at import time, and return standard exit codes (0on success,1onApiError,2whenAPI_TOKENis unset):def main(argv: Optional[List[str]] = None) -> int: parser = argparse.ArgumentParser(description="Fetch courier tracking records and summarize them.") parser.add_argument("url", help="endpoint that returns the tracking records") parser.add_argument("--page-size", type=int, default=100) parser.add_argument("--top-k", type=int, default=5) parser.add_argument("--csv", default="records.csv", help="output path for the CSV file") parser.add_argument("--json", default="records.json", help="output path for the JSON file") args = parser.parse_args(argv) logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") # Read credentials from the environment so secrets never appear in shell history or process tables. token = os.environ.get("API_TOKEN") if not token: logger.error("set the API_TOKEN environment variable") return 2 client = ApiClient(token) try: result = fetch_records(client, args.url, args.page_size) except ApiError as error: logger.error("fetch failed: %s", error) return 1 with open(args.csv, "w", newline="", encoding="utf-8") as csv_file: csv_file.write(records_to_csv(result.records)) with open(args.json, "w", encoding="utf-8") as json_file: json_file.write(records_to_json(result.records)) counts = orders_per_courier(result.records) leaders = top_k(counts, args.top_k) for courier_id, order_count in leaders: print(f"{courier_id}\t{order_count}") return 0Complete solution
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple import argparse import csv import heapq import http.client import io import json import logging import math import os import sys import time import urllib.error import urllib.parse import urllib.request from dataclasses import dataclass, field from datetime import datetime, timezone logger = logging.getLogger("tracking_fetch") # FIELDS: ordered target schema columns for cleaned records and CSV output. FIELDS = ["order_id", "courier_id", "latitude", "longitude", "timestamp"] # RETRYABLE_STATUSES: transient HTTP codes (request timeout, rate limit, server/gateway errors). RETRYABLE_STATUSES = {408, 429, 500, 502, 503, 504} # Numeric timestamps >= 1e11 are treated as epoch milliseconds (1e11 s is year 5138; 1e11 ms is March 1973). EPOCH_MS_THRESHOLD = 100_000_000_000 @dataclass class HttpResponse: """One HTTP answer. Header names are lower-case.""" status: int body: str headers: Dict[str, str] = field(default_factory=dict) class ApiError(Exception): """A request failed for good: a non-retryable status, retries used up, or an unexpected payload.""" @dataclass class FetchResult: """The clean records in API order, plus counts for the log.""" records: List[Dict[str, Any]] malformed: int = 0 duplicates: int = 0 pages: int = 0 # Transport: callable (url, headers, timeout_seconds) -> HttpResponse; raises OSError on network failure. Transport = Callable[[str, Dict[str, str], float], HttpResponse] def urllib_transport(url: str, headers: Dict[str, str], timeout: float) -> HttpResponse: """A real GET with the standard library.""" request = urllib.request.Request(url, headers=headers, method="GET") try: # Phase 1: Send the GET request with a per-socket-operation timeout. with urllib.request.urlopen(request, timeout=timeout) as response: status = response.status raw_headers = response.headers body = response.read() except urllib.error.HTTPError as error: # urllib raises HTTPError on 4xx/5xx, so convert it back to HttpResponse for uniform status handling. try: status = error.code raw_headers = error.headers or {} try: body = error.read() except (http.client.HTTPException, OSError): # If an error body drops mid-stream, keep status and headers so 429/5xx can still retry. body = b"" finally: # Close the underlying socket stream so repeated HTTP errors do not leak connections. error.close() except http.client.HTTPException as error: # Normalize low-level HTTP framing drops (such as IncompleteRead) into an OSError subclass. raise ConnectionError(str(error)) from error # normalized_headers: dict mapping lower-case header name -> value (e.g. {"retry-after": "3"}). normalized_headers = {} for name, value in raw_headers.items(): normalized_headers[name.lower()] = value decoded_body = body.decode("utf-8", errors="replace") return HttpResponse(status, decoded_body, normalized_headers) def parse_retry_after(value: Optional[str]) -> Optional[float]: """Seconds from a Retry-After header, or None if it is missing or not a number of seconds.""" if value is None: return None try: seconds = float(value) except ValueError: # HTTP-date strings (like "Wed, 21 Oct 2015 07:28:00 GMT") return None to fall back to backoff. return None # Reject NaN, infinity, and negative durations because time.sleep rejects negative numbers. if not math.isfinite(seconds) or seconds < 0: return None return seconds class ApiClient: """GET + JSON with bearer-token auth, a per-request timeout and retries with exponential backoff.""" def __init__(self, token: str, transport: Transport = urllib_transport, sleep: Callable[[float], None] = time.sleep, timeout: float = 10.0, max_retries: int = 4, base_delay: float = 0.5, max_delay: float = 30.0) -> None: self.token = token self.transport = transport self.sleep = sleep self.timeout = timeout self.max_retries = max_retries self.base_delay = base_delay self.max_delay = max_delay def backoff_delay(self, attempt: int, retry_after: Optional[float]) -> float: """Seconds to wait after failed attempt number `attempt` (0-based).""" # Honor an explicit server Retry-After header when present. if retry_after is not None: return retry_after exponential_wait = self.base_delay * (2 ** attempt) return min(self.max_delay, exponential_wait) def get_json(self, url: str) -> Any: """The parsed JSON body of a GET to url. Raises ApiError when it cannot succeed.""" # Send the secret token in the Authorization header rather than the URL query string. headers = {"Authorization": f"Bearer {self.token}", "Accept": "application/json"} # Run 1 initial attempt (attempt = 0) plus up to max_retries retry attempts. for attempt in range(self.max_retries + 1): retry_after = None try: response = self.transport(url, headers, self.timeout) except OSError as error: problem = f"network error ({error})" else: if 200 <= response.status < 300: try: return json.loads(response.body) except ValueError: # A 200 body cut off mid-transfer or replaced by proxy HTML is worth retrying. problem = "response body is not valid JSON" elif response.status in RETRYABLE_STATUSES: problem = f"HTTP {response.status}" retry_after = parse_retry_after(response.headers.get("retry-after")) else: # Non-retryable client errors (400, 401, 403, 404) will never succeed; fail immediately. raise ApiError(f"HTTP {response.status} from {url}: {response.body[:200]}") # Stop immediately once all retries are exhausted so we do not sleep one extra time. if attempt == self.max_retries: raise ApiError(f"giving up on {url} after {attempt + 1} attempts; last problem: {problem}") delay = self.backoff_delay(attempt, retry_after) logger.warning("%s; retry %d of %d in %.1f s", problem, attempt + 1, self.max_retries, delay) self.sleep(delay) def with_query(url: str, params: Dict[str, Any]) -> str: """url with params added to its query string, replacing existing values for the same keys.""" parts = urllib.parse.urlsplit(url) # merged_pairs: list of (key, value) query tuples keeping existing keys not overridden by params. merged_pairs = [] for key, value in urllib.parse.parse_qsl(parts.query, keep_blank_values=True): if key not in params: merged_pairs.append((key, value)) for key, value in params.items(): merged_pairs.append((key, str(value))) encoded_query = urllib.parse.urlencode(merged_pairs) updated_parts = parts._replace(query=encoded_query) return urllib.parse.urlunsplit(updated_parts) def iter_pages(client: ApiClient, url: str, page_size: int = 100, max_pages: int = 10_000) -> Iterator[List[Any]]: """Yield each page's list of raw records, following next_cursor until it is null or empty. Expected payload: {"data": [...], "next_cursor": "abc" or null}. A bare JSON list is a single page. """ cursor = None # seen_cursors: set of str cursor tokens already requested (e.g. {"p2", "p3"}) to detect infinite loops. seen_cursors = set() for _ in range(max_pages): params: Dict[str, Any] = {"limit": page_size} if cursor is not None: params["cursor"] = cursor page_url = with_query(url, params) payload = client.get_json(page_url) # A bare JSON array means the endpoint is unpaginated; yield it once and stop. if isinstance(payload, list): yield payload return if not isinstance(payload, dict) or not isinstance(payload.get("data"), list): raise ApiError("unexpected payload: expected a list or an object with a 'data' list") yield payload["data"] next_cursor = payload.get("next_cursor") if next_cursor is None or next_cursor == "": return # Reject booleans or nested containers so a broken "next_cursor": false does not become "?cursor=False". if isinstance(next_cursor, bool) or not isinstance(next_cursor, (str, int)): raise ApiError("unexpected payload: 'next_cursor' must be a string, integer, or null") cursor = str(next_cursor) if cursor in seen_cursors: raise ApiError(f"pagination loop: cursor {cursor!r} came back twice") seen_cursors.add(cursor) raise ApiError(f"stopped after {max_pages} pages") def parse_timestamp(value: Any) -> Optional[str]: """ISO 8601 UTC with milliseconds, like '2023-11-14T22:13:20.000Z', or None if unusable. Numbers are Unix epoch seconds, or milliseconds when at least EPOCH_MS_THRESHOLD. Strings are ISO 8601; a string without a UTC offset is taken as UTC. """ # Reject bool first because isinstance(True, int) is True in Python. if isinstance(value, bool): return None try: if isinstance(value, int): if abs(value) >= EPOCH_MS_THRESHOLD: # Use integer divmod so large millisecond timestamps never lose 1 ms to float rounding. whole_seconds, rem_ms = divmod(value, 1000) moment = datetime.fromtimestamp(whole_seconds, tz=timezone.utc) moment = moment.replace(microsecond=rem_ms * 1000) else: moment = datetime.fromtimestamp(value, tz=timezone.utc) elif isinstance(value, float): if not math.isfinite(value): return None seconds = value / 1000.0 if abs(value) >= EPOCH_MS_THRESHOLD else value moment = datetime.fromtimestamp(seconds, tz=timezone.utc) elif isinstance(value, str): text = value.strip() # Replace trailing Z/z with +00:00 so datetime.fromisoformat works across Python 3 versions. if text.endswith("Z") or text.endswith("z"): text = text[:-1] + "+00:00" moment = datetime.fromisoformat(text) if moment.tzinfo is None: moment = moment.replace(tzinfo=timezone.utc) else: return None utc_moment = moment.astimezone(timezone.utc) except (ValueError, OverflowError, OSError): # Catches unparsable text, huge ints exceeding time_t, and out-of-range years. return None return utc_moment.isoformat(timespec="milliseconds").replace("+00:00", "Z") def _parse_id(value: Any) -> Optional[str]: """A non-empty identifier as a string. Integers are accepted; bools are not.""" if isinstance(value, bool): return None if isinstance(value, int): return str(value) if isinstance(value, str) and value.strip(): return value.strip() return None def _parse_coordinate(value: Any, limit: float) -> Optional[float]: """value as a finite float in [-limit, limit], or None. Numeric strings are accepted.""" if isinstance(value, bool) or not isinstance(value, (int, float, str)): return None try: number = float(value) except (ValueError, OverflowError): # OverflowError happens when json.loads parses a 400-digit integer that cannot fit in float64. return None # Reject NaN, +inf, -inf, and out-of-bounds GPS degrees (latitude +-90, longitude +-180). if not math.isfinite(number) or abs(number) > limit: return None return number def parse_record(raw: Any) -> Optional[Dict[str, Any]]: """Map one raw API record to the target schema (the FIELDS keys), or None if it is malformed.""" if not isinstance(raw, dict): return None order_id = _parse_id(raw.get("order_id")) courier_id = _parse_id(raw.get("courier_id")) latitude = _parse_coordinate(raw.get("latitude"), 90.0) longitude = _parse_coordinate(raw.get("longitude"), 180.0) timestamp = parse_timestamp(raw.get("timestamp")) # Keep the record only if every required field parsed cleanly. if None in (order_id, courier_id, latitude, longitude, timestamp): return None return { "order_id": order_id, "courier_id": courier_id, "latitude": latitude, "longitude": longitude, "timestamp": timestamp, } def fetch_records(client: ApiClient, url: str, page_size: int = 100) -> FetchResult: """Fetch every page, keep the valid records in API order and drop exact duplicates.""" result = FetchResult(records=[]) # seen_keys: set of (order_id, courier_id, normalized_timestamp) tuples already kept. seen_keys = set() for page in iter_pages(client, url, page_size): result.pages += 1 for raw in page: record = parse_record(raw) if record is None: result.malformed += 1 logger.debug("skipping malformed record: %r", raw) continue # Deduplicate after normalization so epoch 1704067200 and "2024-01-01T00:00:00Z" match. dedupe_key = (record["order_id"], record["courier_id"], record["timestamp"]) if dedupe_key in seen_keys: result.duplicates += 1 continue seen_keys.add(dedupe_key) result.records.append(record) logger.info("fetched %d pages: kept %d records, skipped %d malformed and %d duplicates", result.pages, len(result.records), result.malformed, result.duplicates) return result def records_to_csv(records: List[Dict[str, Any]]) -> str: """CSV text with a header row and the columns in FIELDS order.""" buffer = io.StringIO() # csv.DictWriter automatically quotes values containing commas, quotes, or newlines. writer = csv.DictWriter(buffer, fieldnames=FIELDS, lineterminator="\n") writer.writeheader() for record in records: writer.writerow(record) return buffer.getvalue() def records_to_json(records: List[Dict[str, Any]]) -> str: """The records as a JSON array.""" return json.dumps(records, indent=2) def orders_per_courier(records: List[Dict[str, Any]]) -> Dict[str, int]: """Number of distinct order_ids per courier_id.""" # orders_by_courier: dict mapping courier_id -> set of distinct order_ids (e.g. {"c1": {"o1", "o2"}}). orders_by_courier: Dict[str, set] = {} for record in records: courier_id = record["courier_id"] if courier_id not in orders_by_courier: orders_by_courier[courier_id] = set() orders_by_courier[courier_id].add(record["order_id"]) # counts: dict mapping courier_id -> distinct order count. counts: Dict[str, int] = {} for courier_id, order_ids in orders_by_courier.items(): counts[courier_id] = len(order_ids) return counts def _rank(item: Tuple[str, int]) -> Tuple[int, str]: # Negate count so largest counts sort first; break ties alphabetically by courier name. name, count = item return (-count, name) def top_k(counts: Dict[str, int], k: int) -> List[Tuple[str, int]]: """The k (name, count) pairs with the highest counts, ties broken by name ascending.""" if k <= 0: return [] return heapq.nsmallest(k, counts.items(), key=_rank) def main(argv: Optional[List[str]] = None) -> int: parser = argparse.ArgumentParser(description="Fetch courier tracking records and summarize them.") parser.add_argument("url", help="endpoint that returns the tracking records") parser.add_argument("--page-size", type=int, default=100) parser.add_argument("--top-k", type=int, default=5) parser.add_argument("--csv", default="records.csv", help="output path for the CSV file") parser.add_argument("--json", default="records.json", help="output path for the JSON file") args = parser.parse_args(argv) logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") # Read credentials from the environment so secrets never appear in shell history or process tables. token = os.environ.get("API_TOKEN") if not token: logger.error("set the API_TOKEN environment variable") return 2 client = ApiClient(token) try: result = fetch_records(client, args.url, args.page_size) except ApiError as error: logger.error("fetch failed: %s", error) return 1 with open(args.csv, "w", newline="", encoding="utf-8") as csv_file: csv_file.write(records_to_csv(result.records)) with open(args.json, "w", encoding="utf-8") as json_file: json_file.write(records_to_json(result.records)) counts = orders_per_courier(result.records) leaders = top_k(counts, args.top_k) for courier_id, order_count in leaders: print(f"{courier_id}\t{order_count}") return 0 if __name__ == "__main__": sys.exit(main())✅ Submit now — all tests should pass.
Intuition & how it works
Think of pulling courier GPS feeds from a paginated HTTP service like running a warehouse receiving dock and inspection belt. Trucks (API pages) arrive sequentially carrying cartons (raw JSON items): the gatekeeper checks credentials and pauses briefly when the upstream yard signals congestion, the dock clerk tracks the manifest token (next_cursor) so no truck is skipped or unloaded in an endless circle, the inspector diverts damaged cartons (malformed count) without halting the belt, and clean cartons get recorded onto shipping manifests (CSV/JSON) and tallied on a courier leaderboard (top-k distinct orders).
A quick 10-line script calling urlopen(url) inside a bare json.loads(...) loop breaks under real network conditions. Omitting a socket timeout lets one stalled TCP connection hang forever; skipping exponential backoff (doubling the wait duration after each transient failure) turns a brief 429 rate limit or 503 gateway blip into a total job failure; and skipping field-level normalization causes one blank courier_id or mixed epoch/ISO timestamp to either crash with ValueError or double-count repeated boundary pings.
Walk through Example 1 (page_size = 2, k = 2):
1. Page 1 (?limit=2): Returns {order_id: 501, courier_id: " drv-b ", timestamp: 1704067200, ...} and {order_id: 502, courier_id: ""}, plus next_cursor = "tok_2". Order 501 normalizes to ("501", "drv-b", "2024-01-01T00:00:00.000Z"), while order 502 fails validation and increments malformed = 1.
2. Page 2 (?limit=2&cursor=tok_2): First encounters HTTP 429 with Retry-After: 2, sleeps 2.0s, re-requests ?limit=2&cursor=tok_2, and receives {order_id: "501", courier_id: "drv-b", timestamp: "2024-01-01T00:00:00Z", ...} alongside {order_id: "503", courier_id: "drv-a", timestamp: 1704067260500, ...} with next_cursor = null.
3. Because deduplication runs after normalization, the repeated 501 ping matches seen_keys (duplicates = 1), leaving two valid records (drv-b with 1 order, drv-a with 1 order), and top_k breaks the tie alphabetically to return [("drv-a", 1), ("drv-b", 1)].
Complexity
Let N be the total raw items returned across P = ceil(N / page_size) pages, and C (<= N) be the number of unique couriers.
- CPU time —
O(N + C log k)on average: JSON decoding across all pages scans bytes proportional toN. Normalizing each of theNitems performs fixed five-field parsing plus anO(1)average hash-set check inseen_keys. Writing CSV/JSON and grouping distinctorder_ids per courier each traverse the kept records once inO(N), and min-heap selection (heapq.nsmallestmaintaining a binary heap of thekbest couriers seen so far) extracts the topkofCcouriers inO(C log k)comparisons rather than sorting allCcouriers inO(C log C). - Network wall-clock time —
O(P)sequential round trips (plus retry sleeps): Because cursor pagination depends on thenext_cursortoken from pageito request pagei + 1, pages are fetched one after another (50,000rows atpage_size = 100takes500round trips, whereaspage_size = 1,000cuts round trips 10x). - Space —
O(N)memory: Retaining the cleanedrecordslist, theseen_keysdeduplication set, per-courier distinctorder_idsets, and serialized CSV/JSON buffers each scales linearly with the number of unique records kept.
Edge cases
- Empty endpoint (
{"data": [], "next_cursor": null}): Yields0records, a header-only CSV string,[]in JSON, an empty leaderboard, and exit code0. - Empty intermediate page (
{"data": [], "next_cursor": "tok_2"}): Continues followingnext_cursorwhileseen_cursorsandmax_pagesstill block endless loops. - Unrecoverable mid-run failure: Exhausting retries on a middle page raises
ApiErrorbefore opening output files, avoiding half-written CSV/JSON artifacts. - Mixed and large timestamps: Epoch seconds (
1704067200), epoch milliseconds (1704067260500, split via integerdivmodso multi-millennium ints like32503680000001never lose1 msto float rounding), naive ISO strings, and offset ISO strings (+02:00) all map to UTC millisecond text, whileTrue,NaN, and10^400safely returnNone. - Truncated error bodies (
IncompleteReadon503):urllib_transportretains status503andRetry-Afterheaders with an empty body and closes the socket so transient gateway drops still retry cleanly. - Cross-origin HTTP redirects: Default
urllibforwards headers across301/302redirects; when calling untrusted redirect targets, attach a customHTTPRedirectHandlerthat stripsAuthorizationon host changes.
Common mistakes
- Calling
urlopenwithout atimeout: Python defaults totimeout=None, letting one silently dropped firewall connection stall a batch job indefinitely. - Retrying permanent
4xxresponses (400,401,403,404): A malformed URL or invalid bearer token (the secret string inAuthorization: Bearer ...) fails identically on every attempt; fail immediately instead. - Sleeping one extra time after the final failed attempt: Check
if attempt == self.max_retries: raise ApiError(...)before callingsleep(delay). - Deduplicating raw values prior to normalization: Comparing raw JSON treats
501vs"501"or1704067200vs"2024-01-01T00:00:00Z"as distinct pings. - Building CSV lines with
",".join(...): Any identifier containing a comma ("ord,11"), quote ('drv"9'), or newline shifts columns silently; always usecsv.DictWriter. - Accepting tokens via CLI flags or logging request headers: Command-line flags expose credentials in shell history and process tables, and logging
headersleaks tokens into log files. - Running unit tests against live network calls or
time.sleep: Injectingtransportandsleepkeeps retry, rate-limit, and timeout tests offline and deterministic.
Alternative approaches
requests.Session+urllib3.util.retry.Retry: Where external dependencies are allowed, mountingHTTPAdapter(max_retries=Retry(...))handles retry status sets, exponential backoff, and HTTP-dateRetry-Afterheaders out of the box (still pass explicit(connect, read)timeouts on every.get(...)call).- Streaming JSON Lines (
jsonl) output: JSON Lines appends one self-contained JSON object per line as each page arrives, avoiding building a monolithicrecordslist in RAM. - Partitioned worker pool (
asyncioorThreadPoolExecutor): When the upstream API partitions feeds by region or fixed time slices rather than a single sequential cursor chain, fetching slices concurrently behind a shared rate limiter cuts wall-clock duration dramatically.
Follow-up questions
- How would you redesign this pipeline to ingest 50 million tracking pings without exhausting RAM? Keeping 50 million Python dictionaries and deduplication tuples in memory would consume tens of gigabytes, so stream each validated record directly to disk as CSV or JSON Lines (one JSON object per line) instead of storing
result.records. Bound deduplication memory by retaining a bounded LRU/sliding window of recent keys (when duplicates only span adjacent page boundaries) or inserting into an external store with aUNIQUE (order_id, courier_id, timestamp)index, and if per-courierorder_idsets outgrow RAM, approximate distinct counts within ~1.6% error in a few kilobytes per courier using HyperLogLog (a compact probabilistic sketch for cardinality estimation). - What checkpointing and storage guarantees are needed to make a multi-hour ingestion run safely resumable after a crash? Persist a durable checkpoint (
last_cursoror high-waterupdated_sincewatermark) only after flushing that page's records to disk or storage, allowing a restarted worker to resume from the last committed cursor instead of page 1. Because a crash right between writing records and updating the checkpoint replays one page on recovery, downstream writes must be idempotent — meaning applying the identical ping twice leaves the exact same stored state as applying it once (for example, viaON CONFLICT DO NOTHINGor key-based upsert). - Why does synchronized exponential backoff still cause retry storms across many workers, and how do jitter and client-side rate limiting fix it? When dozens of workers hit a transient outage during the same second, fixed waits (
0.5s, 1s, 2s, 4s) wake every worker simultaneously in synchronized waves that repeatedly overwhelm the recovering service; adding jitter (sampling a random sleep uniformly from[0, min(max_delay, base_delay * 2^attempt)]) spreads retries evenly across time. To prevent429bursts before they happen, gate outgoing requests through a shared token bucket (a rate limiter that replenishesRpermits per second up to a burst ceiling and blocks callers when permits reach zero).
Follow-up questions
- How would you redesign this pipeline to ingest 50 million tracking pings without exhausting RAM?
- What checkpointing and storage guarantees are needed to make a multi-hour ingestion run safely resumable after a crash?
- Why does synchronized exponential backoff still cause retry storms across many workers, and how do jitter and client-side rate limiting fix it?
Similar questions
- Live Courier Tracking and Dispatch Platform
- Disjoint-Set Operations with Component Counting
- Undirected Connectivity Queries via Disjoint Sets
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages