The architecture concepts that show up when a product runs LLMs in production, explained with the code and the numbers of a project that actually runs: the llm-gateway.
What an LLM gateway is
It is a server that sits between your apps and the model APIs (Anthropic, OpenAI and others). The apps call the gateway instead of the provider, and the gateway solves in one place what every app with an LLM ends up needing.
Without a gateway, each service calls the model API directly, with the real key:
in each service, without a gateway
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
With the gateway, the service only changes the address and the key. The rest of the code stays the same, because the gateway speaks the same API format:
in each service, with a gateway
const client = new Anthropic({ baseURL: 'http://localhost:3000', apiKey: 'gw_acme_123' });
The problems it solves
The provider goes down
The model API returns overload errors for 20 minutes, and your product goes down with it. The gateway switches providers on its own.
One customer uses up everyone's quota
A customer fires requests in a loop and burns the tokens that belonged to everyone else. The gateway limits each customer separately.
Nobody knows what it costs
Someone asks "how much did customer X cost this month?" and there is no way to answer. The gateway records the tokens and the cost of every request.
The path of a request
Every request goes through these stops, in this order. Each stop answers one question and can end the request right there.
AuthenticationWho is the customer?Rejects with 401lesson 1
CacheHas this question been answered already?Answers right away, without calling the providerlesson 8
Rate limitDoes the customer still have tokens left?Rejects with 429lesson 3
Load balancerWhich provider should get it?Picks among the healthy oneslesson 4
Circuit breakerIs this provider failing?Skips the providerlesson 6
QueueDoes the provider have a free slot now?Waits, or rejects with 503lesson 7
Call and streamingPasses the response along as it arrivesIf it fails, tries another providerlesson 2
A customer of the gateway: an app, a team or a company. Each tenant has its own key and its own quota.
Provider
The API that runs the model. In the project, there are three fake providers that imitate the Anthropic API.
Token
The piece of text the model reads or writes, and the unit it is billed in. A token is about 4 characters of English text; other languages usually get a bit fewer.
SSE
Server-Sent Events: the format the API uses to send the response in pieces, over the same HTTP connection.
TTFT
Time to first token: how long until the first piece of the response arrives. It is what the user feels as "it started answering".
p50 and p99
The latency that 50% and 99% of requests stayed under. The p99 shows the worst case that still happens often.
How each lesson works
Every lesson has the same parts, always in the same order:
In one sentence: what the concept is.
When you need it: real situations where it is the right choice.
Why it is the usual choice: what it gains over the alternatives.
How it works: the flow, step by step, and the piece of the project's code that does it.
What the experiment showed: the mechanism on and off, with measured numbers.
Interview question: a question on the topic in the format of a system design interview, with a short answer.
A lesson counts as read when you scroll its page to the end. Each lesson read lights up a block in the top bar, and the progress is saved in this browser.
About the numbers
The numbers in the lessons come from the repository's pnpm bench command. It starts three fake providers, with a fixed latency (100 ms in most tests), and the gateway, all on the same machine. The numbers show the effect of each mechanism, not the performance against a real API. You can run it and check:
in the terminal
git clone https://github.com/nicomsz/llm-gateway
cd llm-gateway
pnpm install
pnpm test # 94 tests
pnpm bench # the experiments, about 3 minutes
Lesson 1 of 910 minNot read
Reverse proxy: the gateway in the middle
Why put one more server between the app and the provider, and how much that costs in latency.
In one sentence
A reverse proxy is a server that receives requests in place of the real server, decides what to do with each one and forwards it to whoever answers. An LLM gateway is a reverse proxy specialized in model APIs.
When you need it
More than one app uses LLMs
Without a central point, each app reimplements retries, limits and logging its own way, and each one holds a copy of the real API key.
The key cannot leak
The app gets a gateway key (gw_acme_123). The real provider key lives only in the gateway. If the app's key leaks, you revoke just that one.
You need to switch providers
With the gateway, changing providers or adding a second one is a config change in one place, with no deploy of the apps.
Why it is the usual choice
The alternative is a shared library installed in every app. It handles retries and logging, but not what depends on shared state: a tenant's quota has to be counted in a single place, even if the tenant uses three apps. The library also spreads the real key across every app, and a fix in it means updating and shipping each app again.
The cost of the gateway is one more network hop and one more thing that can go down. That is why it needs to be light (the experiment below measures this) and run as more than one copy.
How it works
The app sends POST /v1/messages to the gateway, with the tenant key in the x-api-key header.
The gateway looks up the key in the list of tenants. If it is not there, it answers 401 and stops.
It goes through the other stops (cache, rate limit, load balancer) and calls the chosen provider, now with the real key.
The provider's response goes back to the app unchanged. The gateway only adds its own headers, such as x-gateway-upstream, which says which provider answered.
At the end, the gateway writes one log line with the tenant, the provider, the latency, the tokens and the cost.
Why Object.hasOwn and not config.tenants[key] directly: with direct access, the key "constructor" would find a function inherited from Object and pass as a tenant.
What the experiment showed
2,000 requests, 20 at a time, to a fake provider that answers in 100 ms. First directly, then through the gateway.
Path
p50
p99
Requests per second
Straight to the provider
102.9 ms
113.2 ms
193
Through the gateway
103.9 ms
119.4 ms
189
The gateway added 1 ms to the median and 6 ms to the p99. Next to an LLM call, which takes from hundreds of milliseconds to several seconds, that is noise.
Interview question
Doesn't the gateway become a single point of failure?
It does, if you run a single copy. That is why it runs as several copies behind a regular load balancer, and the state that needs to be shared (tenant quotas and the cache) lives in Redis, not in each copy's memory. Lesson 3 shows what happens when Redis itself goes down.
Lesson 2 of 915 minNot read
Streaming, backpressure and cancellation
How to pass the response along in pieces without holding anything back, without blowing up memory, and without paying for text nobody will read.
In one sentence
With streaming, the provider sends the response in pieces while the model generates it, and the gateway forwards each piece to the app as soon as it arrives.
When you need it
Chat with the user waiting
A long answer takes 10 seconds to be ready. With streaming, the text starts showing in under 1 second. The total time is the same; what changes is when the user sees the first piece (the TTFT).
The user closes the tab
The model keeps generating text, and you keep paying for it, unless someone tells the provider nobody is reading anymore.
The client is on a slow network
The provider sends faster than the customer's phone can receive. Without control, the gateway piles up the excess in memory.
Why it is the usual choice
The Messages API uses SSE (Server-Sent Events): the response is a regular HTTP response, with content-type: text/event-stream, that does not end until the last event. Compared to WebSocket, SSE is plain HTTP: it uses the same headers, the same authentication and the same tools as any request, and data only flows from the server to the client, which is exactly the case of a model response.
The gateway does not assemble the whole response before passing it on. If it did, the app's TTFT would be the total response time, and the provider's streaming would be useless.
How it works
What travels over the connection is text, one event per block, separated by a blank line:
The gateway does three things with this stream, at the same time:
Forwards each piece to the app as soon as it arrives, without waiting for the next one.
Reads the events on the way, to know how many tokens were used (message_start carries the input, message_delta carries the running output total) and compute the cost.
Respects the client's pace:res.write() returns false when the output buffer to the client is full. Then the gateway stops reading from the provider until the drain event, which says the buffer emptied. That is backpressure: whoever receives more slowly controls the speed of whoever sends.
for await (const chunk of response.body!) {
log.ttftMs ??= Math.round(performance.now() - startedAt);
tracker.feed(parser.push(chunk));
// backpressure: if the client can't keep up, stop reading from the provider
if (!res.write(chunk)) await once(res, 'drain', { signal: abort.signal });
}
And cancellation: when the app closes the connection before the end, the gateway cancels the call to the provider with an AbortController. The connection to the provider closes, and it stops generating.
const client = new AbortController();
res.on('close', () => {
if (!res.writableEnded) {
log.canceled = true;
client.abort(); // cancels the queue, the wait and the call to the provider
}
});
What the experiment showed
A provider that sends the first piece in 200 ms and then 20 pieces, one every 50 ms. 300 requests, 20 at a time.
Path
First piece, p50
First piece, p99
Full response, p50
Straight to the provider
202 ms
207 ms
1,208 ms
Through the gateway
203 ms
221 ms
1,208 ms
The first piece arrives through the gateway 1 ms after it arrives directly. If the gateway assembled the response before forwarding it, that number would be 1,208 ms.
In the cancellation test, 100 clients closed the connection 400 ms after sending. All 100 cancellations reached the provider, which generated 429 of the 2,000 pieces it would have generated: 21% of the text, and of the output token cost. Input tokens are billed in full either way.
Interview question
Why doesn't the gateway keep the whole response and send it at once?
Because the app's TTFT would become the total response time, and the gateway's memory would grow with the size of each response times the number of requests in flight. Forwarding piece by piece, with backpressure, each request takes at most the size of one buffer.
Lesson 3 of 915 minNot read
Rate limiting by tokens
How to stop one tenant from using up everyone's capacity, counting what actually costs money: tokens, not requests.
In one sentence
A rate limit caps how much each tenant can consume per unit of time. Here it is counted in model tokens, with the token bucket algorithm.
When you need it
A tenant with a bug in a loop
An app gets stuck in a loop and sends 300 requests per second. Without a per-tenant limit, it takes up the provider's capacity, and the other tenants get errors.
Requests of very different sizes
A 50-token request and a 50,000-token one cost very different amounts. A "100 requests per minute" limit lets the expensive one through and blocks the cheap one.
Free plan and paid plan
Each tenant has its own quota. Changing a customer's plan is changing a number.
Why it is the usual choice
The token bucket keeps only two numbers per tenant: the balance and the time of the last update. The balance refills at a fixed rate up to a cap, and each request takes from it. Compared to a fixed window ("6,000 tokens per minute, reset on the minute"), it does not let the tenant spend the whole quota at the end of one minute and again at the start of the next. Compared to a sliding window that keeps the time of every request, it uses constant memory.
The LLM-specific problem: you only know how many tokens a request used after the response. The solution is to reserve and refund: on the way in, the gateway takes an estimate (the request body length divided by 4, plus the requested max_tokens); at the end, it gives back to the balance whatever was not used.
How it works
Example with a quota of 6,000 tokens per minute, that is, a refill of 100 tokens per second:
The tenant arrives with a full balance: 6,000.
A request is estimated at 1,200 tokens. The balance drops to 4,800, and the request goes through.
The response used only 300. The gateway refunds 900: the balance goes to 5,700, plus the little that refilled during the request.
If a request estimates more than the balance, the gateway answers 429 with the retry-after header: how many seconds until the refill covers the difference.
If the estimate is bigger than the whole quota (6,000), the request would never fit, however long the tenant waits. Then the gateway answers 400, not 429: waiting does not help.
With several copies of the gateway, the balance has to live in one place: Redis. But "read the balance, compute, write" as three separate commands has a race: two copies read the same balance of 1,000, both take 800, and both let the request through. That is why the math runs in a Lua script inside Redis, which runs the whole script before serving any other command.
local data = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
-- ... same refill as the in-memory version ...
if amount <= tokens then
tokens = tokens - amount
allowed = 1
end
redis.call('HSET', KEYS[1], 'tokens', tostring(tokens), 'ts', tostring(now))
And if Redis goes down? The gateway lets the request through (fail open): it goes without limits for a while instead of taking every tenant down along with Redis. For a system where blowing the quota costs more than being down, the right choice would be the opposite (fail closed).
What the experiment showed
A provider with capacity for about 100 requests per second. The tenant acme sends 300 per second; the tenant beta sends 20 per second.
Setup
beta: errors
beta: p50
acme: served
acme: 429
No rate limit
75.1%
1,137 ms
1,665
0
With rate limit
0%
104 ms
245
4,855
Without a limit, beta, which sent little, lost three out of four requests because of acme. With the limit, acme gets 429 and beta does not even notice its neighbor.
Interview question
Why count tokens, and not requests?
Because the cost and the load of an LLM request vary hundreds of times with the size of the text. A per-request limit treats the cheap and the expensive the same. The detail that shows you understood: the real cost is only known at the end, so you reserve an estimate on the way in and refund the difference on the way out.
Lesson 4 of 910 minNot read
Load balancing
How to choose the provider for each request, and why the "smarter" strategy was the one that failed the most when a provider went down.
In one sentence
Load balancing is the rule that decides which of the available providers each request goes to.
When you need it
More than one cloud or region
Each provider has its own requests-per-minute limit. The same model through two routes (the direct API and Amazon Bedrock, for example) or in two regions adds up capacity, as long as the traffic is split between them.
Providers with different speeds
One provider is slower today. Sending it the same amount as the others piles up requests waiting on it.
Why it is the usual choice
The two most common strategies, and the two the project implements:
Round-robin: one each, in order. It needs no information about the providers and splits evenly.
Least in flight: sends to the provider with the fewest requests in progress. It adapts to a slower provider on its own, because its requests take longer to finish and its counter stays high.
"Least in flight" is usually the better choice when response times vary a lot, which is the case with LLMs: one request may take 200 ms and the next one 30 seconds.
let chosen = ordered[0]!; // ordered: the candidates, starting after the last one chosen
if (this.strategy === 'least-in-flight') {
const load = (state: UpstreamState) => state.limiter.inFlight + state.limiter.queued;
for (const state of ordered) if (load(state) < load(chosen)) chosen = state;
}
this.cursor = this.all.indexOf(chosen);
A provider's load is how many requests are in progress on it plus how many are waiting in its queue. On a tie, the round-robin order wins, so everything does not go to the first one in the list.
What the experiment showed
Three 100 ms providers; one of them returning 529 (overloaded) for everything. 150 requests per second for 8 seconds, with no retries.
Strategy
Errors
Calls to the down provider
Round-robin
33.3%
400 of 1,200
Least in flight
87.2%
1,046 of 1,200
Round-robin failed exactly 1 out of 3, as expected. "Least in flight" failed almost everything. The reason: the down provider returns the error almost instantly, so it hardly ever has a request in progress. To the load balancer it is always the least busy one, and it gets almost everything.
The lesson: "least in flight" measures the queue, not health. A provider that fails fast looks great. What fixes this is the circuit breaker (lesson 6), which removes the sick provider from the list of candidates.
Interview question
Is least connections always better than round-robin?
No. It adapts to slow providers, but a provider that returns errors fast ends up with zero connections and starts getting all the traffic. It has to come together with a health check or a circuit breaker, which take the sick provider out of the choice.
Lesson 5 of 915 minNot read
Failover, retries and backoff
When it is worth trying again on another provider, how long to wait first, and the moment when switching is no longer possible.
In one sentence
Failover is trying the same request on another provider when the first one fails; backoff is the wait between one attempt and the next.
When you need it
The provider is overloaded
The API returns 529 (overloaded) or 503. Another provider, or the same one a few seconds later, will probably answer.
The connection dropped on the way
The network failed before the response arrived. Either the request was never processed, or it was and the response got lost; for a question to a model, which changes nothing on the provider side, trying again solves both cases. The price: in the second case, you pay for the call twice.
Why it is the usual choice
Not every error deserves a retry. The project's rule:
Result
Retry?
Why
Connection failure, timeout
Yes
A problem on the way or at the provider
429, 529, 500 to 504
Yes
The provider refused because of a limit or overload, or it is broken
400, 401, 404
No
The problem is the request: another provider would give the same answer
And the wait between attempts doubles with each failure, up to a cap, multiplied by a random number between 0 and 1. That random number is the jitter: without it, 1,000 requests that failed in the same second all retry at the same instant and take down the provider that was recovering.
export function backoffMs(attempt: number, random: number, baseMs = 200, capMs = 2000): number {
return Math.min(capMs, baseMs * 2 ** attempt) * random;
}
// 1st retry: up to 200 ms; 2nd: up to 400 ms; 3rd: up to 800 ms ... never more than 2 s
How it works
The gateway picks a provider among the ones not yet tried for this request.
If it fails with an error worth retrying, the gateway waits the backoff and picks another one.
There is a total deadline per request. If the next wait would go past it, the gateway gives up and returns the last error.
The first-byte rule: in streaming, once the first piece has been sent to the app, there is no more switching providers. The app has already shown part of the text; starting over on another provider would duplicate the answer. If the provider fails midway, the app gets an error event in the stream itself.
for (let attempt = 0; attempt < config.retry.maxAttempts && !client.signal.aborted; attempt++) {
if (attempt > 0) {
const wait = backoffMs(attempt - 1, random(), config.retry.baseMs, config.retry.capMs);
if (Date.now() + wait >= deadline) break;
await sleep(wait);
}
const candidates = states.filter((s) => !tried.has(s) && (!config.breaker.enabled || s.breaker.available()));
const state = balancer.pick(candidates);
if (!state) break;
tried.add(state);
const outcome = await attemptOnce(state, ctx);
if (outcome.kind === 'sent') break; // it answered: done
if (!outcome.retryable) break; // request error: another provider won't fix it
}
What the experiment showed
The same scenario as lesson 4: three providers, one returning 529 for everything.
Setup
Errors
p50
p99
Calls to the down one
Least in flight, no failover
87.2%
104 ms
126 ms
1,046
Least in flight, with failover
0%
206 ms
303 ms
1,196
Failover brought errors to zero, but the median doubled. Almost every request (1,196 of 1,200) still tried the down provider first, got the error and waited the backoff (up to 200 ms, 100 ms on average) before going to a good provider. Failover alone trades errors for latency. Lesson 6 shows how to get the latency back.
Interview question
Why jitter in the backoff?
Because failures come in groups. Without jitter, every client that failed together waits the same time and retries at the same instant, creating a spike that can take the server down again (the thundering herd effect). The random number spreads the retries over time.
Lesson 6 of 910 minNot read
Circuit breaker
Stop calling a provider that is failing, and check every so often whether it came back.
In one sentence
The circuit breaker counts a provider's consecutive failures; past a limit, the gateway stops sending it requests for a while.
When you need it
The provider returns errors
Every request still tries the down provider before moving on, and pays for the error plus the wait (lesson 5).
The provider hangs without answering
Worse than returning an error: every request that lands on it waits the whole timeout before giving up.
The provider is trying to recover
Keeping traffic on an overloaded service slows down its recovery.
Why it is the usual choice
The alternative is a health check: calling the provider every X seconds to see if it is alive. It takes up to X seconds to notice the outage and tests a health endpoint, not the real path. The circuit breaker uses the requests themselves as the signal: it notices the failure at the fifth error in a row, with no extra traffic.
How it works
Three states per provider:
State
What happens
Changes when
Closed
Requests go through; the breaker counts consecutive failures
5 failures in a row: goes to open
Open
No request goes to the provider
The wait time passes (2 s in the experiment): goes to half-open
failure() {
this.tick();
this.probeInFlight = false;
if (this.current === 'half-open') return this.open(); // the test failed
if (this.current === 'open') return;
this.failures++;
if (this.failures >= this.options.failureThreshold) this.open();
}
success() {
this.failures = 0;
this.probeInFlight = false;
if (this.current !== 'closed') this.transition('closed');
}
A detail that matters: only what is the provider's fault counts as a failure (a 5xx error, a timeout, a lost connection). A 400 is the request's fault, and a 429 is the quota: opening the circuit because of them would take a healthy provider offline.
What the experiment showed
Provider returning errors (the same scenario as lessons 4 and 5):
Setup
Errors
p50
p99
Calls to the down one
Failover, no circuit breaker
0%
206 ms
303 ms
1,196
Failover and circuit breaker
0%
104 ms
115 ms
8
Hung provider, which accepts the connection and never answers. 1 s timeout per attempt; 150 requests per second for 15 s:
Setup
p50
p99
Requests over 1 s
No circuit breaker
104 ms
1,270 ms
138
With circuit breaker
104 ms
118 ms
16
Notice the median is the same in both rows: the p99 is what shows the problem. The 16 slow requests left with the breaker are the ones already waiting on the hung provider before the circuit opened, plus the test requests, one every few seconds.
Interview question
With several copies of the gateway, should the breaker's state live in Redis?
Here it lives in each copy's memory, and that is a choice. Each copy finds out about the outage on its own, after 5 failures of its own; with 10 copies, that is 50 bad requests instead of 5. In exchange, the request path does not depend on Redis to decide, and one copy with a network problem does not open the circuit for all of them.
Lesson 7 of 910 minNot read
Bounded queues and load shedding
How many requests each provider can take at once, what to do with the excess, and why refusing fast is better than making people wait.
In one sentence
Each provider has a maximum number of requests in progress; whoever arrives after that waits in a queue with a maximum size and wait time, and whatever does not fit is refused right away (load shedding).
When you need it
The provider has a concurrency limit
The provider can handle a certain number of requests at the same time, say 50: the server of a model you host, or your account limit. The 51st gets an error. It is better for the gateway to hold the 51st for a moment than to spend a call on a guaranteed error.
A spike bigger than capacity arrives
An unbounded queue grows without stopping, the wait grows with it, and the app gives up (timeout) after the gateway has already spent work on the request.
Why it is the usual choice
A queue absorbs short spikes: 10 extra requests for half a second wait a little and go through. But under sustained excess, a queue only postpones the failure. The rule that explains this is Little's law: the number of items in a system is the arrival rate times the time each one stays there.
Applied to the gateway: with 10 slots and 100 ms requests, the provider serves at most 10 ÷ 0.1 s = 100 requests per second. With 100 requests in the queue, the last one in waits 100 ÷ 100 per second = 1 second before being served. A queue of 10,000 would be a 100-second wait: nobody waits that long. That is why the queue has a maximum size and wait time, and the excess gets 503 with retry-after immediately.
How it works
Is there a free slot? The request takes it and moves on.
No free slot, but the queue has room? The request waits in the queue.
The queue is full, or the request waited longer than the maximum? Refuse with 503.
When a request finishes, its slot goes straight to the first one in the queue.
acquire(signal?: AbortSignal): Promise<() => void> {
if (this.inFlight < this.options.maxInFlight) {
this.inFlight++;
return Promise.resolve(this.releaser());
}
if (this.queue.length >= this.options.maxQueue) return Promise.reject(new QueueFullError());
// otherwise: join the queue, with a maxWaitMs timer and the client's cancellation wired in
...
}
The returned function frees the slot, and it is called in a finally block: on success, on error or when the client leaves, the slot always comes back. A slot that never comes back is a leak that only shows up hours later, when all of them are stuck.
What the experiment showed
In the noisy tenant test (lesson 3), the provider had 10 slots, a queue of 100 and a maximum wait of 3 s, and was getting 300 requests per second. Without a rate limit:
What happened
Value
acme requests refused with 503 by the queue
3,435
acme requests served
1,665
Median for beta, which only sent 20 per second
1,137 ms
The 1,137 ms for beta is Little's law in numbers: about 1 s of full queue plus the provider's 100 ms. The queue protected the provider, but on its own it is fair to requests, not to tenants: whoever sends more takes more of the queue. Fairness between tenants is the rate limit's job.
Interview question
What is the difference between the queue and the rate limit, if both refuse requests?
The rate limit protects tenants from each other: it is per tenant and looks at consumption over time. The queue protects the provider: it is per provider and looks at how many requests are in progress right now. The experiment shows both together: the queue alone kept the provider up, but only the rate limit gave beta its service back.
Lesson 8 of 910 minNot read
Response caching
Answering the same question without calling the model again, without mixing up customers and without letting 10 identical requests become 10 calls.
In one sentence
The cache keeps a request's response for a while; the same request, from the same tenant, gets the stored response without going to the provider.
When you need it
Questions that repeat
A FAQ assistant gets "what are your opening hours?" hundreds of times a day, with the same settings. Each call costs tokens and takes seconds.
A spike of identical requests
A popular screen opens and 10 users trigger the same generation in the same second, before the first one finishes.
Why it is the usual choice
Three decisions in the project, each against a common mistake:
Only when the client asks for it, through the x-gateway-cache: 60 header (seconds of validity). The caller is the one who knows whether the response can be reused: a FAQ can, a conversation with the user's context cannot.
The tenant is part of the key. One tenant's response is never delivered to another, even if the question is identical.
One call for simultaneous identical requests (single-flight). Without it, the 10 requests in the spike arrive before the first response exists, all find the cache empty, and all go to the provider.
How it works
The cache key is a hash of the tenant plus the request body, with the JSON keys in alphabetical order: {"a":1,"b":2} and {"b":2,"a":1} are the same request. The stream field is left out, because the response is the same; only the delivery format changes.
Single-flight is a map of calls in progress: the first request for a key registers a Promise; the next ones, instead of calling the provider, wait on that Promise.
let cached = await responses.get(flightKey);
const pending = cached === null ? inProgress.get(flightKey) : undefined;
if (pending) cached = await pending; // someone is already fetching it: wait for their answer
// ...
if (!inProgress.has(flightKey)) inProgress.set(flightKey, new Promise((resolve) => (settleFlight = resolve)));
Only complete, successful responses go into the cache. A provider error, or a stream canceled midway, is not stored.
What the experiment showed
1,000 requests, 10 at a time; 30% of them repeat one of 10 frequent questions. That 30% is an assumption of the test, not real-world data, and the cost uses a sample price.
Setup
Calls to the provider
Answered by the cache
Cost
Average latency
No cache
1,000
0%
US$ 0.159
105 ms
With cache
689
31.1%
US$ 0.110
73 ms
The cache answered 31.1%, practically all the repetition there was. What the test proves is that the mechanism works under concurrency; the real savings depend on how much your traffic repeats.
Interview question
What is a cache stampede and how do you avoid it?
It is when a cache entry does not exist (or expires) and many requests at the same time go fetch the same value from the origin. With LLMs, each fetch is expensive. The project's solution is single-flight: only the first one fetches, the others wait for its result. The map of calls in progress lives in each gateway copy's memory: with 4 copies, the worst case is 4 calls, not 1. Making it a single call across all copies would take a lock in Redis.
Lesson 9 of 915 minNot read
Metrics and load testing
How to know whether each mechanism works: what to record for each request, why to look at the p99 and how to generate load without fooling yourself.
In one sentence
Observability is being able to answer questions about the system in production from what it records; load testing is generating controlled traffic to measure how it behaves.
When you need it
Explaining the bill
"How much did tenant X spend this month?" only has an answer if every request recorded the tenant, the tokens and the cost.
Deciding a setting
"Is 5 failures to open the circuit too many or too few?" only has an answer if you measure the effect.
Defending the project in an interview
"The circuit breaker brought the p99 down from 1,270 ms to 118 ms" is worth more than "I implemented a circuit breaker".
Why it is the usual choice
One JSON log line per request (the JSONL format). Each line has everything about that request; any question becomes a filter and a sum. It is the format tools like Datadog, Loki and BigQuery read directly.
Percentiles, not averages. The average, and even the median, hide the tail: in the hung provider experiment (lesson 6), the median was 104 ms with and without the circuit breaker. Only the p99 showed that 138 requests took over 1 second. A user who uses the product all day hits the p99 several times a day.
export function percentile(values: number[], p: number): number {
if (values.length === 0) return 0;
const sorted = [...values].sort((a, b) => a - b);
return sorted[Math.max(0, Math.ceil((p / 100) * sorted.length) - 1)]!;
}
In load testing, there are two ways to generate traffic, and they answer different questions:
Fixed concurrency: N clients, each sends the next request when the previous one finishes. It measures maximum throughput. If the system gets slow, the clients send less, and the load drops with it: the test relieves the system exactly when it gets worse.
Fixed rate: one request every 1/rate seconds, whether the previous one finished or not. That is how real users arrive. It shows the queue growing and latency rising under excess.
The outage and noisy tenant experiments use a fixed rate; the gateway cost and cache experiments use fixed concurrency.
All on the same machine (2 cores), with fake providers with fixed latency. The numbers show the effect of each mechanism, not the performance against a real API.
Interview question
Why can a load test with N fixed clients hide a problem?
Because each client waits for the response before sending the next one. When the system gets slow, the load drops on its own, and the test never sees the queue grow. Real users do not wait for others to finish before arriving. To measure behavior under excess, the load needs a fixed rate.
Review10 min
Interview questions
Questions in the format of a system design interview about a system like this, with the short answer and the lesson that explains each one.
Overall design
Design a gateway for several LLM APIs.
A reverse proxy with these stops, in this order: authentication, cache, per-tenant rate limit, load balancer with circuit breaker, per-provider queue and the call with streaming. Shared state (quota and cache) lives in Redis; the rest, in each copy's memory. One log line per request. Lessons 1 and 9.
How do you scale to several copies of the gateway?
The copies sit behind a regular load balancer, with no state of their own that matters between requests. Quota and cache go to Redis, so every copy sees the same balance and the same responses. The circuit breaker and the queue stay per copy, on purpose. With the queue per copy, the slots add up: 4 copies with 10 slots each send up to 40 requests at the same time to the provider, so the provider's limit is divided by the number of copies. Lessons 3 and 6.
Limits and queues
Why rate limit by tokens, and not by requests?
The cost of an LLM request varies hundreds of times with the size of the text. The gateway reserves an estimate on the way in and refunds the difference once it knows the real usage. Lesson 3.
What happens if Redis goes down?
The gateway lets requests through without a limit (fail open), instead of taking every tenant down. If blowing the quota cost more than being down, the choice would be to refuse (fail closed). Lesson 3.
How do you make sure two copies don't approve the same balance?
Read, compute and write the balance in a Lua script, which Redis runs in full before serving another command. Three separate commands would have a race between the copies. Lesson 3.
Why does the queue have a maximum size?
By Little's law, the wait is the queue size divided by the throughput. An unbounded queue under sustained excess just makes the wait grow until the client gives up. Better to refuse with 503 right away. Lesson 7.
Failures
Which errors deserve a retry?
The provider's: connection failure, timeout, 429, 529 and 500 to 504. The request's (400, 401) do not: another provider would give the same answer. Lesson 5.
Why jitter in the backoff?
So the clients that failed together don't all retry at the same instant and take down the server that is recovering. Lesson 5.
Can you switch providers in the middle of a stream?
No: the client has already received part of the text, and starting over on another provider would duplicate the answer. After the first byte, a failure becomes an error event in the stream itself. Lesson 5.
Why did least-in-flight get worse with a provider down?
The down provider returns the error almost instantly, so it hardly ever has a request in progress and always looks like the least busy one. In the experiment, errors went from 33.3% (round-robin) to 87.2%. Lesson 4.
Circuit breaker or health check?
The circuit breaker uses the requests themselves as the signal and notices the outage at the fifth failure in a row, with no extra traffic; the health check tests a health endpoint every interval. The two can coexist. Lesson 6.
Performance
What is backpressure?
It is whoever receives more slowly controlling the speed of whoever sends. In the gateway: when res.write() returns false, it stops reading from the provider until the drain event. Lesson 2.
Why look at the p99, and not the average?
The average, and even the median, hide the tail. With a hung provider, the median stayed at 104 ms with and without the circuit breaker; only the p99 (1,270 ms against 118 ms) showed the problem. Lesson 9.
What is a cache stampede?
Many requests fetching the same missing value at the same time. The solution is single-flight: only the first one goes to the provider, the others wait for its answer. Lesson 8.