Fault-Tolerant Concurrent Python CLI for Serial Lookups

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement a fault-tolerant, concurrent Python command-line client and library that fetches metadata for hardware serial numbers from an externally configured HTTP endpoint, classifies and retries transient faults without losing sibling items, deduplicates repeated valid serials, and emits results strictly in caller order.

Because the host URL, route layout, and response payload schema are injected by the caller's environment rather than hardcoded, implement the following decoupled components around Fetch = Callable[[str, float], Tuple[int, bytes]]:

  1. HTTP transport (make_http_fetch(url_template: str) -> Fetch):

    • Return fetch(serial, timeout) that percent-encodes serial with safe="" (so / and reserved characters cannot alter the route), substitutes {serial} into url_template, and performs an HTTP GET bounded by timeout seconds.
    • Return (http_status, body_bytes) for both 2xx and non-2xx HTTP responses, closing sockets cleanly on HTTP errors.
    • Raise TimeoutError on socket or connect timeouts, and raise ConnectionError (an OSError subclass) on network failures or truncated HTTP bodies (http.client.HTTPException).
  2. Per-serial lookup and retries (lookup_serial):

    • Signature: lookup_serial(serial, fetch, timeout=5.0, max_attempts=3, backoff=0.5, sleep=time.sleep) -> Dict[str, Any] (ValueError if max_attempts < 1).
    • Return standardized records:
      • Success (2xx with valid JSON): {"serial": serial, "ok": True, "data": <parsed_json>, "attempts": n}
      • Failure: {"serial": serial, "ok": False, "error": <error_dict>, "attempts": n}
    • Error classifications in error["type"]:
      • "timeout": fetch raised TimeoutError.
      • "connection": fetch raised another OSError.
      • "http": non-2xx status code (include "status": <int> in error).
      • "json": 2xx status whose body is malformed UTF-8 or invalid JSON.
    • Retry only transient errors ("timeout", "connection", and "http" with status in {429, 500, 502, 503, 504}) up to max_attempts total tries, calling sleep(backoff * (2 ** (attempt - 1))) before try attempt + 1. Stop after 1 attempt on deterministic failures (404, "json", etc.).
  3. Bounded concurrent batch orchestration (run_lookups):

    • Signature: run_lookups(serials, fetch, max_workers=8, timeout=5.0, max_attempts=3, backoff=0.5, sleep=time.sleep) -> List[Dict[str, Any]] (ValueError if max_workers < 1).
    • Validate inputs locally: empty strings ("") or strings containing whitespace or non-printable characters fail immediately with error["type"] == "invalid_input" and attempts == 0 without calling fetch.
    • Deduplicate valid serials so each distinct valid serial triggers one concurrent lookup_serial task on a ThreadPoolExecutor(max_workers=max_workers) (shut down cleanly in finally), catching unexpected non-OSError worker exceptions as error["type"] == "internal" (attempts: None).
    • Return one independent dictionary per input occurrence (deep-copying shared results across duplicate positions) in exact input order.
  4. Exit policy and CLI (exit_status and main):

    • exit_status(results) returns 0 when all records have ok == True (including []), otherwise 1.
    • main(argv=None, fetch=None, stdin=None, stdout=None, stderr=None) -> int reads positional serials (or stdin line by line, stripping outer whitespace and skipping blank lines), supports --url-template (default $SERIAL_LOOKUP_URL), --workers (8), --timeout (5.0), and --attempts (3), returns 2 on invalid flags or missing {serial} template, returns 130 on KeyboardInterrupt, writes one JSON object per line (JSON Lines) to stdout, prints "<succeeded> succeeded, <failed> failed" to stderr, and returns exit_status(results).

Examples

Example 1

Input:
  serials = ["SN-10", "SN-20", "SN-10"]
  max_workers = 2, timeout = 2.0
  Simulated service:
    "SN-10" (120 ms) -> (200, b'{"rack": "r3", "healthy": true}')
    "SN-20" ( 10 ms) -> (200, b'{"rack": "r1", "healthy": true}')

Output:
  results -> [
    {"serial": "SN-10", "ok": True, "data": {"rack": "r3", "healthy": True}, "attempts": 1},
    {"serial": "SN-20", "ok": True, "data": {"rack": "r1", "healthy": True}, "attempts": 1},
    {"serial": "SN-10", "ok": True, "data": {"rack": "r3", "healthy": True}, "attempts": 1},
  ]
  exit_status(results) -> 0

"SN-10" appears at indices 0 and 2, so only two network calls run ("SN-10" and "SN-20"). "SN-20" completes first at 10 ms and writes index 1; "SN-10" finishes at 120 ms and populates indices 0 and 2 as independent dictionaries.

Example 2

Input:
  serials = ["GPU-7", "bad id", "GPU-9"]
  max_attempts = 3, backoff = 0.5
  Simulated service:
    "GPU-7": call 1 -> (503, b"busy"), call 2 -> (200, b'{"temp_c": 61}')
    "GPU-9": call 1 -> (404, b"missing")

Output:
  results -> [
    {"serial": "GPU-7", "ok": True, "data": {"temp_c": 61}, "attempts": 2},
    {"serial": "bad id", "ok": False, "error": {"type": "invalid_input", "message": "serial number contains whitespace or control characters"}, "attempts": 0},
    {"serial": "GPU-9", "ok": False, "error": {"type": "http", "status": 404, "message": "HTTP 404"}, "attempts": 1},
  ]
  exit_status(results) -> 1

"bad id" fails local validation (attempts: 0). "GPU-7" retries after HTTP 503 (sleeping 0.5 s) and succeeds on attempt 2. "GPU-9" gets non-retryable HTTP 404 and stops after 1 attempt. Because not every record succeeded, exit_status returns 1.

Constraints

  • max_workers >= 1 and max_attempts >= 1 (ValueError otherwise in library calls; exit code 2 in main when --workers < 1, --attempts < 1, or --timeout <= 0).
  • At most max_workers calls to fetch may execute concurrently, and each distinct valid serial in a batch is requested at most once (up to max_attempts tries on transient errors).
  • Duplicate input positions must receive distinct dictionary objects (mutating results[i] must not mutate results[j]).
  • Standard library only (urllib.request, concurrent.futures, json, argparse).

Step-by-step walkthrough

  1. Pin down the CLI contract and output conventions

    Because the service host, route, and payload schema come from the surrounding environment, state the interface boundaries explicitly before writing code:

    • Configurable endpoint (no invented URLs): Accept a URL template containing {serial} via --url-template or $SERIAL_LOOKUP_URL.
    • Flexible CLI input: Read serial numbers from positional CLI arguments if given; otherwise stream one per line from stdin (trimming outer whitespace and skipping blank lines).
    • Ordered, machine-friendly output: Emit one JSON object per input item in exact input order as JSON Lines (one JSON object per \n-terminated line) on stdout, while sending human summaries and diagnostics to stderr so downstream jq or pipeline parsers never break:
    {"serial": "SN-10", "ok": true, "data": {"rack": "r3", "healthy": true}, "attempts": 1}
    {"serial": "GPU-9", "ok": false, "error": {"type": "http", "status": 404, "message": "HTTP 404"}, "attempts": 1}
    
    • Duplicates & validation: Collapse duplicate valid serials into a single network lookup (reads have no side effects), then copy the result into every matching input position. Reject empty strings and whitespace/control characters locally with type: "invalid_input" (attempts: 0).
    • Exit codes: 0 if all records succeed (including empty input), 1 if one or more records fail, 2 for invalid CLI flags/missing URL configuration, and 130 (128 + SIGINT) on Ctrl-C.
  2. Separate CLI, lookup logic, and HTTP transport

    Splitting the program into three decoupled layers keeps every rule deterministic and fast to test:

    1. CLI shell (parse_args, read_serials, main): Parses flags, reads stdin, formats stdout/stderr, and maps results to an OS exit code.
    2. Core orchestration (request_once, lookup_serial, run_lookups): Handles error classification, retries, thread-pool concurrency, and index-preserving aggregation — with zero direct socket or print calls.
    3. Injected HTTP transport (Fetch): The only function touching urllib.request. Unit tests pass an in-memory fake fetch(serial, timeout) so retries, timeouts, and out-of-order completions run in milliseconds.
    from typing import Callable, Optional, Tuple
    import http.client
    import urllib.error
    import urllib.parse
    import urllib.request
    
    Fetch = Callable[[str, float], Tuple[int, bytes]]
    
    
    def make_http_fetch(url_template: str) -> Fetch:
        """Build an HTTP GET transport from a configured URL template containing '{serial}'."""
        def fetch(serial: str, timeout: float) -> Tuple[int, bytes]:
            encoded_serial = urllib.parse.quote(serial, safe="")
            url = url_template.replace("{serial}", encoded_serial)
            try:
                try:
                    with urllib.request.urlopen(url, timeout=timeout) as response:
                        return response.status, response.read()
                except urllib.error.HTTPError as exc:
                    try:
                        return exc.code, exc.read()
                    finally:
                        exc.close()
            except urllib.error.URLError as exc:
                if isinstance(exc.reason, TimeoutError):
                    raise TimeoutError(str(exc.reason)) from exc
                raise ConnectionError(str(exc.reason)) from exc
            except http.client.HTTPException as exc:
                raise ConnectionError(repr(exc)) from exc
    
        return fetch
    
    
    def validate_serial(serial: str) -> Optional[str]:
        """Return an error reason if serial is obviously malformed, or None if safe to request."""
        if serial == "":
            return "empty serial number"
        if any(ch.isspace() or not ch.isprintable() for ch in serial):
            return "serial number contains whitespace or control characters"
        return None
    

    Notice four careful transport safeguards:

    • quote(serial, safe="") percent-encodes even / ("A/1" -> "A%2F1"), preventing path traversal or route changes.
    • HTTPError subclasses URLError, so an inner try catches HTTPError first, reads the response body, and closes its socket in finally. Keeping that inner try inside the outer try ensures that if reading a 500 error body hits a truncated http.client.IncompleteRead (HTTPException), the outer handler still converts it into a retryable ConnectionError!
    • Connect-phase timeouts arrive wrapped inside URLError.reason; unwrapping TimeoutError preserves distinct timeout classification.
  3. Classify single-request failures cleanly

    Different failure modes mean different things operationally and require different retry decisions:

    Failure symptom                       Classified type   Retry?   Reason
    ------------------------------------  ---------------   ------   ------------------------------------
    fetch() raises TimeoutError           "timeout"         Yes      Server or local queue temporarily slow
    fetch() raises other OSError          "connection"      Yes      Connection reset, refused, or dropped
    HTTP 429, 500, 502, 503, 504          "http"            Yes      Rate limit or transient server fault
    Other non-2xx HTTP (400, 401, 404)    "http"            No       Deterministic client/not-found answer
    2xx status with invalid JSON/UTF-8    "json"            No       Broken payload contract, not a blip
    

    In Python 3, TimeoutError is a subclass of OSError, so except TimeoutError must come before except OSError:

    from typing import Any, Dict
    import json
    
    
    def request_once(serial: str, fetch: Fetch, timeout: float) -> Tuple[Any, Optional[Dict[str, Any]]]:
        """Execute a single attempt and return (parsed_json, None) or (None, error_dict)."""
        try:
            status, body = fetch(serial, timeout)
        except TimeoutError as exc:
            return None, {"type": "timeout", "message": str(exc) or "request timed out"}
        except OSError as exc:
            return None, {"type": "connection", "message": str(exc) or type(exc).__name__}
    
        if not (200 <= status < 300):
            return None, {"type": "http", "status": status, "message": f"HTTP {status}"}
    
        try:
            return json.loads(body), None
        except ValueError as exc:
            return None, {"type": "json", "message": str(exc)}
    
  4. Add bounded retries with exponential backoff

    A serial lookup is an idempotent read — issuing the same GET request twice has the exact same effect on server state as issuing it once — which makes retrying transient glitches safe. We bound retries with:

    • A finite per-attempt timeout (default 5.0 s) and max_attempts cap (default 3 total tries).
    • Exponential backoff (backoff * 2 ** (attempts - 1): 0.5 s after try 1, 1.0 s after try 2) so a struggling local service gets breathing room instead of an instant retry storm.

    With the defaults, a dead serial takes at most 5.0 + 0.5 + 5.0 + 1.0 + 5.0 = 16.5 s before returning its structured error record. Injecting sleep as a parameter lets tests assert exact backoff delays in 0 ms!

    import time
    
    RETRYABLE_STATUSES = {429, 500, 502, 503, 504}
    
    
    def ok_record(serial: str, data: Any, attempts: int) -> Dict[str, Any]:
        """Build a standardized success record."""
        return {"serial": serial, "ok": True, "data": data, "attempts": attempts}
    
    
    def error_record(serial: str, error: Dict[str, Any], attempts: Optional[int]) -> Dict[str, Any]:
        """Build a standardized failure record."""
        return {"serial": serial, "ok": False, "error": error, "attempts": attempts}
    
    
    def is_retryable(error: Dict[str, Any]) -> bool:
        """Return True only for transient network/server failures on an idempotent lookup."""
        if error["type"] in ("timeout", "connection"):
            return True
        return error["type"] == "http" and error["status"] in RETRYABLE_STATUSES
    
    
    def lookup_serial(serial: str, fetch: Fetch, timeout: float = 5.0, max_attempts: int = 3,
                      backoff: float = 0.5, sleep: Callable[[float], None] = time.sleep) -> Dict[str, Any]:
        """Look up one serial with bounded retries and exponential backoff between attempts."""
        if max_attempts < 1:
            raise ValueError("max_attempts must be at least 1")
        attempts = 0
        while True:
            attempts += 1
            payload, error = request_once(serial, fetch, timeout)
            if error is None:
                return ok_record(serial, payload, attempts)
            if attempts >= max_attempts or not is_retryable(error):
                return error_record(serial, error, attempts)
            delay_seconds = backoff * (2 ** (attempts - 1))
            sleep(delay_seconds)
    
  5. Run concurrently while preserving input order

    Because socket I/O releases CPython's Global Interpreter Lock (GIL), a bounded ThreadPoolExecutor overlaps network wait times: 100 lookups taking 200 ms each drop from 100 × 0.2 s = 20.0 s sequentially to ⌈100 / 8⌉ × 0.2 s = 13 × 0.2 s = 2.6 s across 8 workers, without flooding the local service with 100 simultaneous sockets.

    Because fast serials finish before slow ones, we never .append() results in completion order. Instead, we keep two small lookup maps and a pre-sized results list:

    Input serials: ["SN-10", "bad id", "SN-20", "SN-10"]
      results   = [None, invalid_input_record, None, None]
      positions = {"SN-10": [0, 3], "SN-20": [2]}     (2 network calls for 4 inputs)
    
    Worker finishes "SN-20" first -> future_to_serial[f] == "SN-20" -> write slot 2
    Worker finishes "SN-10" next  -> future_to_serial[f] == "SN-10" -> write slots 0 and 3 (deep copy)
    Final results are in exact input order [0, 1, 2, 3]!
    
    from concurrent.futures import Future, ThreadPoolExecutor, as_completed
    from typing import List, Sequence
    import copy
    
    
    def run_lookups(serials: Sequence[str], fetch: Fetch, max_workers: int = 8, timeout: float = 5.0,
                    max_attempts: int = 3, backoff: float = 0.5,
                    sleep: Callable[[float], None] = time.sleep) -> List[Dict[str, Any]]:
        """Run bounded-concurrency lookups and return one record per input item in input order."""
        if max_workers < 1:
            raise ValueError("max_workers must be at least 1")
    
        results: List[Any] = [None] * len(serials)
        positions: Dict[str, List[int]] = {}
    
        for index, serial in enumerate(serials):
            problem = validate_serial(serial)
            if problem is not None:
                results[index] = error_record(serial, {"type": "invalid_input", "message": problem}, 0)
            elif serial in positions:
                positions[serial].append(index)
            else:
                positions[serial] = [index]
    
        pool = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="lookup")
        try:
            future_to_serial: Dict[Future, str] = {}
            for serial in positions:
                future = pool.submit(lookup_serial, serial, fetch, timeout, max_attempts, backoff, sleep)
                future_to_serial[future] = serial
    
            for future in as_completed(future_to_serial):
                serial = future_to_serial[future]
                try:
                    record = future.result()
                except Exception as exc:
                    record = error_record(serial, {"type": "internal", "message": repr(exc)}, None)
    
                indices = positions[serial]
                results[indices[0]] = record
                for dup_index in indices[1:]:
                    results[dup_index] = copy.deepcopy(record)
        finally:
            pool.shutdown(wait=True, cancel_futures=True)
    
        return results
    
  6. Handle pool shutdown, hung requests, and CLI exit codes

    Three operational details make the CLI safe in shell scripts and cron jobs:

    1. Pool cleanup (finally: pool.shutdown(wait=True, cancel_futures=True)): On normal completion all futures are already done. On KeyboardInterrupt (Ctrl-C, raised in the main thread), cancel_futures=True drops queued futures that have not started yet and wait=True waits cleanly for active worker threads to finish.
    2. Why finite timeouts prevent zombie hangs: Python cannot forcibly kill a blocked OS thread, and concurrent.futures joins non-daemon worker threads at interpreter exit. Without timeout=, one hung socket would prevent the CLI from ever exiting! With timeout=5.0 and max_attempts=3, a hung serial occupies one worker slot for at most 16.5 s.
    3. Visible partial failure: exit_status() returns 1 whenever any record has ok == False, so automation immediately detects partial outages while still receiving every successful JSON Line on stdout.
    from typing import TextIO
    import argparse
    import os
    import sys
    
    
    def exit_status(results: List[Dict[str, Any]]) -> int:
        """Return 0 when every record succeeded (including empty input), else 1."""
        for record in results:
            if not record["ok"]:
                return 1
        return 0
    
    
    def read_serials(stream: TextIO) -> List[str]:
        """Read one serial per line from stdin, stripping outer whitespace and skipping blank lines."""
        serials: List[str] = []
        for line in stream:
            cleaned = line.strip()
            if cleaned:
                serials.append(cleaned)
        return serials
    
    
    def parse_args(argv: Optional[Sequence[str]]) -> argparse.Namespace:
        """Parse CLI arguments and options."""
        parser = argparse.ArgumentParser(description="Look up serial numbers in the local service.")
        parser.add_argument("serials", nargs="*", help="serial numbers; read from stdin if omitted")
        parser.add_argument("--url-template", default=os.environ.get("SERIAL_LOOKUP_URL"),
                            help="service URL containing {serial} (default: $SERIAL_LOOKUP_URL)")
        parser.add_argument("--workers", type=int, default=8)
        parser.add_argument("--timeout", type=float, default=5.0, help="seconds per request attempt")
        parser.add_argument("--attempts", type=int, default=3, help="max attempts per serial")
        return parser.parse_args(argv)
    
    
    def main(argv: Optional[Sequence[str]] = None, fetch: Optional[Fetch] = None,
             stdin: Optional[TextIO] = None, stdout: Optional[TextIO] = None, stderr: Optional[TextIO] = None) -> int:
        """CLI entry point: parse inputs, execute lookups, emit JSON Lines on stdout, and return status."""
        if stdin is None:
            stdin = sys.stdin
        if stdout is None:
            stdout = sys.stdout
        if stderr is None:
            stderr = sys.stderr
    
        args = parse_args(argv)
        if args.workers < 1 or args.attempts < 1 or args.timeout <= 0:
            print("error: --workers and --attempts must be >= 1 and --timeout > 0", file=stderr)
            return 2
        if fetch is None:
            if not args.url_template or "{serial}" not in args.url_template:
                print("error: set --url-template or SERIAL_LOOKUP_URL to a URL containing {serial}", file=stderr)
                return 2
            fetch = make_http_fetch(args.url_template)
    
        serials = args.serials if args.serials else read_serials(stdin)
    
        try:
            results = run_lookups(serials, fetch, args.workers, args.timeout, args.attempts)
        except KeyboardInterrupt:
            print("interrupted", file=stderr)
            return 130
    
        failed_count = 0
        for record in results:
            stdout.write(json.dumps(record) + "\n")
            if not record["ok"]:
                failed_count += 1
        succeeded_count = len(results) - failed_count
        print(f"{succeeded_count} succeeded, {failed_count} failed", file=stderr)
        return exit_status(results)
    
  7. Trace a concurrent run with duplicates, timeouts, and 404s

    Trace input ["SN-10", "GPU-8", "GPU-9", "SN-10"] with max_workers=2, timeout=1.0, max_attempts=3, backoff=0.5, where "SN-10" returns 200 immediately, "GPU-8" always times out, and "GPU-9" returns 404:

    Deduplicated positions: {"SN-10": [0, 3], "GPU-8": [1], "GPU-9": [2]}   (3 futures submitted)
    
    Time    Worker 1                             Worker 2
    ------  -----------------------------------  -------------------------------------------
    t=0.0s  "SN-10" -> 200 OK (done -> [0, 3])   "GPU-8" attempt 1 starts...
    t=0.0s  "GPU-9" -> 404 (no retry -> [2])
    t=1.0s  (idle)                               "GPU-8" try 1 times out -> sleep 0.5s
    t=1.5s                                       "GPU-8" try 2 starts...
    t=2.5s                                       "GPU-8" try 2 times out -> sleep 1.0s
    t=3.5s                                       "GPU-8" try 3 starts...
    t=4.5s                                       "GPU-8" try 3 times out -> error at [1] (attempts=3)
    
    Completion order: "SN-10", "GPU-9", "GPU-8"
    Output order:     slot 0 ("SN-10"), slot 1 ("GPU-8"), slot 2 ("GPU-9"), slot 3 ("SN-10")
    stderr summary:   "2 succeeded, 2 failed"   |   exit code: 1
    
  8. Complete solution

    from typing import Any, Callable, Dict, List, Optional, Sequence, TextIO, Tuple
    import argparse
    import copy
    import http.client
    import json
    import os
    import sys
    import time
    import urllib.error
    import urllib.parse
    import urllib.request
    from concurrent.futures import Future, ThreadPoolExecutor, as_completed
    
    # Transport contract: fetch(serial, timeout_seconds) -> (http_status, body_bytes).
    # Raises TimeoutError on timeout and OSError (e.g. ConnectionError) on network/protocol failure.
    Fetch = Callable[[str, float], Tuple[int, bytes]]
    
    # Transient HTTP status codes safe to retry for an idempotent read lookup
    RETRYABLE_STATUSES = {429, 500, 502, 503, 504}
    
    
    def make_http_fetch(url_template: str) -> Fetch:
        """Build an HTTP GET transport from a configured URL template containing '{serial}'."""
        def fetch(serial: str, timeout: float) -> Tuple[int, bytes]:
            # Percent-encode every reserved character (including '/') so serial cannot alter the route
            encoded_serial = urllib.parse.quote(serial, safe="")
            url = url_template.replace("{serial}", encoded_serial)
            try:
                try:
                    with urllib.request.urlopen(url, timeout=timeout) as response:
                        return response.status, response.read()
                except urllib.error.HTTPError as exc:
                    # Non-2xx HTTP status is still a valid HTTP response; read body and always close socket
                    try:
                        return exc.code, exc.read()
                    finally:
                        exc.close()
            except urllib.error.URLError as exc:
                # urlopen wraps connect-time timeouts and DNS/refused errors inside URLError.reason
                if isinstance(exc.reason, TimeoutError):
                    raise TimeoutError(str(exc.reason)) from exc
                raise ConnectionError(str(exc.reason)) from exc
            except http.client.HTTPException as exc:
                # Truncated body (IncompleteRead) or malformed status line maps to ConnectionError
                raise ConnectionError(repr(exc)) from exc
    
        return fetch
    
    
    def validate_serial(serial: str) -> Optional[str]:
        """Return an error reason if serial is obviously malformed, or None if safe to request."""
        if serial == "":
            return "empty serial number"
        # Reject any whitespace or non-printable control character without inventing a vendor format
        if any(ch.isspace() or not ch.isprintable() for ch in serial):
            return "serial number contains whitespace or control characters"
        return None
    
    
    def ok_record(serial: str, data: Any, attempts: int) -> Dict[str, Any]:
        """Build a standardized success record."""
        return {"serial": serial, "ok": True, "data": data, "attempts": attempts}
    
    
    def error_record(serial: str, error: Dict[str, Any], attempts: Optional[int]) -> Dict[str, Any]:
        """Build a standardized failure record."""
        return {"serial": serial, "ok": False, "error": error, "attempts": attempts}
    
    
    def request_once(serial: str, fetch: Fetch, timeout: float) -> Tuple[Any, Optional[Dict[str, Any]]]:
        """Execute a single attempt and return (parsed_json, None) or (None, error_dict)."""
        try:
            status, body = fetch(serial, timeout)
        except TimeoutError as exc:
            # Must precede OSError because TimeoutError is a subclass of OSError in Python 3
            return None, {"type": "timeout", "message": str(exc) or "request timed out"}
        except OSError as exc:
            return None, {"type": "connection", "message": str(exc) or type(exc).__name__}
    
        if not (200 <= status < 300):
            return None, {"type": "http", "status": status, "message": f"HTTP {status}"}
    
        try:
            return json.loads(body), None
        except ValueError as exc:
            # Catches both json.JSONDecodeError and UnicodeDecodeError (both inherit from ValueError)
            return None, {"type": "json", "message": str(exc)}
    
    
    def is_retryable(error: Dict[str, Any]) -> bool:
        """Return True only for transient network/server failures on an idempotent lookup."""
        if error["type"] in ("timeout", "connection"):
            return True
        return error["type"] == "http" and error["status"] in RETRYABLE_STATUSES
    
    
    def lookup_serial(serial: str, fetch: Fetch, timeout: float = 5.0, max_attempts: int = 3,
                      backoff: float = 0.5, sleep: Callable[[float], None] = time.sleep) -> Dict[str, Any]:
        """Look up one serial with bounded retries and exponential backoff between attempts."""
        if max_attempts < 1:
            raise ValueError("max_attempts must be at least 1")
        attempts = 0
        while True:
            attempts += 1
            payload, error = request_once(serial, fetch, timeout)
            if error is None:
                return ok_record(serial, payload, attempts)
            if attempts >= max_attempts or not is_retryable(error):
                return error_record(serial, error, attempts)
            # Exponential backoff: backoff, 2 * backoff, 4 * backoff, ...
            delay_seconds = backoff * (2 ** (attempts - 1))
            sleep(delay_seconds)
    
    
    def run_lookups(serials: Sequence[str], fetch: Fetch, max_workers: int = 8, timeout: float = 5.0,
                    max_attempts: int = 3, backoff: float = 0.5,
                    sleep: Callable[[float], None] = time.sleep) -> List[Dict[str, Any]]:
        """Run bounded-concurrency lookups and return one record per input item in input order."""
        if max_workers < 1:
            raise ValueError("max_workers must be at least 1")
    
        # Pre-allocate one output slot per input item so out-of-order completions land at their input index
        results: List[Any] = [None] * len(serials)
        # positions: maps each distinct valid serial -> list of input indices where it appeared
        positions: Dict[str, List[int]] = {}
    
        # Phase 1: validate inputs locally and collapse duplicate valid serials into one request
        for index, serial in enumerate(serials):
            problem = validate_serial(serial)
            if problem is not None:
                results[index] = error_record(serial, {"type": "invalid_input", "message": problem}, 0)
            elif serial in positions:
                positions[serial].append(index)
            else:
                positions[serial] = [index]
    
        # Phase 2: submit one future per distinct valid serial and collect results as they finish
        pool = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="lookup")
        try:
            # future_to_serial: maps each running Future -> the serial string it is fetching
            future_to_serial: Dict[Future, str] = {}
            for serial in positions:
                future = pool.submit(lookup_serial, serial, fetch, timeout, max_attempts, backoff, sleep)
                future_to_serial[future] = serial
    
            for future in as_completed(future_to_serial):
                serial = future_to_serial[future]
                try:
                    record = future.result()
                except Exception as exc:
                    # Isolate unexpected worker bugs so other serials' results are never lost
                    record = error_record(serial, {"type": "internal", "message": repr(exc)}, None)
    
                indices = positions[serial]
                results[indices[0]] = record
                # Give duplicate positions independent deep copies so caller edits never alias
                for dup_index in indices[1:]:
                    results[dup_index] = copy.deepcopy(record)
        finally:
            # Cancel not-yet-started futures on interruption and wait cleanly for active workers
            pool.shutdown(wait=True, cancel_futures=True)
    
        return results
    
    
    def exit_status(results: List[Dict[str, Any]]) -> int:
        """Return 0 when every record succeeded (including empty input), else 1."""
        for record in results:
            if not record["ok"]:
                return 1
        return 0
    
    
    def read_serials(stream: TextIO) -> List[str]:
        """Read one serial per line from stdin, stripping outer whitespace and skipping blank lines."""
        serials: List[str] = []
        for line in stream:
            cleaned = line.strip()
            if cleaned:
                serials.append(cleaned)
        return serials
    
    
    def parse_args(argv: Optional[Sequence[str]]) -> argparse.Namespace:
        """Parse CLI arguments and options."""
        parser = argparse.ArgumentParser(description="Look up serial numbers in the local service.")
        parser.add_argument("serials", nargs="*", help="serial numbers; read from stdin if omitted")
        parser.add_argument("--url-template", default=os.environ.get("SERIAL_LOOKUP_URL"),
                            help="service URL containing {serial} (default: $SERIAL_LOOKUP_URL)")
        parser.add_argument("--workers", type=int, default=8)
        parser.add_argument("--timeout", type=float, default=5.0, help="seconds per request attempt")
        parser.add_argument("--attempts", type=int, default=3, help="max attempts per serial")
        return parser.parse_args(argv)
    
    
    def main(argv: Optional[Sequence[str]] = None, fetch: Optional[Fetch] = None,
             stdin: Optional[TextIO] = None, stdout: Optional[TextIO] = None, stderr: Optional[TextIO] = None) -> int:
        """CLI entry point: parse inputs, execute lookups, emit JSON Lines on stdout, and return status."""
        if stdin is None:
            stdin = sys.stdin
        if stdout is None:
            stdout = sys.stdout
        if stderr is None:
            stderr = sys.stderr
    
        args = parse_args(argv)
        if args.workers < 1 or args.attempts < 1 or args.timeout <= 0:
            print("error: --workers and --attempts must be >= 1 and --timeout > 0", file=stderr)
            return 2
        if fetch is None:
            if not args.url_template or "{serial}" not in args.url_template:
                print("error: set --url-template or SERIAL_LOOKUP_URL to a URL containing {serial}", file=stderr)
                return 2
            fetch = make_http_fetch(args.url_template)
    
        serials = args.serials if args.serials else read_serials(stdin)
    
        try:
            results = run_lookups(serials, fetch, args.workers, args.timeout, args.attempts)
        except KeyboardInterrupt:
            print("interrupted", file=stderr)
            return 130
    
        # Write machine-readable JSON Lines to stdout and human summary to stderr
        failed_count = 0
        for record in results:
            stdout.write(json.dumps(record) + "\n")
            if not record["ok"]:
                failed_count += 1
        succeeded_count = len(results) - failed_count
        print(f"{succeeded_count} succeeded, {failed_count} failed", file=stderr)
        return exit_status(results)
    
    
    if __name__ == "__main__":
        sys.exit(main())
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of looking up serial numbers concurrently like running a takeout counter with 8 kitchen staff (a bounded thread pool). Instead of making customers wait single-file while one slow order blocks the whole line, up to 8 staff prepare orders in parallel, and every ticket carries its original tray slot number. Fast orders finish ahead of slow ones, so each finished dish is placed onto its numbered slot on the counter rather than shoved onto the end of a pile — ensuring the final delivery matches the exact order requested.

Naive scripts fail in three ways: issuing requests one by one wastes almost 100% of wall-clock time waiting on sockets; spawning an unbounded thread per item (10,000 threads for 10,000 serials) overwhelms a local service and exhausts file descriptors; and appending results as futures finish scrambles output order or aborts the entire batch when one item returns HTTP 500 or invalid JSON.

Trace 4 inputs, ["SN-10", "SN-20", "SN-10", "bad id"], across 2 workers:

  1. Validate & deduplicate: "bad id" has a space, so slot 3 immediately gets an invalid_input error (attempts: 0); "SN-10" maps to slots [0, 2] and "SN-20" maps to [1], needing only 2 network requests.
  2. Submit & race: Worker 1 fetches "SN-10" (slow, 120 ms) while Worker 2 fetches "SN-20" (fast, 10 ms).
  3. Out-of-order completion, in-order placement: "SN-20" finishes first and writes slot 1; "SN-10" finishes second and fills slots 0 and 2 (as independent copies).
  4. Report: stdout prints slots 0, 1, 2, 3 in exact input order, stderr logs 3 succeeded, 1 failed, and the CLI exits with status 1 because one item failed.

Complexity

Let n be the total number of input serials, d the number of distinct valid serials (d <= n), w the worker pool size (max_workers), and t the average latency of one request.

  • Wall-clock time — roughly O(n + ceil(d / w) · t): Scanning and validating the n inputs takes O(n) CPU work, after which w threads overlap socket waits to complete d distinct lookups in roughly ceil(d / w) waves (for example, d = 100, w = 8, t = 0.2 s takes 13 × 0.2 s = 2.6 s instead of 20.0 s sequentially), bounded below by the slowest retrying serial (at most 3 × 5.0 + 0.5 + 1.0 = 16.5 s under defaults).
  • Space — O(n): Pre-allocating results and storing input index lists in positions takes O(n) slots, while future_to_serial holds d <= n Future objects (see Follow-up 1 for streaming millions of items in O(w) memory).
  • Service load — at most w concurrent requests and max_attempts · d total requests: Duplicate inputs share one lookup, and permanent errors (404, malformed JSON) stop after 1 attempt.

Edge cases

  • Empty input ([] or blank stdin): Makes zero HTTP calls, prints zero JSON Lines to stdout, writes 0 succeeded, 0 failed to stderr, and returns exit status 0.
  • Duplicate serials: Requested once over the network, then deep-copied into each matching slot so mutating one output dict never mutates its duplicate.
  • Invalid serial strings: Empty strings, spaces, tabs, or control characters fail locally as invalid_input with attempts: 0 without touching the network.
  • URL-special characters (/, ?, #, %): urllib.parse.quote(serial, safe="") percent-encodes reserved characters so "A/1" requests .../A%2F1 instead of changing the URL route.
  • Truncated bodies and socket cleanup on HTTP errors: Non-2xx HTTPError responses explicitly close their underlying socket in finally, and mid-body disconnects (http.client.IncompleteRead) are normalized to ConnectionError so transient server crashes still retry cleanly.
  • Valid JSON null vs empty 204 body: b"null" parses as valid JSON (data: None, ok: True), whereas an empty b"" body fails json.loads and is classified under type: "json".
  • Unexpected bug inside fetch: Caught per future in run_lookups and recorded as type: "internal" (attempts: None), preserving every other serial's result.

Common mistakes

  • Appending results inside for future in as_completed(...): Emits records in completion order rather than input order, corrupting positional correspondence.
  • Catching OSError before TimeoutError: Because TimeoutError inherits from OSError, putting except OSError first makes the timeout handler unreachable dead code.
  • Omitting timeout= on socket calls: Leaves hung requests blocking worker threads forever, preventing the Python process from exiting when ThreadPoolExecutor joins its threads.
  • Retrying deterministic failures (400, 404, invalid JSON) or retrying without a cap: Wastes 1.5 s+ of backoff per bad serial and multiplies load on an already unhealthy service.
  • Letting one failed future.result() crash the loop: Calling [f.result() for f in futures] without per-item try/except discards all successful lookups whenever a single item raises.
  • Returning exit code 0 on partial failure or printing status chatter to stdout: Hides outages from calling shell pipelines and corrupts machine-parsed JSON Lines output.

Alternative approaches

  • asyncio + aiohttp/httpx with asyncio.Semaphore(w): Runs thousands of concurrent I/O-bound lookups on a single OS thread with lower per-task memory overhead than threads, at the cost of requiring async-compatible libraries end to end.
  • Persistent HTTP keep-alive session (urllib3.PoolManager or httpx.Client): Standard urllib.request.urlopen opens a fresh TCP connection per request (Connection: close); reusing pooled keep-alive sockets across worker threads eliminates repeated TCP/TLS handshakes against a local service.

Follow-up questions

  • How can you bound memory usage so millions of input serials do not queue millions of Future objects at once? Stream stdin lazily and maintain a sliding window of at most W in-flight or buffered items (for example, W = 4 * max_workers) paired with a small reorder_buffer: Dict[int, Dict] and a next_to_write cursor. Whenever submitted - next_to_write >= W, pause reading stdin and call concurrent.futures.wait(pending, return_when=FIRST_COMPLETED), moving finished records into reorder_buffer[idx] and flushing contiguous next_to_write entries to stdout so memory stays O(W) even for 10,000,000 serials (at the minor trade-off of deduplicating only repeats that fall within the active window).
  • Under what conditions is retrying a 500 response safe, and what mechanism do you need when requests mutate server state? Retrying an HTTP 500 or timeout is automatically safe only when the operation is idempotent — meaning executing it multiple times produces the exact same server state as executing it once, as a pure read (GET) lookup should. If the endpoint mutates state (such as charging a card, reserving hardware, or appending an event), a 500 or timeout leaves it ambiguous whether the server committed the write before failing, so safe retries require an idempotency key (a unique client-generated UUID per logical operation that the server deduplicates), a read-your-writes status check, or an explicit server contract guaranteeing rollback before 500.
  • How should the CLI behave when SIGINT arrives partway through a batch with workers still in flight? When Ctrl-C delivers SIGINT, Python raises KeyboardInterrupt in the main thread while worker threads keep executing their current call. A resilient CLI stops submitting new work, calls pool.shutdown(wait=True, cancel_futures=True) to cancel queued futures, passes a shared threading.Event (stop_event) checked before retry sleeps so active workers abort remaining retries promptly (using stop_event.wait(delay) instead of time.sleep(delay)), optionally emits completed records plus "cancelled" error records for unfinished slots if partial output is desired, and exits with code 130.

Follow-up questions

Similar questions

More Coreweave interview questions

All 14 Coreweave questions →