Design an LLM Gateway
Understanding the Problem
🚪 What is an LLM gateway? An LLM gateway is a proxy that sits between a company's applications and the model providers they call: OpenAI, Anthropic, Google, models on Bedrock or Azure, and self-hosted models. Apps call one API with one kind of key; the gateway picks the provider, holds the real credentials, retries and fails over, caches what it can, records every request's tokens and cost, and stops teams from spending more than their budget.
You may get this as "design a proxy for all our OpenAI calls," "design a multi-provider LLM router," or "how would you control LLM spend across 200 teams." Same problem. Open-source projects such as LiteLLM and hosted products such as Cloudflare AI Gateway and Portkey are examples of the shape. It's related to a general API gateway (see /system-design/api-gateway), but LLM traffic is different enough to need its own design: requests are slow and streamed, they cost real money per token, and the "backends" are third-party providers with their own rate limits and outages.
Functional Requirements
Core Requirements
- Apps should be able to call any supported model through one OpenAI-compatible API, including streaming, without holding provider keys.
- The gateway should route each request to a provider deployment based on configured rules, and fall back to another one when a call fails.
- The gateway should cache responses where it's safe to, and make use of provider-side prompt caching.
- Teams should get budgets and quotas (dollars per month, tokens and requests per minute), and see their usage, cost and latency.
Below the line (out of scope)
- Serving models ourselves (see /ml-system-design/llm-inference); a self-hosted cluster is just one more provider to the gateway.
- Prompt management and evaluation tooling, beyond logging the data they need (see /ml-system-design/llm-evaluation).
- Content safety classifiers, beyond leaving a hook for them.
Non-Functional Requirements
Ask for scale and spend. For our design: about 200 internal apps, averaging 100 requests per second and peaking at 1,000. A typical request has 2,000 input tokens and 400 output tokens, and most responses are streamed.
Core Requirements
- The gateway should add little latency: under 10 ms of overhead at p99 before the request reaches the provider, and no added delay per streamed token.
- The gateway should be more available than any single provider: 99.99%, so a provider outage turns into a fallback, not an app outage.
- Budget enforcement should be close to exact: overspend bounded to a small, known amount, never "we found out at month end."
- Every request should be observable: tokens, cost, latency (time to first token and total), errors and the route taken, queryable by team within a minute.
- Provider credentials and logged prompts must be protected: keys never leave the gateway, and prompt logs are access-controlled and redacted.
Below the line (out of scope)
- Multi-region active-active budgets; we'll run budgets out of one primary region with a regional cache.
- Billing teams internally (chargeback), beyond producing the usage data.
Two estimates change the design. First, concurrency: a streamed response takes about 8 seconds on average, so at 1,000 requests per second we hold around 8,000 open streams at peak. The gateway is an I/O-bound proxy holding long-lived connections, not a CPU-bound request handler. Thread-per-request designs fall over here; an async proxy doesn't.
Second, money. 100 requests per second is 8.6 million requests a day, about 17 billion input and 3.4 billion output tokens. At an assumed $3 per million input tokens and $15 per million output, that's roughly $50k + $50k ≈ $100k a day, about $3 million a month. A 10% cache hit rate saves $300k a month; a budget bug that lets one runaway agent loop spend freely can cost more than the gateway's entire infrastructure.
In most systems the request rate drives the design. Here, a modest 100 requests per second carries millions of dollars a month, so cost accounting, budgets and caching are first-class features, not reporting add-ons. Make that point with numbers; interviewers notice.
The Set Up
Planning the Approach
We'll build the proxy path first (one API, credential handling, streaming), then add routing and fallbacks, caching, and budgets with observability. The deep dives cover low-overhead streaming, failover, caching, budget accuracy and safe logging.
Defining the Core Entities
- Virtual Key: the credential an app uses with the gateway. It belongs to a project and carries its limits and allowed models. It's not a provider key, and it can be revoked without touching any provider.
- Budget Scope: a node in the org → team → project → key hierarchy, each with an optional monthly budget and rate limits. A request is charged to every scope above its key.
- Model Route: what a model name or alias resolves to, like
chat-default→ weighted targets, plus an ordered fallback list and timeouts. - Provider Deployment: one concrete endpoint: provider, model, region, credential reference, its own rate limits (tokens and requests per minute) and price table.
- Usage Record: one request's facts: key, scopes, route, deployment attempts, tokens (input, cached, output), cost, latency, status and trace ID.
Separating the Route from the Deployment is what makes routing and fallbacks configurable: apps ask for chat-default, and the platform team decides which provider that means this week.
API or System Interface
The data plane is OpenAI-compatible, since most SDKs and frameworks already speak it:
POST /v1/chat/completions Authorization: Bearer vk_live_...
{ "model": "chat-default" | "claude-sonnet" | "gpt-4o", "messages": [...],
"stream": true, "max_tokens": 800, "temperature": 0.2 }
headers (optional):
X-Gateway-Cache: on | off
X-Gateway-Tags: feature=ticket-summary,env=prod
traceparent: 00-<trace-id>-<span-id>-01
-> 200 (SSE stream, same chunk format as the provider-neutral API)
response headers: X-Gateway-Deployment, X-Gateway-Cache: hit | miss, X-Request-Id
-> 402 { error: "budget_exceeded", scope: "team:search" }
-> 429 { error: "rate_limited", retry_after_ms }
POST /v1/embeddings
GET /v1/usage?scope=team:search&from=2026-11-01&group_by=model,tag
And a control plane for the platform team:
POST /admin/keys { project, allowed_models, rpm, tpm, budget_usd_month }
PUT /admin/routes/chat-default
{ targets: [{ deployment: "anthropic-direct/claude-sonnet", weight: 70 },
{ deployment: "bedrock-us-east/claude-sonnet", weight: 30 }],
fallbacks: ["azure-eastus/gpt-4o"], timeout_ms: 30000, first_token_timeout_ms: 5000 }
High-Level Design
1) Apps should call any model through one API
The simplest version is a fleet of stateless Gateway nodes behind a load balancer. For each request a node:
- Looks up the virtual key (cached in memory, backed by a Config Store in Postgres) and checks the requested model is allowed.
- Resolves the model name to a deployment (just one, for now).
- Translates the request into the provider's format. OpenAI's Chat Completions, Anthropic's Messages API and Gemini's API differ in how they represent system prompts, tool calls, images and stream events, so each provider gets an adapter that maps requests and responses both ways.
- Adds the real provider credential, fetched from a Secrets Manager (Vault, AWS Secrets Manager) and cached in memory, and forwards the call.
- Streams the provider's response back, translating each chunk.
Teams get a key in minutes, the provider keys live in one place, and switching an app from one provider to another becomes a config change. This version works, but one provider outage takes down every app pointing at it, and nobody can see or limit spend.
2) The gateway should route requests and fall back on failure
Now routes become real. A route resolves to one or more weighted targets: the same model through different deployments (Anthropic's API directly and the same model on Bedrock; several Azure OpenAI deployments in different regions, each with its own token quota) or different models entirely. Rules can also pick targets by request properties: data-residency tags send EU traffic to EU deployments, requests over 100k tokens go to a long-context model, and a tier=cheap tag maps to a small model.
Each node keeps a Health Tracker per deployment: recent error rate, latency and remaining rate-limit headroom (many providers return remaining-request and remaining-token headers on every response). Routing skips deployments that are unhealthy or out of headroom.
When a call fails with a retryable error (a 429, a 5xx, a connection error, or no first token within the timeout), the gateway tries the next target in the fallback list. We'll look at the details, especially for streams, in the deep dives.
3) The gateway should cache where it's safe
Two kinds of caching, at different layers:
- Response caching in the gateway. Hash the normalized request (model, messages, tools, sampling parameters) together with the tenant's cache scope, and store the response in Redis. An identical request within the TTL gets the stored response back in milliseconds for free. This helps for deterministic, repeated calls: classifiers and extractors run at temperature 0 over recurring inputs, evaluation re-runs, and retries.
- Provider prompt caching. Providers offer discounted, faster processing of a prompt prefix they've seen recently (some automatically, some with explicit cache markers in the request). The gateway can't cache for the provider, but it can help the cache hit: route requests that share a long prefix to the same deployment, and add cache markers for providers that need them.
Response caching is off by default and on per route or per request, since caching a creative-writing request at temperature 1 changes behavior. The deep dives add a semantic cache and the risks that come with it.
4) Teams should get budgets, quotas and visibility
Every request produces a Usage Record. The gateway computes cost from the provider's reported token usage (input, cached input and output tokens) and the deployment's price table, then:
- updates budget and rate-limit counters in Redis (per key, project, team and org), and
- publishes the record to Kafka, from where it's written to ClickHouse for dashboards and queries ("cost by team by model this month," "p95 time to first token for
chat-defaultper deployment").
Before forwarding a request, the gateway checks the key's scopes: requests and tokens per minute (as in /system-design/rate-limiter, but counting tokens as well as requests) and remaining monthly budget. A team that's out of budget gets a 402 with the scope that ran out.
The gateway also sends OpenTelemetry spans for each request and each provider attempt, so an app's trace shows the LLM call, which deployment served it, retries and token counts next to its own spans.
Potential Deep Dives
1) How do we proxy streams without adding latency?
The gateway sits on every LLM call. If it adds 200 ms, every chat feels slower; if it buffers streams, users stare at a blank box for 10 seconds.
Bad Solution: Buffer, Then Respond
Approach
Forward the request, wait for the provider's full response, count tokens, log it, and then send it to the app. Simple, and token counting is trivial.
Challenges
It throws streaming away. Time to first token becomes the total generation time, which is seconds. A thread or worker per in-flight request also caps concurrency: with 8,000 streams open at peak, a thread-per-request server needs 8,000 threads mostly waiting on sockets.
Good Solution: Async Streaming Proxy
Approach
Run the gateway on an event-driven runtime (Go, Rust, Node, or an Envoy-based proxy with filters) that handles thousands of connections per core. Forward each chunk from the provider to the client as soon as it arrives, translating the event format on the fly. Ask the provider to include token usage in the final stream event (most support this), so cost is known at the end without buffering.
Challenges
Anything that still happens synchronously before forwarding adds up: a Postgres lookup for the key, a call to the secrets manager, a remote budget check, a synchronous log write. Each is a few milliseconds and a new failure mode on the hot path.
Great Solution: Async Streaming With Everything Else Off the Hot Path
Approach
Keep only what must be synchronous on the request path, and make that local:
- Config, keys and routes are pushed to every node and held in memory; a change propagates in seconds through a watch on the config store. A key lookup is a hash map read.
- Provider credentials are cached in memory with a TTL and refreshed in the background.
- Budget and rate checks are one round trip to Redis, run with a single Lua script that checks and reserves across all of the key's scopes at once (deep dive 4). If Redis is slow, a local fallback decides.
- Logging and usage are fire-and-forget: the record goes to an in-memory buffer and then to Kafka in batches. A Kafka hiccup never blocks a response; the buffer spills to local disk if needed.
- Connection pools to each provider are kept warm with HTTP/2 or keep-alive, so we don't pay TLS handshakes per request.
With this, the overhead is a millisecond or two of CPU plus one Redis round trip, well under the 10 ms target, and the provider's own latency (hundreds of milliseconds to the first token) dominates.
Challenges
Fire-and-forget logging means a crashed node can lose its last few seconds of usage records. Budgets are enforced from Redis, so that's mostly a reporting gap; for billing-grade accuracy, reconcile against provider usage exports daily (deep dive 4).
2) How do we fall back when a provider fails or rate-limits us?
Providers have outages, regional incidents and, most often, rate limits. Without a gateway, every app writes its own retry logic, usually badly.
Bad Solution: Let Each App Retry
Approach
Return provider errors to the app and let it retry.
Challenges
Every team builds a different, usually naive retry loop. During a provider incident, thousands of clients retry at once against the same failing endpoint, making it worse. Nobody can switch to another provider without a code change in 200 apps.
Good Solution: Retries With a Fallback List
Approach
The route has an ordered fallback list. On a retryable error, the gateway retries once with jittered backoff on another target of the same model, then moves to the fallback model. Non-retryable errors (400 invalid request, content policy refusals, context too long) go straight back to the app, since another provider won't fix them.
Challenges
Streams complicate this. If the provider fails after we've already streamed 200 tokens to the client, we can't silently restart on another provider: the client would get a response that changes halfway through. And with no notion of health, every request still tries the failing primary first, waits for it to time out, and only then falls back, so an outage adds the full timeout to every request.
Great Solution: Health-Aware Routing, Circuit Breakers and Stream-Safe Fallback
Approach
Make failover proactive and stream-aware.
- Circuit breakers per deployment. If a deployment's error rate or timeout rate over the last 30 seconds crosses a threshold, open its breaker: route around it entirely, then probe it with a small share of traffic until it recovers. During an outage, requests go straight to a healthy target instead of timing out first.
- Rate-limit awareness. Track each deployment's remaining tokens and requests per minute from response headers and our own counts. Route new requests to deployments with headroom before they start returning 429s. For deployments with reserved capacity (provisioned throughput), fill those first since they're paid for anyway, and overflow to pay-as-you-go.
- Fallback only before the first token. A stream can be retried transparently until the first content chunk is sent to the client. After that, a failure is returned to the client as an error event with a clear reason. We use a short first-token timeout (say 5 seconds) separate from the total timeout, because a provider that hasn't produced a token in 5 seconds is probably stuck, while a long answer can legitimately take a minute.
- Retry budgets. Retries across the fleet are capped at, say, 10% of requests per deployment. During a big incident we fail some requests rather than tripling load on providers that are already struggling.
- Optional hedging. For latency-critical routes, send a second request to another deployment if the first hasn't produced a token after the p95 time to first token, and cancel the loser. It costs extra tokens, so it's a per-route opt-in.
Challenges
Fallbacks across models aren't equivalent: a prompt tuned for one model may behave differently on another, and tools or JSON modes may differ. Fallback lists that change model should be configured by the app team, tested with their evals, and visible in the response (X-Gateway-Deployment) so they know when it happened. See /system-design/resilience-patterns for the general patterns.
A crisp line for the interview: "We can fail over freely until the first token is streamed; after that, the client has seen output and we surface the error." It shows you understand that streaming changes what a retry means.
3) How do we cache LLM responses?
At $3 million a month, caching is attractive. But a cache that returns the wrong answer is worse than no cache.
Bad Solution: Cache Every Request by Its Text
Approach
Hash the request body and cache every response for an hour.
Challenges
Requests at temperature above zero are supposed to vary, and caching them changes product behavior. Requests that include the current time, a user ID or a random ID never hit. Worst, if the cache key doesn't include the tenant, one team's cached response, possibly containing its data, can be served to another team that sent the same prompt.
Good Solution: Opt-In Exact Caching, Scoped per Tenant
Approach
Cache only where the route or request opts in. The key is a hash of the normalized request (model, messages, tools, temperature, max_tokens and other parameters that change output) plus the cache scope (the project, unless a team deliberately shares). Store the response and its usage in Redis with a TTL per route. Return cached responses with X-Gateway-Cache: hit, and replay cached streams as streams so clients don't need a second code path. Bill a cache hit at zero (or a small fee) to the team.
Challenges
Exact matching only helps with exactly repeated requests. That's common for batch jobs, evaluation runs and retries, but rare for chat, where every conversation differs.
Great Solution: Layered Caching, From Provider Prefix Caching to an Opt-In Semantic Cache
Approach
Use the layer that fits each workload.
- Provider prompt caching is the biggest win for most traffic, and it's safe because the model still generates a fresh answer. Long system prompts, tool definitions, few-shot examples and RAG documents are often identical across requests; the provider reuses its computation for the shared prefix and charges much less for those tokens. The gateway helps by routing requests with the same prefix to the same deployment (consistent hashing on a hash of the first few thousand tokens), inserting cache markers for providers that need them, and reporting cached tokens per app so teams can see whether their prompts are structured for caching (stable content first, variable content last).
- Exact response caching, as above, for deterministic repeated calls.
- Semantic caching, opt-in per route, for things like FAQ bots where many users ask the same question in different words. Embed the last user message, search a vector index scoped to the route and tenant, and return the cached answer if the similarity is above a threshold tuned for that route. Only the last turn is compared, so it's limited to single-turn or lightly contextual use cases.
Challenges
Semantic caches make mistakes: "how do I cancel my order" and "how do I cancel my subscription" can be close in embedding space and need different answers. The threshold has to be tuned per route with labeled pairs, misses are cheap but false hits are bugs, and personalized or time-sensitive answers must never be cached. It also adds an embedding call and a vector search to every miss. Most teams should start with prefix caching and exact caching and add semantic caching only where they can measure that it's right.
4) How do we enforce budgets accurately?
The hard part of budgets is that we don't know a request's cost until it finishes. Output length is unknown, and a stream might run for a minute.
Bad Solution: Compute Spend From Logs Nightly
Approach
Aggregate usage records in the warehouse every night and disable keys that are over budget.
Challenges
An agent stuck in a loop, or a batch job with a bug, can spend tens of thousands of dollars in an afternoon before the nightly job notices. Budgets enforced a day late are reports, not limits.
Good Solution: Check Before, Charge After
Approach
Keep each scope's month-to-date spend in Redis. Before forwarding, check spend < budget for every scope. After the response, add the actual cost.
Challenges
Between the check and the charge, nothing stops concurrent requests. A team with $10 left can start 500 requests at once, every one passes the check, and the team overspends by 500 requests' worth of cost. For expensive models with long outputs, that's real money.
Great Solution: Reserve, Then Settle, Across the Scope Hierarchy
Approach
Treat each request like a card authorization:
- Reserve. Estimate the worst-case cost: input tokens (counted with the model's tokenizer, or estimated from length) times the input price, plus
max_tokenstimes the output price. A Lua script atomically checks thatspent + reserved + estimate ≤ budgetfor every scope (key, project, team, org) and adds the estimate to each scope'sreserved. If any scope fails, nothing is reserved and the request gets a402. - Settle. When the response finishes, a second script moves the actual cost from
reservedtospentin every scope and releases the rest. Actual cost comes from the provider's usage report; if a stream was cut off before the final usage event, we count tokens we streamed ourselves. - Expire. Each reservation has a TTL. If a gateway node dies mid-request, its reservations expire and are released, and the usage is recovered from the provider's own usage export during reconciliation.
-- KEYS: spent/reserved hashes for each scope; ARGV: estimate, budgets per scope
for i, scope in ipairs(scopes) do
local spent = tonumber(redis.call('HGET', 'spent', scope) or 0)
local reserved = tonumber(redis.call('HGET', 'reserved', scope) or 0)
if spent + reserved + estimate > budget[i] then return {0, scope} end
end
for _, scope in ipairs(scopes) do redis.call('HINCRBYFLOAT', 'reserved', scope, estimate) end
return {1}
Because the output can't be longer than max_tokens, the actual cost can't exceed the reservation (apart from small errors in estimating input tokens), so concurrent requests can no longer overspend. The gateway therefore requires max_tokens, or applies a default, on budgeted keys. Soft limits at 80% and 100% send alerts; a hard limit blocks.
Token rate limits work the same way at minute granularity, and they have a second purpose: provider deployments have their own tokens-per-minute quotas, so the gateway also allocates that shared provider capacity between teams, giving each a guaranteed share and letting them burst into unused capacity.
Daily reconciliation compares our usage totals with each provider's billing export. Differences above a small threshold mean a bug in price tables or token counting, and price tables change often enough that they belong in versioned config, not code.
Challenges
Worst-case estimates are pessimistic: a request with max_tokens: 4096 that usually uses 300 reserves 13× its typical cost, which can block a team near its limit. Reserving a percentile of the route's historical output length instead of the maximum cuts that, at the cost of a small, bounded overspend. Redis is now critical for budgets; if it's unavailable, fail open for small keys within a cached allowance and fail closed for keys with hard limits (the same trade-off as in /system-design/quota-service).
5) How do we log prompts safely and make the logs useful?
The usage record is metadata and is always kept. The prompt and response bodies are a different matter: they're the most valuable data for debugging and evaluation, and the most sensitive data in the company.
- Capture policy per route. Off, metadata-only, sampled (say 5%), or full. Regulated apps choose off or redacted.
- Redaction before storage. Run a PII detector (pattern rules for emails, phone numbers, card numbers, plus an NER model for names and addresses) over bodies before writing them, replacing matches with typed placeholders.
- Separate storage. Bodies go to an encrypted object store (S3 with per-team keys), referenced from the usage record by ID. ClickHouse holds only metadata, so dashboards never expose prompts.
- Access control and retention. Only the owning team can read its bodies, every read is audited, and retention is short by default (30 days).
- Feed evaluation. Sampled, redacted traces are exactly what offline evaluation and regression testing need (see /ml-system-design/llm-evaluation), and the gateway's routing config is a natural place to run model or prompt experiments on a percentage of traffic (see /ml-system-design/llm-ab-testing).
Interviewers often probe the security angle: provider keys exist in one place and never reach apps, virtual keys are scoped and revocable, prompt logs are redacted and access-controlled. Mention it without being asked.
Final Design
The full flow:
- An app calls
POST /v1/chat/completionswith a virtual key and a model alias. A gateway node looks up the key and route in memory (synced from the Config Store). - One Redis call checks rate limits and reserves the worst-case cost across the key, project, team and org budgets.
- If the request opts in, the gateway checks the response cache (exact, or semantic for routes that enable it) and returns a hit immediately.
- Otherwise it picks a deployment by weight, health, rate-limit headroom and prefix affinity, translates the request, adds the provider credential from the Secrets Manager cache, and streams the response back. Failures before the first token fall back to the next target; circuit breakers route around failing deployments.
- At the end of the stream, the gateway settles the reservation with the actual cost, stores cacheable responses, and buffers a usage record (plus a redacted body, if the route captures them) for Kafka.
- Kafka feeds ClickHouse for cost and latency dashboards and alerts, S3 for captured bodies, and a daily reconciliation against provider billing exports.
What is Expected at Each Level?
Mid-level
You should design a stateless proxy that holds provider keys, issues its own keys to apps, translates between provider formats and streams responses through. You should add retries with a fallback provider and per-team rate limits, and log usage with token counts and cost. With prompting, you should see that streaming rules out buffering the response.
Senior
You should do the concurrency and cost math, and design the hot path to be in-memory plus one Redis call with everything else asynchronous. Expect to explain stream-safe failover (only before the first token), circuit breakers and rate-limit-aware routing, opt-in exact caching scoped by tenant, and budget enforcement that handles concurrent requests with reserve-and-settle.
Staff+
You should frame the gateway as the company's control point for LLM cost, reliability and data governance. Expect to discuss sharing provider capacity across teams, provisioned vs on-demand capacity, why cross-model fallback needs evaluation, when semantic caching is worth its risk, reconciliation against provider bills, and prompt-logging policy for regulated data. Knowing what to leave to app teams (prompt design, model choice within allowed lists) is part of a strong answer.