LLM gateway
One proxy in front of every model provider: apps call a single API, and the gateway handles keys, per-team token quotas, retries and fallbacks, caching, redaction, logging and cost attribution in one place.
Analogy: A company travel desk: employees ask for a flight, the desk books it with the corporate card, enforces each department's budget, rebooks on another airline when one cancels, and sends finance one itemized bill.
How it works
- Teams get virtual keys: real provider keys never leave the gateway, and one team can be revoked alone.
- Quotas cap requests and tokens per minute: one 100k-token call is 1 request but can drain a TPM budget.
- Retry 429s, 5xx and timeouts with backoff and jitter; never retry 400, 401 or 403.
- A gateway should add single-digit ms per call, negligible next to hundreds of ms of TTFT.
- It is the platform's control point: switching a model or policy becomes a config change, not a migration.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your shared gateway caps each team at 300 requests/min. Every night the support bot starts getting 429s from the provider, while the batch team stays far under its request cap sending ~80k-token prompts. Which fix addresses the cause?
Go deeper
Full explanation
An LLM gateway is a reverse proxy between every application and every model provider. Apps call one OpenAI-compatible endpoint with a gateway-issued key; the gateway decides whether the call is allowed, where it goes and what gets recorded.
What it centralizes:
- Identity: teams get virtual keys. Real provider keys never leave the gateway, and you can revoke one team without rotating everyone.
- Quotas: per-team limits on requests and tokens per minute, plus dollar budgets. One 100k-token call is 1 request but can drain a whole TPM budget.
- Reliability: retries with backoff on 429/5xx, load balancing across keys and regions, cross-provider fallbacks.
- Cost and tracing: every call logged with model, tokens, latency, cost and team tag. That is your chargeback and your LLM observability & tracing.
- Policy: PII redaction, Guardrails: input, output, action hooks, model allowlists, Semantic caching.
Common picks: LiteLLM (open-source proxy), Portkey, Kong AI Gateway, Agent Router (formerly Envoy AI Gateway, renamed in September 2026), Cloudflare AI Gateway.
Why architects care: it is the control point of an AI platform. Once all traffic flows through it, switching a model, enforcing a new policy or answering "who spent $40k last week?" is a config change, not a migration across 30 services.
Code LiteLLM proxy: aliases, fallbacks, cache, virtual keys
# LiteLLM proxy config.yaml. Apps keep the OpenAI SDK and only change:
# OpenAI(base_url="https://llm-gw.internal/v1", api_key=TEAM_VIRTUAL_KEY)
model_list:
- model_name: chat-default # alias apps call; swap the model behind it
litellm_params:
model: openai/gpt-4.1-mini # example ids: any provider/model
api_key: os.environ/OPENAI_API_KEY # real key lives only here
rpm: 3000 # capacity of this deployment
tpm: 2000000
- model_name: chat-fallback
litellm_params:
model: anthropic/claude-sonnet-4-5
api_key: os.environ/ANTHROPIC_API_KEY
litellm_settings:
num_retries: 2 # 429 / 5xx / timeouts, with backoff
request_timeout: 60
fallbacks: [{"chat-default": ["chat-fallback"]}]
cache: true # exact-match response cache
cache_params:
type: redis
general_settings:
master_key: os.environ/LITELLM_MASTER_KEY
database_url: os.environ/DATABASE_URL # virtual keys, budgets, spend logs
# One key per team: POST /key/generate
# {"team_id": "search", "models": ["chat-default"],
# "rpm_limit": 300, "tpm_limit": 200000,
# "max_budget": 2000, "budget_duration": "30d"}Real example
A company has 25 teams calling OpenAI directly, ~40 keys scattered across repos and one shared bill. They put LiteLLM in front: each team gets a virtual key with a monthly budget and a TPM cap, and chat-default falls back to Claude. Week one, a nightly job sending 80k-token prompts hits its own 200k TPM cap instead of throttling the support bot. Month two, during a ~40-minute provider outage, the bot fails over and stays up. Finance gets per-team spend, and no app code changed beyond a base URL.
Trade-offs +4 · −3
+ You gain
- Swap models, add providers or enforce new policy in one place, without touching apps.
- Real cost attribution and chargeback per team, feature and model.
- Provider outages and 429s become fallbacks instead of incidents.
- Provider keys stay out of app code; virtual keys are scoped and revocable.
− You pay
- A new critical-path dependency: if it goes down, every AI feature goes down.
- One more hop; it must pass streams through unbuffered and stay in single-digit ms.
- A lowest-common-denominator API can hide provider-specific features unless it supports passthrough.
Use it when
As soon as several teams or several providers call LLMs: the moment you need spend per team, central key management, quotas or failover.
Avoid it when
One app, one team, one provider: the SDK with retries is enough. And don't build one from scratch before trying an open-source or managed gateway.
Numbers to know 4
- Provider limits are two-dimensional: requests/min and tokens/min (Anthropic splits input and output TPM). Your quotas must be too.
- Retry 429, 500/502/503, 529 (Anthropic overloaded) and timeouts with backoff + jitter; never retry 400/401/403.
- Rule of thumb: a gateway should add single-digit ms per call, negligible next to hundreds of ms of TTFT.
- LiteLLM exposes 100+ providers behind the OpenAI API format.
Common pitfalls 4
- Limiting requests only: one batch job with 100k-token prompts starves everyone. Cap tokens per minute too.
- Falling back to a model nobody evaluated with that prompt: the outage becomes a silent quality drop.
- Logging full prompts unredacted: the gateway becomes the biggest PII store in the company.
- Running a single instance with in-memory counters: a new SPOF and limits that drift per replica. Use ≥2 replicas and shared Redis.
Interview questions 3
Answer out loud first, then reveal.
Why put a gateway in front of LLM providers instead of letting each team use the SDK?Show answer
Because keys, quotas, spend, failover, logging and PII policy are cross-cutting. Doing them in 30 services gives 30 implementations that drift and no single ledger of who spent what. A gateway gives me one place for policy and one source of truth for cost. The trade-off is a new critical-path hop, so I keep it thin and stateless, run it multi-zone with limits in Redis, and keep business logic out of it. I'd start with LiteLLM or a managed gateway rather than build one.
Design per-team rate limiting for a shared LLM platform.Show answer
I limit on two axes, requests and tokens per minute, because one long-context call costs as much as hundreds of short ones. Output tokens aren't known up front, so at admission I reserve input tokens plus max_tokens and reconcile with real usage from the response. Counters live in Redis with sliding windows, and monthly dollar budgets alert at 80%. Team quotas must sum below the provider's org limit with headroom, and interactive traffic gets priority over batch, or one team's burst becomes everyone's 429s.
What breaks when the gateway fails over from GPT to Claude?Show answer
Anything tuned to one model: prompts, tool-call and structured-output behavior, context window size, token counts since the tokenizers differ, and the prompt cache, which starts cold. So I treat fallbacks as pre-evaluated pairs: each route's fallback passed the same eval suite, with its own prompt variant if needed. Where I can, I fail over to the same model in another region or cloud, like Claude on Bedrock or GPT on Azure, because that changes nothing about behavior.