LLM gateway guide: one control point for routing, keys, budgets and guardrails
What an LLM gateway (or AI gateway) does, which jobs belong in it – routing and fallback, API key management, rate limits and budgets, PII redaction, guardrails, logging and cost per team – when to build or buy one, and how to observe it with the OpenTelemetry GenAI semantic conventions.
Summary
- An LLM gateway (also AI gateway or LLM proxy) is a single service that sits between your applications and the model providers. Every model call passes through it, so routing, keys, limits, redaction, guardrails and logging are handled once instead of in every service.
- The most valuable jobs are usually the boring ones: provider keys that never reach application code, per-team rate limits and budgets, fallback when a provider is overloaded, and one consistent record of model, tokens, duration and errors for every call.
- A gateway is also a new critical dependency and a place where sensitive prompts pass. Keep it thin, record metadata by default and content only by decision, and observe it with the OpenTelemetry GenAI conventions so gateway spans sit inside the trace of the request that caused them.
The first AI feature in a company usually calls a model provider directly. One service, one API key in an environment variable, one SDK. Then a second team builds a chatbot, a third adds summaries to the support tool, someone tries a second provider, and a data team starts batch jobs. A year later there are a dozen keys, three providers, no shared limits, and nobody can say which feature caused last month's bill.
An LLM gateway is the usual answer to that sprawl: one control point that every model call passes through. This guide explains what an AI gateway does, which jobs belong in it and which do not, how to decide between building and buying, and how to observe the gateway itself so it does not become a black box in the middle of every AI feature.
What is an LLM gateway?
An LLM gateway, also called an AI gateway or LLM proxy, is a service between your applications and the model APIs they use. Applications send their requests to the gateway instead of to the provider. The gateway authenticates the caller, applies policies, forwards the request to a provider and model, and records what happened.
It is related to a classic API gateway, but model calls have properties that a generic gateway does not handle well:
- Cost depends on tokens, not on requests. One request can cost a fraction of a cent or much more, depending on the prompt and answer length. Limits and budgets have to count token usage, not just calls.
- Responses are often streamed. The gateway has to pass tokens through as they arrive and still count them at the end.
- Failures are routine. Rate limits, overloaded endpoints and context-length errors are part of daily operation and call for retries or a fallback model, not an outage.
- Payloads are sensitive. Prompts can contain customer data, source code or internal documents. Whatever the gateway logs is a copy of that data.
Why teams introduce an AI gateway
Teams rarely introduce a gateway because of one big problem. It is usually a collection of small ones that become hard to solve in every service separately:
- Key sprawl. Provider keys live in many repositories, CI variables and laptops. Rotating one means finding all copies first.
- No shared limits. A batch job exhausts the provider quota and the customer-facing chatbot starts failing.
- Unattributed spend. The invoice shows a total per account, not per team, feature or customer.
- Inconsistent policies. One team redacts personal data before sending prompts, another does not; one logs full prompts, another logs nothing.
- Provider lock-in. Switching models or adding a second provider means changing code in every service.
A gateway moves these concerns to one place. That is its strength and also its risk: everything that goes wrong there goes wrong for every AI feature at once.
LLM routing and fallback between providers
Routing decides which provider and model answer a request. Common rules:
- By alias. Applications ask for a logical name such as
summarize-default; the gateway maps it to a concrete model. Changing the model becomes a configuration change instead of a code change in every service. - By task or tenant. Simple classification goes to a smaller model, long documents to a model with a larger context window, a customer with data residency requirements to an endpoint in the right region.
- By weight. A small share of traffic goes to a new model, so you can compare duration, tokens and errors before switching fully.
Fallback rules that do not make things worse
Fallback means trying another model or provider when the first one fails. Done carelessly, it multiplies load and cost exactly when a provider has problems. A few rules help:
- Fall back only on errors that another provider can solve: rate limits, overload, timeouts. Do not retry invalid requests or context-length errors on another provider with the same input.
- Limit retries per request and use backoff. A request that tried three models and failed should fail fast, not keep trying.
- Check that the fallback model is good enough for the task. A cheaper fallback for a summary is fine; for a task with strict output formats it may silently break parsing downstream.
- Record every fallback on the span, so you can see how often it happens and which model actually answered.
API key management: keys that never reach application code
With a gateway, provider keys are stored in one place, ideally a secret store, and only the gateway uses them. Applications receive their own gateway credentials instead, one per service or team. That has several advantages:
- Rotating a provider key is one change in the gateway.
- Revoking a single team's access does not affect anyone else.
- Every call can be attributed to the credential that made it, which is the basis for limits, budgets and cost reports.
- Leaked application credentials can be limited in scope, for example to certain models or a daily budget.
Keep the provider keys out of logs, error messages and traces, and scan repositories for keys that were committed before the gateway existed.
Rate limits and budgets per team and feature
Rate limiting protects shared quotas; budgets protect money. A gateway can enforce both per credential, team, feature or customer:
- Request limits per minute protect against loops and runaway jobs.
- Token limits per minute or day are closer to what providers bill and limit.
- Budgets per team or feature per month can warn at a threshold and, if you decide so, block or downgrade to a smaller model when reached.
- Priorities keep customer-facing traffic ahead of batch jobs when the shared quota runs low.
Decide upfront what happens when a limit is hit. A clear error with a retry hint is better than a silent timeout, and a hard stop on a customer-facing feature is a business decision, not a technical default.
PII redaction and guardrails at the gateway
Because every prompt passes through the gateway, it is a natural place for policies on content. Two kinds are common.
PII redaction before the prompt leaves your network
PII masking replaces personal data such as email addresses, phone numbers or account numbers with placeholders before the prompt is sent to the provider. Pattern-based detection catches structured values well; names and free-text details are harder and need more careful rules or a dedicated detection step. Two points to plan for:
- Redaction changes the prompt. Test that answers are still useful when placeholders replace real values.
- If the answer needs the original value, the gateway has to map placeholders back, which means it holds the mapping for the duration of the request. Do not log that mapping.
AI guardrails on input and output
AI guardrails check prompts and answers against rules: blocked topics, signs of prompt injection, output that must match a schema, answers that contain secrets. At the gateway, guardrails apply to every application at once. That is useful for baseline rules, but application-specific checks often belong closer to the application, which knows what a correct answer looks like. Every guardrail adds latency and can produce false positives, so record each decision with the rule that triggered it and review blocked requests regularly.
Logging and tracing prompts and responses, with privacy
A gateway sees every call, which makes it the best place for a consistent record and the most dangerous place for an accidental copy of sensitive data. Separate two kinds of data:
| Data | Examples | Default |
|---|---|---|
| Metadata | Caller, team, feature, provider, requested and answering model, input and output tokens, duration, time to first token, finish reason, error type, fallback, guardrail decision | Always record |
| Content | Prompt text, system instructions, retrieved documents, model answer, tool arguments | Off by default; enable per use case with masking, short retention and restricted access |
For most operational questions, such as which model is slow, why costs rose or which feature fails, metadata is enough. Content is useful for debugging and evaluation, but it should be a deliberate decision with a purpose, a retention period and masking of personal data before storage.
Observing the gateway with OpenTelemetry GenAI semantic conventions
The OpenTelemetry GenAI semantic conventions describe how a model call is recorded as a span and as metrics. If the gateway emits telemetry in this format, its data fits into the same traces, dashboards and alerts as the rest of your system, and it is not tied to the gateway's own logging format. The conventions are still marked as in development, so pin the version you follow.
Which attributes the gateway should set
gen_ai.operation.name,gen_ai.provider.name,gen_ai.request.modelandgen_ai.response.modelfor operation, provider and modelgen_ai.usage.input_tokensandgen_ai.usage.output_tokensfor token usagegen_ai.response.finish_reasonsanderror.typefor how the call ended- the metrics
gen_ai.client.operation.durationandgen_ai.client.token.usagefor duration and tokens over time - your own attributes for team, feature, customer, route, fallback and guardrail decision; these are not part of the conventions, so name them consistently, for example with an
app.prefix
An example of a gateway span for a call that fell back to a second provider:
span: chat summarize-default
gen_ai.operation.name = chat
gen_ai.provider.name = provider-b
gen_ai.request.model = model-large
gen_ai.response.model = model-large-2026-09
gen_ai.usage.input_tokens = 1840
gen_ai.usage.output_tokens = 312
gen_ai.response.finish_reasons = ["stop"]
app.team = support
app.feature = ticket-summary
app.gateway.route = summarize-default
app.gateway.fallback = true
app.gateway.fallback_from = provider-a (rate limit)
app.gateway.guardrail = pass
Keep the gateway inside the trace
The most important detail is context propagation. When the calling service sends the W3C traceparent header and the gateway continues that trace, the gateway span appears inside the trace of the user request, next to database queries and HTTP calls. Then a slow answer can be traced from the user click through the service and the gateway to the provider. Without propagation, the gateway produces a separate trace for every call and the connection to the feature is lost.
If your applications are already instrumented with the OpenTelemetry instrumentation for their model SDK, decide which layer records the GenAI span. Client-side spans show what the application experienced, gateway spans show routing, fallback and policies. Both can coexist, as long as only one of them is used to count tokens and cost, otherwise every call is counted twice.
Cost per team, feature and customer
Once every call carries model, tokens and attribution attributes, cost per team, feature or customer is a calculation: tokens times the price of the model, grouped by the attributes you set. A few practical points:
- Set attribution at the source. The gateway knows the credential; only the application knows the feature and customer. Pass them as headers and record them on the span.
- Count cached tokens separately where the provider supports caching, because they are priced differently.
- Keep a price table per model with a validity date, so that historical reports do not change when prices change.
- Coding agents used by developers often do not go through your gateway. Collect their usage separately, for example from the OpenTelemetry data the agents export.
Our guide to LLM observability in production covers dashboards, alerts and cost control for AI features in more depth.
Build vs. buy: options for an LLM gateway
There are three broad options: a thin gateway you build yourself, an open-source proxy you run, or a managed gateway from a cloud or AI platform. A comparison of the trade-offs:
| Question | Build | Run open source | Managed service |
|---|---|---|---|
| Time to first value | Slow, depends on scope | Fast | Fastest |
| Control over data flow | Full | Full, you host it | Prompts pass through a further vendor |
| Provider and feature coverage | Only what you build | Broad, follows the project | Broad, follows the vendor |
| Operations effort | High | Medium | Low |
| Telemetry format | Your choice | Check for OpenTelemetry GenAI support | Check whether export to your own backend is possible |
Whatever you choose, check four things before you commit: latency overhead with streaming, behaviour when the gateway itself is down, whether telemetry can be exported via OTLP to your own backend, and where prompts and logs are stored. A gateway that cannot export its data keeps your most important AI telemetry in a separate silo.
Rolling out an LLM gateway step by step
- Inventory. List the services, jobs and keys that call model providers today.
- Start thin. Introduce the gateway with authentication, key management and telemetry only. Add routing and policies once traffic flows reliably.
- Migrate one service. Choose a service with real traffic but low risk, compare duration and errors before and after.
- Add limits and budgets. Start with warnings, then enforce once the numbers are understood.
- Add redaction and guardrails where the data and the use case require them, and measure their latency and false positives.
- Retire direct keys. Rotate the old provider keys so that calls bypassing the gateway stop working.
LLM gateway checklist
- Provider keys are stored only in the gateway; applications have their own credentials.
- Every call records caller, team, feature, provider, model, tokens, duration, finish reason and error type.
- The gateway continues the incoming trace context, so its spans appear in the request trace.
- Fallback only on retryable errors, with a retry limit, and each fallback is recorded.
- Request and token limits per credential; budgets per team or feature with a defined action at the limit.
- Prompt and response content is off by default; where enabled, it is masked, access-restricted and kept only briefly.
- Guardrail decisions are recorded with the rule that triggered them.
- The gateway has its own alerts on error rate, latency and unusual token growth, and a plan for when it is down.
- Tokens and cost are counted in one layer only.
- Old direct provider keys are rotated after migration.
How Obseria helps
Obseria is not an LLM gateway: it does not route, limit, redact or block model calls. It is where the telemetry from your gateway and your applications ends up, so you can see what the gateway does. Obseria AI Observability covers this within what you instrument:
- Model calls from spans: LLM monitoring identifies model calls via
gen_ai.request.model, the attribute the OpenAI and Anthropic instrumentations set on their own, and shows tokens, duration and error rates per model, filterable by model or service. - Inside the trace: because model calls are spans, gateway and client spans appear in the distributed trace of the request that triggered them, next to database queries and HTTP calls.
- Cost attribution: AI cost analytics breaks AI spend down by model, feature and customer, and for coding agents by model, person and team.
- Masking at ingest: the sensitive data scanner masks values such as email addresses, IBANs, card numbers, tokens, phone numbers and IP addresses in logs and spans before they are stored. It masks what reaches Obseria; it does not redact prompts on their way to the provider.
- Alerts and dashboards: check rules on error rates or durations notify your channels, and dashboards put AI spend next to other KPIs.
Obseria does not score the quality of model answers and has no guardrails of its own; if your gateway runs guardrails, send their decisions as span attributes or events and analyse them alongside the rest. To see your gateway's calls in your own data, start a free trial.
Frequently asked questions about LLM gateways
What is the difference between an LLM gateway and an API gateway?
An API gateway handles generic HTTP traffic: authentication, routing and request limits. An LLM gateway adds what model calls need: token-based limits and budgets, streaming, provider fallback, content policies such as PII redaction, and records of model and token usage.
Is an AI gateway the same as an LLM proxy?
In practice the terms are used for the same thing. "LLM proxy" often describes a simpler pass-through layer, "AI gateway" one with more policies, but there is no fixed boundary.
Does an LLM gateway add latency?
Yes, at least one extra network hop, plus the time for any redaction or guardrail checks. Measure it with spans on both sides and keep heavy checks out of the path where they are not needed.
Should the gateway log full prompts and responses?
Not by default. Metadata such as model, tokens, duration and errors answers most operational questions. Record content only for a defined purpose, with masking, restricted access and short retention.
Do we still need instrumentation in the applications?
Yes, at least trace context propagation and the attributes only the application knows, such as feature and customer. Without them, the gateway sees calls but cannot connect them to user requests.
When is a gateway not worth it?
With one service and one provider, a gateway mostly adds a dependency. It pays off once several teams, keys or providers are involved, or when you need shared limits, budgets or policies.