SYSTEM DESIGN · DESIGN PROBLEMS · AI SYSTEMS · MEDIUM · 57 OF 57

Design an LLM Gateway: Quotas, Routing, Caching and Cost for Every Team

How to design the one internal service every team calls instead of calling model providers directly: a unified chat API, keys per team, token-per-minute quotas with reserve and refund, cost tracking and chargeback, routing with breakers and fallbacks, retries with idempotency, streaming pass-through, exact and semantic caching, PII redaction, data residency, sampled logging, a latency budget and high availability.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
1 / 21

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Token quotas
  • per-team chargeback
  • breakers and fallbacks
  • idempotent retries
  • careful caching
  • PII and region policy

Notes

Listen

Listen. Teams send chat and embedding requests to one endpoint in one format, whatever the provider behind it. Each team and app gets its own key. We enforce quotas in tokens per minute, track cost per team for a monthly bill, route and fall back between providers, stream answers, cache where safe, redact personal data, enforce which models and regions a team may use, and keep logs and traces.

The qualities. The gateway must add at most about twenty milliseconds at p ninety-nine, small next to a model's first token. It needs four nines, because it now sits in front of every AI feature. No app holds a provider key, no data goes to a model or region a team is not allowed, and one noisy team cannot starve the rest. Out of scope: training, agent logic and serving the models ourselves.

Functional
  • one endpoint for every model and provider, same format
  • a key per team and app
  • quotas in tokens per minute
  • cost per team, monthly bill
  • routing, retries, fallback
  • streaming responses
  • caching where it is safe
  • PII redaction, allow-lists, data residency
  • logs and traces for debugging
Non-functional + scope
  • adds ≤ 20 ms at p99
  • 99.99%: it sits on every AI feature in the company
  • no provider keys in apps
  • no data to a model or region a team is not allowed
  • one team cannot starve others
  • internal callers only out of scope: training, agent logic, serving the model

Ask scale

Scale. Say three hundred teams and about a thousand apps make ten million requests a day. That is about a hundred fifteen a second, and with a daytime peak of five times, about six hundred a second. A typical request sends two thousand input tokens and gets three hundred back. That is twenty billion input and three billion output tokens a day, and at peak about eighty-three million tokens a minute.

Turn that into decisions. At an assumed three dollars per million input tokens and fifteen per million output, that is about a hundred five thousand dollars a day, three million a month. That is why chargeback matters. Each answer streams for about seven seconds, so at peak four thousand two hundred streams are open. Providers cap tokens per minute per account, so eighty-three million must be spread over several accounts, regions and providers.

Back of the envelope
300 teams, ~1,000 apps and jobs
10M requests/day
  ≈ 115/s avg; daytime peak ×5
  ≈ 600 requests/s

per request: 2,000 in + 300 out
  = 2,300 tokens
day: 20B in + 3B out tokens
peak: 600 × 2,300 ≈ 1.4M tok/s
  ≈ 83M tokens per minute
What the numbers say
cost, at $3 / $15 per M tokens:
  20B in × $3 = $60k
  3B out × $15 = $45k
  ≈ $105k/day ≈ $3M/month
streams: 600/s × ~7 s each
  ≈ 4,200 open at peak
provider cap per account,
  e.g. 10M tokens/min per model
  → spread over accounts,
    regions and providers
bodies: 10M × 10 KB = 100 GB/day

Define API

The API. A chat call carries the team key and an idempotency key. The body names a model alias such as chat default, not a vendor model, so we can change what it points to without touching any app. It has messages, max tokens and a stream flag. The response is server-sent events: deltas, then a final usage event. Shape it like the most common chat API, so existing SDKs just work. Add embeddings, a usage report and admin calls.

API
POST /v1/chat
  Authorization: team key
  Idempotency-Key: 7f3a…
  { model: "chat-default",
    messages, max_tokens,
    stream: true, metadata }
→ SSE: delta … delta … usage
POST /v1/embeddings
GET  /v1/usage?team=&month=
admin: keys, policies, routes

Data model

Data model. Config is small and read on every request: teams with a cost center, a token limit and a budget; keys, stored only as hashes; policies listing allowed models, region, PII mode, cache mode and log sampling; routes mapping an alias to ordered targets; and a price table with validity dates. That lives in Postgres and is pushed to the gateways. Usage events are big and append-only, so they go to a columnar warehouse.

Data model
teams: id, cost_center,
  tpm_limit, monthly_budget
api_keys: key_hash PK, team_id,
  app, scopes, revoked_at
policies: team_id, models[],
  region, pii_mode, cache, sample
routes: alias → ordered targets
  (provider, model, region)
prices: model, from, in/out/$
usage_events (columnar):
  ts, team, model, tokens, cost

High-level design

Trace a request. The gateway hashes the key and finds the team in its local config. It reserves tokens from the team's quota in Redis, runs policy checks, and the router resolves the alias to a provider, model and region. Policy and routing are modules inside the gateway process, not network hops. The provider streams tokens, and the gateway passes each chunk straight to the caller, converted to our one event format.

Interviewers will ask what the gateway costs in latency, so budget it. Key lookup from local memory is a tenth of a millisecond. The quota script in Redis is about one. Counting prompt tokens takes a millisecond or two, regex PII and secret scanning a few, an exact cache lookup one. Keep warm, pooled connections to providers. That is under ten milliseconds against a first token of up to two seconds. Slower checks are opt-in per route.

Policy runs before any byte leaves. Is this model on the team's allow-list? What data class and region is the team in? An EU team only reaches EU endpoints, and restricted data only goes to the self-hosted model. Personal data is blocked, masked or allowed per policy. Masking swaps an email for a placeholder and restores it in the answer, holding a few tokens so a placeholder split across chunks is caught. Leaked secrets are blocked.

Two side flows. The control plane pushes keys, policies, routes and prices to every node, which keeps them in memory. And every request emits a usage event, about a kilobyte, with tokens, cost, time to first token and status. Full prompts and answers are a hundred gigabytes a day and sensitive, so log one percent plus all errors, redacted and encrypted for thirty days. Carry the caller's trace id, and write everything asynchronously.

Overhead budget (ms)
target: p50 ≤ 5, p99 ≤ 20
auth: key hash, local cache  0.1
quota: Redis Lua script      1
tokenize the prompt          1-2
PII regex + secrets scan     2-5
exact cache lookup           1
route, pooled connection     0.5

model first token: 300-2,000
→ gateway ≈ 1-2% of TTFT
semantic cache, ML PII: opt-in
Policy before bytes leave
  • 1 key → team → policy
  • 2 model on allow-list? else 403
  • 3 data class + region: EU team → EU endpoints only restricted → self-hosted only 4 PII: block, mask or allow mask: email → [EMAIL_1], restore it in the response
  • 5 secrets in a prompt → block
  • 6 output: scan every ~50 tokens in a small buffer
Logging and tracing
  • every request → usage event: team, model, tokens in/out, cached, cost, TTFT, status 100%, about 1 KB each bodies: 1% sample + all errors redacted, encrypted, 30 days per-team opt in or out trace id from the caller; spans: policy, cache, provider, first token
  • async: local buffer → Kafka

Deep dive: quotas

Deep dive one: quotas. Requests per second is the wrong unit, because one request can be fifty tokens or a hundred thousand. Use a token bucket per team, say two million tokens a minute. Output size is unknown up front, so reserve the counted input plus max tokens, here twenty-eight hundred, then refund the unused four hundred ninety when the usage arrives. Over the limit returns four twenty-nine with Retry-After. The same buckets guard each provider account.

Cost. A consumer prices each usage event with the price row valid at that moment, because prices change, and treats cached input tokens at their cheaper rate. Totals roll up per team per hour into the warehouse and a monthly chargeback per cost center. A subtle case: the client hangs up mid-stream. Cancel the provider call so we stop paying, count the tokens already generated, and still bill them. Alert at eighty percent of budget, block at a hundred.

Tokens per minute
team bucket: 2M tokens/min
problem: output size unknown

before: reserve
  input 2,000 (counted)
  + max_tokens 800 = 2,800
after: actual 2,000 + 310
  refund 490 to the bucket
one Redis Lua script, atomic
over → 429 + Retry-After
tiers: interactive > batch
Cost and chargeback
usage event → Kafka →
  aggregate per team per hour
cost = in × price_in
  + cached × price_cached
  + out × price_out
  (price row valid at ts)
client hangs up mid-stream:
  cancel upstream, count what
  was generated, still bill
budget: alert 80%, block 100%
monthly chargeback by cost_center

Deep dive: routing

Deep dive two: routing. An alias maps to ordered targets, provider A, then B, then self-hosted, all in the allowed region. A circuit breaker per provider, model and region watches errors, rate-limit responses and time to first token. Slow counts as down. When A's breaker opens, new requests go to B. Fall back only before the first token is sent; mixing two models mid-answer is wrong. And run your eval set against each fallback model first.

Retries. Retry rate limits, server errors and timeouts, with backoff and jitter, at most twice, and never retry a bad request or a policy block. Cap retries at about ten percent of traffic, so an outage does not triple the load. Callers also retry, so store each idempotency key in Redis for a day. A duplicate of a running call waits; a finished one replays the stored answer. A timeout is not free: the provider may already have billed us.

Routes and fallbacks
  • route chat-default: 1 provider A, model X, EU 2 provider B, model Y, EU 3 self-hosted, EU
  • breaker per provider+model+ region: errors, 429s, TTFT
  • fall back only before the first token is sent
  • never leave allowed region
  • fallback model is evaluated on the same test prompts
Retries + idempotency
retry: 429, 5xx, timeout
  backoff + jitter, max 2
never retry 400 or a
  policy block
retry budget ≤ 10% of calls
  (stops retry storms)
Idempotency-Key in Redis 24 h:
  running → wait or 409
  done → replay stored answer
timeout is not free: the
  provider may have billed

Deep dive: caching

Deep dive three: caching. An exact cache keys on a hash of team, model version, full messages and parameters. It is safe for deterministic work: temperature zero extraction, classification, embeddings and eval reruns. Never share entries across teams, and skip calls that use tools. Separately, providers cache prompt prefixes and bill those tokens at a big discount. Help them: keep the system prompt stable and first, and route the same prefix to the same provider and region.

A semantic cache embeds the prompt, finds the nearest stored prompt, and above a similarity threshold returns its answer. It sounds great until refund order eleven eighty-two and refund order eleven eighty-three score point nine nine, and one customer gets the other's answer. So make it opt-in per route, only for FAQ-style prompts without user data, never across teams, with short lifetimes, and measure the false-hit rate on sampled traffic. It also adds an embedding call.

Exact + prefix caching
exact cache (Redis, per team):
  key = hash(team, model,
    version, messages, params)
  safe: temperature 0,
    extraction, classification,
    embeddings, eval reruns
  TTL hours; skip if tools run

provider prefix caching:
  stable system prompt first,
  sticky route → cheap tokens
Semantic cache: careful
  • embed the prompt, nearest neighbour, similarity ≥ 0.95 → return the stored answer
  • danger: near but different "refund order 1182" "refund order 1183" similarity 0.99, wrong answer
  • safe only: opt-in per route, FAQ-like, no user data, never across teams, short TTL
  • measure the false-hit rate

Trade-offs

Availability. Gateway nodes are stateless, a dozen across three zones and two regions, sized so a whole zone can fail. If the control plane is down, nodes keep serving from cached config. If Redis is down, each node enforces its share of every quota locally and fails open, because blocking all AI traffic is worse. If Kafka is down, buffer usage to disk. Drain long streams before deploys, and isolate critical teams in their own cell.

The trade-off is one extra hop and one more critical system, in exchange for keys, cost, policy and fallbacks in a single place. Many companies start from an open-source proxy and add their own policy plugins. Monitor the gateway's own overhead, first-token time per provider, rate-limit responses, fallback rate, cache hits and dollars per team. At ten times the scale, add provider accounts and regions, and move simple high-volume tasks to self-hosted models.

High availability
  • stateless nodes, 3 zones, 2 regions; one zone can die
  • config cached in each node: control plane down → serve
  • Redis down → local quota share per node, fail open
  • Kafka down → disk buffer, drop sampled bodies first
  • deploys: drain streams 5 min
  • cells: critical teams apart
  • SDK: retry the other region
Trade-offs + monitoring
  • gateway vs direct calls: + one place for keys, cost, policy; - a hop, a SPOF
  • build vs buy: open-source proxy + our policy plugins
  • monitor: overhead p99, TTFT per provider, 429s, fallback rate, cache hits, $ per team
  • at 10x: more provider accounts, regions, self-hosted share for simple, high-volume tasks

Interview summary

The thirty-second version. Six hundred requests and eighty-three million tokens a minute at peak, about a hundred thousand dollars a day. One chat API with a model alias and a key per team. Token buckets that reserve and refund, and usage events that drive chargeback. Ordered routes with breakers, falling back only before the first token. Retry budgets and idempotency keys. Exact caching freely, semantic caching carefully. Policy before data leaves, all within twenty milliseconds.

Interview summary
  • 600 req/s, 83M tokens/min peak
  • one chat API, keys per team
  • TPM bucket: reserve, refund
  • usage events → chargeback
  • routes: ordered targets, breakers, fall back pre-token
  • retry budget + idempotency key
  • exact cache safe; semantic only opt-in policy: PII, allow-list, region
  • overhead p99 ≤ 20 ms, stateless

Interview questions

Q1Why rate limit an LLM gateway in tokens instead of requests?

Cost and provider capacity scale with tokens, and one request can be fifty tokens or a hundred thousand, so a token bucket per team, with tokens per minute as the unit, is the only limit that reflects real load and spend.

Q2How do you enforce a token quota when you do not know the output length in advance?

Count the input tokens and reserve input plus max_tokens atomically in Redis before calling the provider, then refund the difference once the final usage is known; reject with 429 and Retry-After when the reservation does not fit.

Q3When is it safe to fall back to another provider?

Only before the first token has been sent to the caller, only to a target that satisfies the same allow-list and data residency policy, and only to a model that has passed the same evaluation set; once streaming has started, fail the request instead of mixing outputs.

Q4How do you avoid double charges and duplicate answers when callers retry?

Callers send an idempotency key that the gateway stores in Redis with the request status; a duplicate of an in-flight call waits or gets a conflict, and a duplicate of a finished call replays the stored answer instead of calling the model again.

Q5When is semantic caching dangerous?

When prompts that differ in a small but important detail, such as an order number or a user name, embed almost identically, so the cache returns another request's answer; it is only safe as an opt-in for FAQ-style routes without user data, scoped per team, with short TTLs and a measured false-hit rate.

Q6How do you track and charge back cost accurately?

Emit a usage event for every request with input, cached and output tokens, price each event with the price row valid at that timestamp, aggregate per team and cost center, and still bill tokens generated before a client disconnected, after cancelling the upstream call.

Q7How do you keep the gateway from adding latency?

Keep auth, policy and routing in-process with config cached in memory, use one Redis round trip for quotas, cheap regex scanning on the hot path, warm pooled provider connections, and async logging, which keeps overhead to a few milliseconds against a first token of hundreds of milliseconds or more.

Q8How do you handle PII and data residency?

Each team has a policy with a data class and region; requests are only routed to allowed models in allowed regions, restricted data goes only to self-hosted models, and PII is blocked, masked with reversible placeholders, or allowed per policy before the request leaves.

Q9What happens if Redis or the control plane goes down?

Nodes keep serving from cached config, enforce an approximate local share of each quota and fail open, and buffer usage events locally, because blocking every AI feature in the company is worse than briefly loose limits.

Q10Why not let teams call providers directly?

Direct calls scatter provider keys across apps and give no central view of cost, no shared quotas against provider limits, no consistent fallback, and no single place to enforce privacy and residency; the gateway trades one extra hop for all of that.