Build a Token-Auth Fetch-and-Upsert CLI Pipeline
System DesignModel answerLast updated
Design a layered CLI tool that calls a bearer-token API, validates JSON into records, and idempotently upserts them into a relational table.
Context
A downstream reporting job needs data that lives behind an HTTP API. The API requires a bearer token, returns a JSON payload containing a list of items (each with an id, a timestamp, and a free-text message), and the job must land those items in a relational table so that later queries can run against them. The tool runs on a schedule, so it will be invoked repeatedly against overlapping data.
What you must produce
A command-line program that:
- Calls the API. Issue an HTTP(S) request to a URL supplied at runtime, sending the token in an
Authorization: Bearer <token>header. - Parses the payload. Decode the JSON body and turn each element into a validated in-memory record. The payload may be a bare list or an object wrapping the list under an
itemskey. Timestamps may arrive as ISO-8601 strings or as epoch numbers. - Persists the records. Write them to a relational table (
id,ts,message) using a connection string from configuration. Re-running the tool must not create duplicate rows, and an older timestamp must never clobber a newer one already stored. - Fails loudly but predictably. Distinguish network/timeout failures, auth rejections, other non-2xx responses, malformed bodies, and database failures — each with a clear log message and a distinct exit code so schedulers can tell them apart.
- Takes its inputs from the environment. URL, token, and DB credentials are configurable; the token must not be passed as a visible command-line argument.
Constraints and edge cases to address
- Empty item list is a success, not an error.
- A 200 response whose body is HTML or otherwise not JSON.
- Items missing
id, with a null/blankid, with an unparseable timestamp, or that are not objects at all. - The same
idappearing twice inside one response. - Retries must only apply to requests that are safe to repeat.
- Non-ASCII message text must round-trip intact.
- Entire-batch atomicity: a mid-batch DB failure leaves no partial writes.
Deliverable
Explain your layering, configuration strategy, retry and idempotency decisions, and testing approach, and give working code for the pipeline.
Hints
Hint 1
Split into three collaborators — an HTTP client, a pure parsing function, and a repository — and let `main` only do wiring plus exception-to-exit-code mapping. Each piece then gets tested without the other two.
Hint 2
Make the write an upsert keyed on the primary key, and add a guard so an incoming row only overwrites the stored row when its timestamp is at least as new. Also dedupe within the batch first, since some databases reject touching the same key twice in one statement.
Hint 3
The token belongs in an environment variable (sourced from a secret store), never in argv — arguments end up in shell history and process listings. Never log the token or the full connection string either.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Structure: three layers plus wiring
I keep the pipeline as ApiClient → parse_items → Repository, with main() doing nothing but configuration, orchestration, and error mapping. Each layer raises one dedicated exception type (FetchError, ParseError, StoreError), and main maps each to a log line and its own exit code (e.g. 2 fetch, 3 parse, 4 store). That way a scheduler can alert differently on "token expired" versus "database down".
HTTP layer. ApiClient owns a requests.Session, sets Authorization: Bearer <token> and Accept: application/json once on the session so every request carries them, and configures explicit connect/read timeouts — without them a hung connection stalls the job indefinitely. Retries use exponential backoff on 429 and 5xx only, and only for GET, since a GET is safe to repeat; other 4xx codes fail immediately because repeating them cannot help. 401/403 get a specific message ("check the token") because a rotated credential is by far the most common operational failure. urllib3's exhausted-retry error surfaces as a RequestException subclass, so one except covers both timeout and retry exhaustion. Status codes are checked before JSON decoding, so an HTML error page served as a 200 is caught by the decode step and reported as a parse problem.
Parsing layer. parse_items is a pure function: untrusted JSON in, validated immutable records out. If the envelope itself is wrong (not a list and not an object with a list under items), it raises ParseError and aborts — a wrong contract should not be half-processed. Individual bad items are different: a missing or blank id, a non-object element, or an untimestampable value is logged with its index and skipped, so one malformed element doesn't discard a thousand good ones. Timestamps are normalized to timezone-aware UTC — epoch numbers via fromtimestamp(..., tz=utc), strings via fromisoformat after rewriting a trailing Z, and naive datetimes are stamped as UTC. Finally the parser dedupes by id in a dict, keeping the newest timestamp; this is required, not cosmetic, because an upsert statement that touches the same primary key twice in one shot is rejected by Postgres (ON CONFLICT DO UPDATE command cannot affect row a second time).
DB layer. The table is items(id TEXT PRIMARY KEY, ts TIMESTAMPTZ, message TEXT) — TEXT keeps UTF-8 messages safe. Writes go through execute_values in pages of ~500 rows using INSERT ... ON CONFLICT (id) DO UPDATE SET ts = EXCLUDED.ts, message = EXCLUDED.message WHERE items.ts <= EXCLUDED.ts. The WHERE guard makes the write monotone: replaying an old page never regresses a row. The whole batch runs inside one transaction (with conn:), so a constraint violation or dropped connection rolls everything back — no half-loaded state that a later run would have to reason about.
Configuration. Flags with environment fallbacks: --url/FETCH_URL, --dsn/DATABASE_URL. The token is read only from an environment variable (API_TOKEN, with --token-env to name a different variable) — arguments leak into shell history and ps output. In deployment the variable is injected from a secret manager. Logging includes the URL host and row counts but never the token or the full DSN.
Complexity
Parsing and dedupe are O(n) time and O(n) space in the response size. The upsert is roughly O(n log N) for index lookups against N existing rows, sent as n/500 round trips. For very large feeds, follow a pagination cursor and commit one page per transaction, bounding memory to the page size.
Testing
Unit tests use a fake session object (or responses/requests-mock) to cover: success, 401, 500-then-200 retry, timeout, HTML body, wrong envelope, duplicate ids in one batch, and epoch-vs-ISO timestamps. Parser tests are pure and fast; no network. Repository tests run against a throwaway Postgres (testcontainers or a docker-compose service) and assert three behaviors: replaying the same batch is a no-op, an older row does not overwrite a newer one, and a forced failure mid-batch leaves the table untouched. One end-to-end test wires all three layers against a stubbed API and the test database.
Common mistakes
Passing the token as a CLI flag; omitting timeouts; retrying non-idempotent or 4xx requests; letting one bad item kill the batch — or the opposite, silently swallowing errors so the job reports success; using INSERT without a conflict clause and relying on the DB to reject duplicates loudly; skipping in-batch dedupe and hitting the "cannot affect row a second time" error; committing per row instead of per batch; and logging the connection string, which typically embeds the password.
#!/usr/bin/env python3
import argparse, logging, os, sys
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any
import psycopg2, requests
from psycopg2.extras import execute_values
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
log = logging.getLogger("fetch_store")
class FetchError(Exception): pass
class ParseError(Exception): pass
class StoreError(Exception): pass
@dataclass(frozen=True)
class Record:
id: str
ts: datetime
message: str
class ApiClient:
def __init__(self, token, timeout=(3.05, 15), retries=3, session=None):
self.session = session or requests.Session()
retry = Retry(total=retries, backoff_factor=0.5,
status_forcelist=(429, 500, 502, 503, 504),
allowed_methods=frozenset({"GET"}))
adapter = HTTPAdapter(max_retries=retry)
self.session.mount("https://", adapter)
self.session.mount("http://", adapter)
self.session.headers.update({"Authorization": f"Bearer {token}",
"Accept": "application/json"})
self.timeout = timeout
def fetch(self, url):
try:
r = self.session.get(url, timeout=self.timeout)
except requests.RequestException as e:
raise FetchError(f"GET {url} failed: {e}") from e
if r.status_code in (401, 403):
raise FetchError(f"auth rejected (HTTP {r.status_code}); check the token")
if not r.ok:
raise FetchError(f"HTTP {r.status_code}: {r.text[:200]!r}")
try:
return r.json()
except ValueError as e:
raise ParseError(f"body is not valid JSON: {e}") from e
def parse_ts(v):
if isinstance(v, (int, float)) and not isinstance(v, bool):
return datetime.fromtimestamp(v, tz=timezone.utc)
if isinstance(v, str):
dt = datetime.fromisoformat(v.replace("Z", "+00:00"))
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
raise ValueError(f"bad timestamp {v!r}")
def parse_items(payload):
items = payload.get("items") if isinstance(payload, dict) else payload
if not isinstance(items, list):
raise ParseError("expected a list or {'items': [...]}")
latest = {}
for i, raw in enumerate(items):
try:
rid = raw["id"]
if rid is None or rid == "" or isinstance(rid, bool):
raise ValueError("empty id")
rec = Record(str(rid), parse_ts(raw["timestamp"]), str(raw.get("message") or ""))
except (KeyError, TypeError, ValueError, AttributeError) as e:
log.warning("skipping item %d: %s", i, e)
continue
prev = latest.get(rec.id)
if prev is None or rec.ts >= prev.ts:
latest[rec.id] = rec
return list(latest.values())
DDL = """CREATE TABLE IF NOT EXISTS items (
id TEXT PRIMARY KEY, ts TIMESTAMPTZ NOT NULL, message TEXT)"""
UPSERT = """
INSERT INTO items (id, ts, message) VALUES %s
ON CONFLICT (id) DO UPDATE SET ts = EXCLUDED.ts, message = EXCLUDED.message
WHERE items.ts <= EXCLUDED.ts
"""
class Repository:
def __init__(self, conn, page=500):
self.conn, self.page = conn, page
def save(self, records):
try:
with self.conn, self.conn.cursor() as cur:
cur.execute(DDL)
rows = [(r.id, r.ts, r.message) for r in records]
for i in range(0, len(rows), self.page):
execute_values(cur, UPSERT, rows[i:i + self.page])
except psycopg2.Error as e:
raise StoreError(f"database write failed: {e}") from e
def main(argv=None):
p = argparse.ArgumentParser()
p.add_argument("--url", default=os.environ.get("FETCH_URL"))
p.add_argument("--dsn", default=os.environ.get("DATABASE_URL"))
p.add_argument("--token-env", default="API_TOKEN")
a = p.parse_args(argv)
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
token = os.environ.get(a.token_env)
if not (a.url and a.dsn and token):
log.error("missing URL, DSN, or token env var %s", a.token_env)
return 1
try:
payload = ApiClient(token).fetch(a.url)
except FetchError as e:
log.error("fetch failed: %s", e); return 2
try:
records = parse_items(payload)
except ParseError as e:
log.error("parse failed: %s", e); return 3
try:
with psycopg2.connect(a.dsn) as conn:
Repository(conn).save(records)
except (StoreError, psycopg2.Error) as e:
log.error("store failed: %s", e); return 4
log.info("stored %d records", len(records))
return 0
if __name__ == "__main__":
sys.exit(main())