System Design: LLM Gateway (Walnut Gateway: One API, Token Limits and Budgets, Fallback, Smart Routing, Caching, Metering and Billing)
We design an LLM gateway and call it Walnut Gateway. An LLM is a large language model, such as the models behind chat assistants.
A company's apps call many models from many companies. Each model company has its own API, its own limits, its own prices and its own failures. Walnut Gateway sits between the apps and all of them.
The apps see one API and one set of keys. The gateway holds the model companies' keys, enforces limits and budgets, falls back when a model fails and picks a cheaper model when it can. It also counts every token, so each customer gets a correct bill.
As in any system design interview, every number here is our own assumption for planning, and the design is our own.
All times are Eastern unless another time zone is named. All people, companies, apps and IDs in the story are made up; the cities are real.
1. Requirements
1.1 What we are building
Walnut sells Walnut Gateway to other companies. About 4,000 companies use it. We call each customer company a tenant. Walnut Gateway does six jobs:
- One API. Apps call every model through one API in one format, with keys we issue.
- Limits and budgets. Each tenant, team, app and key has limits in tokens a minute and budgets in dollars. Our accounts at each model company have limits too.
- Fallback. When a model fails or is busy, the gateway tries another place that runs the same model.
- Smart routing. An app can ask for "auto". The gateway then sends easy questions to a small, cheap model and hard ones to a large model.
- Caching and privacy. The gateway reuses answers where that is safe. It hides personal details before a prompt leaves, and keeps each tenant's data in its allowed region.
- Metering and billing. Every token is counted, each tenant gets a correct monthly bill, and our own bill from each model company is checked.
The story. It is the last week of October 2026.
- Tue 27 Oct, 10:14. In Boston, Laura Bennett's app at Harbor Health asks for a summary of a doctor's visit notes. The gateway hides the patient's name before the notes leave, and streams back the summary.
- 10:20. One model company has a bad hour in one region. One of Laura's answers breaks after 140 tokens. A Pinecrest Outfitters request fails twice and works on its third try.
- 13:02. A Pinecrest app gives up waiting after 30 seconds and sends the same long request again. Both run.
- 13:40 Pacific. In Seattle, Kevin Park's coding agent at Ridgeway Labs runs out of its team's daily budget.
- 21:12. A contractor at Ridgeway pushes one of its gateway keys to a public code site. Strangers start using it.
- Wed 28 Oct, 09:10. Jessica Nguyen works in Pinecrest's finance team. She asks why they were charged twice at 13:02.
- Thu 29 Oct, 10:00. Olivia Martinez is Pinecrest's product lead. She turns on smart routing for Pinecrest's product advice app.
- 11:05. One of our counter stores in US West slows down for 9 minutes.
- Fri 30 Oct, 15:00 Pacific. In Portland, Juniper Tutors uses up its prepaid credit.
- Mon 2 Nov, 10:00. After a five-day test, Pinecrest's help app starts answering repeat questions from a cache.
What happens to each of them:
- Laura's summaries all arrive. The broken one is asked again and answered 10 seconds later, and Harbor pays nothing for the broken one.
- Pinecrest pays only for the attempt that worked. Its two 13:02 charges are both correct. Its copy app now sends an Idempotency-Key, so a repeat of the same request gets the first answer and no second charge.
- Kevin's agent waits 12 minutes, until his admin raises the budget.
- On Thursday, Kevin's agent and the other tenants with hard budgets on the slow store get "retry in 5 seconds" for 9 minutes. Their retries pass from 11:14, and no budget is overspent.
- The leaked key is cut back after 7 minutes and revoked after 11. The strangers spent $212, inside the key's own daily budget.
- Pinecrest's advice app costs about 59% less, and its answers grade 85.4 out of 100 instead of 86.0.
- Juniper buys more credit and is back in 20 minutes.
- Pinecrest's help app answers about 18% of its questions from the cache. At most 1% of those cached answers are wrong for the question asked.
The hard part has four sides:
- Nobody knows the cost before the answer. The price depends on how many tokens the model writes. That is known only at the end.
- Two sets of limits. Our tenants have limits, and our own accounts at each model company have limits too. One model company counts all of max_tokens the moment a request arrives. Another counts output only as the model writes it.
- Failures in the middle. An answer streams for seconds. A model can fail after it has already sent half an answer.
- Every token is money. The gateway passes about $15 million of model spend a day. A counting error of 1% is $150,000 a day.
1.2 Words we use
Models and the companies that run them:
| Word | Meaning here |
|---|---|
| Model | One trained LLM, such as B-large. A larger model writes better answers, more slowly and at a higher price |
| Provider | A company that runs models and sells their use. In this post: Provider A, Provider B and Cloud C |
| Cloud C | A cloud company that runs Provider B's models in its own data centers and sells them too |
| Private pool | GPUs that Walnut runs itself for a few open models. GPUs are the chips that run models |
| Token | The unit a model reads and writes: a word or part of a word. About 4 characters of English |
| Input tokens | The tokens sent to the model: the instructions, the question and any earlier messages |
| Output tokens | The tokens the model writes. They cost about 5 times more than input tokens |
| Prompt | The text an app sends to a model |
| Stream | An answer sent piece by piece as the model writes it, so the reader sees words at once |
| Deployment | One place that runs one model, such as B-large at Provider B in US East. We reach it through one or more of our accounts there |
| Provider account | One of our accounts at a provider. Each has its own limits per minute |
Our parts and our rules:
| Word | Meaning here |
|---|---|
| Tenant | One customer company, such as Harbor Health |
| Virtual key | A key we issue to a tenant's app. It is not a provider's key and is useless outside our gateway |
| Alias | A model name we offer, such as "smart". Each alias maps to deployments of one model |
| Limit | A maximum number of tokens or requests a minute |
| Budget | A maximum number of dollars a day or a month |
| Hard budget | A budget that refuses new requests when it is spent |
| Soft budget | A budget that only sends an alert when it is spent |
| Reserve | Hold tokens and dollars before a call, for the most it could cost |
| Settle | Replace the hold with the real use, after the call |
| Lease | A share of a tenant's budget that one region may spend on its own, without asking the tenant's home region |
| Fallback | Sending a failed request to another deployment |
| Attempt | One try at one deployment. A request has one or more attempts |
| Prompt cache | A provider's cheaper price for the start of a prompt it saw a few minutes ago |
| p99 | The value that 99 of every 100 requests stay under |
Where things run:
| Word | Meaning here |
|---|---|
| Region | A part of the world where we run servers. We run three: US East, US West and EU West |
| Zone | One data center building inside a region. A region has three zones, so one can fail and the others keep working |
| Shard | One part of a store. The Counter store is split into shards by tenant, so each shard takes only part of the calls |
| Hash | A short fixed code made from some text. The same text always gives the same code, and the code cannot be turned back into the text |
| Hash tag | The part of a counter's name in braces, such as {harbor}. The store puts all names with the same tag on one shard |
IDs in the story. Every ID is made up.
| ID | What it names | Example from the story |
|---|---|---|
| req_7H2K | A request ID | Laura's first summary, Tuesday 10:14 |
| att_7H2K_1 | An attempt ID | The first attempt of that request |
| key_hb_notes_01 | A virtual key ID | The key of Harbor's notes app |
| dep_blarge_use1 | A deployment ID | B-large at Provider B in US East |
| pb-use-03 | A provider account ID | Harbor's own account at Provider B in US East, kept for Harbor alone |
| cc-harbor-1 | A provider account ID | Harbor's own account at Cloud C |
| pv_18 | A price version | The price list in force on Tuesday |
| cfg-88412 | A config version | The settings snapshot that revokes the leaked key |
| cfg-88903 | A config version | The settings that add the new model |
| key_rw_ci_07 | A virtual key ID | The Ridgeway key that leaked |
1.3 Every kind of request and change
Each kind comes in at a different rate and is handled by different parts. Every row is covered by a stage or a deep dive.
| Kind | What it is | How big or how often | Part that handles it | Outside company that takes part |
|---|---|---|---|---|
| Chat request | An app sends messages and gets an answer, streamed or whole | 1.5 billion a day; 60% streamed | Gateway | Provider A, Provider B or Cloud C |
| Auto request | A chat request with the model left to us | 10% of chat requests | Gateway, with its Difficulty scorer | The same providers |
| Embedding request | Text in, a list of numbers out, for search | 200 million a day | Gateway | Provider A or the Private pool |
| Batch job | A file of many requests, answered within 24 hours | About 50 million requests a day | Batch queue, Batch worker, Batch results store | The same providers |
| Key change | A tenant admin makes, rotates or revokes a virtual key | About 20,000 a day | Admin API, Config publisher | none |
| Budget or limit change | A tenant admin sets a budget or a limit | About 5,000 a day | Admin API | none |
| Credit purchase | A prepaid tenant buys credit | About 300 a day | Admin API | A card payment company |
| New model or price | Walnut adds a model or a provider changes a price | A few a week | Admin API, Config publisher | The provider |
| Monthly invoice | One bill per tenant, after each month | 4,000 a month | Billing job | none |
| Provider bill check | Our records against each provider's usage report | Every night, per provider account | Reconciler | Each provider's usage report |
1.4 Functional requirements
- One API. Apps call chat, embeddings and batch through one API in one format, and stream answers.
- Keys. Tenants make and revoke virtual keys. Provider keys never leave Walnut.
- Limits and budgets. Limits in tokens a minute and budgets in dollars. Each tenant, team, app and key can have them.
- Fallback. A failed attempt moves to another deployment of the same model, within the tenant's rules.
- Smart routing. For "auto", pick the cheapest model that keeps the answer quality the tenant set.
- Caching. Keep the provider's prompt cache working. Reuse whole answers only for apps that turn it on.
- Privacy. Hide personal details when a tenant asks, and keep data in the tenant's region. Store no prompt text for tenants that ask for zero retention.
- Metering. Count every token of every attempt, and show each tenant its use by team, app and key.
- Billing. A monthly invoice for each tenant, prepaid credit for small tenants, and a check of each provider's bill.
- Control. Add models, change prices and revoke keys without a deploy.
Out of scope:
- running the models themselves, which the LLM Inference Serving design covers;
- safety checks of the text, which the LLM Safety Pipeline design covers. The gateway only calls that check where a tenant turns it on;
- tool calls that agents make to other systems.
1.5 Non-functional requirements
- Fast. The gateway adds at most 20 ms at p99 to a request. Hiding personal details adds at most 30 ms more, only for apps that turn it on.
- Available. 99.99% of requests get an answer the app can use, about 4 minutes of failure a month. A failure that a fallback could have avoided counts against us.
- Budgets hold. A hard budget is never overspent by more than the estimate error of the requests in flight.
- Limits close. A limit in tokens a minute is right within 10% while the counter stores are healthy. While one is slow, a tenant may use more than its limit for a few minutes.
- Every token counted. Every attempt has a usage record within 1 minute. Our monthly total for each provider account is within 1% of its bill.
- Quick switch. Traffic leaves a failing deployment within 30 seconds.
- Region rules hold. A tenant's prompts never go to a region its rules do not allow, even in a failure.
- Capacity. 50,000 requests a second and 350,000 open connections.
1.6 The numbers
These sums count chat requests only. Embeddings and batch add about 250 million small requests a day, which change no decision here.
| Number | How we get it | Result | What it decides |
|---|---|---|---|
| Requests | 1.5 billion a day ÷ 86,400 seconds = about 17,400 a second. The busy hour is about 2 times that | About 35,000 a second at the busy hour; 50,000 at design | Gateway servers hold no data, so we add servers in three regions |
| Open connections | An answer of 400 tokens takes 0.8 s to start, then 400 ÷ 70 tokens a second, about 6 s. So about 7 s. 50,000 × 7 | About 350,000 open at once | The gateway mostly waits, so it is an event-driven program, not one thread per request |
| Counter calls | Reserve and settle, for the tenant and for our provider account: 4 calls a request. Each US region is built to carry 85% of design alone. If one fails, the other takes 42,500 × 4 = 170,000 calls a second | 170,000 a second in one region. That needs 15 shards at 12,000 each, so 17 with spare | Counters split by tenant. The tenant's checks need one call, and our provider account's checks one more |
| Tokens | 1.5 billion × 2,000 input and 400 output tokens | 3.6 trillion a day | Our provider accounts run out before our servers. Many accounts per model, each with its own counters |
| Spend | About $0.01 a request × 1.5 billion | About $15 million a day | 1% wrong is $150,000 a day, so every provider account is checked every night |
| Usage records | 1.05 attempts a request × 1.5 billion × 1.5 KB. For 13 months: 2.4 TB × 395 days = about 950 TB raw | About 2.4 TB a day. About 95 TB for 13 months, after compression of about 10 times | A store built for sums over columns, filled from a log, off the request path |
| Time budget | 20 ms added, against about 7 s for the answer | About 1 ms for each counter call | Every check runs in memory or in one call inside the region. Nothing on the path crosses regions |
| Auto requests | 10% of 50,000, scored in about 3 ms each on a CPU | 5,000 a second | The scorer is small and runs inside each gateway server, with no extra network call |
What these numbers tell us. Our servers are not the hard part; provider limits and money are. Every day, 3.6 trillion tokens pass through accounts that each count their own way. Every hold, retry and broken stream in the $15 million a day must be counted right.