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]]:
-
HTTP transport (
make_http_fetch(url_template: str) -> Fetch):- Return
fetch(serial, timeout)that percent-encodesserialwithsafe=""(so/and reserved characters cannot alter the route), substitutes{serial}intourl_template, and performs an HTTPGETbounded bytimeoutseconds. - Return
(http_status, body_bytes)for both2xxand non-2xxHTTP responses, closing sockets cleanly on HTTP errors. - Raise
TimeoutErroron socket or connect timeouts, and raiseConnectionError(anOSErrorsubclass) on network failures or truncated HTTP bodies (http.client.HTTPException).
- Return
-
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](ValueErrorifmax_attempts < 1). - Return standardized records:
- Success (
2xxwith valid JSON):{"serial": serial, "ok": True, "data": <parsed_json>, "attempts": n} - Failure:
{"serial": serial, "ok": False, "error": <error_dict>, "attempts": n}
- Success (
- Error classifications in
error["type"]:"timeout":fetchraisedTimeoutError."connection":fetchraised anotherOSError."http": non-2xxstatus code (include"status": <int>inerror)."json":2xxstatus 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 tomax_attemptstotal tries, callingsleep(backoff * (2 ** (attempt - 1)))before tryattempt + 1. Stop after1attempt on deterministic failures (404,"json", etc.).
- Signature:
-
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]](ValueErrorifmax_workers < 1). - Validate inputs locally: empty strings (
"") or strings containing whitespace or non-printable characters fail immediately witherror["type"] == "invalid_input"andattempts == 0without callingfetch. - Deduplicate valid serials so each distinct valid serial triggers one concurrent
lookup_serialtask on aThreadPoolExecutor(max_workers=max_workers)(shut down cleanly infinally), catching unexpected non-OSErrorworker exceptions aserror["type"] == "internal"(attempts: None). - Return one independent dictionary per input occurrence (deep-copying shared results across duplicate positions) in exact input order.
- Signature:
-
Exit policy and CLI (
exit_statusandmain):exit_status(results)returns0when all records haveok == True(including[]), otherwise1.main(argv=None, fetch=None, stdin=None, stdout=None, stderr=None) -> intreads positionalserials(orstdinline by line, stripping outer whitespace and skipping blank lines), supports--url-template(default$SERIAL_LOOKUP_URL),--workers(8),--timeout(5.0), and--attempts(3), returns2on invalid flags or missing{serial}template, returns130onKeyboardInterrupt, writes one JSON object per line (JSON Lines) tostdout, prints"<succeeded> succeeded, <failed> failed"tostderr, and returnsexit_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 >= 1andmax_attempts >= 1(ValueErrorotherwise in library calls; exit code2inmainwhen--workers < 1,--attempts < 1, or--timeout <= 0).- At most
max_workerscalls tofetchmay execute concurrently, and each distinct valid serial in a batch is requested at most once (up tomax_attemptstries on transient errors). - Duplicate input positions must receive distinct dictionary objects (mutating
results[i]must not mutateresults[j]). - Standard library only (
urllib.request,concurrent.futures,json,argparse).
Step-by-step walkthrough
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-templateor$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) onstdout, while sending human summaries and diagnostics tostderrso downstreamjqor 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:
0if all records succeed (including empty input),1if one or more records fail,2for invalid CLI flags/missing URL configuration, and130(128 + SIGINT) onCtrl-C.
- Configurable endpoint (no invented URLs): Accept a URL template containing
Separate CLI, lookup logic, and HTTP transport
Splitting the program into three decoupled layers keeps every rule deterministic and fast to test:
- CLI shell (
parse_args,read_serials,main): Parses flags, readsstdin, formatsstdout/stderr, and maps results to an OS exit code. - 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. - Injected HTTP transport (
Fetch): The only function touchingurllib.request. Unit tests pass an in-memory fakefetch(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 NoneNotice four careful transport safeguards:
quote(serial, safe="")percent-encodes even/("A/1" -> "A%2F1"), preventing path traversal or route changes.HTTPErrorsubclassesURLError, so an innertrycatchesHTTPErrorfirst, reads the response body, and closes its socket infinally. Keeping that innertryinside the outertryensures that if reading a500error body hits a truncatedhttp.client.IncompleteRead(HTTPException), the outer handler still converts it into a retryableConnectionError!- Connect-phase timeouts arrive wrapped inside
URLError.reason; unwrappingTimeoutErrorpreserves distinct timeout classification.
- CLI shell (
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 blipIn Python 3,
TimeoutErroris a subclass ofOSError, soexcept TimeoutErrormust come beforeexcept 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)}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(default5.0 s) andmax_attemptscap (default3total tries). - Exponential backoff (
backoff * 2 ** (attempts - 1):0.5 safter try 1,1.0 safter 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 sbefore returning its structured error record. Injectingsleepas a parameter lets tests assert exact backoff delays in0 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)- A finite per-attempt
Run concurrently while preserving input order
Because socket I/O releases CPython's Global Interpreter Lock (GIL), a bounded
ThreadPoolExecutoroverlaps network wait times:100lookups taking200 mseach drop from100 × 0.2 s = 20.0 ssequentially to⌈100 / 8⌉ × 0.2 s = 13 × 0.2 s = 2.6 sacross8workers, without flooding the local service with100simultaneous 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-sizedresultslist: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 resultsHandle pool shutdown, hung requests, and CLI exit codes
Three operational details make the CLI safe in shell scripts and cron jobs:
- Pool cleanup (
finally: pool.shutdown(wait=True, cancel_futures=True)): On normal completion all futures are already done. OnKeyboardInterrupt(Ctrl-C, raised in the main thread),cancel_futures=Truedrops queued futures that have not started yet andwait=Truewaits cleanly for active worker threads to finish. - Why finite timeouts prevent zombie hangs: Python cannot forcibly kill a blocked OS thread, and
concurrent.futuresjoins non-daemon worker threads at interpreter exit. Withouttimeout=, one hung socket would prevent the CLI from ever exiting! Withtimeout=5.0andmax_attempts=3, a hung serial occupies one worker slot for at most16.5 s. - Visible partial failure:
exit_status()returns1whenever any record hasok == False, so automation immediately detects partial outages while still receiving every successful JSON Line onstdout.
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)- Pool cleanup (
Trace a concurrent run with duplicates, timeouts, and 404s
Trace input
["SN-10", "GPU-8", "GPU-9", "SN-10"]withmax_workers=2,timeout=1.0,max_attempts=3,backoff=0.5, where"SN-10"returns200immediately,"GPU-8"always times out, and"GPU-9"returns404: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: 1Complete 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:
- Validate & deduplicate:
"bad id"has a space, so slot3immediately gets aninvalid_inputerror (attempts: 0);"SN-10"maps to slots[0, 2]and"SN-20"maps to[1], needing only 2 network requests. - Submit & race: Worker 1 fetches
"SN-10"(slow,120 ms) while Worker 2 fetches"SN-20"(fast,10 ms). - Out-of-order completion, in-order placement:
"SN-20"finishes first and writes slot1;"SN-10"finishes second and fills slots0and2(as independent copies). - Report:
stdoutprints slots0, 1, 2, 3in exact input order,stderrlogs3 succeeded, 1 failed, and the CLI exits with status1because 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 theninputs takesO(n)CPU work, after whichwthreads overlap socket waits to completeddistinct lookups in roughlyceil(d / w)waves (for example,d = 100,w = 8,t = 0.2 stakes13 × 0.2 s = 2.6 sinstead of20.0 ssequentially), bounded below by the slowest retrying serial (at most3 × 5.0 + 0.5 + 1.0 = 16.5 sunder defaults). - Space —
O(n): Pre-allocatingresultsand storing input index lists inpositionstakesO(n)slots, whilefuture_to_serialholdsd <= nFutureobjects (see Follow-up 1 for streaming millions of items inO(w)memory). - Service load — at most
wconcurrent requests andmax_attempts · dtotal requests: Duplicate inputs share one lookup, and permanent errors (404, malformed JSON) stop after1attempt.
Edge cases
- Empty input (
[]or blankstdin): Makes zero HTTP calls, prints zero JSON Lines tostdout, writes0 succeeded, 0 failedtostderr, and returns exit status0. - 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_inputwithattempts: 0without touching the network. - URL-special characters (
/,?,#,%):urllib.parse.quote(serial, safe="")percent-encodes reserved characters so"A/1"requests.../A%2F1instead of changing the URL route. - Truncated bodies and socket cleanup on HTTP errors: Non-2xx
HTTPErrorresponses explicitly close their underlying socket infinally, and mid-body disconnects (http.client.IncompleteRead) are normalized toConnectionErrorso transient server crashes still retry cleanly. - Valid JSON
nullvs empty204body:b"null"parses as valid JSON (data: None,ok: True), whereas an emptyb""body failsjson.loadsand is classified undertype: "json". - Unexpected bug inside
fetch: Caught per future inrun_lookupsand recorded astype: "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
OSErrorbeforeTimeoutError: BecauseTimeoutErrorinherits fromOSError, puttingexcept OSErrorfirst 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 whenThreadPoolExecutorjoins its threads. - Retrying deterministic failures (
400,404, invalid JSON) or retrying without a cap: Wastes1.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-itemtry/exceptdiscards all successful lookups whenever a single item raises. - Returning exit code
0on partial failure or printing status chatter tostdout: Hides outages from calling shell pipelines and corrupts machine-parsed JSON Lines output.
Alternative approaches
asyncio+aiohttp/httpxwithasyncio.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.PoolManagerorhttpx.Client): Standardurllib.request.urlopenopens 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
stdinlazily and maintain a sliding window of at mostWin-flight or buffered items (for example,W = 4 * max_workers) paired with a smallreorder_buffer: Dict[int, Dict]and anext_to_writecursor. Wheneversubmitted - next_to_write >= W, pause readingstdinand callconcurrent.futures.wait(pending, return_when=FIRST_COMPLETED), moving finished records intoreorder_buffer[idx]and flushing contiguousnext_to_writeentries tostdoutso memory staysO(W)even for10,000,000serials (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
500or 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), a500or 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 before500. - How should the CLI behave when SIGINT arrives partway through a batch with workers still in flight? When
Ctrl-CdeliversSIGINT, Python raisesKeyboardInterruptin the main thread while worker threads keep executing their current call. A resilient CLI stops submitting new work, callspool.shutdown(wait=True, cancel_futures=True)to cancel queued futures, passes a sharedthreading.Event(stop_event) checked before retry sleeps so active workers abort remaining retries promptly (usingstop_event.wait(delay)instead oftime.sleep(delay)), optionally emits completed records plus"cancelled"error records for unfinished slots if partial output is desired, and exits with code130.
Follow-up questions
- How can you bound memory usage so millions of input serials do not queue millions of Future objects at once?
- Under what conditions is retrying a 500 response safe, and what mechanism do you need when requests mutate server state?
- How should the CLI behave when SIGINT arrives partway through a batch with workers still in flight?
Similar questions
- Resilient OAuth API Record Migration Client
- Bounded Worker Threads and Linux Thread Diagnostics
- Composable Record Filter with Boolean Predicate Trees
- Resource Tree Queries Using BFS and DFS
- Composable Boolean Predicate Filter Trees
- Design a Human-in-the-Loop Task Routing Platform
More Coreweave interview questions
- Bounded Worker Threads and Linux Thread Diagnostics Medium
- High-Throughput Notification Platform for Million-Write Bursts Medium
- Strongly Consistent PostgreSQL Storage for Fleet Health Checks Medium Pro
- Defending a Custom Build Over Off-the-Shelf Tools Medium Pro
- Resilient OAuth API Record Migration Client Medium Pro
- Design a Rolling Fleet Reboot Orchestrator Medium Pro
- Resource Tree Queries Using BFS and DFS Medium Pro
- Design a Human-in-the-Loop Task Routing Platform Medium Pro
- Global Synthetic Uptime Monitoring Platform Medium Pro
- Composable Record Filter with Boolean Predicate Trees Medium Pro