The Problem#
An LLM chat service lets a person type a question and watch an answer appear word by word, written by a large language model (LLM). The person can come back tomorrow, open yesterday's conversation, and carry on where they stopped, with the model still "remembering" what was said earlier. ChatGPT, Claude, Gemini and Copilot all have this shape. ChatGPT, launched by OpenAI at the end of November 2022, became one of the fastest-growing consumer products ever recorded; OpenAI has since spoken publicly of several hundred million weekly users.
At first sight this looks like an ordinary chat application with a clever bot on the other end. It is not. Three things make it a different kind of system:
- The expensive part is the answer, not the message. A normal chat app stores and forwards a few hundred bytes per message; its servers are cheap. Here, every answer is computed on graphics processors (GPUs) that cost tens of thousands of dollars each, and one answer can occupy a slice of a GPU for 5 to 60 seconds. The GPU fleet costs far more than everything else in the system put together. Who gets compute, and when, is a business decision as much as an engineering one.
- The answer is produced slowly, one piece at a time. A model emits its answer as a sequence of tokens (word pieces), at roughly 30 to 100 tokens per second per user. A 500-token answer takes 5 to 15 seconds. Users will not stare at a spinner for 15 seconds, so the system must stream: send each token to the browser as it is made. That turns a simple request into a long-lived connection that must survive flaky networks, server deploys and reloaded pages.
- Conversations grow, and every turn re-reads the whole conversation. The model has no memory between requests. To answer turn 20, it must read turns 1 to 19 again. Cost and latency grow with conversation length unless the design deliberately caches, trims or summarises the history.
So the interesting questions are not "how do we store messages" (that part is a modest, well-understood database problem) but: how do we stream tokens reliably, how do we schedule a scarce and expensive GPU fleet across hundreds of millions of users fairly, how do we keep a long-running generation alive when connections drop, and how do we keep the cost per conversation under control.
Analogy. Think of a popular restaurant with a small number of very expensive chefs. Diners (users) place orders (prompts). The chefs (GPUs) are the bottleneck; the front of house (web servers, databases) is cheap. A good restaurant does not make diners wait in silence until the whole meal is ready; it brings out courses as they are cooked (streaming). The kitchen batches work cleverly, so one chef stirs several pots at once (continuous batching). Regulars who pay for membership get seated first when it is busy (priority tiers), everyone is limited to a reasonable number of dishes per hour (quotas), and if a diner steps outside to take a phone call, their food is kept warm at the pass rather than thrown away (resumable streams). A host at the door checks that orders are not abusive (moderation). And the owner watches food cost per plate obsessively (cost control), because ingredients, not waiters, are what can bankrupt the place.
Background: a few terms used in this design#
- Large language model (LLM): a neural network (almost always a transformer, introduced in "Attention Is All You Need" by Vaswani et al., 2017) that, given a sequence of tokens, predicts a probability for every possible next token. Generating text means repeatedly picking a next token and appending it.
- Token: the unit the model reads and writes. A tokenizer (usually byte-pair encoding, BPE) splits text into pieces; in English one token is on average about 4 characters, or roughly three quarters of a word. "Unbelievable" might be 3 tokens. Prices, limits and speeds are all quoted in tokens.
- Prompt (input) and completion (output): the prompt is everything sent to the model for one request: a system prompt (fixed instructions from the operator), the earlier turns of the conversation, any retrieved documents, and the user's new message. The completion is what the model generates.
- Prefill: the first phase of serving a request. The model processes all prompt tokens in parallel, in one big matrix computation, to build its internal state. Prefill is compute-bound: limited by the GPU's arithmetic speed.
- Decode: the second phase. The model generates the output one token at a time; each step depends on the previous one, so it cannot be parallelised across the output. Decode is memory-bandwidth-bound: each step must read the model's weights from GPU memory, and that reading, not the arithmetic, sets the speed.
- KV cache: during prefill and decode the model computes, for every token, a "key" and a "value" vector in every layer. Caching them means later tokens do not recompute earlier ones. The KV cache lives in scarce GPU memory and grows with every token, so it is the central resource in LLM serving.
- Time to first token (TTFT): how long the user waits before the first token appears. Dominated by queueing plus prefill.
- Time per output token (TPOT) or inter-token latency: the gap between successive tokens once streaming starts. Dominated by decode speed and how many other requests share the GPU.
- Context window: the maximum number of tokens (prompt plus completion) the model can handle in one request, such as 8,000, 128,000 or 1,000,000 tokens depending on the model.
- Batching: running many users' requests through the GPU together. One decode step for 64 users costs only a little more than for 1 user, because the weights are read once for all of them. Batching is the single biggest lever on cost.
- Inference server (engine): the software that runs the model on GPUs and handles batching and KV-cache memory, such as vLLM, SGLang, NVIDIA TensorRT-LLM with Triton, or Hugging Face Text Generation Inference.
- Server-Sent Events (SSE): a simple HTTP standard for a server to push a stream of text events to a browser over one long response. This is what most LLM APIs use for streaming.
If these are new, the concept page Designing LLM and AI-Powered Systems explains them in depth. This case study assumes the model already exists and focuses on the system around it.
Clarifying Questions#
| Question | Assumed answer | Why it matters |
|---|---|---|
| Are we building the model or the service around it? | The service. The model weights are given; we design serving, streaming, storage, quotas, safety and cost | Keeps the interview on system design rather than machine learning research |
| What must users be able to do? | Send a prompt and get a streamed answer; see past conversations and continue any of them with context | Defines the two core flows: generate and resume |
| What is out of scope? | Editing and branching messages, images and voice, sharing links, custom assistants, plugins and web browsing, full-text search over history | Each one is a large feature; we leave hooks in the data model but do not design them |
| How many users? | A little over 200 million daily active users | Sizes the stateless tier, storage and, above all, GPU demand |
| How many prompts? | About 1 billion prompts a day; peak about 20,000 prompts per second | Sets the request rate the scheduler and GPU fleet must absorb |
| How long are answers, and how fast should they arrive? | Average about 300 output tokens; first token within about 1 second at p50 and 3 seconds at p99 for paid users; at least 30 tokens per second while streaming | Time to first token is what users feel; it drives queueing and prefill design |
| How many answers are streaming at once? | Around 120,000 concurrent streams at peak | Sizes streaming gateways, connection state and the token buffer |
| Is there more than one model? | Yes: a large flagship model and a small, cheap model, possibly more | Enables routing, fallback under load and cost control |
| Free and paid tiers? | Yes. Paid users get priority, higher limits and the flagship model; free users get lower limits and may be moved to the small model under load | Fairness and priority must be designed in, not bolted on |
| How long do we keep conversations? | Until the user deletes them; deleted data purged within a fixed period, such as 30 days | Storage is cheap but large; deletion and privacy shape the data model |
| Safety requirements? | Inputs and outputs are checked against a content policy; clearly abusive requests are refused; the system must never show one user another user's data | Adds a moderation pipeline and strict isolation |
| Single region or global? | Users worldwide; several regions, GPU capacity in a handful of them | Drives routing, failover and where conversations live |
Requirements#
Functional#
- Send a prompt and receive a streamed response. The user types a message in a conversation (new or existing); the answer appears token by token, and the user can stop it at any time.
- View past conversations and resume them with context. The user sees a list of conversations, newest first; opening one shows its messages; sending a new message continues it, and the model answers with the earlier turns as context.
- Survive interruptions. If the user's connection drops or they reload the page mid-answer, they see the answer continue (or complete) rather than lose it.
- Respect limits. Each user has usage limits by tier; exceeding them gives a clear message about when they can continue, or offers a cheaper model.
Out of scope: editing or regenerating messages to create branches, image or voice input and output, sharing conversations publicly, custom assistants, tool use and web browsing, and full-text search across a user's history. We keep a parent_id on messages so branching could be added later, and note where tools would plug in.
Non-Functional#
- Time to first token matters more than total time. Users judge responsiveness by when text starts appearing. Target TTFT p50 under 1 second, p99 under 3 seconds for paid traffic under normal load; free traffic may wait longer under heavy load.
- Smooth streaming. At least 30 output tokens per second per stream (faster than people read, which is roughly 4 to 8 tokens per second), with no long stalls.
- GPU compute is scarce and expensive; allocate it deliberately. The system must decide, explicitly and fairly, who gets compute when demand exceeds supply: paid before free, interactive before batch, and no single user able to starve others. Keeping GPUs busy (high utilisation) is a first-class goal.
- Durability of conversations. Once an answer is shown as complete, it is never lost. A partial answer interrupted by a failure is either completed, resumed or clearly marked as interrupted.
- Availability. 99.9% or better for the chat experience. When GPU capacity is short, degrade gracefully (smaller model, queue with a visible wait, or a clear "busy" message) rather than fail hard.
- Isolation and privacy. One user's data is never served to another. This is a hard requirement; in March 2023 OpenAI disclosed an incident in which a bug in the open-source Redis client library caused some users to see the titles of other users' conversations, which shows how a caching or connection-handling bug becomes a privacy incident.
- Scale. About 200 million daily users, 20,000 prompts per second at peak, about 120,000 concurrent streams, petabytes of conversation history over time.
- Cost. Cost per answer is tracked and actively reduced; it is a design constraint, not an afterthought.
Which matter most? Time to first token and fairness of GPU allocation first, then streaming reliability, then cost. Throughput of the stateless tier and storage are comparatively easy. The defining tension of the whole design is that the business wants GPUs as full as possible (big batches, cheap answers) while users want them as empty as possible (no queue, fast tokens). Every major decision is a position on that trade-off.
Capacity Estimation#
Only the numbers that change the design. To make GPU numbers concrete we use a reference model: a dense 70-billion-parameter transformer with grouped-query attention (the shape of Llama 2 70B and Llama 3 70B: 80 layers, 8 key/value heads of dimension 128), served in 8-bit floating point (FP8) on nodes of 8 NVIDIA H100 80 GB GPUs. Real flagship models are larger and often mixture-of-experts (only part of the network runs per token), which changes the constants but not the shape of the reasoning.
Request rate.
- 200 million daily users × about 5 prompts each = 1 billion prompts per day.
- 1 billion ÷ 86,400 seconds ≈ 11,600 prompts per second on average. Traffic follows the sun and the working day; a peak-to-average ratio of about 1.7 gives about 20,000 prompts per second at peak.
Tokens per request.
- New user message: about 100 tokens on average (most are short; a few paste whole documents).
- System prompt: about 1,000 tokens of instructions, the same for everyone using a given model and product surface.
- Conversation history: varies from zero (first turn) to tens of thousands. Averaged across all requests, about 1,000 tokens.
- So the average prompt is about 2,100 input tokens, and the average completion about 300 output tokens.
Token throughput at peak.
- Input: 20,000 × 2,100 = 42 million prompt tokens per second to prefill, before caching.
- Output: 20,000 × 300 = 6 million output tokens per second to decode.
Concurrent streams (Little's law). The number of requests in a system equals arrival rate times time in system: L = λ × W. Each stream lasts TTFT plus 300 tokens at about 50 tokens per second, roughly 6 seconds. So L = 20,000 per second × 6 seconds = about 120,000 concurrent streams at peak. That is the number of open SSE connections, live token buffers and active sequences in GPU batches at any moment.
Prefill compute. A forward pass costs about 2 floating-point operations per parameter per token, so prefill of one token on a 70B model is about 2 × 70 × 10⁹ = 1.4 × 10¹¹ operations. At 42 million tokens per second that is 5.9 × 10¹⁸ operations per second. An H100 offers roughly 1,000 teraflops of dense BF16 (about twice that in FP8); real prefill reaches perhaps 40 to 50% of peak. Taking about 800 effective teraflops per GPU in FP8, prefill needs about 5.9 × 10¹⁸ ÷ 8 × 10¹⁴ ≈ 7,400 GPUs without caching. With prefix caching (the system prompt and earlier turns are already in the KV cache from the previous turn; Deep Dive 5), perhaps 70% of prompt tokens are cache hits, cutting prefill to about 2,200 GPUs. This one optimisation is worth thousands of GPUs.
Decode throughput. Decode is limited by memory bandwidth. A 70B model in FP8 is about 70 GB of weights. An 8-GPU node splitting the model with tensor parallelism has about 8 × 3.35 TB/s ≈ 27 TB/s of memory bandwidth, so in theory one decode step (reading all weights once) takes about 70 GB ÷ 27 TB/s ≈ 2.6 ms; in practice, with communication between GPUs and attention over the KV cache, 15 to 25 ms per step. Every sequence in the batch gets one token per step. With a batch of about 160 sequences at 20 ms per step, a node produces about 160 × 50 = 8,000 tokens per second while giving each user 50 tokens per second. For 6 million tokens per second we need about 750 nodes, about 6,000 GPUs for decode.
Total fleet. Roughly 2,200 + 6,000 ≈ 8,000 GPUs busy at peak, plus 25 to 40% headroom for failures, deploys, regional imbalance and bursts: about 10,000 to 11,000 H100-class GPUs for one flagship model at this traffic. At a few dollars per GPU-hour that is on the order of $250 to $400 million per year. That number is why the GPU scheduler, caching and cost control are the heart of the design. A small model for simple prompts, if it can handle half the traffic at a tenth of the cost, saves a large fraction of it.
KV cache memory. For the reference model, each token's KV cache is 2 (key and value) × 80 layers × 8 heads × 128 dimensions × 2 bytes (FP16) = 327,680 bytes, about 320 KB per token (160 KB with FP8 KV cache). An average sequence of 2,400 tokens therefore holds about 770 MB in FP16. An 8×H100 node has 640 GB of memory; after 70 GB of weights and working space, roughly 500 GB is left for KV cache: about 650 average sequences, or only about 48 sequences at 32,000 tokens each (each holds about 10.5 GB). Long conversations do not just cost more compute; they crowd other users out of GPU memory. (An older model without grouped-query attention, such as Llama 2 7B with 32 layers of 32 heads, needs 512 KB per token even though it is ten times smaller; attention design matters as much as size.)
Streaming bandwidth. 6 million tokens per second × about 4 bytes of text each, plus JSON framing of about 60 bytes per event if we sent one event per token, is roughly 400 MB/s. Grouping tokens into events every 30 to 50 ms cuts framing overhead several times. The streaming tier is small: 120,000 connections fit on a few dozen gateway servers.
Conversation storage.
- Each prompt and answer pair stores about 400 tokens of text (100 in, 300 out), about 1.6 KB, plus metadata, call it 2.5 KB per turn.
- 1 billion turns a day × 2.5 KB = 2.5 TB per day, about 0.9 PB per year before replication, about 2.7 PB with 3 copies. Compressed with zstd (text compresses 3 to 4 times), well under 1 PB per year on disk.
- Reads: opening the conversation list and a conversation, perhaps 3 to 5 reads per prompt sent: 50,000 to 100,000 reads per second at peak, which a sharded database plus a cache handles comfortably.
What the numbers tell us.
- GPUs dominate cost by orders of magnitude; anything that saves GPU time (caching, batching, routing to smaller models, trimming context) is worth real complexity.
- Decode capacity, not prefill, is the larger fleet; output length caps and model choice matter.
- KV cache memory, not arithmetic, often limits batch size for long conversations.
- 120,000 concurrent streams is modest for the networking tier; the hard part is making them resumable, not holding them open.
- Conversation storage is a large but ordinary key-value problem.
Core Entities#
- User: an account with a tier (free, plus, team, enterprise), a region and settings.
- Conversation: a thread owned by one user, with a title, a model, timestamps and a pointer to its latest message.
- Message: one turn in a conversation, written by the user, the assistant or the system. Has text, a role, a parent message (to allow branches later), a status (streaming, complete, cancelled, failed, blocked) and token counts.
- Generation (run): one attempt by the system to produce an assistant message: which model and replica served it, when it was queued, started and finished, how many tokens it used, why it ended. A message may have more than one run if a failure forced a retry.
- Token stream: the ordered sequence of output chunks of a running generation, kept briefly in a fast buffer so disconnected clients can resume.
- Usage record: tokens consumed by a user per model per time window, used for quotas and billing.
- Moderation result: the outcome of a safety check on a prompt or an answer, with categories and scores.
API Design#
The browser talks to our own API over HTTPS. The interesting design choice is to separate starting a generation from watching it: one call creates the user message and starts the run, and a separate, resumable stream delivers tokens. Many products fold both into one streaming POST for simplicity; we show the separated form because it makes reconnection, deploys and multi-device viewing straightforward.
# Conversations
POST /v1/conversations -> { conversationId }
GET /v1/conversations?cursor=...&limit=30 -> list, newest first
GET /v1/conversations/{cid}/messages?cursor= -> messages, oldest to newest page
DELETE /v1/conversations/{cid}
# Send a prompt: stores the user message, starts a run
POST /v1/conversations/{cid}/messages
Idempotency-Key: 7f3c...
{ "content": "Explain TCP slow start", "parentId": "m_41", "model": "auto" }
-> 202 { "userMessageId": "m_42", "assistantMessageId": "m_43", "runId": "r_9a" }
# Watch the answer (Server-Sent Events), resumable
GET /v1/runs/{runId}/stream
Accept: text/event-stream
Last-Event-ID: 57 (only on reconnect)
# Stop generating
POST /v1/runs/{runId}/cancel -> 200 { "status": "cancelled", "outputTokens": 118 }The stream is a sequence of SSE events. Each has an id (a sequence number within the run), an event type and a JSON payload:
id: 1
event: start
data: {"runId":"r_9a","model":"flagship-2026-10","messageId":"m_43"}
id: 2
event: delta
data: {"text":"TCP slow start is"}
id: 3
event: delta
data: {"text":" the phase where a new connection"}
: keep-alive
id: 58
event: done
data: {"finishReason":"stop","inputTokens":2140,"cachedTokens":1890,"outputTokens":312}Design notes:
- The
Idempotency-Keyon the POST means a retried send (the user double-clicks, or the network drops before the 202 arrives) does not create two messages and two expensive runs. See Idempotency and Safe Retries. model: "auto"lets the server pick a model (Deep Dive 9). An explicit model name pins it, subject to the user's tier.- Rate limit responses. When a user is over their limit the POST returns HTTP 429 Too Many Requests immediately, with headers such as
X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-ResetandRetry-After, plus a body saying which limit was hit and what the user can do (wait, or use the smaller model). Failing fast is kinder than queueing a request that will not be served for minutes. OpenAI's public API returns similar per-request and per-token headers (x-ratelimit-remaining-tokensand friends). - The event stream ends with usage. Reporting input, cached and output tokens on the final event lets the client show usage and lets billing reconcile.
- Server-to-server API. Developer customers get the same capabilities in a stateless form (send the whole message list, get a stream back), which is what OpenAI-compatible chat completion APIs look like. Our consumer product sits on top of the same internal inference service.
High-Level Design#
We build the design one requirement at a time, starting from the simplest thing that works and fixing each problem as it appears.
1) Send a prompt and receive a streamed response#
Start simple. The browser sends the prompt to an API server. The API server loads the conversation, builds the full prompt (system prompt, history, new message), calls an inference server running the model on a GPU, waits for the complete answer, saves both messages, and returns the answer. This works for a demo with ten users.
It fails in three ways at our scale:
- The user waits for the whole answer. 300 tokens at 50 tokens per second is 6 seconds of blank screen, and long answers take 30 seconds or more. Time to first token is the requirement users feel most, and this design makes TTFT equal to total time.
- Each API server holds a GPU request open synchronously. If inference servers are busy, requests pile up inside API servers with no global view of who should go first.
- Nothing decides who gets the GPUs. With 20,000 prompts per second and finite GPUs, requests arriving at random API servers cannot be fairly prioritised.
Fix 1: stream. The inference server already produces tokens one at a time; we pass each one through to the browser as soon as it exists. The browser opens an HTTP response with Content-Type: text/event-stream (Server-Sent Events) and the server writes one small event per chunk of tokens. TTFT drops from "whole answer" to "queue wait plus prefill", typically well under a second. SSE suits this perfectly: the data flows one way (server to client), it is plain HTTP so it passes through load balancers, proxies and CDNs, and it is trivial to parse. We compare it with WebSockets in Deep Dive 1.
2) Decide who gets the GPUs: an inference gateway, queues and a scheduler#
API servers should not talk to GPU servers directly. We insert an inference gateway in front of the GPU fleet with three jobs:
- Admission control. Check the user's quota and the current load before accepting work. If a free user is over their limit, or the system is overloaded and this request would wait too long, reject it right now with a 429 and a clear message, instead of letting it sit in a queue.
- Queueing by priority. Accepted requests go into per-model queues, separated by priority class: paid interactive, free interactive, and background (summaries, titles, batch jobs). Within a class, the scheduler takes requests fairly across users, so one heavy user cannot starve others (Deep Dive 4).
- Placement. The scheduler picks which model replica runs the request, preferring a replica that already holds this conversation's earlier turns in its KV cache (prefix affinity), and otherwise the least-loaded one (Deep Dive 3).
Each model replica is one inference engine (such as vLLM, SGLang or TensorRT-LLM) running the model across one or more GPUs. Inside a replica, the engine uses continuous batching: at every decode step it can add new sequences to the running batch and remove finished ones, so the GPU stays full without waiting for a whole batch to finish. The replica reports its load (running sequences, free KV-cache memory, queued prefill tokens) to the scheduler several times a second.
3) Keep the stream alive across reconnects: decouple generation from the connection#
In the simple design, the token stream flows through one chain of TCP connections: GPU → API server → load balancer → browser. If any link breaks (the user's phone switches from Wi-Fi to mobile data, the user reloads the tab, we deploy a new version of the API server), the answer is lost even though the GPU is still producing it, and the user must re-ask, paying for the whole generation again.
Fix: the generation writes to a durable-enough buffer; the connection only reads from it. The replica (or a thin worker attached to it) appends each chunk of tokens to a token stream buffer keyed by run id, for example a Redis Stream with a sequence number per chunk. A separate fleet of stream gateways holds client SSE connections. A client asks for /runs/{runId}/stream; the gateway reads all chunks so far from the buffer, sends them, then tails the buffer for new ones. If the connection breaks, the client reconnects (to any gateway) with Last-Event-ID: 57, and the gateway resumes from chunk 58. The generation itself never noticed.
When the run finishes, the complete assistant message is written to the conversation database and the buffer entry expires after a few minutes. Partial text is also checkpointed to the database periodically (every few seconds) so even a buffer loss leaves most of the answer recoverable. Deep Dive 2 covers the details, including what happens when the GPU replica itself fails mid-answer.
4) View past conversations and resume them with context#
Conversation store. Conversations and messages go into a horizontally scalable database partitioned by user for the conversation list and by conversation for messages. The access patterns are narrow and predictable:
- "List my conversations, most recent first, 30 at a time." Partition by
user_id, sort byupdated_atdescending. - "Get the messages of conversation X in order." Partition by
conversation_id, sort by message sequence. - "Append a message to conversation X." A single-partition write.
This fits a wide-column or key-value store such as Cassandra, ScyllaDB or DynamoDB, or a sharded relational database (PostgreSQL or MySQL sharded by user id, for example with Vitess or Citus). The details and trade-offs are in the Data Model section and Deep Dive 6.
Resuming with context. The model has no memory between requests; "resuming" a conversation means sending earlier turns again as part of the prompt. A context builder in the API tier loads recent messages (from a cache, falling back to the database), counts tokens, and decides what fits: the system prompt, a summary of old turns if the conversation is long, the most recent turns verbatim, any retrieved memories, and the new message. Keeping that prompt's beginning byte-for-byte stable from turn to turn matters a great deal, because it lets the GPU replica reuse the KV cache computed on the previous turn (Deep Dive 5).
5) Safety, limits and cost as first-class components#
Three more components complete the picture:
- Moderation service. Classifies the user's prompt before (or in parallel with) generation, and the streaming output as it is produced. Clearly disallowed prompts are refused without spending flagship-model GPU time; problematic output can be stopped mid-stream and replaced with a notice (Deep Dive 8).
- Quota and usage service. Tracks tokens and messages per user per window in a fast counter store (Redis), enforces limits at admission time, and writes a durable usage log for billing and analytics (Deep Dive 4).
- Model router and cost policy. Picks a model per request: flagship for paid users and hard prompts, a smaller model for simple prompts, free users over their flagship limit and overload. Also enforces output caps and context budgets (Deep Dive 9).
The full high-level design#
Components:
- Clients and CDN. The web app and mobile apps; the CDN serves the static application bundle and images. Clients parse SSE streams, render markdown incrementally, and reconnect with
Last-Event-ID. - Global load balancer and web application firewall (WAF). Terminates TLS, routes users to the nearest healthy region, blocks obvious abuse such as credential stuffing and scraping bursts.
- API servers. Stateless. Authenticate, serve conversation lists and messages, accept new prompts idempotently, create runs and enqueue them.
- Context builder and model router. Build the prompt within a token budget, keep its prefix stable for caching, and choose the model.
- Stream gateways. Hold client SSE connections, replay and tail token buffers, send keep-alive comments, and drain gracefully during deploys.
- Quota and usage service. Enforce per-user, per-tier limits on messages and tokens; issue 429s with reset times; record usage.
- Moderation. Fast classifiers on prompts and outputs; policy decisions; abuse signals per account.
- Inference gateway and scheduler. Admission control, priority and fair queueing, placement with prefix affinity and load awareness, cancellation, retries on replica failure.
- Model replicas. Inference engines on GPU nodes, using continuous batching, paged KV cache, prefix caching, quantisation, and in larger deployments separate prefill and decode pools.
- Token stream buffer. A short-lived, replicated in-memory log per run (Redis Streams, or a similar store) that decouples generation from delivery.
- Conversation store and cache. The durable home of conversations and messages, with a cache of hot conversations.
- Usage log and analytics. Kafka topics for usage, run outcomes and moderation events, feeding billing, dashboards, capacity planning and evaluation pipelines.
Key Flows#
Flow 1: send a prompt and stream the answer#
- The client sends the message with an idempotency key. A duplicate POST with the same key returns the same
runIdinstead of starting a second generation. - The API server asks the quota service whether this user may send now (message and token windows for their tier) and asks moderation for a fast verdict on the prompt. Both are low-latency calls, a few milliseconds each; in practice the moderation check can run in parallel with queueing so it adds no TTFT unless it says no.
- The API server writes the user message (status
complete) and a placeholder assistant message (statusstreaming) to the conversation store, creates the run, and builds the context. - The run is enqueued at the inference gateway with its priority class, the user id (for fairness), an estimate of prompt tokens, and a hash of its prompt prefix (for cache affinity).
- The API server returns
202 Acceptedimmediately. The client opens the SSE stream for the run, which a stream gateway serves from the token buffer. - The scheduler dispatches the run to a replica. The replica prefills only the tokens it does not already have cached, then decodes. Every 30 to 50 ms it appends the newly generated text to the run's token buffer.
- The stream gateway forwards chunks as SSE
deltaevents with increasing ids. - When the model emits its end-of-sequence token (or hits the output cap), the replica reports completion and usage. The API tier writes the final assistant message, marks it complete, records usage (adjusting the user's counters by actual tokens), and the stream sends a
doneevent.
Latency budget for TTFT (paid user, normal load): edge and API about 30 ms; quota and moderation in parallel about 10 ms; queue wait 0 to 200 ms; prefill of the uncached part of the prompt, say 300 new tokens on a 70B model, 30 to 80 ms; first decode step about 20 ms; buffer and gateway about 5 ms. Total typically 100 to 400 ms, well inside the 1-second target. Without prefix caching, prefilling 2,100 tokens adds roughly 100 to 300 ms; with a 30,000-token pasted document, prefill alone can take 0.5 to 2 seconds, which is why long prompts get chunked prefill and why TTFT targets are usually stated for typical prompt sizes.
Flow 2: connection drops mid-answer and the client resumes#
- The generation keeps running regardless of the client. Chunks 58 to 70 are generated while the client is offline and land in the buffer.
- The client notices the connection closed (or the stream stalled past a heartbeat timeout) and reconnects with backoff. Browsers' built-in
EventSourcedoes this automatically and sendsLast-Event-ID; apps that usefetchwith a POST body (becauseEventSourceonly supports GET without custom headers) implement the same logic themselves. - Any stream gateway can serve the reconnect, since state lives in the buffer, not in the gateway. It replays chunks after 57 and then tails live chunks.
- If the user reloads the page entirely, the app loads the conversation, sees the assistant message in status
streamingwith itsrunId, and opens the stream from the beginning (noLast-Event-ID), so it gets the full text so far and then the rest. - If the run already finished, the gateway sends the remaining chunks and
donestraight from the buffer; if the buffer entry has expired, the client reads the final message from the conversation store instead.
Flow 3: the user presses Stop#
- The cancel goes through the API to the inference gateway, which knows where the run is.
- If the run is still queued, it is simply removed: no GPU time spent, no tokens charged.
- If it is decoding, the replica removes the sequence from its batch at the next step (within about 20 ms) and returns its KV-cache blocks to the free pool, where they immediately serve other users. Prefix blocks shared with other sequences, such as the system prompt, are not freed while still referenced.
- The partial answer is saved with status
cancelled, and the user is charged only for tokens actually generated. - Cancel is idempotent: cancelling a finished or already-cancelled run returns its final state.
Closing the tab is not the same as pressing Stop. A dropped connection might be a reconnect in progress, so we keep generating (that is the point of resumability). But generating an answer nobody will read wastes GPU time. A common compromise is a grace timer: if no client has been attached to the run for, say, 30 to 60 seconds and the user has not reconnected, the gateway cancels it. Short answers finish before the timer matters; very long ones stop wasting compute. Some products instead always finish the answer so the user finds it when they return; it is a product decision with a visible cost.
Data Model#
The relational form, useful for discussion even if the production store is wide-column:
CREATE TABLE conversations (
user_id TEXT NOT NULL,
conversation_id TEXT NOT NULL,
title TEXT,
model TEXT,
latest_message_id TEXT,
updated_at TIMESTAMPTZ NOT NULL,
deleted_at TIMESTAMPTZ,
PRIMARY KEY (user_id, conversation_id)
);
-- "my conversations, newest first"
CREATE INDEX conv_by_recent ON conversations (user_id, updated_at DESC)
WHERE deleted_at IS NULL;
CREATE TABLE messages (
conversation_id TEXT NOT NULL,
seq BIGINT NOT NULL, -- order within the conversation
message_id TEXT NOT NULL UNIQUE,
parent_id TEXT, -- enables branching later
role TEXT NOT NULL, -- user, assistant, system
status TEXT NOT NULL, -- streaming, complete, cancelled, failed, blocked
content TEXT, -- or a pointer to a blob for large pastes
tokens INT,
run_id TEXT,
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (conversation_id, seq)
);| Data | Store | Why |
|---|---|---|
| Conversations and messages | Cassandra, ScyllaDB or DynamoDB; or PostgreSQL sharded by user id | Predictable single-partition reads and appends at about 50,000 writes per second; petabyte scale; easy horizontal growth |
| Hot conversation context | Redis or Memcached, keyed by conversation id | The last few turns are read on every new prompt; a cache saves a database read and token counting |
| Token stream buffer | Redis Streams with replicas, TTL a few minutes | Ordered, append-only, readable from any offset, fast; loss of a buffer is survivable because of checkpoints |
| Usage counters | Redis, with sliding or fixed windows per user and model class | Checked on every request; must be sub-millisecond |
| Usage events, run outcomes, moderation events | Kafka topics into a warehouse | Durable log for billing, analytics, capacity planning and evaluation |
| Large pasted files | Object storage with a pointer in the message | Keeps message rows small; see Pattern: Handling Large Files and Blobs |
| Model weights | Object storage, cached on local NVMe on GPU nodes | Hundreds of gigabytes per model; loading speed limits how fast we can add replicas |
Why not a single relational database? It is fine at the start and remains attractive for user accounts, billing and settings, where transactions and joins matter. Conversation history is different: billions of rows a day, accessed almost only by key, never joined, and growing forever. A store partitioned by conversation id, with the conversation list partitioned by user id, matches those access patterns exactly. The broader reasoning is in Choosing a Database: A Decision Guide.
Two partitioning keys, one consistency question. The conversation list (keyed by user) and the messages (keyed by conversation) live in different partitions, so "append message, then bump updated_at on the conversation" is two writes. If the second fails, the conversation is slightly out of order in the list, which is harmless and fixed by the next write. We do not need a distributed transaction here; we do need each write to be idempotent (the message id is deterministic per run), so retries are safe.
Message sequence numbers. Within a conversation, seq is assigned by the API server that handles the send, using a conditional write ("insert seq 43 if not exists") so two concurrent sends from two devices cannot claim the same position. The loser retries with the next number. Conversations are effectively single-writer most of the time, so contention is rare.
Deletion. Deleting a conversation sets deleted_at immediately (it disappears from the list), and a background job purges messages, buffers, caches and derived data such as embeddings within the promised period. In wide-column stores, deleting a whole partition is a single tombstone, which is cheap; deleting individual rows across many partitions is not. Partitioning messages by conversation makes purges efficient.
Deep Dives#
1. Streaming tokens to the client: SSE, WebSockets and what sits in between#
Why stream at all. Reading speed is about 4 to 8 tokens per second; models generate 30 to 100. If the first words appear within half a second, the user starts reading while the rest is produced, and the perceived wait almost disappears. The same 10-second answer feels fast when streamed and broken when not. Streaming also lets the user stop a bad answer early, which saves GPU time.
The options. The concept page Polling, Long Polling, SSE, WebSockets and Webhooks covers the general trade-offs; here is how they apply to token streams.
| Option | How it works | Fit for LLM output |
|---|---|---|
| Polling | Client asks "anything new?" every 200 ms | Wasteful and adds up to the polling interval of delay to every chunk; only a fallback |
| Long polling | Request held open until new data, then client re-requests | Works through anything, but one round trip per chunk; clumsy at 20 to 50 chunks per second |
| Server-Sent Events | One HTTP response that never ends, carrying event:, id: and data: lines | Natural fit: one-way, text, ordered, built-in resume ids, plain HTTP through proxies and CDNs |
| WebSockets | Upgraded TCP connection, full duplex frames | Works well; needed if the client must also send data mid-stream (voice, live tool approvals); more infrastructure (sticky routing, custom heartbeat, no HTTP semantics) |
| HTTP/2 or HTTP/3 streaming of raw chunks or newline-delimited JSON | Same idea as SSE without the SSE framing | Fine for server-to-server APIs; loses Last-Event-ID conventions |
Why SSE wins for the core flow. The request is one-way after the prompt is sent. SSE is just HTTP, so authentication, TLS, load balancers, WAFs, logging and HTTP/2 multiplexing all work unchanged. Each event can carry an id, and the protocol defines Last-Event-ID for resumption, which is exactly what Deep Dive 2 needs. OpenAI's, Anthropic's and most other public LLM APIs stream over SSE for these reasons. WebSockets become attractive when the session is genuinely two-way and continuous, such as real-time voice, where audio flows both ways at once.
Details that bite in production.
- Proxy buffering. Reverse proxies and some CDNs buffer responses to make them efficient, which silently turns a stream into one late blob. Disable buffering for stream routes (in nginx,
proxy_buffering offor the response headerX-Accel-Buffering: no), and make sure compression middleware flushes per event. This is one of the most common "streaming works locally but not in production" bugs. - Idle timeouts. Load balancers close connections that are silent for too long (AWS Application Load Balancer defaults to 60 seconds; many proxies use 60 to 120 seconds). During a long queue wait or a slow tool call, send an SSE comment line (
: keep-alive) every 15 seconds. Comments are ignored by clients but reset idle timers. - Connection limits. Browsers allow only about 6 concurrent HTTP/1.1 connections per origin; several tabs each holding a stream can exhaust them. Serving streams over HTTP/2 or HTTP/3 multiplexes them onto one connection.
- Chunk size and pacing. Sending one event per token costs a write system call, framing and a render per token. Coalescing tokens produced within about 30 to 50 ms into one event cuts overhead several times with no visible difference. Some products also smooth the output on the client (render at a steady rate) so bursts from batching do not look jerky.
- Token boundaries are not character boundaries. A token can be half of a multi-byte UTF-8 character (an emoji or a Chinese character is often split). The server must detokenise incrementally and only emit complete characters, holding back a partial byte sequence until the next token completes it.
- Incremental markdown. The answer is markdown with code blocks and tables. The client re-renders the growing text; it must tolerate unclosed code fences and half-written tables, and avoid re-parsing the whole message on every chunk for long answers (parse incrementally or throttle re-renders to a few per second).
- Backpressure. If the client reads slowly (a weak mobile connection), the gateway's send buffer fills. Because tokens are also in the buffer store, the gateway can simply stop reading from the buffer for that client and resume when the socket drains; the generation is never slowed by a slow reader. This is the same decoupling a queue gives producers and consumers.
Gateway sizing. 120,000 concurrent streams at peak. A well-written asynchronous gateway (Go, Rust, Java with virtual threads, Node.js) holds tens of thousands of idle-ish connections per server; the work per stream is a few events per second. 10 to 20 servers carry the load with room for failure; we run more across zones for redundancy. The cost is dominated by TLS and memory per connection, not CPU.
Stream gateway deploys. A deploy must not cut 120,000 answers. Gateways drain: on shutdown they stop accepting new streams, and for existing ones either wait until they finish (most finish within 30 seconds) or close them deliberately, relying on clients to reconnect elsewhere with Last-Event-ID. Because state lives in the buffer, a forced close costs the user a few hundred milliseconds of pause, not a lost answer. Connection-draining deploys are covered in CI/CD and Deployment Strategies.
2. Keeping streams alive across reconnects, reloads and deploys#
The problem: a generation lasts 5 to 60 seconds (minutes for long reasoning models), but connections between phones and data centres break all the time. Losing an answer is bad for the user and expensive for us, because regenerating it costs the same GPU time again.
Design principle: the run is a server-side object with its own lifecycle, and connections are just viewers. Once accepted, a run proceeds to completion (or cancellation, or failure) whether or not anybody is watching. Its output is written in order to a buffer that any viewer can read from any position.
The token buffer. For each run, an ordered log of chunks. Requirements: append at about 20 to 50 chunks per second per run, read from an arbitrary sequence number, tail new entries with low latency, expire automatically a few minutes after the run ends. Total size is small: 120,000 active runs × about 2 KB of text each is under 1 GB, plus recently finished runs.
Choices:
- Redis Streams (
XADD run:r_9a * text ...to append,XREAD BLOCKfrom an id to read and tail). Ordered, persistent within Redis, readable from any id, and blocking reads give push-like latency. Cluster it by run id so load spreads; replicate each shard. See Redis in Practice. - Redis pub/sub plus a list. Pub/sub alone is fire-and-forget: a subscriber that was disconnected misses messages. It needs a list or stream alongside for replay, so Streams is simpler.
- Kafka. Durable and replayable, but one partition per run is not how Kafka is meant to be used, and per-run topics would be absurd; runs would share partitions, so a reader must filter. Better as the durable log of finished messages and usage events than as the live per-run buffer.
- In-process buffer on the replica host, with the gateway connecting to it. Lowest latency, no extra store, but if the host dies the buffer dies with it, and gateways must know which host holds each run. Fine for small systems; at our scale the separate buffer earns its keep.
Event ids. Each chunk gets a monotonically increasing integer id within the run (1, 2, 3...). The SSE id: field carries it. On reconnect the client sends Last-Event-ID: 57 and receives 58 onward; a client that has nothing sends no header and receives everything from 1. Because ids are per run, there is no global ordering problem.
Checkpointing to the database. Every few seconds (and at the end) the run's accumulated text is written to the assistant message row. This bounds the loss if the buffer shard fails, and lets a user who returns after the buffer expired still see the answer. Checkpointing every chunk would multiply database writes by about 50; every 2 to 5 seconds is a good compromise.
When the GPU replica fails mid-answer. A replica can crash, a GPU can throw an error (Xid errors and ECC faults are routine at fleet scale), or a node can be preempted. The KV cache dies with it. Options:
- Fail the run and mark the message
failedwith a "regenerate" button. Simple and honest. Users lose the partial answer only if we do not keep it, so keep it. - Restart from scratch on another replica. The user sees the answer restart, which is jarring, and the second answer may differ because sampling is random.
- Continue from the partial output. Send a new request to another replica whose prompt is the original prompt plus the tokens already generated, and continue decoding. Mathematically the model's next-token distribution depends only on the token sequence so far, so continuing from the same prefix is a valid continuation; the cost is one extra prefill of prompt plus partial output, often a fraction of a second. The stream just pauses briefly and carries on with ids continuing from where they stopped. This is the most user-friendly option and the one we choose for interactive runs, with a retry limit of one or two to avoid loops on a poison request.
The scheduler detects replica death through missed heartbeats (a few seconds) and the engine's own health reports, as in Heartbeats, Failure Detection and Gossip. It must also guard against the opposite error: a replica that is merely slow, not dead, continuing to write chunks after its run was reassigned. Each run assignment carries an attempt number, and the buffer rejects appends from an older attempt, a simple fencing token.
Deploying the inference fleet. Model replicas are deployed (new engine version, new weights) by draining: the scheduler stops sending new runs to a replica, lets running sequences finish (or, after a deadline, migrates them using the continue-from-partial trick), and only then restarts it. Loading 70 to 140 GB of weights from local NVMe takes tens of seconds to a couple of minutes; from remote object storage several minutes. So rolling deploys go a few percent of replicas at a time, during off-peak hours when spare capacity exists.
Multiple devices. Because the run is server-side, a user can start a question on their laptop and open the same conversation on their phone, which connects to the same run's stream. No special design is needed beyond authorising that the viewer owns the conversation.
The state machine of a run makes the rules explicit:
3. Routing and scheduling across GPU workers#
This is the core of the design. Two levels of scheduling interact: inside a replica (which sequences share the GPU at each step) and across replicas (which replica gets each request).
Inside a replica: from static batches to continuous batching
Static batching. The naive approach collects, say, 32 requests, runs them together until all are done, then takes the next 32. Requests that finish early leave empty slots that sit idle until the longest one ends; new requests wait for the whole batch. With output lengths ranging from 5 to 2,000 tokens, GPU utilisation collapses.
Continuous (iteration-level) batching. The scheduler decides the batch at every decode step. When a sequence finishes, its slot is filled by a waiting request at the next step. This idea was introduced in "Orca: A Distributed Serving System for Transformer-Based Generative Models" (Yu et al., OSDI 2022) and is now standard in every serious inference engine. It raises throughput several times over static batching at the same latency.
Paged KV cache. Continuous batching needs flexible memory: sequences start, grow and end at different times. Allocating each sequence a contiguous KV region sized for its maximum possible length wastes most of the memory. "Efficient Memory Management for Large Language Model Serving with PagedAttention" (Kwon et al., SOSP 2023), the paper behind vLLM, borrowed the operating-system idea of virtual memory pages: the KV cache is split into fixed-size blocks (for example 16 tokens each), a sequence holds a list of block pointers, and blocks are allocated as it grows. Waste drops to under one block per sequence, and blocks can be shared between sequences with a common prefix (copy-on-write). The paper reported 2 to 4 times higher throughput than earlier systems at the same latency, mostly from fitting larger batches.
Mixing prefill and decode. A long prefill (a 30,000-token pasted document) takes hundreds of milliseconds of pure compute. If the engine runs it in one go, every user decoding on that replica sees a stall of that length: a visible freeze in their stream. Chunked prefill splits big prefills into slices (say 512 to 2,048 tokens) and mixes one slice into each step alongside the decode tokens, keeping each step's duration roughly constant. "Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve" (Agrawal et al., OSDI 2024) studied this "stall-free" scheduling in detail. The engine typically enforces a token budget per step (for example 2,048 to 8,192 tokens of prefill plus decode) that sets the trade-off between TTFT for new requests and smoothness for running ones.
Preemption. When memory runs out mid-generation (sequences grew longer than expected), the engine must evict someone. Choices: swap the victim's KV blocks to CPU memory and bring them back later, or drop and recompute them by re-running prefill when the sequence resumes. Recompute is often cheaper than it sounds because prefill is fast and parallel. The victim should be the lowest-priority, most recently admitted sequence, which ties into tiers (Deep Dive 4).
Prefill and decode disaggregation. Prefill is compute-bound and bursty; decode is memory-bandwidth-bound and steady. Running both on the same GPUs means each interferes with the other. Several systems run them on separate pools: prefill replicas compute the KV cache for a prompt and transfer it over a fast interconnect (NVLink, InfiniBand or RoCE) to a decode replica, which streams the answer. "DistServe" (Zhong et al., OSDI 2024) and "Splitwise" (Patel et al., ISCA 2024) showed that this lets each pool be sized and tuned for its own phase and can meet TTFT and TPOT targets at lower cost. Moonshot AI's "Mooncake" paper (2024) described a production chat service built around a disaggregated, KV-cache-centric design with a large distributed KV store in CPU memory and SSDs. The cost is moving the KV cache: 2,000 tokens × 160 KB is about 320 MB per request, which at 50 GB/s takes about 6 ms. Fine on a fast fabric, impossible across regions.
Across replicas: placement
The scheduler sees every replica's state: running sequences, free KV blocks, queued prefill tokens, and which prefixes it holds in cache. For each request it picks a replica. Options, from simple to clever:
- Round robin or random. Ignores load and cache. A replica stuck with several long prompts falls behind while others idle.
- Least loaded. Pick the replica with the most free KV memory or the shortest queue. Good balance, but ignores cache: the conversation's earlier turns were computed on replica 7 and are sitting in its memory, yet we send turn 20 to replica 12, which must recompute 15,000 tokens of history.
- Prefix affinity (cache-aware routing). Hash the conversation id (or the prompt's prefix) and prefer the replica that served this conversation last. Turn 20 lands where turns 1 to 19 left their KV cache, so prefill shrinks to the new message. This is the single most valuable placement rule for chat. SGLang's RadixAttention ("SGLang: Efficient Execution of Structured Language Model Programs", Zheng et al., 2024) organises cached prefixes in a radix tree inside a replica; cache-aware routers across replicas build on the same idea.
- Prefix affinity with bounded load. Pure affinity creates hot spots: a replica holding a popular prefix or a few very long conversations is overloaded while others idle. Combine them: use consistent hashing to pick the preferred replica, but if its load is above (1 + ε) times the average, walk to the next replica on the ring. This is exactly "Consistent Hashing with Bounded Loads" (Mirrokni, Thorup and Zadimoghaddam, SODA 2018), described in Consistent Hashing. In practice the scheduler scores each candidate: expected cached tokens saved, minus a penalty for its queue depth and memory pressure.
The system prompt is a shared prefix. Every request for a given model and product surface starts with the same 1,000-token system prompt. Every replica keeps it permanently cached (pinned blocks), so that part of prefill is free everywhere. This is why the context builder must keep the system prompt byte-identical: changing the date string at the top of the prompt every minute would invalidate it.
How long does a conversation's cache survive? A replica has room for KV cache of a few hundred to a few thousand sequences; idle conversations are evicted (LRU over prefix blocks) within minutes when the replica is busy. Users often reply within a minute or two, so affinity pays off for active conversations. For conversations resumed hours later, the cache is gone and the full prefill is paid, unless the system keeps a second-tier KV cache in CPU memory or local SSD (hundreds of gigabytes to terabytes per node), which is what systems such as Mooncake and engine features for KV offloading provide. Reading 300 MB of KV cache from local NVMe at several GB/s takes about 100 ms, versus roughly 0.5 to 1 second of GPU prefill for a long history, and it spares the GPU that work.
Queueing and admission
Requests wait at the inference gateway, not inside replicas, so the scheduler has a global view and can reorder by priority. Each replica keeps only a short local queue (enough to keep its batch full). Rules:
- Deadline per request. Every queued request carries a deadline based on its class: perhaps 5 seconds for paid interactive, 15 seconds for free interactive, minutes for background. A request still waiting at its deadline is rejected with a "busy, try again" response rather than served late. A queue that grows without bound is the classic way an overloaded service turns a capacity problem into an outage for everyone; see Asynchronous Processing and Message Queues and Resilience Patterns: Timeouts, Retries and Circuit Breakers.
- Estimate cost before admitting. A request's cost is roughly its uncached prompt tokens (prefill) plus expected output tokens (decode). The scheduler uses these estimates to keep each replica's memory from overflowing.
- Little's law sets the queue length. If a model's fleet serves 20,000 requests per second and we allow an average queue wait of 200 ms, about 4,000 requests are waiting at any moment. A queue of 100,000 requests means waits of 5 seconds, already past the paid deadline.
Autoscaling the fleet
GPU capacity is the slowest thing in the system to change. New cloud GPU capacity may not be available on demand at all; even with machines in hand, a replica takes minutes to start (boot, pull the container, load weights, warm up compiled kernels). So:
- Plan, then react. Capacity is provisioned for forecast daily peaks (traffic is strongly diurnal and weekly) plus headroom. Reactive scaling moves replicas between models and between interactive and batch work within the existing fleet, which takes minutes, rather than buying new machines, which takes weeks.
- Scale on the right signal. CPU and GPU utilisation are poor signals (a GPU can look 100% busy while serving small batches). Better signals are queue wait time, KV-cache utilisation, and achieved TTFT and TPOT against their targets.
- Fill the troughs. At night, interactive load falls by half; the freed GPUs run batch work (asynchronous batch APIs, evaluation runs, data generation), which is preempted when morning traffic rises. OpenAI's Batch API, for example, offers a discount in exchange for results within 24 hours, which is the price signal for exactly this.
- Spread across regions. Users in Asia and Europe peak at different hours from users in America. If the model is deployed in several regions, overflow can be routed to a region in its trough at the cost of extra network latency (100 to 200 ms, small next to generation time). This is how a fleet's average utilisation is kept high. Capacity Planning and Load Testing covers forecasting and headroom.
4. Fairness, tiers and rate limits: deciding who gets compute#
When demand exceeds GPU supply, someone waits or is refused. The design question is who, and whether the rule is deliberate. Without one, the answer is "whoever sends the most requests", which rewards scripts and abusers and punishes ordinary users.
Limit what costs money: tokens, not requests. A request asking "hi" and a request pasting a 50,000-token document differ in cost by a factor of hundreds. So limits are expressed in tokens per window (and, for the consumer product, also in messages per window because that is easier to explain to users). For developer APIs the convention is limits on both requests per minute and tokens per minute, per model, per organisation.
Two-phase accounting. Output length is unknown at admission. The quota service reserves an estimate (prompt tokens plus the request's max_tokens, or a typical output size) when the request is admitted, and settles with the actual count when the run ends, refunding the difference. Without reservation, a user could launch 50 long requests at once, all admitted because none has finished and been counted yet.
Algorithms. Token bucket per user per model class is the usual choice: capacity sets the burst size, refill rate sets the sustained rate. Sliding window counters suit "40 messages every 3 hours" style product limits. Both live in Redis and are updated atomically with a Lua script or a single INCRBY with expiry. Rate Limiting and Throttling compares the algorithms; Design a Distributed Rate Limiter builds a full service.
-- Reserve tokens from a user's bucket; refill continuously.
-- KEYS[1] bucket key; ARGV: capacity, refill_per_sec, now_ms, cost
local cap, rate, now, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]), tonumber(ARGV[4])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or cap
local ts = tonumber(b[2]) or now
tokens = math.min(cap, tokens + (now - ts) / 1000 * rate)
if tokens < cost then
local wait_ms = math.ceil((cost - tokens) / rate * 1000)
return {0, math.floor(tokens), wait_ms} -- rejected, remaining, retry after
end
tokens = tokens - cost
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate * 1000))
return {1, math.floor(tokens), 0}The settle step calls a similar script with a negative cost to refund unused tokens.
When a limit is exceeded: reject quickly and say what to do. The response is HTTP 429 with:
X-RateLimit-Limit: the size of the window or bucket, such as 40 messages or 2,000,000 tokens.X-RateLimit-Remaining: how much is left (0 here).X-RateLimit-Reset: when the window resets or enough capacity refills, as a timestamp or seconds.Retry-After: seconds to wait before trying again, which well-behaved clients and SDKs honour.- A body that names the limit and offers alternatives: "You have reached the limit for the flagship model until 14:20. You can continue with the smaller model now."
Failing fast is better than queueing because the user gets an immediate, actionable answer, and the system does not hold resources for work it will not do. Clients must back off exponentially with jitter on 429s; a client that retries in a tight loop turns a limit into a self-inflicted denial of service.
Priority classes and fair queueing. Admission is necessary but not sufficient: under load, admitted requests still compete. The inference gateway keeps separate queues per class:
- Between classes: weighted, not strict priority. Strict priority (always serve paid first) can starve free users entirely during a long peak. Weighted sharing guarantees each class a fraction of capacity under contention while letting any class use idle capacity. Background work has a small guaranteed share so it eventually finishes, and is the first to be preempted.
- Within a class: fair across users. A queue per user (or per organisation) served by deficit round robin measured in tokens: each user gets a quantum of tokens per round; a user with one short request is served promptly even if another has 500 long requests queued. This is the network idea of weighted fair queueing applied to GPU time. Concurrency caps per user (for example at most 2 or 3 simultaneous generations in the consumer app) are a simpler, complementary guard.
- Enterprise reservations. Large customers may buy dedicated or reserved throughput (OpenAI and Azure OpenAI call this provisioned throughput). That is capacity carved out of the fleet with its own queue, so their traffic is isolated from consumer spikes, and its unused share can be lent to others when idle.
Graceful degradation instead of hard failure. Think of video streaming with adaptive bitrate: when your bandwidth drops, the player switches to a lower resolution rather than stopping. An LLM service can do the same when GPUs run short:
- Lower-priority classes wait longer; background work pauses.
- Free users are routed to the smaller model (much cheaper per token) rather than refused; the product says so.
- Output caps shrink for free traffic; expensive features (very long context, reasoning modes) are limited.
- Only then, free requests are rejected with a "busy" message and a retry time. Paid traffic is protected until last.
ChatGPT has publicly used caps for its most expensive models and falls back to a smaller model for free users when those caps are reached, which is this ladder in action.
Abuse is a fairness problem too. Scripts that create many free accounts to get around limits, or that resell free access, consume capacity meant for real users. Signals: account age, device and network fingerprints, request patterns (identical prompts at machine regularity), payment status. Responses range from tighter limits and challenges to account suspension. Limits keyed only on user id are easy to dodge; layering limits by IP range, device and payment instrument makes it costly.
5. Controlling cost as conversations grow#
The model is stateless, so every turn re-sends the whole conversation. If each turn adds about 400 tokens (100 from the user, 300 from the model), turn n's prompt is about 1,000 + 400 × (n − 1) tokens. Without caching, the total prefill over a 50-turn conversation is about 50 × 1,000 + 400 × (0 + 1 + ... + 49) = 50,000 + 400 × 1,225 ≈ 540,000 tokens, versus only 20,000 new tokens actually typed or generated. Cost grows with the square of conversation length. Each turn also gets slower to start (more prefill) and holds more KV memory, crowding other users. Five levers fix this, usually in combination.
Lever 1: prefix caching, so old turns are not recomputed. If turn n's prompt is exactly turn n − 1's prompt plus the last answer plus the new message, the KV cache from turn n − 1 is reusable: only the new tokens need prefill. With prefix affinity routing (Deep Dive 3), this turns quadratic prefill compute back into linear. Memory is still proportional to the full length, and the cache only survives while the conversation is active. Provider APIs expose this as prompt caching: OpenAI applies it automatically to long repeated prefixes and bills cached input tokens at a discount; Anthropic's API lets callers mark cache breakpoints explicitly and charges cache reads at a fraction of the normal input price. The exact discounts and time-to-live values change over time, so check current documentation, but the principle is stable: a stable prefix is cheap, a changed prefix is full price.
Lever 2: a context budget with truncation. Decide a maximum prompt size per model and tier (for example 16,000 tokens for free, more for paid), well under the model's maximum context window. When the conversation exceeds it, drop the oldest turns (keeping the system prompt and the most recent turns). Simple and predictable, but the model forgets early details, and dropping turns from the front changes the prefix, invalidating the cache. Dropping in large steps (cut 8,000 tokens at once, rarely) rather than one turn at a time each turn keeps the prefix stable between cuts.
Lever 3: summarisation of old turns. Replace older turns with a summary produced by a small, cheap model in the background ("The user is planning a trip to Japan in April with two children; they prefer trains; we discussed Kyoto and Osaka hotels"). The prompt becomes system prompt + summary + recent turns + new message. Costs: a summary call (cheap), possible loss of detail, and a prefix change whenever the summary is regenerated, so regenerate it rarely, at the same moments truncation would cut.
Lever 4: retrieval instead of inclusion. Store each older turn's embedding in a vector index scoped to the conversation (or the user), and at each turn retrieve the few most relevant older passages to include, the same pattern as retrieval-augmented generation ("Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks", Lewis et al., 2020). This scales to very long histories and to cross-conversation memory ("the user is vegetarian"), which several products now offer as an explicit, user-visible feature. The hard part is quality: retrieval may miss what matters, so it complements rather than replaces recent turns. See Vector Databases and Similarity Search.
Lever 5: bigger context is not always better. Models attend less reliably to information buried in the middle of very long contexts ("Lost in the Middle: How Language Models Use Long Contexts", Liu et al., 2023, published in TACL 2024). Trimming irrelevant history can improve answers as well as cost.
Worked example. A 60-turn conversation has 26,000 tokens of history. With pure inclusion and no cache, turn 61 costs 26,000 prefill tokens. With prefix caching and an active conversation, it costs about 100 (the new message), but holds about 8 GB of KV cache in FP16 (4 GB in FP8) on the reference model for the duration of the answer. With the budgeted prompt above and the conversation resumed after the cache expired, it costs about 12,500 prefill tokens and holds about 4 GB in FP16. The right mix depends on whether the conversation is hot (cache wins) or cold (budget wins), which is why the context builder checks whether the preferred replica still holds the prefix before deciding how much history to send.
6. Conversation storage at petabyte scale#
Conversation storage is the "ordinary" part of the system, but at 1 billion turns a day it still needs care.
Write path. Each prompt produces at least three writes: the user message, the assistant placeholder, and the final assistant message (plus a few checkpoints). At 20,000 prompts per second that is 60,000 to 100,000 writes per second of 1 to 3 KB each, a comfortable load for a Cassandra or ScyllaDB cluster of a few dozen nodes, or for DynamoDB with on-demand capacity. Wide-column stores are a good fit because writes are appends to a partition, reads are range scans within one partition, and there are no joins. See Apache Cassandra in Practice and Amazon DynamoDB in Practice.
Partition sizing. Partitioning messages by conversation_id keeps each conversation's messages together and sorted by seq. Most conversations are small (a few turns, a few kilobytes); a few are huge (thousands of turns with pasted documents, tens of megabytes). Very large partitions hurt wide-column stores (slow compaction, slow repairs, hot nodes), so long conversations are split into buckets: the partition key becomes (conversation_id, bucket) where bucket = seq ÷ 1,000. Reads of the latest messages touch only the newest bucket. Large pasted files go to object storage, with the message holding a pointer.
The conversation list. Users open the app and see their recent conversations. This is a read of the user's partition in the conversations table sorted by updated_at. In Cassandra, sorting by a mutable column needs a separate table (conversations_by_recency with clustering key updated_at DESC, conversation_id), where each update deletes the old row and inserts the new one, or simply a bounded read of all the user's conversations sorted in the application for users with a few hundred conversations. Heavy users with tens of thousands need the separate table. Pagination uses a cursor (the last updated_at and id seen), never offsets; API Design Best Practices explains why.
Titles. New conversations get an automatic title from a small model in the background after the first answer. It is a classic asynchronous job: enqueue, run on the small-model pool in the background class, write the title, push it to the client through the open stream or on the next list refresh.
Read path and caching. On every new prompt, the context builder needs the recent turns. Reading them from the database each time works but is wasteful; a cache of the last N turns per active conversation (Redis, TTL about 30 minutes, written through when messages are saved) removes most of those reads. The conversation list is cached per user for a few seconds, and on the client. Deep Dive 7 covers the caching strategy.
Hot and cold data. Most reads touch conversations from the last few days; old conversations are rarely opened. Over years the store grows to petabytes, almost all cold. Two techniques keep cost under control, the same ideas as compaction and archival in collaborative editors and in Data Lifecycle, Tiering and Retention:
- Compaction of finished conversations. While a conversation is active, it is a sequence of small rows, plus checkpoint versions of streaming messages. Once idle for, say, 30 days, a background job rewrites it as one compressed document (all messages, zstd-compressed, typically 3 to 4 times smaller) and deletes the intermediate rows and stale checkpoints.
- Archiving to object storage. After 90 days or so, compacted conversations move to object storage (cheaper per gigabyte by an order of magnitude than replicated database SSD storage), with the database keeping only the conversation's list entry and a pointer. Opening an archived conversation costs one object read (tens of milliseconds), after which it is rehydrated into the hot store if the user continues it.
Deletion and privacy. Users can delete conversations and their whole account; regulations such as the EU's GDPR give them a right to erasure. Deletion must reach every copy: database rows, caches, token buffers, search and memory indexes (embeddings derived from the conversation), archives, analytics exports and backups (usually by letting backups age out within a stated period, or by encrypting each user's data with a per-user key and destroying the key, called crypto-shredding). A deletion pipeline that walks a registry of every store holding user data is more reliable than hoping each team remembers.
Isolation as a correctness requirement. Every read of a conversation checks that the authenticated user owns it; cache keys include the user id or conversation id and nothing ambiguous; connection pools and clients are not shared in ways where a cancelled request can leave stale data for the next one. The March 2023 incident mentioned earlier came from exactly this class of bug: OpenAI's report described how a request cancelled at the wrong moment left a shared Redis connection in a state where the next request on it received the previous user's data. Tests should include fault injection around cancellation and timeouts, not only the happy path.
Multi-region placement. Each user has a home region where their conversations live (chosen at sign-up, or by data residency rules for enterprise customers). Inference may happen in another region when GPU capacity is there, but the conversation store is read and written in the home region. Cross-region replication for disaster recovery is asynchronous, which means a region failure can lose the last few seconds of messages; acceptable for chat history. Multi-Region and Global Data discusses the options.
7. Caching: what, where and how in an LLM service#
Caching in this system has an unusual shape. The classic targets (database rows, rendered pages) are cheap; the expensive thing to cache is GPU computation. Applying the usual method from Caching Fundamentals step by step:
1. Identify the bottleneck. GPU time per request (prefill of long prompts, decode of long outputs), then conversation reads on every prompt, then the conversation list on every app open.
2. Decide what to cache, and where.
| What | Where | Pattern | Hit rate and value |
|---|---|---|---|
| Static app bundle, fonts, images | CDN and browser | Long TTL with content-hashed file names | Near 100%; standard |
| KV cache of prompt prefixes (system prompt, earlier turns) | GPU memory, then CPU memory and local SSD on the replica | Engine-managed, LRU over blocks; routing affinity makes it work | The biggest win: 50 to 80% of prompt tokens in active conversations |
| Recent turns of active conversations | Redis or Memcached | Write-through on message save, cache-aside on read | High during a session; saves a database read per prompt |
| Conversation list per user | Client memory and a short-TTL server cache | Cache-aside, invalidated on new conversation or title change | High; app opens are frequent |
| Usage counters and tier lookups | Redis; tier also cached in-process for seconds | Source of truth for counters is Redis itself | Every request; must be sub-millisecond |
| Exact response cache | Redis keyed by a hash of model, settings and full prompt | Cache-aside with TTL | Low for conversations, useful for first-turn suggested prompts and repeated API calls |
| Semantic response cache | Vector index of prompt embeddings | Lookup by similarity threshold | Risky for chat; useful only for narrow FAQ-style products |
3. Choose the pattern. For conversation data, write-through keeps the cache of recent turns exact (we write the message to the database and update the cache in the same code path), and cache-aside fills it on a miss. Write-behind (buffering writes in the cache and flushing later) is tempting for checkpoint writes of streaming text but risks losing them; the token buffer already plays that role, with the database receiving periodic checkpoints. Read-through caches (where the cache itself loads from the database) are a matter of library choice. Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind compares them.
4. Eviction. LRU with TTLs is the safe default for conversation caches: active conversations stay, idle ones expire. KV-cache blocks inside the engine are evicted LRU as well, with pinned blocks for the system prompt. An interesting refinement is to evict by expected value: a 20,000-token prefix that is likely to be reused soon saves far more GPU time than a 500-token one, so size-aware and frequency-aware policies (LFU-like, or GreedyDual-Size) can beat plain LRU. FIFO and random eviction are rarely right here. Cache Eviction and Invalidation covers the algorithms.
5. Address the downsides.
- Consistency. A message saved on one device must appear on another. Write-through on the same code path, plus short TTLs, keeps the conversation cache correct; the client refetches on focus.
- Stampedes. If the system prompt changes (a new product release), every replica's pinned prefix is invalidated at once and every request pays full prefill until caches warm: a GPU-level thundering herd that can push TTFT up sharply for minutes. Roll out prompt changes gradually, region by region, and pre-warm replicas with the new prefix before switching traffic. The same applies to cache failures in Redis: if the conversation cache shard fails, reads fall back to the database, which must be sized for it, with request coalescing so one popular key is not fetched a thousand times. Cache Failure Modes: Stampedes, Hot Keys and Penetration has the full toolbox.
- Hot keys. Usage counters of a single abusive account can become hot; tier configuration read on every request should be cached in-process for a few seconds instead of read from Redis each time.
Why exact and semantic response caches are mostly a trap here. Answers are sampled with randomness (temperature above zero), personalised by conversation history and user memory, and expected to be fresh. A cache hit returns somebody's earlier answer, which is wrong if anything in the context differed, and dangerous if the cache key accidentally omits the user scope. A semantic cache adds the risk of serving the answer to a similar but different question ("How do I kill a Python process" versus "How do I kill a parent process"). They make sense for stateless, public, repeated prompts (suggested starter prompts, product FAQs, deterministic API calls with temperature zero), and only with keys that include model version, settings and any per-user context.
When to introduce caching in the interview. Not first. Establish the bottleneck with numbers: "Without prefix caching we need about 7,400 GPUs for prefill; with a 70% hit rate, 2,200. That is the cache that matters." Then the conversation cache: "Each prompt reads the last turns; at 20,000 prompts a second, a Redis cache saves most of 20,000 database reads a second."
8. Moderation and safety in the request path#
A public LLM service must refuse clearly harmful requests, avoid producing harmful output, detect abuse, and do this without making every user wait. Much of safety lives inside the model itself (training with human feedback, as in "Training language models to follow instructions with human feedback", Ouyang et al., 2022, the InstructGPT paper; or Anthropic's "Constitutional AI: Harmlessness from AI Feedback", Bai et al., 2022). The system around the model adds independent layers, because no single layer is perfect.
Layers, cheapest first.
- Account and abuse signals. Before any content check: is this account rate-limited, flagged, newly created in a burst of similar accounts, or coming from a known abusive network? Cheap lookups that stop much of the automated abuse.
- Input classification. A fast classifier scores the prompt against policy categories (violence, self-harm, sexual content involving minors, weapons, harassment and others). Options include small fine-tuned transformer classifiers, the free OpenAI moderation endpoint for teams building on its API, or open models such as Meta's Llama Guard ("Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations", Inan et al., 2023). A small classifier takes a few milliseconds on a GPU or tens on a CPU.
- Model-level behaviour. The model's own training and system prompt make it decline or redirect many borderline requests gracefully, which is usually a better experience than a hard block.
- Output classification while streaming. The answer is scored as it is generated, in windows (for example every 50 to 100 tokens, over the text so far). If a window crosses a threshold, the run is stopped, the stream sends a
blockedevent, and the client replaces the partial text with a notice. - Asynchronous review. Flagged conversations, user reports and sampled traffic go to slower, more accurate checks and to human reviewers under strict privacy rules, feeding improvements to classifiers and policies.
The latency trade-off. Running the input check before queueing adds its latency to TTFT for everyone. Running it in parallel with queueing and prefill hides the latency: if the verdict is "block" before the first token is released, cancel the run and show the refusal; the small cost is wasted prefill on blocked prompts (a tiny fraction of traffic). We choose parallel, holding back the first streamed token until the verdict arrives, which in practice it almost always does before prefill finishes.
Streaming output is hard to moderate. A sentence can look harmless for 40 tokens and turn harmful at token 41. Options:
- Hold back a small window. The gateway delays release of the last k tokens (say 20 to 30, a fraction of a second at 50 tokens per second) until the output classifier has seen them. Users barely notice a small fixed delay. Larger windows catch more but make the stream feel laggy.
- Release immediately and retract. Stream as produced and, if a later window is flagged, stop and tell the client to replace the text. Faster, but the user may have seen a few problematic words.
- Tiered by risk. Most traffic gets immediate release; conversations already flagged as risky, or surfaces used by minors, get the hold-back window.
Precision and recall, and who pays for errors. A classifier with too low a threshold blocks legitimate medical, legal, security or historical questions (false positives, which frustrate users and cost trust); too high a threshold lets harmful content through (false negatives, which cost safety and reputation). Thresholds are set per category: near-zero tolerance for child sexual abuse material and similar categories, more permissive for everyday topics with context. Measure both error rates continuously on labelled samples and when a new model ships.
Prompt injection and jailbreaks. Users try to talk the model out of its rules ("ignore previous instructions", role-play framings, encoded text). Defences: model training on adversarial examples, classifiers tuned for jailbreak patterns, monitoring for repeated attempts per account, and (for products where the model uses tools or reads untrusted documents) treating any text that came from outside the user's own message as data, not instructions. AI Agents, Tool Use and Advanced RAG covers injection defences for tool-using systems.
Privacy in the safety path. Moderation sees user content, so it is subject to the same retention, access-control and deletion rules as the conversation store. Human review uses minimal excerpts, audited access and strict retention; enterprise customers often contractually exclude their data from review and training.
9. Cost control: model routing, output caps and utilisation#
The capacity estimate put the flagship fleet at hundreds of millions of dollars a year. Every percentage point of efficiency is worth millions, so cost control is designed in from the start.
Measure cost per request. Each run records input tokens, cached tokens, output tokens, model, replica type and GPU-seconds. Joined with GPU-hour prices, this gives cost per request, per user, per feature and per tier. Without this, "which feature is expensive" is guesswork. The usage events flow through Kafka into the warehouse with the other run outcomes (Observability: Logs, Metrics and Traces).
Lever 1: route to the cheapest model that is good enough. Many prompts ("translate this sentence", "fix the grammar", "hi") do not need the flagship model. A router (a small classifier, or rules on prompt length and features) sends easy prompts to a small model costing a tenth as much per token or less, and hard ones (multi-step reasoning, code, long documents) to the flagship. Getting this wrong is visible: a weak answer to a hard question costs more in user trust than the GPU time saved. Routers are therefore evaluated like models, on labelled prompts, comparing answer quality from both paths. Users can usually override (pick the flagship explicitly) within their tier's limits. If 40% of traffic can go to a model costing a tenth as much, total cost drops by about 36%.
Lever 2: bound the output. Decode dominates the fleet. A per-tier maximum output length (max_tokens) caps runaway answers; the system prompt can ask for concise answers by default; reasoning models get a bounded "thinking" budget. Output caps are a direct, predictable cost control: halving the average answer from 600 to 300 tokens halves the decode fleet.
Lever 3: keep GPUs full. Utilisation is the hidden multiplier. A replica at 30% of its achievable throughput costs three times more per token than one at 90%. Continuous batching, good placement, chunked prefill, filling night troughs with batch work, and routing overflow across regions all serve this. But running too close to 100% blows up queueing delay (queueing theory: wait time grows as 1 ÷ (1 − utilisation) for simple queues), so interactive pools target perhaps 70 to 85% at peak, with batch work soaking up the rest.
Lever 4: cheaper tokens through serving optimisations. Quantisation, speculative decoding and attention optimisations (Deep Dive 10) reduce cost per token, often by large factors, without changing the product.
Lever 5: caching. Prefix caching (Deep Dive 5), reusing the system prompt everywhere, and caching titles and summaries rather than regenerating them.
Lever 6: price the work. The batch tier (slower, cheaper) and the free tier's limits are price signals that shape demand into the shape the fleet can serve. A cost-aware product does not offer unlimited free use of the most expensive model.
Worked example: cost per answer. Take an 8×H100 node at about $2.50 per GPU-hour, so $20 per node-hour. At 8,000 output tokens per second, a node produces 28.8 million output tokens per hour, so decode costs about $0.70 per million output tokens at full utilisation; at a realistic 60% average utilisation, about $1.15. A 300-token answer then costs about $0.00035 in decode. Prefill of 600 uncached tokens adds perhaps a third of that. So one average answer costs on the order of $0.0005, and a billion answers a day about $500,000 per day, the same order of magnitude as the capacity estimate. A user who pastes 50,000-token documents into every message costs a hundred times more than average, which is why token-based limits exist.
10. Inside the replica: inference optimisations that change the numbers#
An interviewer at a company that runs models will push into the replica. These are the techniques that move cost per token and latency by large factors, and the trade-off each makes.
Why decode is memory-bound, in one calculation. One decode step for a batch of B sequences reads all weights once (70 GB in FP8 for the reference model) and does about 2 × 70 × 10⁹ × B operations. An H100 reads about 3.35 TB/s and computes about 1,000 teraflops in BF16, a ratio of roughly 300 operations per byte. With weights read once per step, the arithmetic intensity is about 2B operations per byte (in FP8, 1 byte per parameter), so the GPU is bandwidth-bound until B reaches roughly 150 to 300. At batch 1 the GPU's arithmetic units are more than 99% idle. Batching is free throughput until the batch is large enough to become compute-bound, which is why serving engines push batch sizes up until memory (the KV cache) or latency targets stop them.
Quantisation. Store weights (and possibly activations and KV cache) in fewer bits: FP16 → FP8 or INT8 halves memory and bandwidth per step; 4-bit weights quarter it. Methods include "LLM.int8()" (Dettmers et al., 2022), "GPTQ" (Frantar et al., 2022, published at ICLR 2023) and "AWQ: Activation-aware Weight Quantization" (Lin et al., 2023, MLSys 2024). FP8 on H100-class hardware is now common for serving with small quality loss when calibrated well; 4-bit weights work well for many models but need careful evaluation, especially for maths and code. Quantising the KV cache to FP8 doubles the number of sequences that fit, directly raising batch size for long conversations. Trade-off: quality risk, which must be measured with evaluations (Deep Dive 12), never assumed.
Attention architecture and kernels. Multi-query attention ("Fast Transformer Decoding: One Write-Head is All You Need", Shazeer, 2019) and grouped-query attention ("GQA", Ainslie et al., 2023) share key and value heads across query heads, shrinking the KV cache by 4 to 8 times or more; this is why the reference model's cache is 320 KB per token rather than 2.5 MB. FlashAttention ("FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness", Dao et al., 2022, and later versions) computes attention in tiles that stay in fast on-chip memory, cutting memory traffic and making long contexts practical. These are model and engine choices, but they set the system's capacity.
Speculative decoding. A small draft model proposes the next k tokens quickly; the big model checks all k in one forward pass (like a short prefill) and accepts the longest prefix that matches what it would have produced, with a rejection-sampling rule that keeps the output distribution exactly the same as the big model's ("Fast Inference from Transformers via Speculative Decoding", Leviathan, Kalman and Matias, ICML 2023; and "Accelerating Large Language Model Decoding with Speculative Sampling", Chen et al., 2023). When the draft agrees often (simple, predictable text), each big-model step yields several tokens: speedups of 2 to 3 times in token latency are commonly reported. Variants avoid a separate draft model by adding extra prediction heads (Medusa, Cai et al., 2024) or by drafting from the model's own features (EAGLE, Li et al., 2024). Trade-off: extra compute per step; gains shrink at large batch sizes, where the GPU is already compute-bound, so it helps latency-sensitive, lightly loaded paths most.
Parallelism across GPUs. A 70B model in FP8 fits on one 80 GB GPU only barely, with little room for KV cache; larger models cannot fit at all. Engines split models across GPUs:
- Tensor parallelism splits each layer's matrices across GPUs in a node (usually 2, 4 or 8), exchanging partial results every layer over NVLink. It cuts per-token latency, but communication overhead grows with the number of GPUs, so it stays within a node.
- Pipeline parallelism puts different layers on different GPUs or nodes. It adds latency per token (the token passes through each stage) but scales to models larger than a node.
- Expert parallelism for mixture-of-experts models places different experts on different GPUs, routing each token to the GPUs holding its chosen experts. It makes huge models affordable per token, but introduces all-to-all communication and load imbalance between experts.
- Data parallelism is simply more replicas, which is what the scheduler balances across.
The replica shape (how many GPUs, which parallelism) is a capacity-planning decision: smaller replicas mean more independent units to schedule and less blast radius per failure; larger ones mean lower latency and room for bigger batches.
Putting it together. For the reference model, moving from FP16 weights with static batching to FP8 weights, FP8 KV cache, continuous batching, paged attention and prefix caching can plausibly improve throughput per GPU by an order of magnitude at the same latency. That factor is larger than almost anything the rest of the architecture can achieve, which is why serious LLM services have a dedicated inference-engine team. Designing LLM and AI-Powered Systems explains each technique from first principles.
11. Multi-region capacity, failures and overload#
Where things live. The stateless tier, stream gateways and conversation store run in every serving region near users. GPU capacity, constrained by what can be bought and powered, sits in fewer, larger regions. So the request path often crosses regions: a user in Europe connects to a European API region, whose inference gateway may send the run to a GPU region in America when Europe's GPUs are full. The extra 80 to 150 ms of round-trip time once per request is small compared to generation time, and the token stream crosses back over a single long-lived connection.
Global scheduling. Each region's inference gateway knows its own queues; a global capacity service, updated every few seconds, knows the free capacity of every region per model. When a region's queue wait exceeds a threshold, new runs (not running ones) spill to the region with the most headroom, respecting data-residency rules (some enterprise traffic must stay in its region). This is how diurnal peaks in one continent use idle GPUs in another.
Failure modes and responses.
- A GPU or node fails. Routine at this scale: with 10,000 GPUs, hardware faults happen daily. The scheduler detects it within seconds, marks the replica dead, and recovers its runs by continuing from partial output on another replica (Deep Dive 2). The node is drained and repaired automatically; health checks run GPU diagnostics before returning it to service.
- A model version is bad (quality regression, crashes on certain inputs). Rollouts are gradual (Deep Dive 12) so a bad version reaches a few percent of traffic before automated metrics catch it; rollback means routing traffic back to replicas running the old version, which must be kept warm during rollout.
- A poison request (an input that crashes the engine every time) would bounce from replica to replica, taking each one down. Limit retries per run to one or two, then fail the run and quarantine its input for investigation, the same idea as a dead-letter queue in Asynchronous Processing and Message Queues.
- Redis shard holding token buffers fails. Replicas promote; runs on that shard lose at most the chunks since the last replication, and clients may see a short gap. Because the final message and periodic checkpoints go to the database, nothing complete is lost. A run whose buffer is gone can re-seed it from its latest checkpoint and continue.
- Conversation store degradation. The chat path can keep working briefly with cached context and buffered writes, but must not acknowledge completion of a message it has not stored. Better to show "saving..." than to lose a reply the user saw as done.
- Demand spike (a launch, a viral moment). The degradation ladder from Deep Dive 4 applies: pause background work, slow free traffic, route free users to the small model, then reject free requests with a retry time. Paid traffic and enterprise reservations are protected. A visible "we're at capacity" page for free users is a legitimate, honest outcome; an unstable system for everyone is not.
- Control-plane failures. Large outages are often caused not by GPUs but by the platform underneath: OpenAI's December 2024 incident report, for example, described a new telemetry service that overloaded Kubernetes control planes and broke internal DNS-based service discovery across clusters. The lessons are standard but important: stage rollouts of infrastructure changes, keep data-plane traffic working when the control plane is down, and have break-glass access to fix it. Incident Management and Postmortems covers the practice.
Availability arithmetic. The chat path depends in series on the edge, API, quota service, moderation, inference gateway, GPUs, token buffer and conversation store. Eight components at 99.95% each compose to about 99.6%, below a 99.9% target. Raising availability means making some of them non-blocking: quota checks fail open for paid users with short local caches if Redis is down (accepting slight over-use), moderation failing open for low-risk classes or closed for high-risk ones (a policy decision), the conversation store write retried asynchronously with the message held in the buffer. Designing for High Availability works through these composition rules.
12. Observability, evaluation and safe model rollouts#
An LLM service fails in two ways: like any service (errors, latency, outages) and in a way only it can (answers get worse while every dashboard stays green). It needs both kinds of instruments.
Serving metrics.
- TTFT (p50, p95, p99) per model, region, tier and prompt-size bucket. Breaking it down into queue wait, prefill time and network time tells you which part to fix.
- TPOT / inter-token latency and stall rate (gaps over, say, 500 ms within a stream), which users feel as freezing.
- Goodput: requests per second completed within their latency targets, rather than raw throughput. A fleet that serves 10% more tokens while missing TTFT targets for 20% of users has not improved. DistServe framed its optimisation target in these terms.
- GPU-level: batch size, KV-cache utilisation, prefix-cache hit rate, preemptions per minute, tokens per second per GPU, model FLOPs utilisation.
- Queue and admission: queue wait by class, rejection rate (429s and "busy") by reason, spillover to other regions.
- Streaming: reconnects per stream, resumptions served from the buffer, runs finished with no attached viewer.
- Cost: cost per request and per thousand tokens by model and feature, updated daily.
Traces through the whole path (edge, API, gateway, scheduler, replica, buffer, stream gateway) with one run id make slow requests explainable. See Observability: Logs, Metrics and Traces.
Quality evaluation. Before a new model, prompt, quantisation scheme or router ships, it is evaluated:
- Offline benchmark suites for capabilities (reasoning, coding, maths, multilingual), safety (refusal of harmful requests and, equally, not refusing harmless ones) and product-specific tasks drawn from anonymised, consented traffic patterns.
- LLM-as-judge. A strong model grades answers against a rubric, or compares two answers side by side, which scales far beyond human grading. "Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena" (Zheng et al., NeurIPS 2023) found strong judges agree with human preferences at rates similar to human-human agreement, and also documented biases: preferring the first-shown answer (position bias), longer answers (verbosity bias) and their own style (self-enhancement). Mitigations: swap answer order and average, control for length, calibrate against a human-labelled set, and never use the model being evaluated as its own judge.
- Human evaluation for high-stakes changes and to keep the judge honest.
- Pairwise preference data from users (thumbs up or down, choosing between two answers) is noisy but huge, and catches regressions that benchmarks miss. Public leaderboards such as Chatbot Arena ("Chatbot Arena: An Open Platform for Evaluating LLMs by Human Preference", Chiang et al., 2024) use the same pairwise idea at internet scale.
LLM Fine-Tuning and Evaluation covers evaluation design in depth.
Safe rollout. Model changes roll out like risky code changes, with extra steps:
- Shadow traffic: the new model answers a copy of real requests whose outputs are not shown; compare latency, refusal rates, output lengths and judge scores.
- Canary: 1% of real traffic, with automatic rollback on serving or quality regressions (error rate, TTFT, thumbs-down rate, moderation flags, average output length).
- Progressive ramp to 5%, 25%, 100%, region by region, keeping old-version replicas warm until the new one is proven.
- A/B experiments for product decisions (router thresholds, context budgets, summarisation): measure user satisfaction and retention against cost.
Capacity is part of every rollout. A new model version needs its own replicas, warm caches and weight downloads; running both versions doubles capacity needs for that model during the ramp. Ramps are therefore scheduled into off-peak windows and planned with the capacity team. The general practice is in DevOps, SRE and Platform Engineering and CI/CD and Deployment Strategies.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| GPU demand exceeds supply at peak | Queue waits grow, TTFT targets missed for everyone | Admission control with deadlines, weighted priority classes, degrade free traffic to the small model, spill to other regions, then reject with Retry-After |
| Long prompts stall other users' streams | Visible freezes during big prefills on the same replica | Chunked prefill with a per-step token budget; disaggregated prefill pool for very long prompts |
| KV cache memory exhausted by long conversations | Smaller batches, preemptions, lower throughput | Paged KV cache, FP8 KV, context budgets and summarisation, CPU and SSD KV tiers, preempt lowest class first |
| Prefix cache misses after routing to a cold replica | Full prefill of long histories, higher cost and TTFT | Prefix-affinity routing with bounded load; stable prompt prefixes; second-tier KV cache |
| System prompt or model change invalidates caches fleet-wide | GPU-level stampede: prefill load jumps, TTFT spikes | Gradual rollout by region, pre-warm replicas with the new prefix, keep old version warm |
| Client connection drops mid-answer | Lost answer, user re-asks, GPU work wasted twice | Run decoupled from connection, token buffer with event ids, Last-Event-ID resume, checkpoints to the database |
| Replica crash or GPU fault mid-generation | Stream stops, KV cache lost | Heartbeat detection, continue from partial output on another replica, attempt numbers as fencing tokens, retry limit |
| Poison input crashes engines repeatedly | Cascading replica failures | Retry limit per run, quarantine the input, crash signature alerts |
| Abusive users or scripts | Capacity stolen from real users, cost spike | Token-based limits with reservation, per-user fair queueing, concurrency caps, abuse signals across accounts, devices and payment |
| Proxy buffering or idle timeouts | Streams arrive in one blob or are cut at 60 seconds | Disable buffering on stream routes, SSE keep-alive comments every 15 seconds, HTTP/2 |
| Cache or connection-pool bug mixes users' data | Privacy incident | User-scoped cache keys, ownership checks on every read, no shared state across cancelled requests, fault-injection tests around cancellation |
| Conversation store slow or partitioned | Messages fail to save, history missing | Keep text in buffer until stored, retry asynchronously, never mark complete before durable, cached context for reads |
What Interviewers Expect#
Mid-level. Get the core flow right: a stateless API, conversations and messages stored by user and conversation, an inference service on GPUs, and streaming the answer over SSE with a clear reason for choosing SSE over WebSockets. Explain that the model is stateless, so every turn resends history, and that this costs more as conversations grow. Know that GPU capacity is limited and that requests need rate limits and a queue, with a 429 when a user is over their limit. Produce reasonable estimates: prompts per second, concurrent streams via Little's law, storage per day.
Senior. Separate the run from the connection: a token buffer with event ids, resumable streams with Last-Event-ID, and what happens on deploys and replica failures. Explain prefill versus decode, why decode is memory-bound, why batching is the main cost lever, and continuous batching with a paged KV cache. Design the inference gateway: admission with deadlines, priority classes, fair queueing across users, token-based quotas with reservation and settlement, and graceful degradation to a smaller model. Explain prefix caching and why prefix-affinity routing matters, and give concrete context-budget strategies (truncation, summarisation, retrieval). Place moderation in the path without adding latency.
Staff and above. Frame the system around its economics: GPU fleet size from token throughput, cost per answer, and the levers that move it (routing, output caps, quantisation, speculative decoding, utilisation, batch tiers in the troughs). Discuss prefill and decode disaggregation and when it pays, KV-cache transfer costs and tiered KV storage, consistent hashing with bounded loads for cache-aware routing, and the queueing-theory reason interactive pools cannot run at 100%. Treat quality as an operational metric with evaluation pipelines, LLM-as-judge and its biases, shadow and canary rollouts of models, and capacity planning for rollouts. Address multi-region capacity sharing with residency constraints, availability composition across many dependencies, privacy and deletion across every derived store, and the organisational split between product, inference platform and safety teams.
Deep Dive: how real serving stacks compareShow
- vLLM. Open-source engine from UC Berkeley that introduced PagedAttention. Continuous batching, prefix caching, chunked prefill, speculative decoding, quantisation and tensor and pipeline parallelism; an OpenAI-compatible HTTP server. A common default for self-hosting.
- SGLang. Open-source engine and language from the LMSYS group, known for RadixAttention (automatic prefix sharing in a radix tree) and fast structured output. Strong for workloads with heavy prefix reuse, such as chat and agents.
- TensorRT-LLM with Triton Inference Server. NVIDIA's compiled, highly optimised engine and serving layer. Top performance on NVIDIA hardware, at the cost of model compilation steps and less flexibility.
- Hugging Face Text Generation Inference (TGI). Production server used behind Hugging Face's hosted endpoints, with continuous batching and quantisation support.
- Managed APIs (OpenAI, Anthropic, Google, and cloud resellers such as Azure OpenAI and Amazon Bedrock). Somebody else runs the fleet; you design around their rate limits, prompt caching and batch discounts, and add your own fallback across providers.
- Disaggregated designs. DistServe and Splitwise (research), and Mooncake (described by Moonshot AI from its production chat service), separate prefill and decode with a KV-cache transfer layer; NVIDIA's Dynamo framework and other orchestrators also target disaggregated serving with KV-aware routing.
The architecture in this case study sits above any of these: the gateway, scheduler, streaming, storage, quotas and safety are the same whichever engine runs inside the replica.
Deep Dive: what happens during a launch-day spikeShow
A new model launches and traffic triples within an hour. Walking through it shows how the pieces interact.
- Minute 0 to 10. Queue wait rises from 100 ms to 2 seconds for free traffic. Dashboards show KV-cache utilisation at 95% and rising preemptions. The scheduler already favours paid traffic (weighted classes), so paid TTFT stays near 500 ms.
- Minute 10. Background work (titles, summaries, batch API) is paused automatically when queue wait crosses its threshold. That frees perhaps 10% of capacity.
- Minute 15. Spillover starts sending new runs to regions in their night trough. TTFT rises by about 100 ms for spilled requests, which is acceptable.
- Minute 20. Still over capacity. The degradation policy moves free users to the small model with a banner. The flagship fleet now serves only paid traffic and free users who have not used their quota; load on it drops by half.
- Minute 30. Operators move replicas from less-used models to the new one (minutes per replica, because of weight loading), and lower output caps for free traffic.
- Hours later. Additional capacity reserved for the launch comes online. Limits are restored gradually, watching TTFT and preemption metrics, to avoid an oscillation where everything is restored at once and the queue explodes again.
What should never happen: retry storms (clients honour Retry-After with jitter), a queue that grows without deadlines, or the stateless tier falling over because of 120,000 extra waiting connections (streams wait in the gateway, which is sized for it). The postmortem asks whether the forecast and the degradation thresholds were right.
Deep Dive: adding tools, browsing and agents laterShow
Out of scope here, but the design should not block them. A tool call turns one run into a loop: the model emits a structured "call this tool" output, the system executes the tool (search, code execution, an API), appends the result to the context and continues decoding. Consequences for the architecture:
- Runs get long and bursty. A run may pause for seconds while a tool executes. The replica should release the sequence's slot (keeping or offloading its KV cache) during the pause, rather than holding GPU memory idle. This makes the run state machine gain a
WaitingForToolstate. - The stream carries more event types: tool call started, tool result, and so on, all with event ids so resumption still works.
- Durability matters more. Agentic runs that take minutes look like workflows: persist each step so a failure resumes from the last completed step, the problem Temporal and Workflow Engines and Pattern: Managing Long-Running Tasks address.
- Security changes. Tool outputs are untrusted input; prompt injection through retrieved web pages or documents is the main new risk. Tools must run sandboxed, with the user's permissions and nothing more.
Deep Dive: a 45-minute interview planShow
| Minutes | What to cover |
|---|---|
| 0 to 5 | Clarify scope: streamed answers and resumable history in scope; branching, multimodal, tools out. Confirm scale: 200M daily users, about 20,000 prompts per second at peak |
| 5 to 10 | Non-functional priorities: TTFT over total time, GPUs scarce so allocation is deliberate, conversations durable, privacy hard. Quick estimates: tokens per second, concurrent streams by Little's law, GPU fleet order of magnitude |
| 10 to 15 | API: send prompt returns a run id; SSE stream with event ids; cancel; 429 with rate-limit headers |
| 15 to 25 | High-level design built step by step: streaming, inference gateway with queues and scheduler, token buffer and stream gateways, conversation store, context builder |
| 25 to 40 | Deep dives the interviewer picks, usually two or three of: resumable streams, GPU scheduling and continuous batching with prefix affinity, fairness and quotas, cost of growing conversations, moderation |
| 40 to 45 | Failures and overload: replica loss, demand spike and degradation ladder, cache stampede on prompt changes; wrap up with the cost picture |
If time is short, protect the three ideas that distinguish a strong answer: the run decoupled from the connection, the gateway that decides who gets GPUs, and prefix caching as the main cost lever for conversations.
Deep Dive: follow-up questions and short answersShow
- Why not WebSockets? Output is one-way; SSE is plain HTTP with built-in resume ids. WebSockets fit truly two-way sessions such as real-time voice.
- How do you resume a stream on another server? State lives in a per-run token buffer, not the connection. Any gateway replays from
Last-Event-IDand tails live chunks. - What if the GPU dies mid-answer? Re-prefill the prompt plus the partial output on another replica and keep decoding; the user sees a short pause. Fence the old attempt.
- Why is the KV cache the bottleneck? It grows with every token of every active sequence, lives in GPU memory, and limits batch size; batch size sets cost per token.
- How do you stop one user starving others? Token-based quotas with reservation, concurrency caps, fair queueing across users within each priority class.
- Why charge or limit by tokens? Cost is proportional to tokens processed, not to requests.
- How do you make long conversations cheaper? Prefix caching with affinity routing; context budgets with truncation in large steps, summaries and retrieval.
- Can you cache answers? Rarely for chat: personalised, sampled, fresh. Cache computation (KV prefixes), conversation context and static assets instead.
- How do you roll out a new model safely? Offline evaluations, LLM-as-judge calibrated against humans, shadow traffic, canary with automatic rollback, progressive ramp with old replicas warm.
- What is the single biggest cost lever? Batching and utilisation inside replicas, then routing easy prompts to a smaller model.
Key Takeaways#
- An LLM chat service is a GPU scheduling system with a chat app on top. The GPU fleet dominates cost by orders of magnitude, so who gets compute, and how efficiently it is used, is the central design question.
- Stream with SSE: time to first token is what users feel. Coalesce tokens into events, disable proxy buffering, send keep-alives, and serve streams over HTTP/2.
- Decouple the run from the connection. A run is a server-side object that writes to a per-run token buffer with event ids; any gateway can resume a viewer from
Last-Event-ID. Deploys, reloads and network switches then cost a pause, not an answer. - Prefill is compute-bound, decode is memory-bound. Continuous batching and a paged KV cache keep GPUs full; chunked prefill keeps streams smooth; disaggregating prefill and decode lets each be sized for its phase.
- Route with prefix affinity and bounded load so each conversation's earlier turns are reused from the KV cache, and keep prompt prefixes byte-stable.
- Allocate compute deliberately: admission control with deadlines, token-based quotas with reservation, weighted priority classes, fair queueing within a class, and a degradation ladder (smaller model before refusal). Reject fast with 429 and clear rate-limit headers.
- Conversations cost quadratically unless you cache prefixes and budget context with truncation, summaries and retrieval.
- Conversation storage is a well-understood, sharded key-value problem: partition messages by conversation, lists by user, compact and archive cold data, and make deletion reach every derived copy. Isolation bugs are privacy incidents.
- Moderate in layers, in parallel with generation where possible, with a small hold-back window for risky output, and measure false positives as seriously as false negatives.
- Measure cost per request and quality per release. Model routing, output caps, quantisation, speculative decoding and filling troughs with batch work are the cost levers; evaluations, LLM-as-judge and canaries are the quality guardrails.