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:

  1. HTTP transport & retry client (urllib_transport, parse_retry_after, ApiClient):

    • urllib_transport(url, headers, timeout) executes a GET request via urllib.request with timeout seconds. Return an HttpResponse(status, body, headers) with lowercased header names and UTF-8 decoded text (errors="replace") for both 2xx and 4xx/5xx HTTP responses (closing error streams and preserving status and headers with an empty body if reading an error stream fails mid-transfer). Raise an OSError subclass on network errors or low-level HTTP framing failures.
    • parse_retry_after(value) parses a Retry-After header string into a finite float >= 0 representing seconds, returning None when missing, negative, non-finite, or non-numeric (such as an HTTP-date).
    • ApiClient.backoff_delay(attempt, retry_after) returns retry_after if provided; otherwise min(self.max_delay, self.base_delay * (2 ** attempt)) for 0-based attempt.
    • ApiClient.get_json(url) sends Authorization: Bearer <token> and Accept: application/json. Retry OSError, invalid JSON in 2xx responses, and statuses in RETRYABLE_STATUSES = {408, 429, 500, 502, 503, 504} up to self.max_retries times, sleeping backoff_delay(...) between attempts (passing parsed retry-after on retryable HTTP statuses). Raise ApiError immediately on non-retryable HTTP statuses (such as 400, 401, 403, 404) or once all max_retries retries fail (without sleeping after the final failed attempt).
  2. Cursor pagination (with_query, iter_pages):

    • with_query(url, params) merges params into url's query string, replacing existing values for keys present in params while keeping other existing query parameters intact.
    • iter_pages(client, url, page_size=100, max_pages=10_000) requests limit=<page_size> on the first request and adds cursor=<cursor> on subsequent pages. If a response is a bare JSON list, yield it once and stop. Otherwise expect {"data": [...], "next_cursor": ...}, yield data, and stop when next_cursor is None or "". Accept str or int cursors (rejecting bool or containers); raise ApiError on malformed page envelopes, repeated cursors, or exceeding max_pages.
  3. 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', returning None for booleans, non-finite values, or unparsable inputs.
    • parse_record(raw) converts a raw dict into the five FIELDS (["order_id", "courier_id", "latitude", "longitude", "timestamp"]): order_id and courier_id become trimmed non-empty strings (int allowed, bool rejected); latitude in [-90, 90] and longitude in [-180, 180] become finite floats (int, float, or numeric str allowed, bool rejected); timestamp uses parse_timestamp. Return None if raw is not a dict or any field fails validation.
    • fetch_records(client, url, page_size=100) iterates through all pages, skips malformed records (incrementing FetchResult.malformed), drops subsequent records matching a previously kept (order_id, courier_id, timestamp) tuple after normalization (incrementing FetchResult.duplicates), counts FetchResult.pages, and preserves first-seen API order.
  4. Serialization, leaderboard & CLI (records_to_csv, records_to_json, orders_per_courier, top_k, main):

    • records_to_csv(records) returns CSV text with header FIELDS and \n line terminators; records_to_json(records) returns a JSON array string.
    • orders_per_courier(records) maps each courier_id to its count of distinct order_ids.
    • top_k(counts, k) returns the k highest (courier_id, count) pairs ordered by count descending, then courier_id ascending ([] if k <= 0).
    • main(argv) reads API_TOKEN from os.environ (returning exit code 2 if missing, 1 on ApiError, 0 on success), writes the CSV and JSON files, and prints courier_id\tcount lines for the top-k couriers.

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).
  • latitude must be finite and satisfy -90.0 <= latitude <= 90.0; longitude must 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 large int values); smaller magnitudes represent Unix epoch seconds.
  • RETRYABLE_STATUSES = {408, 429, 500, 502, 503, 504}; non-retryable 4xx responses fail immediately without sleeping.
  • iter_pages stops with ApiError if any cursor repeats or total fetched pages exceed max_pages.

Step-by-step walkthrough

  1. 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 the API_TOKEN environment variable rather than a command-line flag, keeping secrets out of shell history and ps listings.
    • 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_id and courier_id to trimmed non-empty strings, latitude in [-90, 90] and longitude in [-180, 180] to finite floats, and timestamp (Unix seconds, Unix milliseconds >= 10^11, or ISO 8601 text) to UTC YYYY-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-k couriers by distinct order_id count (breaking ties alphabetically by courier_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.

  2. Isolate network I/O behind a pluggable transport

    Calling urllib.request.urlopen directly inside pagination or retry code makes unit tests slow and dependent on live network sockets. Injecting a transport callable (url, headers, timeout) -> HttpResponse (plus a sleep callable) lets production traffic use urllib_transport while 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_transport in real deployments: 1. urlopen raises HTTPError on 4xx and 5xx statuses; converting that into HttpResponse lets one status table govern retries, and error.close() prevents socket leaks. 2. When a 503 error body drops mid-stream (IncompleteRead), keeping status = 503 and raw_headers (including Retry-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.

  3. 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 glitch
    

    Between retries, exponential backoff doubles the wait after each failed attempt (base_delay * 2^attempt, capped at max_delay), unless the server supplies a numeric Retry-After header specifying exact seconds to wait. With base_delay = 0.5 and max_retries = 4, the four waits are 0.5s, 1.0s, 2.0s, 4.0s across 5 total 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.warning records only the failure summary and delay, never headers, keeping the bearer token out of log files.

  4. 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 numeric offset= 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_cursors and raise ApiError if any cursor comes back twice. 2. Bound total iterations by max_pages in case a faulty server invents fresh cursors endlessly. 3. Validate envelope shape (data must be a list, and non-empty next_cursor must be a str or int, never bool or 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_2 hits HTTP 429 with Retry-After: 2, client.get_json sleeps 2.0s, re-requests that exact cursor URL, and yields page 2 cleanly.

  5. 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"), rejecting bool (isinstance(True, int) is True in Python).
    • Coordinates (_parse_coordinate): accept numbers or numeric strings inside [-90, 90] and [-180, 180], catching both ValueError and OverflowError (e.g. 400-digit JSON integers) and rejecting NaN/inf via math.isfinite.
    • Timestamps (parse_timestamp): normalize epoch seconds (1704067200), epoch milliseconds (1704067260500 >= 10^11), and ISO 8601 strings to UTC YYYY-MM-DDTHH:MM:SS.sssZ, using integer divmod(value, 1000) so large millisecond integers never lose 1 ms to 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,
        }
    
  6. 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 at DEBUG, with one INFO health 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 result
    
  7. Serialize to CSV/JSON and compute deterministic top-k

    For serialized output, csv.DictWriter quotes 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-2 reports "ord-10" at 08:30 and 08:31), so grouping distinct order_ids per courier_id via sets counts actual deliveries. Finally, heapq.nsmallest(k, counts.items(), key=_rank) with (-count, name) extracts the k leaders in O(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-2 has pings ("ord-10", "ord-10") -> 1 distinct order, and rider-1 has ("ord,11", "ord-12") -> 2 distinct orders, so top_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)].

  8. Wire up the CLI entry point

    Configure logging.basicConfig inside main rather than at import time, and return standard exit codes (0 on success, 1 on ApiError, 2 when API_TOKEN is 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 0
    
  9. Complete 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 to N. Normalizing each of the N items performs fixed five-field parsing plus an O(1) average hash-set check in seen_keys. Writing CSV/JSON and grouping distinct order_ids per courier each traverse the kept records once in O(N), and min-heap selection (heapq.nsmallest maintaining a binary heap of the k best couriers seen so far) extracts the top k of C couriers in O(C log k) comparisons rather than sorting all C couriers in O(C log C).
  • Network wall-clock time — O(P) sequential round trips (plus retry sleeps): Because cursor pagination depends on the next_cursor token from page i to request page i + 1, pages are fetched one after another (50,000 rows at page_size = 100 takes 500 round trips, whereas page_size = 1,000 cuts round trips 10x).
  • Space — O(N) memory: Retaining the cleaned records list, the seen_keys deduplication set, per-courier distinct order_id sets, and serialized CSV/JSON buffers each scales linearly with the number of unique records kept.

Edge cases

  • Empty endpoint ({"data": [], "next_cursor": null}): Yields 0 records, a header-only CSV string, [] in JSON, an empty leaderboard, and exit code 0.
  • Empty intermediate page ({"data": [], "next_cursor": "tok_2"}): Continues following next_cursor while seen_cursors and max_pages still block endless loops.
  • Unrecoverable mid-run failure: Exhausting retries on a middle page raises ApiError before opening output files, avoiding half-written CSV/JSON artifacts.
  • Mixed and large timestamps: Epoch seconds (1704067200), epoch milliseconds (1704067260500, split via integer divmod so multi-millennium ints like 32503680000001 never lose 1 ms to float rounding), naive ISO strings, and offset ISO strings (+02:00) all map to UTC millisecond text, while True, NaN, and 10^400 safely return None.
  • Truncated error bodies (IncompleteRead on 503): urllib_transport retains status 503 and Retry-After headers with an empty body and closes the socket so transient gateway drops still retry cleanly.
  • Cross-origin HTTP redirects: Default urllib forwards headers across 301/302 redirects; when calling untrusted redirect targets, attach a custom HTTPRedirectHandler that strips Authorization on host changes.

Common mistakes

  • Calling urlopen without a timeout: Python defaults to timeout=None, letting one silently dropped firewall connection stall a batch job indefinitely.
  • Retrying permanent 4xx responses (400, 401, 403, 404): A malformed URL or invalid bearer token (the secret string in Authorization: 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 calling sleep(delay).
  • Deduplicating raw values prior to normalization: Comparing raw JSON treats 501 vs "501" or 1704067200 vs "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 use csv.DictWriter.
  • Accepting tokens via CLI flags or logging request headers: Command-line flags expose credentials in shell history and process tables, and logging headers leaks tokens into log files.
  • Running unit tests against live network calls or time.sleep: Injecting transport and sleep keeps retry, rate-limit, and timeout tests offline and deterministic.

Alternative approaches

  • requests.Session + urllib3.util.retry.Retry: Where external dependencies are allowed, mounting HTTPAdapter(max_retries=Retry(...)) handles retry status sets, exponential backoff, and HTTP-date Retry-After headers 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 monolithic records list in RAM.
  • Partitioned worker pool (asyncio or ThreadPoolExecutor): 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 a UNIQUE (order_id, courier_id, timestamp) index, and if per-courier order_id sets 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_cursor or high-water updated_since watermark) 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, via ON CONFLICT DO NOTHING or 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 prevent 429 bursts before they happen, gate outgoing requests through a shared token bucket (a rate limiter that replenishes R permits per second up to a burst ceiling and blocks callers when permits reach zero).

Follow-up questions

Similar questions

More Motive interview questions

All 4 Motive questions →