LLM Gateway
2026
The problem
Calling a model provider directly means your application inherits every outage, rate limit and price change it has. I wanted one place that owns those failure modes — so that a provider returning 503 is the gateway's problem, not the client's.
What it does
A gateway that speaks the OpenAI API, so any OpenAI SDK can point at it by changing base_url alone. Each request is authenticated against a hashed API key, checked against the tenant's requests/min, tokens/min and monthly budget, looked up in the cache, then routed along a configured fallback chain: retry once with jitter, fail over on 5xx, 429 or timeout, and skip providers whose circuit breaker is open. Streams are held until the first token, because failover is free before it and impossible after it. Cost is computed from each provider's reported usage, and every request is logged asynchronously through a Redis stream into Postgres, with Prometheus and Grafana on top. Everything, including a fault-injecting mock provider, runs locally under Docker Compose.
Engineering
- Built the OpenAI-compatible API surface and per-provider adapters, translating at the edge rather than depending on LiteLLM or LangChain — the failure handling was the point, so it is written against raw HTTP.
- Implemented the router: configured fallback chains, retry with jitter, and circuit breakers that open in ~0.4s and recover within one cooldown.
- Held streams until the first token so pre-token failures stay invisible to the client, and emitted an explicit error event rather than a silent truncation when a provider dies mid-stream.
- Put rate limits, budgets and breaker state in Redis via Lua so they are shared across every worker process and host.
- Designed budget handling to reserve the worst case and settle to real usage, so a burst of concurrent requests cannot overspend a tenant's budget.
- Added exact and semantic response caching on Postgres with pgvector, then measured the semantic threshold against 20k Quora question pairs and shipped it off by default — it added 0.4 points of hit rate while making every miss ~55ms slower.
- Versioned configuration in Postgres with hot reload and one-call rollback, plus an admin API for tenants, keys, spend, breakers and per-request attempt history.
- Wrote the benchmark suite that produces the numbers: latency overhead, a scripted chaos run with six injected failures, cache accuracy and cost replay.
- Covered the system with 82 tests running the real gateway and mock provider in-process, with CI running lint, tests and a Docker build on every push.
Measured
- +15ms p50 added latency at 10 concurrent streams, +37ms at 100
- 0 failed requests across 2,559 requests during a scripted provider outage
- 53.2% of spend saved by exact caching on an FAQ-style workload
- ~100–140 new streams/s on two worker processes
From the project's own benchmark suite on a single 4-vCPU VM running every component. Methodology and caveats are in the repository.