MLOps & InfrastructureLLM gatewayAI infrastructuremodel routingcost optimization

LLM Gateway Architecture: Routing, Failover, and Cost Control in Production

How production LLM gateways handle model routing, provider failover, and cost control—plus observability patterns for enterprise AI infrastructure.

Why an LLM Gateway Belongs in Your AI Infrastructure

An LLM gateway is the single control point between your applications and one or more model providers. Every prompt and completion passes through it. That position makes it the natural place to enforce policy, route traffic, absorb failures, and meter spend—concerns that otherwise get duplicated across every service that calls a model.

Three production pressures drive adoption. First, multi-provider sprawl: teams integrate OpenAI, Anthropic, Azure OpenAI, Bedrock, and self-hosted models independently, each with its own SDK, retry logic, and credential handling. The pain is concrete—Bedrock authenticates with AWS SigV4, most others with bearer API keys, and every provider returns a different response schema. Second, unpredictable spend: token costs scale with usage, and without centralized accounting, a single runaway loop can burn a quarterly budget in an afternoon. Third, reliability expectations: when a provider has an outage or a latency spike, your product still has to respond.

It helps to be precise about boundaries. A gateway is not a model—it doesn't generate anything. It's not an agent framework—it doesn't plan or manage tool-use loops. And it's not a replacement for application-level orchestration—your app still owns prompt construction, context assembly, and business logic. The gateway sits beneath all of that as shared infrastructure. (See also: LLM gateway vs. proxy vs. orchestration layer)

What a gateway actually does (and doesn't do)

A gateway does normalize provider APIs, apply routing and fallback rules, enforce quotas, and emit telemetry. It doesn't decide what your product should say, and it shouldn't hide model behavior from the teams that depend on it. Treat it as a transparent proxy with policy—powerful precisely because it stays out of the semantic layer.

The gateway's job is to make model access boring: one API surface, predictable costs, and graceful behavior when a provider misbehaves.

Core Architecture: The Request Path End to End

A production request moves through a predictable sequence:

  1. Authentication and tenant identification — resolve the caller, key, and org context.
  2. Policy evaluation — check quotas, content rules, and allowed models.
  3. Routing decision — select a provider and model based on current signals.
  4. Provider call — execute with timeout, retry, and circuit-breaker logic.
  5. Response normalization — map provider-specific payloads to a canonical schema.
  6. Telemetry emission — record latency, tokens, cost, and outcome.

Each stage must be fast and observable. The routing and normalization hops should add only low single-digit milliseconds at p50 and stay bounded at p99—policy checks that hit an external rate-limit service or classifier must be cached or co-located so they don't dominate the budget. If the gateway becomes the slowest hop, teams will route around it. (Related: designing a low-latency LLM request path)

The control plane vs. the data plane

Separate configuration from traffic handling. The control plane holds routing rules, policy definitions, provider credentials, and model catalogs. It changes on human timescales and can afford to be heavier—versioned configs, approval workflows, audit logs. The data plane handles live requests and must be lean.

Keeping them apart lets you update a routing rule or rotate a key without redeploying the request path, and it prevents a config change from taking down production traffic. Push config to the data plane as versioned snapshots so a bad rule can be rolled back atomically.

Stateless request handling and the latency budget

The data plane should be stateless and horizontally scalable. Session state, counters, and caches live in external stores (Redis, a managed cache, a rate-limit service), not in process memory. That way any instance can serve any request, and scaling is a matter of adding replicas.

Budget latency explicitly, and budget it in two separate buckets. Steady-state overhead is what the gateway itself adds: auth, policy lookup, routing, normalization—keep this in the low single-digit milliseconds. Failure-path overhead is retries and failover, and it is governed by a deadline, not a retry count. If your end-to-end target is 2 seconds and the provider averages 1.2 seconds, a single retry already consumes another ~1.2 seconds—so a retry only fits if you set a per-attempt timeout that leaves room for one bounded second attempt. Instrument both buckets separately so neither becomes an invisible tax. (See: latency budgeting for AI applications)

Model Routing Strategies That Hold Up Under Load

Routing is where most of the value—and most of the complexity—lives. Three families cover nearly every production case.

Static, rule-based, and semantic routing

Static routing maps a model name or application to a fixed provider via config. It's simple, predictable, and the right default for single-provider setups or strict compliance requirements.

Rule-based routing adds conditions: route by tenant tier, prompt length, requested capability, or time of day. A free-tier user might hit a smaller model; an enterprise tenant gets the premium one. Rules are auditable and easy to reason about.

Semantic routing classifies the request—by intent, complexity, or domain—and dispatches accordingly. A short factual question goes to a cheap model; a multi-step reasoning task goes to a frontier model. This is the highest-leverage approach and the hardest to keep correct. Be honest about its costs: the classifier is itself a model call (an embedding lookup or a small LLM), so it adds latency and spend to every request, and it can misclassify. Gate it behind an evaluation on a held-out set of real traffic before trusting it, keep a deterministic fallback, and monitor classification drift over time. (Related: semantic routing and model selection for LLM apps)

Routing on cost, latency, and capability signals

Production routing usually combines signals:

  • Cost: prefer the cheapest model that meets the quality bar.
  • Latency: honor per-route SLOs; shift traffic away from providers in a degraded window.
  • Capability: tier models by task complexity—small model first, escalate on low confidence or explicit failure.

The classic pattern is cascade or escalation: try the small model, check confidence or output validity, and escalate to a larger model only when needed. Done well, this cuts spend substantially. Done carelessly, it doubles latency and adds a second failure mode—so escalation must be bounded by the same deadline as retries, and the confidence check must be cheap and reliable.

Watch for routing drift—the traffic mix shifts and your assumptions about cost or quality stop holding—and stale classifiers that were tuned on last quarter's prompts. Re-evaluate routing rules against sampled production traffic on a schedule, and alert when the model mix or escalation rate moves outside expected bands.

Failover: Making Provider Failures Boring

Failover is the part of the title that earns its keep during an incident. The mechanics matter more than the intent.

Distinguish retry from failover. A retry re-attempts the same provider (useful for transient 5xx and timeouts); a failover switches to a different provider or region. Both must be bounded by a request deadline, and both must respect idempotency: a completion request that times out may still have been processed and billed, so retrying can double-charge and—if the call triggers side effects—duplicate work. Treat completion calls as at-least-once and design downstream handling accordingly.

Circuit breakers, not blind retries. Track provider error rate and latency; open the breaker when a provider crosses a threshold, route around it, and probe cautiously before closing. Blind exponential backoff against a provider that is already degraded just adds load.

Hedging vs. retry. For latency-sensitive routes, fire a second request to a backup provider after a delay and take the first response—accepting the cost of the redundant call in exchange for tail-latency control. Use this deliberately; it roughly doubles spend on the hedged fraction of traffic.

Failover changes the quality contract. Failing over to the same model on another provider preserves behavior. Failing over to a different, smaller model keeps you up but silently changes output quality—so make that a separate, explicitly configured degraded mode, not an accident of routing.

Cost Control: Metering, Budgets, and Caching

Cost control is where a gateway pays for itself, and it requires accounting at every layer.

Meter both directions. Record input and output tokens per request (they're priced differently), attribute them to tenant, application, and route, and reconcile against provider invoices. Provider-reported usage is the source of truth; local estimates drift.

Enforce budgets before the call. Estimate prompt tokens pre-request, check the tenant against a rolling budget, and reject or downgrade when it's exhausted. A hard cap on a runaway loop is the difference between a bad afternoon and a bad quarter. Pair it with rate limits per key so a single misbehaving client can't exhaust a shared pool.

Cache aggressively. Prompt/response caching for repeated or near-duplicate requests is usually the single largest cost lever—often larger than model downgrading. Cache exact matches first; add semantic caching only with a similarity threshold you've validated, since it trades cost for quality risk.

Make spend observable. Emit per-request cost as a metric, dashboard spend by tenant and route, and alert on anomalous burn rate. Cost you can't see is cost you can't control.

Operating the Gateway in Production

  • Version and canary routing rules. Treat config like code: review, version, and roll out to a small traffic slice before full deployment.
  • Keep the data plane stateless. No in-process counters; externalize rate limits and caches so any replica can serve any request.
  • Instrument the gateway's own latency and error rate as first-class SLOs—if it degrades, everything behind it degrades.
  • Log enough to debug, not enough to leak. Capture model, route, tokens, latency, and outcome; scrub prompt content per your data-handling policy.
  • Test failover regularly. A circuit breaker you've never tripped is a hypothesis, not a safeguard.

The gateway's job is to make model access boring: one API surface, predictable costs, and graceful behavior when a provider misbehaves—so your application teams can focus on the semantic layer instead of reinventing retries and accounting in every service.

ShareX / TwitterLinkedIn
← Back to Learn