What it is
An LLM gateway is a service between your applications and the model providers they use. Applications call one internal API, often compatible with a popular provider's API shape; the gateway authenticates the caller, applies policy (quotas, budgets, allowed models), picks a provider and model, forwards the request, streams the response back and records what happened. It is an API gateway specialised for model traffic: token-based metering, streaming, provider-specific translation and model-level routing.
Why it exists
Model calls have properties that make direct integration painful at scale:
- Providers fail and throttle. Outages, overloaded models, per-account quotas in requests and tokens per minute, and model versions that get deprecated.
- Cost is per token and highly variable. Without central accounting, nobody knows which team or feature spends what until the invoice arrives.
- Many teams share limited quota. One batch job can exhaust it for everyone.
- Models change. Switching a model should be a configuration change after evaluation, not a deploy in every service.
Putting this logic in every application means duplicated retries, scattered keys and no shared view. A gateway puts it in one place.
How it works
Routing. The gateway maps a requested model or alias (support-default) to one or more concrete deployments with an order or weights. Common strategies: primary with fallback, weighted split across providers or regions, latency- or cost-based selection, and routing by request class (a small model for classification, a large one for hard reasoning).
Fallback. Two signals trigger it: health (probes or passive error tracking mark a deployment unhealthy, as in the simulation) and per-request errors (timeouts, 5xx, 429). On a per-request error the gateway can retry the same request on the next deployment, honouring Retry-After. Streaming complicates this: once tokens have been sent to the caller, a mid-stream failure can no longer be retried transparently.
Quotas and budgets. Each team or application gets a virtual key with limits: requests and tokens per minute, and spend per day or month. Limits are typically token buckets; token counts are estimated before the call and corrected from the provider's usage data after it.
Accounting. For each request: caller, model and provider that actually answered, input, output and cached tokens, latency (time to first token and total), cost, and whether fallback or cache was used. This feeds dashboards, budget alerts and chargeback.
Caching. Exact-match caching of identical requests is safe for deterministic calls. Semantic caching (matching similar prompts) is possible but needs care; see the semantic caching lesson. Provider-side prompt caching (reusing a long, identical prompt prefix) is different: it lowers cost and latency of the call but does not skip it.
When to use it
- Several teams or applications call models, or one application calls several providers.
- You need failover across providers or regions, or to stay inside provider quotas.
- You need to attribute and limit cost.
- You want to change models centrally, behind aliases, after evaluation.
When not to
- A single small application with one provider and modest traffic: the provider SDK's retries and a budget alert may be enough.
- When the extra hop's latency matters more than the features (rare: model calls take hundreds of milliseconds to seconds; a gateway should add a few).
- If you cannot run it reliably: an unreliable gateway is a worse single point of failure than the provider.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Gateway instead of direct calls | Central routing, keys, limits, accounting | Another critical service in every request path |
| Automatic fallback to another model | Availability during outages | Different answers, latency and cost; prompts must be tested on both |
| Weighted split across providers | Stays under quotas, spreads risk | Inconsistent behaviour between requests; two contracts |
| Strict per-team quotas | Contained noisy neighbours, predictable spend | Teams hit limits and need a process to raise them |
| Response caching in the gateway | Fewer calls, lower cost | Stale or mismatched answers if keys are too loose |
Alternatives
- Provider SDKs with retries in each application: fine for one team and one provider.
- A general API gateway or service mesh: handles auth, rate limits and routing, but not token metering, model translation or streaming-aware accounting without extensions.
- A managed AI gateway from a cloud or provider: less to operate, but tied to that platform's providers and features.
Failure modes
- Silent fallback: traffic has been on the fallback model for days and quality dropped; nobody noticed. Alert when fallback is active and log which model answered.
- Retry storms: gateway retries plus application retries multiply load on an already throttled provider. Retry in one layer, with backoff and a budget.
- Fallback overload: the fallback was sized for a trickle and saturates when it gets everything. Plan its capacity or shed lower-priority traffic.
- Shared quota exhaustion: one tenant's spike fails everyone. Per-tenant limits.
- Broken streaming: a gateway that buffers responses turns a first token in 300 ms into a full answer in 10 s.
- The gateway itself fails or becomes slow; every model call fails with it.
In production
Run the gateway stateless and redundant, with quota counters in a shared store and fail-open or fail-closed behaviour decided per limit. Keep keys for providers only in the gateway (a secrets vault behind it), and give teams virtual keys they can rotate. Expose per-team and per-model dashboards for tokens, cost, latency, error and fallback rates. Use model aliases so a model upgrade is a config change, gated by an evaluation run. Separate interactive and batch traffic, and use provider batch APIs where latency allows.
Common misconceptions
- "Health checks handle provider problems." They catch outages, not quota exhaustion or degraded quality.
- "Fallback is transparent." A different model is a different system; test and monitor it as such.
- "Rate limits are per request." Providers usually limit tokens per minute too, so one long prompt can count like many short ones.
- "A gateway saves money by itself." It makes spend visible and enforceable; savings come from the decisions that follow (caching, smaller models, limits).
Interview angle
In an AI system design, place a gateway between services and providers and explain what it owns: keys, routing with fallback, per-tenant quotas, accounting and streaming. Then go into failure handling: how outages are detected, how 429s are handled without retry storms, how fallback capacity is sized ("fallback does 32 ÷ 1.8 s ≈ 18 calls/s, we need 24, so we add a second fallback or shed batch traffic"), and how you would notice that quality dropped after a switch.
Model assumptions
The simulation is a simplified queueing model, not a benchmark. Each provider is a server whose workers stand for concurrent generations: Provider A has 48 slots and a 1.2 s mean call time, Provider B 32 slots and 1.8 s (lognormal, cv 0.5); each request is one model call. Provider A's quota is a token bucket of 18 requests per second; real providers also limit tokens per minute, which is not modelled. The gateway is a balancer with health checks every 500 ms (2 failures eject, 3 successes restore) using smooth weighted round robin, where weight 0 means "only if nothing else is healthy". Per-request retry on a fallback after a 429 is not simulated. Per-team quotas are token buckets in front of the router. Arrivals are Poisson; network hops are fixed. Numbers show behaviour and orders of magnitude only.