# Design an LLM Gateway

> How to build one front door for every AI model call in a company, with keys, token budgets, fallback and cost logs, for your AI interview.

**In short:** An LLM gateway is one service that every app calls instead of calling model providers directly. It holds the provider keys, checks each team's token budget, falls back when a provider fails, and records what each call cost.

AI and LLM interview question Q353, LLM system design. Advanced, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/design-an-llm-gateway

## Say it in 30 seconds

I'd put one gateway in front of every model provider, so apps never call a provider directly. The gateway holds the keys, checks each team's token budget, and picks a provider. If one fails, it retries only where that is safe, then moves to a backup. It logs tokens and cost per team. The hard part is counting tokens, not requests, so one batch job can't starve the claims app.

## Say it in 2 minutes

Picture a mid-size insurer with twenty-five internal apps. The claims assistant, the policy search tool and the call centre summariser all call a model. Today each one holds its own provider key and its own retry code. Nobody can see what the company spends, and one team can slow down all the others. An LLM gateway fixes that with one service in the middle that every app calls.

The gateway keeps the real provider keys, so each app gets its own app key, which can be revoked on its own. Before a call goes out, the gateway checks the team's token budget for the minute. Budgets count tokens, because some providers, such as Microsoft Foundry, set quotas in tokens per minute. If a provider returns an error, the gateway reads the reply, retries a few times where that is safe, and then sends the same request to a backup provider. A circuit breaker stops sending calls to a provider that keeps failing.

Three things I would say honestly. A gateway adds a hop, and if it goes down, everything goes down, so I would run several copies behind a load balancer, which spreads calls across them. A backup model can answer differently, so the log must say which model answered. A cache can save cost, but Cloudflare's cache only reuses exact repeats by default, and it must never share an answer between teams.

Last, every call writes one log line with the team, the model, the tokens and the cost. That log is sensitive too, because it can hold prompts, so it gets the same access rules as the data itself.

## What is an LLM gateway, in plain words?

An LLM gateway is one service that sits between your apps and the model providers. Every app sends its model calls to the gateway, and the gateway forwards them. Apps never hold a provider's key themselves, so only one place has to keep the keys safe. A token is a small chunk of text, often part of a word, that a model reads and charges for.

Think of a bank's payment switch. Branch systems don't call each card network on their own. Each payment goes through one switch that checks limits, picks a route and writes the record. If one network fails, the switch can send the payment another way. A gateway does the same job for AI calls.

A real case: a claims assistant at an insurer reads a policy and drafts a reply for an agent. It should never be able to use the pricing team's key or spend the whole company's budget. The gateway enforces both.

- **Gateway:** The one service every app calls for model answers.
- **Provider:** The company that runs the model, such as a cloud service or the model maker.
- **App key:** The key an app uses to call the gateway. Revoking it leaves the provider key alone.
- **Token budget:** How many tokens a team may use in a minute or a month.
- **Circuit breaker:** A switch that stops calls to a provider that keeps failing, for a short time.

## How does one request travel through the gateway?

*Diagram, One request through the gateway: Every app calls the gateway, never a provider. The gateway checks the caller and the team's token budget, then picks a provider. The backup is used only when the main provider fails.*
1. The claims assistant sends its call to the gateway, never to a provider.
2. The batch job sends its call the same way.
3. A known app and team: the call moves on to the budget check.
4. The call is within the team's budget, so it moves on to pick a provider.
5. The call goes to the main provider first.
6. If the main provider fails, the same call goes to the backup.
7. The main provider's answer goes back out through the gateway.
8. The backup's answer does too, and the log records which one answered.

1. **Check the caller:** The gateway checks the app's key against its list of known apps and teams.
2. **Check the budget:** It estimates the input tokens before the call, then corrects the count from the real usage in the reply. It refuses the call if the team is over its limit for the minute.
3. **Pick a provider:** It sends the call to the main provider and keeps the backup ready in case the main one fails.
4. **Log the call:** It writes one log line with the team, the model, the tokens and the cost.

> **Tip:** Asked what the gateway leaves alone: the answer. It moves, limits and records calls, and the model writes the answer.

## Why count tokens and not requests?

A request count says little about load. One call that sends a 60-page contract uses far more model work than a hundred short chat messages. Some providers, such as Microsoft Foundry, assign quotas in tokens per minute, and Anthropic caps input and output tokens per minute as well as requests, so the gateway has to count tokens too.

The shared quota is where things break. When one app uses the whole quota, the other apps fail, even if they sent fewer requests. Microsoft's gateway guide describes this exact case, and OWASP's 2026 list says request counting is not enough on its own.

> "Traditional request-rate limiting alone is no longer sufficient." (OWASP, LLM06:2026)
>
> "Effective defense demands token-aware cost controls, hard spending caps, agent-level circuit breakers, and continuous cost-attribution monitoring." (OWASP, LLM06:2026)
>
> "You need to make sure that one app doesn't use the whole TPM quota and block other apps from accessing the backends they need." (Microsoft, API Management AI gateway)

Here is the budget check in plain Python. The providers are pretend, and the budget and the backup decide what happens.

```python
# A simplified gateway: a token budget per team for each minute, then a backup provider.
# No real providers here. Numbers are made up.
BUDGET = {"claims": 50_000, "pricing-batch": 20_000}  # tokens per minute, per team (demo: the count never resets)
used = {"claims": 0, "pricing-batch": 0}

def call(provider, healthy):
    if not healthy:
        raise RuntimeError(provider + " returned 503")
    return "answered by " + provider

def handle(team, tokens, main_healthy):
    if used[team] + tokens > BUDGET[team]:
        return "429: " + team + " is over its minute budget"  # refuse here: no retry, no backup
    used[team] += tokens
    try:
        return call("main provider", main_healthy)
    except RuntimeError as err:
        return call("backup provider", True) + " (after: " + str(err) + ")"

print(handle("claims", 12_000, True))
print(handle("pricing-batch", 25_000, True))
print(handle("claims", 12_000, False))
print(used["claims"])
```

Output:

```text
answered by main provider
429: pricing-batch is over its minute budget
answered by backup provider (after: main provider returned 503)
24000
```

Read the 429 line. The gateway refuses the call without retrying it or sending it to the backup. A good refusal also carries a retry interval in seconds, so the caller knows when to try again.

## What happens when a provider fails?

Not every error should be retried, so the gateway has to tell them apart. A 429 reply means too many requests, and a 5xx reply means the provider's own server failed. It reads the error first, then follows the steps below.

*Diagram, When a provider fails: A provider error goes into a short retry step on the same provider, unless it is a spend-cap error, which skips the retries and goes to the owner. Each retry waits the time the error gives and is counted. When the tries run out, the same request moves to a backup provider.*
1. A rate-limit or 5xx error starts the retry step. A spend cap does not.
2. Each retry waits the retry-after time, if one is sent, and is counted.
3. When no tries are left, the call moves to the backup.
4. The backup's answer goes out, and the log says which model answered.

1. **Read the error:** A rate-limit reply with a retry-after time, the number of seconds the provider asks you to wait, means wait that long, then retry.
2. **Retry on the same provider:** A few tries, with pauses. Each retry is counted, so retries never run forever.
3. **Move to the backup:** Out of tries, the same request goes to a backup provider.
4. **Trip the breaker:** After repeated failures, new calls skip the sick provider for a while. Microsoft's breaker uses the Retry-After value to set that time.

Some errors must never be retried. Anthropic's monthly spend cap is one: the provider stops answering until access resumes, so a retry only fails again.

> "Retrying, including the SDK's automatic retries, fails until access resumes." (Anthropic, API rate limits)

> **Tip:** Asked how you would know which model answered? Have the gateway return the step that answered, as Cloudflare's gateway does with a response header.

## Where do the keys, the cache and the logs live?

Keys live only in the gateway. Each app gets its own app key, so one leaked key can be revoked without touching any provider key. Cloudflare's guide warns that a token with permission to run calls can reach every gateway in the account, including stored provider keys. So isolation has to come from separate Cloudflare accounts or a server-side binding, not from a token's scope.

A cache saves cost, but Cloudflare's cache only reuses an exact repeat by default. It matches the whole request, so one changed word means a new call. The cache key must include the team, so one team's answer never reaches another team.

Logs are sensitive. A log line can hold prompts and answers, and those can hold customer data. Give logs the same access rules as the data, and keep cost totals separate if the wider company needs them.

### How would you stop a batch job from starving the claims assistant?

Put the batch job on its own budget. The claims assistant keeps its share, and the batch runs in quiet hours under a lower cap. Keep a monthly spend cap as well, so one runaway job cannot run up the bill.

- **Without budgets: Claims fail all afternoon.** The batch job uses most of the shared quota, and claims calls fail with 429 errors until it ends.
- **With budgets: Each team keeps its share.** The batch job hits its own cap and waits. Claims keeps its tokens, and the log shows which team used what.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: one service that every model call goes through.
- [ ] What it holds: provider keys, team budgets, retries, fallback and logs.
- [ ] Token budgets, not just request counts, and why.
- [ ] A backup provider and a breaker, and the spend cap that must never be retried.
- [ ] Isolation: separate keys per app, a cache key per team, and private logs.
- [ ] Its own risk: it is one more hop, so it runs in several copies.

**Common traps**

- Trap: "It only forwards requests, so it needs no logic." Better: It holds the keys, the budgets, the retries and the logs. Most of the design work sits there.
- Trap: "Counting requests per minute is enough." Better: One large call can use more of the shared quota than many small ones. Count tokens.
- Trap: "Retry every error three times." Better: Read the error first. A spend cap must never be retried. A budget refusal waits for the window to reset.

## Can you spot the problem?

**Spot the problem:** Which gateway setting is wrong?

A. Budget: claims 50,000 tokens per minute, pricing batch 20,000
B. Retry: on a spend-cap error, try the same call three times
C. Fallback: after a 5xx error, send the same request to the backup
D. Logs: one line per call with team, model, tokens and cost

**Answer:** B. Anthropic's spend-cap error has no retry-after time, and retries fail until access resumes. The gateway should stop and alert the owner, not retry.

**Quick check:** A team's batch job uses most of the shared tokens per minute. What should the gateway do first?

A. Count requests per minute only
B. Refuse that team's calls once it passes its own token budget
C. Send the batch calls to the cache
D. Give the batch job the provider's master key

**Answer:** B. A per-team token budget stops one job from using the whole quota. Request counts miss big calls, Cloudflare's cache only reuses exact repeats by default, and a shared master key removes isolation.

## Can you answer these from memory?

**Flash cards**

- **What is an LLM gateway?** One service every app calls. It holds the keys, budgets, retries and logs.
- **Why count tokens, not requests?** One huge call can use more shared quota than hundreds of small ones.
- **Who holds the provider keys?** The gateway. Each app gets its own app key, which can be revoked.
- **When does a fallback fire?** When the main provider errors. Cloudflare can also fall back on timeouts.
- **Can you retry Anthropic's spend-cap error?** No. Retries fail until access resumes, so stop and alert the owner.
- **What does a circuit breaker do?** It stops calls to a provider that keeps failing, for a short time.

## Likely follow-up questions

- Q354 What are the multi-tenant concerns? https://designervenkat.online/interview/ai/what-are-the-multi-tenant-concerns
- Q355 What is your fallback when a provider is down? https://designervenkat.online/interview/ai/what-is-your-fallback-when-a-provider-is-down
- Q356 Design rate limiting. https://designervenkat.online/interview/ai/design-rate-limiting
- Q357 Scale to millions of users. https://designervenkat.online/interview/ai/scale-to-millions-of-users
- Q359 Design an insurance-claims agent with RAG and cost control. https://designervenkat.online/interview/ai/design-an-insurance-claims-agent

## Learn it in depth

- [Protecting AI APIs](https://designervenkat.online/learn/ai-guardrails/api-protection)
- [Watching cost and speed](https://designervenkat.online/learn/ai-engineering/cost-latency-monitoring)
