esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
Let’s talk

I’ll build the agent for it.

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.

12 min readAdvancedCommon · estimateFacts checked 27 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

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.

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.

Key words

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?

One request through the gateway

Your apps

Claims assistant

reads a policy, drafts a reply

Pricing batch job

runs overnight, uses lots of tokens

The gateway

Check the caller

known app and team key?

Check the budget

tokens left this minute?

Pick a provider

picks the provider for each call

Main provider

first choice for the call

Backup provider

used only if the main fails

Answer to the app

one answer, one log line

  1. 1The claims assistant sends its call to the gateway, never to a provider.
  2. 2The batch job sends its call the same way.
  3. 3A known app and team: the call moves on to the budget check.
  4. 4The call is within the team's budget, so it moves on to pick a provider.
  5. 5The call goes to the main provider first.
  6. 6If the main provider fails, the same call goes to the backup.
  7. 7The main provider's answer goes back out through the gateway.
  8. 8The backup's answer does too, and the log records which one answered.
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. 1

    Check the caller

    The gateway checks the app's key against its list of known apps and teams.

  2. 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. 3

    Pick a provider

    It sends the call to the main provider and keeps the backup ready in case the main one fails.

  4. 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

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.

When a provider fails

Provider error

a rate-limit or 5xx reply

Same provider

Wait, then retry

use the retry-after time if sent

Tries left?

yes: retry, no: go to backup

Try backup provider

same request, different model

Answer or clear error

log which model answered

  1. 1A rate-limit or 5xx error starts the retry step. A spend cap does not.
  2. 2Each retry waits the retry-after time, if one is sent, and is counted.
  3. 3When no tries are left, the call moves to the backup.
  4. 4The backup's answer goes out, and the log says which model answered.
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. 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. 2

    Retry on the same provider

    A few tries, with pauses. Each retry is counted, so retries never run forever.

  3. 3

    Move to the backup

    Out of tries, the same request goes to a backup provider.

  4. 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."

    BetterIt holds the keys, the budgets, the retries and the logs. Most of the design work sits there.

  • Trap"Counting requests per minute is enough."

    BetterOne large call can use more of the shared quota than many small ones. Count tokens.

  • Trap"Retry every error three times."

    BetterRead 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?

Quick check

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

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q354What are the multi-tenant concerns?11 min
  2. Q355What is your fallback when a provider is down?12 min
  3. Q356Design rate limiting.12 min
  4. Q357Scale to millions of users.13 min
  5. Q359Design an insurance-claims agent with RAG and cost control.13 min

Learn it in depth

Last updated on 27 November 2026

Building an AI gateway for your company?

Venkat designs and builds AI products and agents, including the screens and the system behind them. Book a short call and say what you need.