Learn
Hardware & deployment

What is an AI / LLM Gateway?

The short answer

An LLM gateway is a single API layer in front of many models and providers. It handles API keys, routing, retries, fallbacks, rate limits, logging and cost tracking, so each application integrates one endpoint instead of five SDKs and every provider's quirks.

On this page

A reverse proxy with opinions about models

Strip away the marketing and a gateway is a reverse proxy that understands the shape of model requests. Applications send an OpenAI-style chat request to one base URL. The gateway authenticates the caller, decides which upstream model should serve the request, forwards it with the provider's own credentials, normalises the response, records what happened, and streams it back. The application never holds a provider key and never learns which vendor answered.

That position in the request path is what makes it valuable. Anything you want to apply uniformly across models, teams and providers has exactly one place to live: authentication, quotas, retry policy, fallback order, prompt logging, PII redaction, caching, cost attribution and content policy. Without a gateway, each of those becomes code duplicated in every service, drifting until two teams disagree about what the retry policy is. The gateway turns model access into a platform capability rather than an implementation detail.

The integration maths

Suppose you have three applications and four model providers, and each application needs to be able to switch providers for cost or reliability. Without a shared layer that is twelve integrations, twelve sets of credentials, twelve retry implementations and twelve logging formats. With a gateway it is three integrations to the gateway and four adapters inside it. The saving is not the initial code, it is the maintenance when a provider changes its tool-call schema or deprecates a model.

The second-order benefit is portability. A model is a dependency that can be repriced, rate-limited, deprecated or made unavailable in a region with little notice. If switching means editing a base URL and a model name in one config, you switch. If it means rewriting the parts of the product that depended on a vendor-specific response field, you do not switch, and the vendor knows it. Gateways are as much a negotiating position as an engineering convenience.

Routing, fallbacks and retries

Routing can be as simple as a lookup from a public model name to an upstream deployment, or as involved as a policy that weighs price, latency, region and tenant tier. Common patterns include sending classification and extraction to a small cheap model, sending user-facing generation to a stronger one, pinning regulated tenants to a specific region, and splitting traffic between two providers to measure quality. A gateway is the natural place to express those rules because it sees the request, the caller and the live error rates at the same time.

Fallbacks are where gateways earn their keep and where they are most often misconfigured. A chain of three providers is only useful if the second one can actually serve the request: the same context length, the same tool-calling format, the same structured-output support, and a compatible tokeniser for your token budget. Teams discover this during an outage, when the fallback rejects a 40K-token prompt that the primary handled fine. Test the fallback monthly by forcing it, and treat an untested fallback as absent.

Retries need the same discipline. Retrying a 429 immediately makes the rate limit worse; retrying a 500 three times without jitter creates synchronised retry storms across replicas. Cap the attempts, add exponential backoff with jitter, honour the Retry-After header when a provider sends one, and never retry a 400 or a 401 because the request or the key is wrong and will stay wrong. Also decide whether a retry can double-bill you: if the upstream processed the request and the response was lost in transit, the second attempt pays again, so retries belong on idempotent reads and short generations rather than on long expensive calls.

Keys, quotas and the money trail

A gateway usually issues virtual keys: credentials that map to a real provider key plus a tenant, team, budget and rate limit. That lets you give every service and every customer a distinct key without distributing the underlying provider secret, and it lets you revoke one without touching the others. Per-key limits are usually expressed as requests per minute and tokens per minute, because providers enforce both and a request-count limit alone lets a single request with a 100K-token prompt blow through your quota.

Cost attribution is the feature finance notices. If the gateway records prompt and completion tokens per request, tagged by tenant and feature, you can answer which customer is unprofitable and which prompt template is burning budget. Hard budget caps prevent the classic incident where a retry loop or an agent stuck in a tool-calling cycle spends four figures overnight. Soft alerts at 50 and 80 percent of budget give you time to react. The accounting is only as good as the token counts, so prefer the usage block returned by the provider and fall back to a tokeniser per model family rather than assuming one tokeniser for everything.

Observability, caching and policy

  • Per-request traces with model, provider, token counts, latency, status and cost, joinable to your application's request ID.
  • Aggregate dashboards for error rate by provider and model, which is how you notice a silent quality or availability regression.
  • Exact-match response caching for deterministic requests such as classification, and semantic caching only with a carefully measured similarity threshold.
  • Prompt and completion logging behind a retention policy, with redaction of personal data and secrets before anything is written.
  • Regional routing to satisfy data residency rules, and provider allowlists per tenant.
  • Content policy hooks for blocked categories, prompt injection screening, and output schema validation.
  • Shadow traffic: send a copy of production prompts to a candidate model, compare, and never show the result to users.

Build or buy

The open-source option most teams start with is LiteLLM's proxy, a Python service that speaks the OpenAI format to roughly a hundred providers and includes virtual keys, budgets, fallbacks and logging. Portkey offers an open-source gateway with a managed control plane. Kong, Envoy, Traefik and Cloudflare all ship AI gateway features aimed at teams that already run their edge infrastructure. OpenRouter is a hosted router with a marketplace model, useful for experimentation and less so when you need a private deployment. Hyperscaler offerings exist too, usually as policy layers in front of that vendor's own model catalogue.

Self-hosting gives you control over where prompts are stored and which providers are reachable, at the cost of running another stateful service with its own database and Redis. A managed gateway gives you the same API with someone else's uptime and someone else's data processing agreement. The decision usually turns on two questions: does your compliance posture allow prompts to transit a third party, and do you have the on-call capacity to own another critical path? A team of three should probably buy; a platform team with a compliance requirement should probably self-host.

An architecture that survives contact with production

Keep the proxy tier stateless and put shared state in Redis for rate-limit counters and exact-match cache, and in Postgres for keys, budgets and spend. Run at least two replicas behind a load balancer even in staging, because a single gateway is a single point of failure for every AI feature you have. Write logs asynchronously to a queue so that a slow observability backend cannot add latency to user requests, and make logging failure non-fatal by design.

Streaming needs special handling. Once the gateway has sent a 200 and the first token, it cannot change the status code if the upstream fails, so it must emit an error event inside the stream and let clients handle it. Timeouts must be per-token or idle-based rather than a single total budget, because a legitimate 4,000-token generation can take a minute while a stalled connection should be dropped in seconds. And the gateway's own latency budget should be a few milliseconds: a proxy that adds 200 ms to every request has negated the reason you chose a fast model.

Failure modes worth designing for

The gateway becomes the outage. If it is down, every model is down, including the fallbacks it was supposed to provide. Keep a documented break-glass path: applications should be able to read a direct provider credential from the secret manager and bypass the gateway when it is unavailable, with the understanding that quotas and logging are suspended. That is ugly, and it is better than a total outage during a gateway upgrade.

Retry amplification is the second classic. One provider slowdown causes every replica to retry, which triples load on the fallback, which then fails too. Cap total attempts globally, add jitter, and use a circuit breaker that stops sending traffic to a failing provider for a cooling period. The third is silent semantic drift: the gateway normalises responses, and a field your application depends on, such as a reasoning block or a tool-call index, gets dropped in translation. Contract tests against the gateway, not only against providers, catch that.

The fourth is data leakage. Prompt logs are among the most sensitive data a company holds, and gateways are where they accumulate by default. Turn on redaction, set retention in days rather than forever, restrict who can query the log store, and make sure the gateway's own vendor does not retain payloads. A gateway that solves cost visibility while creating a secondary copy of every customer document has traded one problem for a worse one.

The metrics that tell you it is working

  • Time to first token at p50 and p95, split by model and by prompt size bucket.
  • Time per output token, which exposes bandwidth and batching problems that throughput averages hide.
  • Error rate by provider and by status class, with 429s separated from 5xx because they need different responses.
  • Fallback rate: a healthy system falls back rarely, and a rising rate is an early warning about a provider.
  • Cost per request and cost per active user, by tenant and feature, reconciled monthly against provider invoices.
  • Cache hit rate for both exact and semantic caches, with the false-positive rate of the semantic cache measured separately.
  • Gateway overhead, measured as the difference between upstream latency and end-to-end latency at the client.

What a gateway is not

It is not an inference engine. A gateway forwards requests to vLLM, a hosted API or a managed endpoint; it does not hold weights, schedule GPU work or batch tokens. Teams sometimes expect a gateway to fix latency, when the fix is a better serving configuration behind it. It is also not an orchestration framework. LangGraph, the OpenAI Agents SDK and similar libraries decide what to ask, when to call a tool and how to manage conversation state; the gateway only sees the resulting HTTP requests. Mixing the two responsibilities produces a proxy that tries to own prompt logic and becomes impossible to test.

Nor is it an evaluation harness. A gateway can log prompts and responses and can shadow traffic to a candidate model, but deciding whether the output is good requires task-specific scoring, golden sets and human review. A gateway that reports a 99.9 percent success rate is reporting HTTP status codes, not answer quality. Keep the evaluation pipeline separate and feed it with gateway logs rather than asking the gateway to grade itself.

A rollout order that avoids pain

  • Start in observe-only mode: route traffic through the gateway, log model, tokens, latency and cost, and change no behaviour.
  • Move credentials into the gateway and remove provider keys from application environments, one service at a time.
  • Add per-tenant virtual keys and soft budget alerts before adding hard caps, so you can see what normal spend looks like.
  • Introduce fallbacks for the two or three models that matter, force each fallback in staging, and record the failure modes you find.
  • Add routing policy only when you have data: price and latency per model from your own traffic, not from a benchmark leaderboard.
  • Turn on caching for deterministic endpoints last, with a measured false-positive budget for any semantic layer.

Common mistakes

  • Bolting a gateway on after applications already import provider SDKs directly, so half the traffic bypasses it and quotas are meaningless.
  • Configuring a fallback and never testing it, then discovering the fallback model cannot handle the prompt length.
  • Retrying 429s without backoff and turning a rate limit into an outage.
  • Logging full prompts and completions by default, with no retention limit and no access control.
  • Counting tokens with one tokeniser for all models, which makes budget enforcement wrong by 10 to 30 percent.
  • Putting the gateway in a different region from the application and adding 150 ms to every request.
  • Running one replica with no break-glass path, so a gateway restart is a full AI feature outage.
  • Routing on price alone and ignoring that the cheap model needs three attempts to produce a usable answer.
Page feedback

Was this helpful?

A quick signal helps improve these notes.

Report a mistake Straight to the lab inbox

Put it to work

See the models, datasets and gateway this lab runs.