Course contents

16. AI System Design Lesson 8 of 10

Model Routing and LLM Gateways

See an LLM gateway fail over between providers, route around 429 quotas, contain a noisy team with per-team limits, and track cost in one place.

15 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • An LLM gateway gives applications one internal API and owns provider keys, routing and policy.
  • Health-checked fallback turns a provider outage into a short error burst, plus a latency and quality change.
  • A rate-limited provider is healthy: stay under quotas with routing, and retry 429s on a fallback.
  • Per-team quotas make a spike fail for the team that caused it, not for everyone.
  • Because every call passes through it, the gateway is where spend, caching and model aliases are managed.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. Every team calls the provider directly

    Two teams use the same model provider: a support bot at 8 requests per second and a search feature at 4. Each team has its own API key, its own SDK version, its own retry code and its own idea of what the bill will be.

    It works. Provider A answers in about 1.2 s on average and has plenty of room. In this model each request is one model call, and a provider’s capacity is the number of generations it runs at once.

    Scene: Team A sends 8 and team B 4 requests per second straight to Provider A. Everything succeeds with about 1.2 s average latency.

    Key idea: Calling providers directly is simple until you need to change, limit, observe or survive one of them.

  2. 2. The provider goes down

    One second in, Provider A has an outage. Both teams’ requests fail, and there is nowhere else for them to go: switching providers means a code change and a deploy in every team, plus a second contract, key and SDK.

    Provider incidents are routine: regional outages, overloaded models, deprecated model versions. An application that knows only one endpoint inherits every one of them.

    Scene: Provider A fails one second in. Every request from both teams fails from then on.

    Key idea: A hard-coded provider is a single point of failure you don’t operate.

  3. 3. One gateway in front of all models

    Both teams now call an LLM gateway with one internal API. The gateway holds the provider keys, translates requests where providers differ, and routes them. Provider A is the primary; Provider B is a fallback with weight 0, used only when A is unhealthy. It probes both providers every 500 ms.

    Provider A is back. All traffic goes to A; B sits idle, ready.

    Scene: Both teams call the LLM gateway, which routes every request to Provider A. Provider B is connected as a fallback and receives nothing.

    Key idea: A gateway decouples applications from providers: routing, keys and policy live in one place.

  4. 4. Provider A fails; the gateway switches

    At 1.5 s Provider A goes down again. For about a second the gateway still sends it requests and they fail; then two failed health checks mark A unhealthy and every request goes to Provider B. No team changed anything.

    The fallback is not free: B is slower here (about 1.8 s), so P95 rises, and a different model can answer differently. Prompts tuned for one model need to be tested on the other before you rely on it.

    Scene: Provider A fails. Requests to it fail until the gateway’s health checks eject it about a second later; then all traffic goes to Provider B and succeeds, with higher latency.

    Key idea: Fallback turns a provider outage into a short error burst plus a quality and latency change you must have tested.

  5. 5. Rate limited: the provider says 429

    Provider A is healthy again, and both teams grow: 14 + 10 = 24 requests per second. But the account’s quota at Provider A allows about 18 per second. Everything above it is answered with HTTP 429 Too Many Requests, and the gateway passes those errors straight back.

    Health checks don’t help: A is up, it is just refusing work over the quota. Roughly a quarter of all requests fail. Real quotas are usually counted in tokens per minute as well as requests; the effect is the same.

    Scene: At 24 requests per second, Provider A accepts about 18 per second and rejects the rest with 429. Provider B stays idle; about a quarter of requests fail.

    Key idea: Provider quotas are a capacity limit you don’t see in your own metrics until requests start failing.

  6. 6. Route around the quota

    The gateway now splits traffic 2 : 1 between A and B: about 16 requests per second to A, under its quota, and 8 to B. The 429s disappear. Average latency rises a little, because a third of requests use the slower provider.

    Real gateways also retry a request that got a 429 on the fallback, honouring Retry-After, and track each provider’s remaining quota from response headers. That per-request retry is not simulated here; the split shows the capacity effect.

    Scene: The gateway sends two thirds of requests to Provider A and one third to Provider B. Provider A stays under its quota and nothing fails.

    Key idea: Know each provider’s quota and route so you stay under it, with retry-on-fallback for the bursts.

  7. 7. One team’s batch job hurts everyone

    Team B starts a backfill job: from 10 to 40 requests per second, one second in. The gateway faithfully spreads it: Provider A goes far over its quota and returns 429s, and Provider B becomes much busier.

    Team A changed nothing, but its support bot now fails too. Shared quotas without per-team limits mean the noisiest client sets everyone’s error rate.

    Scene: Team B jumps to 40 requests per second. Provider A rejects many requests with 429 and Provider B gets much busier. Team A’s requests start failing as well.

    Key idea: Without per-tenant limits, one tenant’s spike becomes every tenant’s outage.

  8. 8. A quota per team, enforced at the gateway

    Each team now gets its own virtual key with a quota: team A 16 requests per second, team B 10. The gateway checks the key before routing. Team B’s backfill above 10 per second is rejected at the gateway with a 429 that names team B’s own limit, and the job slows down to fit.

    Team A is back to nearly zero errors. The overall error rate stays high, because it counts team B’s rejected backfill requests: that is the point, the failure now lands on the team that caused it. The providers see about 24 requests per second again, which the 2 : 1 split handles. Batch work belongs in a separate, lower-priority quota (or a provider’s batch API), not in the interactive one.

    Scene: Each team passes through its own quota check at the gateway. Team B’s excess requests are rejected there; team A’s requests succeed and both providers are within their limits.

    Key idea: Per-team quotas contain spikes where they start; the providers only see traffic you have agreed to serve.

  9. 9. Cost tracking and caching in one place

    Because every call passes through it, the gateway is where you measure: per request it records team, model, input and output tokens, latency and computed cost, so you can show each team its spend, alert on budgets and spot a prompt change that doubled token usage.

    It is also a natural place for an exact-match response cache (identical request, identical answer, useful for deterministic calls and retries) and, with more care, a semantic cache. Model aliases (support-default → a concrete model version) let you upgrade models centrally, after evaluation.

    Scene: The same running system, annotated with what the gateway records per request (team, model, tokens and cost) and where budgets and model aliases apply.

    Key idea: The gateway is your control point for spend, caching and model versions, not just routing.

  10. 10. What the gateway costs you

    Every model call now depends on the gateway. Run it redundantly, keep its added latency to a few milliseconds, and make sure it streams responses through instead of buffering them, or users lose the token-by-token output.

    Don’t let fallback hide reality: log which provider and model actually answered, alert when fallback is active, and evaluate fallback models with the same test set as the primary.

    Scene: Two teams behind per-team quotas, one LLM gateway splitting traffic between two providers. The gateway is highlighted as a critical dependency.

    Key idea: Centralise routing, limits and accounting, then treat the gateway as critical infrastructure.