Skip to content

What an LLM gateway does, and when you need one

An LLM gateway is a proxy between your applications and model providers. It gives you one API, one place for keys and budgets, and shared failover.

Published
Updated
Reading time
11 min read

In short

  • An LLM gateway is a reverse proxy for model traffic. Applications call it with one API and one key, and it forwards each request to a provider.
  • It does five jobs: authenticate the caller, pick a provider, handle failure, enforce limits, and record the call. Unlike a generic API gateway, it counts tokens and dollars, not just requests.
  • You need one once more than one team, application, or provider is involved. A single service calling a single provider is better served by the provider's SDK.
  • The price is an extra network hop, a new component that can take every AI feature down, and support for provider features that arrives late.

An LLM gateway is a reverse proxy that sits between your applications and the model providers they call. Applications send every request to the gateway in one API format with one credential. The gateway decides which provider and model should serve the request, forwards it, and records what happened.

The idea is borrowed from API gateways, and so is the reasoning. Once several services depend on the same upstream, the logic for calling it safely should live in one place.

Support botBatch pipelineCoding agentGatewayONE ENDPOINT · ONE KEYAuthenticate and meterPick a providerRetry and fail overEnforce limitsRecord the callProvider AProvider BSelf-hosted model429 · RATE LIMITED
A gateway gives every application one endpoint and one key, then decides per request which provider gets the call.

What a gateway does on each request

A gateway does five things to every request, in this order.

  1. It authenticates the caller. Applications hold keys issued by the gateway, often called virtual keys. The real provider keys stay inside the gateway, so rotating one does not need a deploy.
  2. It picks a target. A rule maps the request to a provider and model. The rule can be a fixed mapping, a weighted split, or a choice based on price or measured latency. LLM routing covers the strategies and what each one costs.
  3. It sends the request and handles failure. A rate limit, a timeout, or an overloaded provider triggers a retry or a switch to another target.
  4. It enforces limits. Budgets and rate limits apply per key, team, or model, before the provider's own limits are reached.
  5. It records the call. Model, token counts, latency, status, and cost go to one log that covers every application.

Most gateways speak the OpenAI API format, so adopting one is usually a base URL change.

client.ts
import OpenAI from "openai";
 
// The application talks to the gateway. Provider keys never reach this service.
const client = new OpenAI({
  baseURL: "https://llm-gateway.internal.example.com/v1",
  apiKey: process.env.GATEWAY_VIRTUAL_KEY,
});

LLM gateway vs API gateway vs LLM proxy

An LLM proxy translates one API format into each provider's and forwards the call. An API gateway enforces generic policy on any HTTP traffic: authentication, request-count limits, and routing by path. An LLM gateway does both jobs with rules that understand models: it counts tokens, prices them, keeps streams intact, and tells one provider error from another.

"AI gateway" is usually a synonym for LLM gateway, sometimes widened to cover tool and agent traffic. The useful distinction is what each layer can see.

CapabilityLLM proxyAPI gatewayLLM gateway
One API format across providersYesNoYes
Unit of rate limitingUsually noneRequestsRequests and tokens
Cost per requestNoNoYes
Provider error classificationPass-throughStatus codes onlyRate limit, spend cap, overload, invalid
Streaming awarenessForwards bytesForwards bytesCounts tokens, handles mid-stream errors

The categories converge. Kong's AI Gateway started as AI plugins on Kong Gateway and now models AI providers as first-class entities, while proxies grow keys, budgets, and logs. If you already run an API gateway, check that its AI features count tokens and price them per model. Request counts will not show you one caller sending a 200,000-token prompt a thousand times.

Why failover belongs in the gateway

Failover belongs in the gateway because a provider error has to be classified before it is retried, and that logic is the same for every application you run.

Providers fail in several distinct ways. Anthropic returns 429 with rate_limit_error when you exceed a limit, and 529 with overloaded_error when the API itself is saturated. OpenAI returns 429 for rate and spend limits, and 503 when a model is overloaded. Each one calls for a different reaction.

SignalWhat it meansRight response
429 with a retry-after headerYou are over a rate limitWait as told, or send the request elsewhere now
429 from a spend limitThe budget is used upDo not retry. Fail over or return the error
529 or 503The provider is overloadedFail over. Retrying adds to the load
400The request is invalidReturn the error. No provider will accept it

The second row is the one that catches people. Anthropic documents that a 429 caused by a spend cap carries no retry-after header, because waiting will not help. A retry loop that treats all 429s alike will spin until it times out.

Blind retries also cost you quota. OpenAI's rate limit guide warns that unsuccessful requests still count toward your per-minute limit, so a tight loop burns the allowance it is waiting for.

Provider SDKs already retry with exponential backoff. Anthropic's retry twice by default and honor retry-after. That is enough for one service. It cannot move traffic to a second provider, and five services each retrying on their own multiply the pressure on a provider that is already struggling. LLM failover covers the full chain of retries, fallbacks, and circuit breakers, and what each one costs.

Caching and cost controls at the gateway

A gateway lowers model spend in three ways: it passes provider prompt caching through intact, it can answer repeated requests from its own response cache, and it enforces budgets before the invoice arrives. The first is close to free, the second can return a wrong answer, and the third is only as accurate as the gateway's price table.

ControlWhat it savesWhat it risks
Prompt caching pass-throughMost of the input price on repeated prefixesNothing, if cache markers pass unchanged
Response cachingThe whole call on a repeated requestA stored answer to a question that needed a new one
Budgets and token limitsRunaway spend from one callerBlocking a legitimate burst
Cheaper models for easy requestsThe price gap between modelsA weak answer no error code reports

Protect prompt caching first. Anthropic isolates caches by organization, and by workspace on the Claude API, and OpenAI does not share them across organizations. A gateway that spreads one conversation across keys turns cache reads into fresh writes, so keep each session on one target and confirm that cache_control markers and tool order pass through unchanged. Prompt caching covers the mechanics.

Response caching is a separate decision. An exact-match cache is safe but rarely hits. A semantic cache hits more often and can answer a different question, so scope it per caller.

Budgets are only as accurate as the gateway's price table, because cost is computed from each response's token counts. Hosted gateways enforce them too: Vercel's AI Gateway rejects requests with a 402 once a team, project, or key exceeds its budget. Virtual keys covers how to structure them.

When you need one

You need a gateway when the count of teams, applications, or providers goes above one. Any of these is a sufficient reason:

  • You call two or more providers, or you expect to within the year.
  • More than one team ships LLM features and finance wants spend broken down by team.
  • Security or compliance asks for a single audit log of model traffic.
  • A provider outage would take a user-facing feature down with it.

You do not need one for a single service that calls a single provider. Use the SDK's built-in retries and the provider's usage dashboard, and keep one less system on your pager. Add the gateway when the second caller shows up. Retrofitting it is cheap because the change on the application side is one URL.

Gateways for MCP and agent traffic

The reasons to centralize model calls apply to tool calls too: one place for credentials, per-caller permissions, and an audit log of what ran. Several gateways now also proxy Model Context Protocol servers and agent-to-agent (A2A) traffic, so one control plane can govern all three.

agentgateway, a Linux Foundation project, was built around MCP and A2A and also routes LLM traffic. Kong's AI Gateway covers all three, and LiteLLM can call MCP tools through its chat completions endpoint. If agents are on your roadmap, check how a candidate authenticates tool calls and filters which tools each caller sees. What an MCP gateway does covers those requirements.

What it costs

A gateway costs you latency, a new point of failure, and slower access to provider features.

Latency is the smallest of the three. Every request takes an extra network hop and pays for the gateway's own work. Against a model call that runs for seconds, a few milliseconds will not be noticed. Do not take a vendor's benchmark as your number. Measure the added p99 at your own peak concurrency, with streaming on, and watch time to first token, which is the delay users feel.

The failure point matters more. The gateway now stands in front of all model traffic, so its outage is everyone's outage. Run at least two instances. Decide ahead of time whether it fails open or closed when its own database is unreachable, and test that decision.

Feature lag is the cost people find last. Providers add request fields faster than a proxy can map them. Before you commit, confirm that the features you rely on pass through unchanged: streaming, tool calls, structured output, and the cache controls described in the prompt caching article.

Hosted, self-hosted, or an add-on to your API gateway

The three kinds of gateway differ in who runs the proxy and where your prompts travel. Choose a hosted service when you want no infrastructure and can route prompts through a third party. Choose a self-hosted open-source LLM gateway when prompts must stay inside your network or you need to change how the proxy behaves. Choose an add-on when you already run that API gateway and want one control plane.

Among the self-hosted options, Bifrost, an open-source AI gateway by Maxim AI, is the strongest default for a platform team. It is written in Go, and Maxim AI's published benchmarks report about 11 microseconds of added overhead per request at 5,000 requests per second. Treat that as a figure to confirm on your own traffic, like any vendor number.

Beyond speed, it governs model calls, MCP tool calls, and agent traffic under one set of rules, and its virtual keys carry budgets and rate limits per key, team, or customer.

OptionKindNotable for
BifrostSelf-hosted, open sourceMicrosecond overhead; model, MCP, and agent traffic under one policy
agentgatewaySelf-hosted, open sourceBuilt around MCP and A2A, also routes LLM traffic
LiteLLMSelf-hosted, open sourceOne OpenAI-format API for 100+ providers, virtual keys
Kong AI GatewayAdd-on to Kong GatewayLLM, MCP, and A2A traffic for teams already on Kong
Cloudflare AI GatewayHostedCaching, rate limits, model fallback, cost analytics
OpenRouterHostedHundreds of models behind one endpoint, automatic fallbacks
Vercel AI GatewayHostedBudgets per team, project, or key, and provider failover

For the open-source options, read the license of the exact feature you need. agentgateway and Bifrost are Apache-2.0, though Bifrost puts clustering, identity-provider access control, and in-VPC deployment in a paid Enterprise tier. LiteLLM is MIT outside its enterprise/ directory, which has a separate commercial license.

How to evaluate one

Test a gateway on the behavior that breaks in production, in this order of importance:

  • Streaming. Tokens should arrive as the provider sends them, and a provider error in the middle of a stream should reach the client as an error.
  • Error handling. You should be able to set different behavior for rate limits, overload, and invalid requests.
  • Overhead. Record p99 added latency at your peak concurrency, not the median on an idle machine.
  • Key storage. Find out where provider keys live and who can read them.
  • Its own failures. Kill its database during a load test and watch what callers see.
  • Pass-through. Send a request that uses each provider-specific field you depend on and compare what the provider receives.

There is no single best LLM gateway. The right one passes these six tests on your traffic, at your concurrency, with your providers. Run the same script against two candidates and the choice usually makes itself.

Once all model traffic crosses one point, that point is also the cheapest place to measure it. What to record on every request covers that next step.

Frequently asked questions

What is an LLM gateway?

An LLM gateway is a reverse proxy between your applications and model providers. Applications call it with one API format and one gateway-issued key. The gateway authenticates the caller, picks a provider and model, fails over on errors, enforces budgets and rate limits, and logs every call with its tokens and cost. Adopting one is usually a base URL change.

What is the difference between an AI gateway and an API gateway?

An API gateway applies generic policy to HTTP traffic: authentication, routing by path, and limits counted in requests. An AI gateway understands model traffic. It counts tokens, prices each request, classifies provider errors such as rate limits and overload, and keeps streamed responses intact. If an API gateway adds AI plugins, check that they meter tokens, not just requests.

Is an LLM proxy the same as an LLM gateway?

Not quite. An LLM proxy translates one API format into each provider's and forwards the call. An LLM gateway adds the operational controls on top: caller keys, routing and failover rules, budgets, token-based rate limits, and a central log. The names overlap in practice, because most open-source proxies have grown gateway features over time.

What is the best open-source LLM gateway?

It depends on what you need to govern. For a platform team that wants model, MCP, and agent traffic under one policy with low overhead, Bifrost is the strongest default. agentgateway fits teams focused on agent protocols, and LiteLLM fits teams that want a large provider list. Test streaming, error handling, and p99 overhead on your own traffic before you choose.

Does an LLM gateway add latency?

Yes, but usually far less than users notice. A gateway adds a network hop and its own processing, which well-built gateways keep to microseconds or low milliseconds, against model calls that take seconds. Measure it yourself: record p99 added latency and time to first token at peak concurrency with streaming on, rather than trusting a vendor's benchmark.

Do I need an LLM gateway if I only use one provider?

Usually not, if one service calls that provider. The provider's SDK already retries with backoff, and its dashboard shows usage. A gateway starts paying for itself when a second team, application, or provider appears, or when security asks for one audit log. Adding it later is cheap, because the application change is a base URL and a key.

Sources

  1. 01ErrorsClaude API docs
  2. 02Rate limitsClaude API docs
  3. 03Prompt cachingClaude API docs
  4. 04Rate limitsOpenAI API docs
  5. 05Error codesOpenAI API docs
  6. 06AI GatewayCloudflare docs
  7. 07AI GatewayVercel docs
  8. 08QuickstartOpenRouter docs
  9. 09AI GatewayKong docs
  10. 10agentgatewayGitHub
  11. 11BifrostGitHub
  12. 12Bifrost benchmarksMaxim AI
  13. 13LiteLLMGitHub