Skip to content

How to design an LLM gateway

The first sections are free. The deep dives, level expectations and quiz are part of Pro.

On this page
Asked at
Practice this question

The problem

An LLM gateway is the one service a company's teams call to reach language models: it takes a request in a single shape, picks a provider deployment for it, holds the team to its limits, streams the answer back and records what the call cost. The answer turns on one fact: the company holds a single set of limits at each provider, and all teams draw on it. So admission has to be counted in one shared place rather than per instance, and the router has to read an overloaded provider as a reason to go elsewhere for a while, not as a reason to retry harder.

Clarifying questions

AskWhy it mattersA typical answer

How much traffic goes through the gateway, and how does that compare with the limits the providers give us?

It decides whether the gateway's own capacity or the provider's quota is the scarce thing, and that decides where the design effort goes.

About 16 million calls a month, around 25 a second at peak, against a provider limit of 10,000 requests and 10 million input tokens a minute for one model. The gateway instances are lightly loaded; the shared quota is what runs out.

Do teams name a provider's model directly, or an alias that we map to deployments?

An alias gives the gateway room to route, weight and fall back without changing callers. A hard-coded provider model leaves it almost nothing to decide.

Teams call an alias. The deployments behind it, their weights and the fallback order are set per alias.

When a provider is down, may we answer with a similar model from another provider, or must the call fail?

A different model answers differently, which some teams can live with and some can't. It fixes how deep the fallback chain may go.

Per team. Some accept a similar model, some would rather see an error. Make it a setting on the route, preferring a deployment of the identical model elsewhere.

Which limits do we hold a team to: requests, tokens, money, or all three?

Requests are easy to count before the call; tokens and money depend on an answer length you don't know yet, which shapes the admission step.

All three: requests a minute, tokens a minute, and a monthly spend budget.

Do callers need streamed answers?

Streaming turns a short request into a long open connection, which changes how instances are sized and what a mid-call failure looks like.

Yes. Answers stream token by token over server-sent events.

May the gateway store prompts and answers, or just the metadata of each call?

Content is the useful part for debugging and audit, and the sensitive part for privacy. The answer decides the shape of the usage pipeline.

Metadata for all calls. Prompts and answers as each team's logging policy allows, redacted where the policy says so.

Are the models all external providers, or do we also front models served on our own GPUs?

Self-hosted serving brings batching and scheduling with it, which is a different design. It belongs behind the gateway, not in it.

External providers in this round. An internal deployment could sit behind the same adapter interface later.

The requirements menu

RequirementScopeWhy

One API for every team, in one request shape, whichever provider serves the call

Core

The reason the gateway exists: callers write against one shape and the gateway translates per provider. Mirroring a widely used provider interface lets existing clients and libraries work unchanged.

Route each call to a provider and model by the team’s policy, and fall back to another when one fails

Core

Routing is what lets you move traffic without asking teams to redeploy, and fallback is what keeps callers working through a provider incident.

Hold each team to its limits: requests and tokens per minute, and a spend budget

Core

Without it one team's burst spends the company's shared quota and money. It is the requirement the hardest deep dive hangs off.

Stream answers back token by token

Core

Callers show answers as they appear, so the first token's latency is what users feel. It also makes the gateway hold long connections.

Record each call’s team, model, tokens, cost and latency for bills and audits

Core

Finance needs a bill per team and security needs a trail per call. Recording it off the request path is the design choice to defend.

Serve a stored answer when an identical request repeats

Optional

Tempting as a cost cut, and hosted gateways offer it. Take it when the interviewer asks about cost reduction: a cached answer changes semantics for prompts that expect fresh output, and the hit rate depends on how often prompts repeat exactly.

Let a team use a provider account of its own

Optional

It isolates that team's burst and makes its bill the provider's own invoice. Leave it unless asked: it removes the shared-quota problem the round is built around, and it scatters keys the gateway was meant to hold.

Redact personal data from prompts before they leave for an outside provider

Optional

Worth taking if security comes up, since Uber's gateway does exactly this and restores the redacted entities in the answer. It costs latency and some answer quality, so name that cost.

Embeddings and other endpoints beyond chat

Optional

The same path with a different request shape. Name it so the interviewer knows you saw it, then keep the round on chat.

Content guardrails that block harmful prompts or answers

Out of scope

A moderation system with its own models and policies. Say where it would plug in, before the provider call and on the answer, and move on.

Serving models on our own GPUs: batching and scheduling are behind the providers here

Out of scope

Inference serving is its own design. The gateway sees a self-hosted model as one more deployment behind an adapter.

Writing prompts and judging answer quality

Out of scope

Prompt engineering and evaluation belong to the teams that own the use case. The gateway carries prompts; it doesn't author them.

Training or fine-tuning models

Out of scope

A batch workload against training infrastructure, nothing like a request path. Park it.

Running agents and their tools

Out of scope

Agents make many model calls and run tools between them. Each call still goes through the gateway as an ordinary request, so nothing in the design changes for them.

Non-functional requirements

RequirementWhat it forces

Adds little latency: the first token arrives about as fast as when calling the provider directly

Admission is a handful of fast reads and increments against an in-memory store, with no synchronous database write on the request path. The stream is relayed as events arrive instead of being buffered, and the usage record is written after the answer, not before it.

Keeps the company inside each provider’s own limits, which every team shares

A second layer of counters, one per provider deployment, sized from the provider's published requests-per-minute and tokens-per-minute limits and checked before the per-team ones let a call through. When the provider still answers with an HTTP 429, the router backs off for the time the provider asks for.

One provider’s outage does not take the gateway down

The router keeps a health record per deployment, stops sending to one that keeps failing, and moves to the next deployment in the alias's chain with a cap on attempts and on total time. Gateway instances stay stateless so an instance tied up by a sick provider's hanging connections can be replaced without losing any state, though its open calls fail and are retried.

Limits hold across every gateway instance, not per instance

The counters sit in one store that all instances update with atomic increments, and no instance keeps an authoritative count of its own. You also have to say what the gateway does when that store is unreachable: fail open and risk the provider's rate-limit errors, or fail closed and refuse calls.

Prompts and answers are logged only as each team’s policy allows

The usage event carries metadata for all calls and no content. Prompts and answers go to a separate store behind a per-team flag, redacted before they are written, and the audit log records which key called which alias at what time, without the text.

Estimates

QuantityWorkingResultWhat it sizes

Average calls a second, and the peak against it

16,000,000 calls a month ÷ (30 days × 86,400 seconds = 2,592,000 seconds) ≈ 6.2 a second; peak 25 ÷ 6.2 ≈ 4

About 6 calls a second on average, with a peak about 4 times the average

The gateway fleet: a few instances cover this, so the design effort goes to the shared quota and the open streams, not to request throughput.

Share of the provider's request limit used at peak

10,000 requests a minute ÷ 60 ≈ 167 a second; 25 ÷ 167 ≈ 15%

Peak traffic uses about 15% of one model's request limit

The headroom that one team's burst can take from everyone else before the provider starts refusing.

Tokens per request at which the token limits bind before the request limit

10,000,000 input tokens a minute ÷ 10,000 requests a minute = 1,000 input tokens a request; 2,000,000 output tokens a minute ÷ 10,000 = 200 output tokens a request

Above about 1,000 input tokens or 200 output tokens a request, tokens run out before requests do

A rough sign of which bucket a team's traffic presses on first: input tokens when prompts run long, requests when they are short. Output length, cache reads and the other teams' traffic can shift it either way.

One team's hundredfold burst against the provider limit

25 a second ÷ close to 30 teams ≈ 0.8 a second ≈ 50 a minute for an average team; × 100 = 5,000 a minute; at 1,000 input tokens each, 5,000,000 input tokens a minute

One average team at a hundred times its traffic takes about half the request limit and half the input-token limit

The per-team cap: well under half the provider limit, so a single runaway job can't take the rest of the company past it.

An even split of the provider's limit across teams

10,000 requests a minute ÷ 30 teams ≈ 333 a minute each; 10,000,000 input tokens a minute ÷ 30 ≈ 333,000 input tokens a minute each

About 333 requests and 333,000 input tokens a minute per team if split evenly

The floor each team keeps for itself. Whenever a team sits below its floor, that share is idle, which is why borrowing matters.

Retry amplification when half of calls fail

10,000 calls a minute with half failing = 5,000 failures; one retry each on the same provider = 15,000 attempts a minute; two retries each = 20,000

One blind retry turns a full provider into one and a half times full; two retries double the load

Why retries need a cap and a cooldown: at a limit of 10,000 a minute the retries themselves come back as rate-limit errors.

Open streams the fleet holds at once

10,000 calls a minute ≈ 167 a second; if each stream stays open for an assumed 10 seconds, 167 × 10 ≈ 1,670 open at once; at an assumed 30 seconds, about 5,000

Between about 1,700 and 5,000 open connections, depending on how long answers take

Gateway instances: by concurrent connections and the memory each holds, not by requests a second.

Usage log growth

16,000,000 calls a month × an assumed 500 bytes of metadata per record ≈ 8 GB a month; with prompts and answers at an assumed 4 KB per call, 16,000,000 × 4 KB ≈ 64 GB a month more

About 8 GB a month of metadata; about 64 GB a month more if full content is kept

The usage store: metadata is cheap enough to keep for years; content is what the per-team logging policy decides.

Core entities

EntityWhat it holds

Team

Who is calling, what they may call, and how much of it they may use.

Route

One model alias and the ordered list of deployments that can serve it.

Provider deployment

One model at one provider in one region, with its own health and its own limits.

Usage record

One event per finished or cut call, the row a bill and an audit both read.

Price

What a token costs at one provider for one model, with the date the price took effect.

The API

EndpointNotes

POST /v1/chat { model, messages, stream } → the answer, or tokens over SSE

The one shape all teams use; model is an alias, not a provider's name. The gateway checks the key, runs admission, picks a deployment and returns a request id in a header so a caller can quote it. With stream true the response is server-sent events; a failure after the first token arrives as an error-typed event on the open stream.

GET /v1/usage?team=…&from=…&to=… → tokens and cost

Reads the priced usage records, not the fast counters, so it matches the bill. The latest minutes may be missing until the cost job has run; say so in the response.

PUT /teams/{id}/limits { rpm, tpm, monthly_budget }

Writes the team row and pushes the new values to the gateway instances' policy cache. The next request is admitted against the new limits; running calls are not cut.

PUT /routes/{alias} { deployments, weights, fallbacks }

Changes where an alias goes without any team redeploying. Validate that each fallback can take the alias's request shape, and roll a change out by weight first so a bad deployment gets a small share before it gets the whole alias.

The high-level design

streamTeam serviceGatewayAdaptersProviders

Step 1 of 4

One shape in, one adapter per provider out

Start with the translation job. A team service sends POST /v1/chat with an alias in the model field. The gateway checks the team's key, loads its policy, and hands the request to the adapter for the provider behind that alias. The adapter rewrites the common request into the provider's own API, opens the call, and relays the provider's stream back as server-sent events in the gateway's common event shape, so a caller sees the same events whichever provider answered. Uber built its gateway this way, as a Go service wrapping each vendor's client behind an OpenAI-style interface. Instances are stateless, so any of them can take any request.

policyadmitauditerrorsstreamusagereadsTeam policyGatewayinstancesTeam serviceShared countersRouterAudit logDeployment healthProvider adaptersModel providersUsage logCost jobPrice tableTeam billsReconcile vsprovider reports
The whole design

What breaks first

The deep dives

Routing and fallback. At peak the main provider begins refusing half its calls with overload errors. What does the gateway do with the next request, how does it decide a deployment is unhealthy, when does it try that deployment again, and what does a caller see when a retried call ran twice?

A concept that helps here: Retries and dead-letter queuesA concept that helps here: Idempotency keys

Limits and budgets per team. One team's batch job sends a hundred times its usual traffic, and the company holds one limit at the provider for all teams. How does the gateway keep the other teams working, and how does it count a team's tokens when the answer's length isn't known until the call ends?

A concept that helps here: Rate limiting algorithmsA concept that helps here: Multi-tenant isolationA concept that helps here: Failing open or failing closed

Streaming through the gateway. A user watches an answer appear word by word and the provider's connection drops halfway. Walk the stream from the provider through the gateway to the caller, name what limits how many streams one instance holds, and say what the usage log records for the cut stream and who pays for it.

A concept that helps here: Streaming LLM tokensA concept that helps here: WebSockets, server-sent events and pollingA concept that helps here: Backpressure and load shedding

Cost tracking and audit. Finance wants each team's bill to the cent and security wants each call traceable. How does one call's tokens become a cost on the right team's bill without slowing the call down, what happens to the records when the usage store is down for an hour at peak, and how do your bills get matched against the provider's invoice?

A concept that helps here: Event sourcing and ledgersA concept that helps here: Reconciliation against an external systemA concept that helps here: Queues and logs

Concepts this guide uses

Sources

  1. Uber engineering: Navigating the LLM landscape, Uber's GenAI Gateway
  2. Claude Platform docs: Rate limits
  3. Claude Platform docs: API errors
  4. Claude Platform docs: Streaming messages
  5. Claude Platform docs: Pricing (prompt caching multipliers)
  6. LiteLLM docs: Router, load balancing and cooldowns
  7. LiteLLM docs: Retries, fallbacks and cooldowns
  8. LiteLLM docs: Fallbacks (provider failover)
  9. LiteLLM docs: Budgets and rate limits
  10. Cloudflare docs: AI Gateway features
  11. Redis documentation: INCR (counter and rate limiter patterns)
  12. OpenAI developer docs: Rate limits
Sign in to report a mistake