LLM API Gateway architecture: client request through auth, rate limiter, cache, provider router with fallback, cost tracker

The problem

More than one person ends up calling an LLM through a shared API key, and suddenly you need rate limiting, caching, a fallback when a provider is down, and a way to know who's spending what. I built a small, self-contained gateway that handles exactly that — no vendor SDK, no real network calls, deterministic mock providers so the routing and accounting logic can be tested without mocking HTTP.

What it enforces, and how

  • Rate limiting: a token bucket per API key, with the check-and-consume step under a single lock — the whole read-then-decrement happens atomically, so concurrent requests can't both read a stale token count and both get admitted when only one should be. Proven with a 50-thread concurrency test against a 10-token bucket: exactly 10 admitted, 40 rejected, every run.
  • Caching: the response cache is keyed on the full normalized request — model, messages, and temperature — not just the prompt text.
  • Provider fallback: if the primary provider for a model is down, the router tries the next one that supports it before giving up.
  • Cost tracking: a per-API-key ledger derived from simulated token usage and a per-model pricing table.

The real bug the test suite caught

The first version of the cache key only hashed messages and temperature:

payload = json.dumps({"messages": messages, "temperature": temperature}, sort_keys=True) 

That passes every obvious test — ask the same thing twice, get a cache hit. But it means two different models asked the exact same prompt would silently share a cache entry. Ask the expensive, high-quality model something, and depending on request order, get back what the cheap, fast model answered earlier for the same wording. No exception, no log line — just a quietly wrong response that looks completely normal.

Two tests failed against that version immediately:

def test_cache_key_differs_by_model(): messages = [{"role": "user", "content": "summarize this contract"}] key_small = make_cache_key("fast-small", messages, 0.0) key_large = make_cache_key("quality-large", messages, 0.0) assert key_small != key_large # AssertionError: they were equal 

The fix is one line — include model in the hashed payload — but it's the kind of bug that never announces itself. It just quietly erodes trust in the gateway's output the moment more than one model is in play.

Stack

Python, FastAPI, pytest. 21 tests covering concurrency, cache correctness, provider fallback, and the full request flow through the gateway. CI runs the exact same pytest tests -v invocation as local, no hidden path differences.

Repo: https://github.com/Athilaf/llm-api-gateway