Short answer
Look up a carrier in a local cache first (SQLite is enough). If the row is missing or older than your refresh interval, call the official FMCSA QCMobile API with your web key, store the JSON and a fetched_at timestamp, then return the stored record. Refresh on a schedule, not on every page view. Honor HTTP 429 and the API’s published limits. Cached FMCSA data is a starting point for vetting; it is not a substitute for the official record at decision time, and it is not a way to bypass access rules.
This is about caching the official API. It does not replace a one-shot lookup tutorial, and it does not describe scraping a blocked page.
Why cache?
QCMobile is a public API, but it still has limits. A directory, a CRM side panel, or a batch of USDOT numbers will request the same carriers repeatedly. If you call the API on every request you will hit those limits and you will be slower than a local read.
Two other official options exist and should be considered first for large sets: downloadable FMCSA census files, and the documented QCMobile endpoints. A cache sits in front of QCMobile for interactive lookups. A census file is often better for a bulk load.
The cache schema
CREATE TABLE IF NOT EXISTS carrier_cache ( dot TEXT PRIMARY KEY, payload_json TEXT NOT NULL, fetched_at TEXT NOT NULL, -- ISO-8601 UTC http_status INTEGER NOT NULL, etag TEXT ); CREATE INDEX IF NOT EXISTS carrier_cache_fetched ON carrier_cache (fetched_at); Normalize the DOT number (digits only, no leading-zero surprises in your own convention) before you use it as the key. Store the official payload as you received it so you can show the source and the fetch time in the UI.
Lookup, then maybe refresh
import json, os, sqlite3, time from datetime import datetime, timezone, timedelta import httpx DB = "carrier_cache.sqlite" TTL = timedelta(hours=24) WEBKEY = os.environ["FMCSA_WEBKEY"] # never hard-code BASE = "https://mobile.fmcsa.dot.gov/qc/services/carriers" def now_utc() -> datetime: return datetime.now(timezone.utc) def get_cached(conn, dot: str, ttl=TTL): row = conn.execute( "SELECT payload_json, fetched_at, http_status FROM carrier_cache WHERE dot = ?", (dot,), ).fetchone() if not row: return None fetched = datetime.fromisoformat(row[1]) if now_utc() - fetched > ttl: return None return json.loads(row[0]) def fetch_live(dot: str, attempts: int = 5) -> tuple[int, dict | None]: url = f"{BASE}/{dot}" for n in range(attempts): r = httpx.get(url, params={"webKey": WEBKEY}, timeout=20) if r.status_code in (429, 500, 502, 503, 504): time.sleep(min(2 ** n, 60)) continue if r.status_code == 404: return 404, None r.raise_for_status() return r.status_code, r.json() raise RuntimeError(f"QCMobile gave up for DOT {dot}") def upsert(conn, dot: str, status: int, payload: dict | None) -> None: conn.execute( """INSERT INTO carrier_cache (dot, payload_json, fetched_at, http_status) VALUES (?, ?, ?, ?) ON CONFLICT(dot) DO UPDATE SET payload_json = excluded.payload_json, fetched_at = excluded.fetched_at, http_status = excluded.http_status""", (dot, json.dumps(payload or {}), now_utc().isoformat(), status), ) conn.commit() def lookup(conn, dot: str) -> dict: dot = "".join(c for c in dot if c.isdigit()) cached = get_cached(conn, dot) if cached is not None: return {"source": "cache", "dot": dot, "content": cached} status, payload = fetch_live(dot) upsert(conn, dot, status, payload) return {"source": "live", "dot": dot, "http_status": status, "content": payload} Show source and fetched_at in the UI. People trust a lookup more when they can see that the data came from FMCSA and when it was fetched.
A scheduled refresh, not a scrape
A periodic job walks rows older than the TTL (or a random subset, if the table is large) and refreshes them with the same limiter you would use for any official API: low concurrency, backoff on 429, a daily budget. Python’s cron or a systemd timer is enough. Rust can own the refresh worker if you want a small binary that only reads SQLite and calls HTTP; Python can still own the web app.
Do not refresh on every keystroke in a search box. Debounce the UI and always hit the cache first.
Stale reads when the API is down
If the live call fails and you have an expired row, you can return the stale row with a clear flag: stale: true, plus the old fetched_at. Do not silently present stale data as current. If you have no row at all, show the error.
FAQ
How often should I refresh?
There is no official “correct” TTL in this article. Many directories start at 12 or 24 hours and tighten the interval for carriers they show every day. Check QCMobile documentation and any terms that apply to your key before you pick a schedule.
Should I cache 404s?
Yes, for a short time, so a typo does not become a tight retry loop. Use a shorter TTL for negative lookups than for successful ones.
Can I share one cache across several apps?
Yes. Keep SQLite on a single host, or move the same schema to Postgres if several services need it. The contract stays the same: key by DOT, store payload and fetched_at.
How is this different from scraping SAFER pages?
This path uses the official API and a local store. If you also use official census files, load those in bulk and use QCMobile for on-demand refresh. Do not hammer HTML pages that the API already covers.
Where does Rust fit?
A Rust refresh worker is optional. It can apply rate limits and write SQLite or Postgres without standing up a Python runtime on a small host. The web app can stay in Python.
What this is not
This is not a complete carrier-vetting product, not legal or safety advice, and not a claim about how many carriers you can look up per day. Always confirm current endpoints and field names in FMCSA’s QCMobile documentation before you ship.
