Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
LLM servingServing an LLM fast, and cheap.
After this you can
- Explain why serving is a memory problem, and prefill vs decode
- Do the KV-cache arithmetic for real models
- Say what continuous batching, PagedAttention, quantization and speculative decoding each buy
About this handbook
Training an LLM makes headlines; serving it pays the bills. Once a model is deployed to real users, a handful of systems tricks — the KV cache, continuous batching, quantization, speculative decoding — decide whether it feels instant or sluggish, and whether it costs a fortune or a rounding error. This is how they work.
Why serving is a memory problem
An LLM writes one token at a time, and to produce each token it must read every one of its billions of weights out of GPU memory. The arithmetic per token is trivial next to that data movement — so generation is memory-bandwidth-bound, not compute-bound. The GPU's math units sit mostly idle, waiting on memory.
This one fact explains almost every serving optimization. If the bottleneck is moving data, then the wins come from moving less of it (quantization), reusing what you've moved (the KV cache), and amortizing the move across many requests (batching). Keep "it's memory, not math" in mind and the whole field makes sense.
Reading the weights for one token is like driving to the warehouse to pick up a single item. The drive dominates — so you batch many orders into one trip, carry lighter boxes, and never re-fetch what's already in the truck.
Prefill vs decode — two very different phases
Every request has two phases with opposite characteristics, and serving systems treat them differently.
Prefill — read the prompt
Process the entire input prompt at once, in parallel. Compute-heavy, fast per token, done once. Produces the first token and fills the KV cache.
Decode — write the answer
Generate output tokens one at a time, each depending on the last. Memory-bound, slow, repeated once per output token. This is where most of the time goes.
The split matters for two metrics you'll live by: time to first token (TTFT) is dominated by prefill, while tokens per second after that is a decode property. A long prompt slows your first token; a long answer slows everything after it.
The KV cache — the thing that eats your memory
Attention lets each new token look back at every previous token — specifically at their Key and Value vectors. Recomputing those for the whole history at every step would be madness, so they're computed once and kept around: the KV cache. It's what makes decode fast.
The catch is size. The cache grows with every token, every layer, and every request in the batch — and it lives in the same precious GPU memory as the model weights. On long contexts and big batches, the KV cache, not the model, becomes the thing that runs you out of memory. Managing it well is the central problem of modern LLM serving.
The KV cache is why context length is expensive to serve, not just to train: double the context and you roughly double the cache each request holds. It's also why FlashAttention's memory savings matter so much — see the FlashAttention breakdown.
The arithmetic, worked with real models
Everything above becomes concrete with one formula. The KV cache stores a key and a value vector per token, per layer, per KV head:
Run it on real models at fp16 (2 bytes):
| Model | Shape | KV per token | One 4K-token sequence |
|---|---|---|---|
| Llama-2-7B (no GQA) | 32L × 32 KV heads × 128 | 2·32·32·128·2 = 512 KB | 2.0 GB |
| Llama-3-8B (GQA, 8 KV heads) | 32L × 8 KV heads × 128 | 2·32·8·128·2 = 128 KB | 0.5 GB — 4× less |
| 70B-class (GQA, 8 KV heads) | 80L × 8 KV heads × 128 | 2·80·8·128·2 = 320 KB | 1.25 GB |
Now the punchline that explains half of modern serving. Take an A100-40GB running Llama-2-7B: weights eat 14 GB, leaving ~26 GB. At 512 KB/token, a batch of 16 sequences at 4K context wants 32 GB of KV cache — more than the GPU has left. That is why grouped-query attention exists (4× fewer KV heads = 4× more batch), why PagedAttention stopped wasting reserved-but-unused KV space, and why long context is priced the way it is.
Decode speed is the same kind of one-liner. Generating one token requires reading essentially all the weights once, and decode is memory-bandwidth-bound. Take a round 2 TB/s (the 80 GB A100's figure; the 40 GB card above is closer to 1.6 TB/s, which gives ~114):
No kernel wizardry beats that ceiling for one stream — but the same weight read can serve a whole batch. At batch 32, those identical reads produce 32 tokens instead of 1, lifting the weight-read ceiling to ~4,500 tok/s aggregate — but only if 32 sequences' KV caches fit. At 4K context that is 64 GB, more than the whole 40 GB card, so that figure needs short contexts, and every sequence's own KV read still slows each step. Batching is free throughput until you run out of KV memory — which the table above just showed you is the real constraint. The whole modern serving stack is these two formulas fighting each other. Want to run the numbers on your own model and GPU? The interactive KV-cache calculator does exactly this arithmetic.
Continuous batching — keep the GPU full
Because moving the weights is the cost, you want as many requests as possible sharing each trip — that's batching. But naive static batching waits for the whole batch to finish before starting the next, so one long request holds up a dozen short ones and the GPU idles.
Continuous batching (popularized by vLLM) fixes this: it adds and removes requests from the running batch at every token step. The instant one request finishes, a waiting one takes its slot — the GPU never stalls.
This is the single biggest throughput win in modern serving, and it's why open-source servers like vLLM became the default. It costs nothing in quality — the outputs are identical; you're just scheduling the GPU better.
PagedAttention — no wasted memory
Continuous batching creates a new problem: requests come and go, each with a KV cache that grows unpredictably. Allocating one big contiguous block per request wastes huge amounts of memory to fragmentation and over-provisioning.
PagedAttention borrows the operating-system idea of virtual memory. It chops the KV cache into small fixed-size blocks (pages) that don't have to be contiguous, and keeps a lookup table mapping each request's logical sequence to its scattered physical blocks. Memory is handed out a page at a time, exactly as needed — so almost none is wasted, and you can fit far more concurrent requests on the same GPU.
PagedAttention is the trick that makes continuous batching practical at scale. Together they're why one GPU can serve many more simultaneous users than a naive implementation — the difference between renting one GPU and ten.
Quantization — carry lighter weights
Since serving is memory-bound, storing the model in lower precision is a direct speedup: smaller weights mean less data to move per token, plus more room for the KV cache. Quantization converts 16-bit float weights down to 8-bit or even 4-bit integers.
| Precision | Relative memory | Speed | Quality |
|---|---|---|---|
| FP16 / BF16 | 100% | baseline | full |
| INT8 | ~50% | faster | near-full |
| INT4 | ~25% | fastest | small, usually acceptable loss |
Going to 4-bit can shrink a model to a quarter of its size, often letting it run on a single consumer GPU with only a modest quality dip. The art is choosing what to quantize and how — weights are easy, activations are trickier — to keep the loss below what your product can notice.
Speculative decoding — guess ahead, verify in parallel
Decode is slow because it's sequential — one token, then the next. Speculative decoding breaks the sequence with a bet. A small, fast draft model guesses several tokens ahead; then the big model checks all of them in a single forward pass. Verifying in parallel is cheap, so:
Draft model guesses
- Small & fast, proposes 4–5 tokens
- Cheap to run
- Often right on easy tokens ("the", "of")
Big model verifies
- Checks all guesses in one pass
- Accepts the correct prefix for free
- Rejects the rest, continues normally
The crucial property: the output is exactly what the big model would have produced alone — verification guarantees it. You get lower latency with zero quality change, as long as the draft model is right often enough to pay for itself.
Latency vs throughput — the knob you're really turning
Every serving decision trades one against the other. Knowing which you're optimizing is half the job.
| You want… | Turn this up | Cost |
|---|---|---|
| Higher throughput (cheaper per token) | Bigger batches | Higher latency per request |
| Lower latency (snappier) | Smaller batches, speculative decoding | Lower GPU utilization / higher cost |
| Bigger model on the GPU | Quantization | Small quality loss |
| More concurrent users | PagedAttention + continuous batching | Engineering complexity |
A chat UI optimizes for TTFT and streams tokens so the wait feels short; a bulk document-processing job optimizes for raw throughput and happily runs huge batches. The last lever is routing: send easy requests to a small cheap model and only escalate hard ones to the big model — the job of an LLM gateway.
When asked to "make the LLM faster," don't jump to a trick. First ask: is this latency-sensitive or throughput-sensitive? TTFT or tokens/sec? Prefill-bound or decode-bound? The right optimization falls out of the answer.
Worked example: batch LLM requests on one GPU
An interview prompt that tests every section above at once, answered with one real model, one real GPU and arithmetic you can redo on a whiteboard.
The prompt, as prep sites report it. Exponent's question bank lists "Design an inference batching system": one GPU that can process up to 100 inputs per batch, with users who submit requests synchronously and wait for the result. Exponent says it is the most commonly reported Anthropic system-design prompt. That attribution comes from a prep site collecting candidate reports, not from Anthropic, so treat the wording as unverified. A strong answer usually starts with the model as a black box (queue, batcher, worker, response path), then the interviewer pushes on the LLM-specific part. That is the part this section works through.
Step 1: three ways to form a batch
Why the first answer needs a follow-up: in one batch, one request may generate 10 tokens and another 2,000. How you form the batch decides whether the short one waits for the long one.
| Policy | When a batch starts | When a slot frees | Where it breaks |
|---|---|---|---|
| Static | When N requests have arrived | Only when the whole batch finishes | At low traffic the first request waits for N to arrive. Every request also waits for the longest one in its batch. |
| Dynamic (request-level) | At N requests or after a maximum wait, whichever comes first (NVIDIA Triton's dynamic batcher has a queue-delay setting for this) | Still only when the whole batch finishes | The arrival wait is bounded, but the batch still runs as long as its longest member. It is ideal for embeddings or classifiers, where every item costs about the same. |
| Continuous (in-flight, iteration-level) | Never "starts": the scheduler re-forms the batch at every decode step | The step after a sequence emits its stop token | It needs KV memory that can be handed out and reclaimed per sequence (PagedAttention), plus a scheduler that admits, preempts and evicts. |
The Orca paper (Yu et al., OSDI 2022) named the idea iteration-level scheduling. TensorRT-LLM calls it in-flight batching, and vLLM calls it continuous batching. With it, "up to 100 inputs per batch" stops being a fixed size. It becomes a ceiling, and the real limit is usually KV memory, as step 3 shows.
Step 2: GQA and MQA, the reason kv_heads is in the formula
In the original multi-head attention, every query head has its own key and value head, so the cache stores one K and one V vector per head. Multi-query attention (MQA, Shazeer 2019) keeps all the query heads but shares a single K/V head between them. Grouped-query attention (GQA, Ainslie et al. 2023) sits between the two: query heads are split into groups, and each group shares one K/V head. The GQA paper reports quality close to multi-head attention at a speed comparable to MQA. That is why most current open models ship with it.
For the cache, only num_key_value_heads matters, not the number of query heads. The model used below has 28 query heads sharing 4 KV heads, so 7 query heads read each K/V pair. Its cache is 7× smaller than the same model with full multi-head attention. MQA would cut it by another 4×, at some cost in quality. When you read a model card, look for the KV-head count first.
Step 3: the numbers, Qwen2.5-7B-Instruct on one H100 SXM
The inputs come from primary sources. From the model's official config.json on Hugging Face: num_hidden_layers: 28, num_attention_heads: 28, num_key_value_heads: 4, hidden_size: 3584 (so dhead = 3584 ÷ 28 = 128), torch_dtype: bfloat16 (2 bytes), max_position_embeddings: 32768. From its model.safetensors.index.json, the weights total 15,231,233,024 bytes (15.23 GB, about 7.62B parameters). From NVIDIA's H100 spec sheet, the H100 SXM has 80 GB of memory at 3.35 TB/s. Its BF16 figure of 1,979 TFLOPS is quoted with sparsity, so the dense peak is half that, about 989 TFLOPS.
- KV per token. 2 × 28 layers × 4 KV heads × 128 × 2 bytes = 57,344 bytes (56 KiB). With 28 KV heads instead of 4, it would be 401,408 bytes.
- Memory left for the cache. 80 GB − 15.23 GB of weights − 8 GB reserved for activations, CUDA graphs and the framework = 56.77 GB. The 8 GB is an assumption for this exercise. vLLM measures the real figure with a profiling run at startup.
- Tokens that fit. 56.77 GB ÷ 57,344 bytes ≈ 989,968 tokens of KV cache, shared by every request on the GPU.
- Pages. The PagedAttention paper sets vLLM's default block at 16 tokens (§7.2), so one block is 16 × 57,344 = 917,504 bytes, and the pool is 61,873 blocks.
- One request. Take a 2,000-token prompt and a 500-token answer, 2,500 tokens in all. That needs ⌈2,500 ÷ 16⌉ = 157 blocks, 143 MB. The last block is 12 tokens short of full, so only 0.5% is wasted.
- Maximum concurrent sequences. 61,873 ÷ 157 = 394. The prompt's "up to 100 per batch" uses 14.3 GB of KV at this shape, so it fits with room to spare.
Now compare the naive allocator, which reserves the model's full 32,768-token context for every request up front. That is 32,768 × 57,344 = 1.88 GB each, so only 30 sequences fit, 13× fewer than 394. A hundred of them would need 188 GB, more than any single GPU has. This is the waste PagedAttention was built to remove: its authors measured that existing systems used only 20.4–38.2% of their KV-cache memory for actual token states. Without GQA (28 KV heads), each 2,500-token request would hold 1.0 GB, and the GPU would top out at 56 sequences even with paging.
Step 4: what each batch size costs each user
Use the page's decode model: each step reads all the weights once, plus every live sequence's KV cache. The table below assumes every sequence is at its full 2,500 tokens, which is the worst case, so treat the figures as ceilings. The last column checks the compute side at about 2 FLOPs per parameter per token, against the 989 TFLOPS dense peak.
| Batch | Bytes read per step | Step time at 3.35 TB/s | Per user | Whole GPU | Compute floor |
|---|---|---|---|---|---|
| 1 | 15.37 GB | 4.59 ms | 218 tok/s | 218 tok/s | 0.02 ms |
| 64 | 24.41 GB | 7.29 ms | 137 tok/s | 8,785 tok/s | 0.99 ms |
| 256 | 51.93 GB | 15.50 ms | 65 tok/s | 16,514 tok/s | 3.94 ms |
| 394 (full) | 71.72 GB | 21.41 ms | 47 tok/s | 18,405 tok/s | 6.06 ms |
Going from batch 1 to 394 multiplies the GPU's output 84×, while each user's stream gets 4.6× slower. Even at full batch, the memory time (21.4 ms) is more than three times the compute time (6.1 ms; attention math is left out), so decode stays memory-bound. That is the page's opening claim, now with a real card behind it. The interview answer is to choose the batch from the latency target. If the product promises at least 60 tokens/s per user, cap concurrency near 256. If it is an overnight batch job, fill all 394 slots.
Step 5: prefill, decode and chunked prefill
Prefill is the opposite case. A 2,000-token prompt costs about 2 × 7.62B × 2,000 = 30.5 TFLOP, which takes at least 30.8 ms even at the dense peak. Real kernels run below peak, so the true time is longer. That step is compute-bound. A 30,000-token prompt costs at least 462 ms. If the scheduler runs it as one step next to 256 decoding streams, all 256 users see a pause of half a second or more between two tokens, when they were getting one every ~15 ms.
Chunked prefill splits a long prompt across several steps, under a per-step token budget (vLLM's max_num_batched_tokens). vLLM's documentation says that in its V1 engine chunked prefill "is enabled by default whenever possible". It also says the scheduler "batches all pending decode requests before scheduling any prefill operations". With a 2,048-token budget, the 30K prompt becomes 15 chunks of about 31 ms of compute each. That is a small bump on every decode step instead of one long stall, and the prompt's own TTFT goes up a little. The docs state the trade directly: smaller budgets (e.g. 2048) give better inter-token latency, larger ones give better TTFT, and for throughput they recommend a budget above 8,192.
Step 6: scheduling and fairness
- Admission. Admit a request only when the free blocks cover its prompt plus some headroom for growth. Otherwise it waits in the queue. Count the queue time in TTFT, because the user does.
- Preemption. If the pool runs out in the middle of generation, a running sequence has to give up its blocks. vLLM's default is to recompute its cache later rather than swap it to CPU memory. Each preemption wastes work, so alert on the preemption rate.
- Order. First-come-first-served is the simple default. vLLM also offers a priority policy, so interactive traffic can go ahead of bulk jobs.
- Fairness between tenants. One customer's batch job can fill all 394 slots. Rate-limit on tokens rather than requests (one request can be 30K tokens), cap each tenant's concurrent sequences, and clamp
max_tokens. - Cancellation. Synchronous clients time out and disconnect. A disconnect must abort the sequence and free its blocks right away. Otherwise abandoned requests keep decoding and filling memory.
- Failure. If the GPU dies, every in-flight request on it is lost. Return a retryable error and let clients retry, which is safe because generation has no side effects. Scaling out means a router in front of several of these servers, sending each request to the replica with the most free KV blocks.
Step 7: what to measure
- TTFT (time to first token): queue wait plus prefill. Long prompts and full queues show up here.
- TPOT (time per output token, the mean gap after the first token) and ITL (each individual gap between tokens). The p99 ITL is what catches prefill stalls.
- Throughput: output tokens per second and requests per second across the whole GPU.
- p50 and p99 of each, not just means. Continuous batching makes the tail depend on who else is on the GPU.
- KV-cache usage, queue depth and preemptions: the signals that you are near the memory ceiling from step 3.
- Goodput: the share of requests that met both the TTFT and the TPOT target. Raw throughput can rise while goodput falls.
vLLM's serving benchmark reports TTFT, TPOT and ITL with their percentiles. Run it with your real distribution of prompt and output lengths, not toy lengths, or step 3's numbers will not match what production sees.
Worked example: design the OpenAI Playground
The full-stack version of the serving question: the GPU work is behind an API, and the design is everything around it.
The prompt, as prep sites report it. Exponent's OpenAI interview guides list "Design the OpenAI Playground", a developer tool for trying prompts, simulating conversations, managing threads and integrating with the API. They list it both as a phone-screen prompt and as a full-stack onsite prompt, where the frontend is expected to get as much care as the backend. That comes from a prep site's candidate reports and is unverified. Where the answer below cites OpenAI's real API behaviour, it links the documentation. Everything else is a design choice you should be ready to defend.
Requirements
- Functional. Write system, user and assistant messages. Pick a model and set its parameters (temperature, max output tokens and so on). Stream the reply as it is generated, with a Stop button. Save a prompt, version it and share it within a project. Define tools and step through tool calls. Show token counts and cost.
- Non-functional. The first token should appear about as fast as the model allows, so the Playground adds no latency of its own. Its behaviour must match the API exactly, because developers copy the settings into code. Tenants must be isolated from each other. Usage and billing must be exact. Prompts are customer data and need privacy controls.
- Out of scope, said out loud. Training, and the inference servers themselves, which are the previous section's problem. Here they are a model API with rate limits.
Architecture
The key decision is that the Playground calls the public API with the user's project credentials, not a private back door. It then gets the same rate limits, billing, moderation and logging as everyone else, and a setting that works in the Playground behaves the same way in code. The cost is that any new Playground feature that touches generation needs API support first. Interviewers like candidates who notice that trade.
The components, one decision each
- Streaming (SSE). OpenAI's API streams with
stream=trueover server-sent events, with events such asresponse.output_text.deltaandresponse.completed(streaming guide). SSE fits because the data flows one way and runs over plain HTTP. The browser'sEventSourceonly sends GET requests with no body, so the UI POSTs withfetchand reads the response body as a stream. Two traps: any proxy that buffers responses breaks streaming, so turn buffering off along the path, and Stop must cancel the generation all the way to the GPU. Otherwise the sequence keeps decoding, holding KV blocks (step 6 above) and billing the user for tokens nobody reads. - Model and parameter selection. The model list comes from a server-side catalog filtered by what this project may use. Parameter ranges are validated per model on the server.
max_tokensis clamped to the context window minus the prompt. The UI can count tokens client-side with the model's tokenizer, but only as an estimate. The authoritative count comes back from the API. - Saved prompts and versions. A preset bundles messages, model, parameters and tool schemas. Each save creates a new immutable version (prompt id plus version number) rather than overwriting, so code can pin a version and a teammate's edit cannot silently change production. Use optimistic concurrency on save, keep unsaved drafts locally, and show a diff between versions.
- Tool-calling UI. The developer writes each function's JSON Schema. When the model returns a tool call with arguments, the UI shows it, and the developer types or mocks the result, which goes back as the tool output. The server never runs developer-defined functions: that would mean running arbitrary code on behalf of any tenant. Validate schemas on both sides, and flag arguments that do not parse rather than hiding them.
- Rate limits and quotas. OpenAI's limits are measured in requests and tokens per minute and per day, apply at the organization and project level, and trip on whichever limit is hit first. The API returns headers such as
x-ratelimit-remaining-tokensandRetry-After(rate-limits guide). A token limit cannot be checked exactly at admission, because output length is unknown. So the gateway reserves prompt tokens plusmax_tokensfrom a token bucket, then refunds the difference when the real usage arrives. Keep monthly spend caps per project as a separate control. - Cost display. Before sending, show an upper bound: input tokens × input price +
max_tokens× output price. After the reply, show the exact figure from the usage numbers in the final stream event. Store prices in a versioned table, because prices change and cached input tokens are priced differently. The browser only displays cost. Billing is computed once, server-side, from the usage meter. - Abuse prevention. Moderate input and output. Rate-limit and step up verification for new or unverified accounts. Watch keys for anomalies, such as a sudden spike from new IP ranges, which is how a leaked key usually shows up. Per-key spend caps limit the damage from a key that does leak.
- Multi-tenant keys. Organizations contain projects, and projects contain keys. Store keys hashed, like passwords. Show a key once at creation, then display only a prefix to identify it. Scope each key to one project and a set of permissions, and make revocation reach the gateway's cache within seconds. The Playground itself uses the logged-in session mapped to a project. It never puts a secret API key in browser JavaScript.
- Logging and privacy. Split metadata (model, token counts, latency, status), which billing and rate limits need, from content (prompts and outputs). Content gets a retention window, tight access control, encryption, and a per-organization option to opt out or keep nothing. Deletion requests must reach every copy. Saved prompts are data the user chose to keep, so they follow different rules from request logs. Never log API keys.
Trade-offs to say out loud
| Choice | Pick | What you give up |
|---|---|---|
| SSE or WebSocket | SSE: one-way, plain HTTP, easy to proxy and retry | No client-to-server channel on the same connection. Stop has to be a separate cancel (closing the stream or a cancel call). |
| Public API or internal shortcut | Public API: same limits, billing and behaviour | Playground-only features wait for API support. |
| Autosave everything or explicit versions | Local drafts + explicit immutable versions | A save step. In return, production code pinned to v7 never changes under it. |
| Token limits checked before or after | Reserve prompt + max_tokens, refund afterwards | A large max_tokens can be refused even when the real reply would have fit. |
| Keep content logs or not | Short retention + opt-out | Less material for abuse investigations and debugging. |
Common mistakes in this interview
- Designing a chat app. The users are developers. Exact parity with the API, visible parameters and reproducible versions matter more than chat polish.
- Putting an API key in the frontend. Anyone can read it from the page. Use session auth mapped to a project.
- Making Stop a UI-only change. Hiding the stream while the GPU keeps generating wastes capacity and bills the user for tokens they never see.
- Rate-limiting by requests only. One 100K-token request can cost as much as a thousand short ones. Limit tokens too.
- Computing billing in the browser, or estimating it from the prompt length, instead of using the usage the API returns.
- Running tool calls on the server. In a playground, the developer supplies the result. Running tenant-defined code is a separate product with its own sandboxing problem.
What an interviewer probes
- "The user clicks Stop halfway through a 4,000-token answer. Trace what happens, all the way to the GPU." (Cancellation, KV blocks freed, partial usage billed.)
- "A teammate edits a saved prompt that production code uses. What breaks?" (Nothing, if versions are immutable and code pins one.)
- "How do you enforce tokens per minute when you don't know the output length?" (Reserve, then refund.)
- "A key leaks on GitHub. How fast do you detect it and contain it?" (Anomaly signals, spend caps, revocation latency at the gateway.)
- "Where does the first token's latency go?" (Gateway and auth, queueing and prefill on the GPU pool, then any proxy buffering. That last part is the previous section's TTFT budget.)
- "What do you log, and who can read it?" (Metadata compared with content, retention, opt-out.)
Cost and trade-offs: batch size against memory, in numbers
The page’s two formulas, run together. A decode step reads every weight once and the whole KV cache of every sequence in the batch. Take the page’s 40 GB GPU, its 2 TB/s bandwidth and 4K-token sequences. (As the page notes, 2 TB/s is the 80 GB A100’s figure; the 40 GB card is closer to 1.6 TB/s, which makes every time below about 25% longer.) Here Time is one decode step and the tokens per second it gives, and Space is the memory it holds. Activations and framework overhead are ignored.
| Case | Time | Space | Why |
|---|---|---|---|
| Llama-2-7B fp16, batch 1 | 16 GB read → 8 ms; 125 tok/s | 14 GB weights + 2 GB KV | Below the page’s 143 tok/s ceiling: at 4K context the KV read adds 2 GB to every step. |
| Same, batch 8 | 30 GB → 15 ms; 533 tok/s in total, 67 per user | 14 + 16 = 30 GB | The weights are read once for all 8 users. The KV cache is not shared, so it is read 8 times. |
| Same, batch 13 | 40 GB → 20 ms; 650 tok/s, 50 per user | 14 + 26 = 40 GB: full | The most that fits. Total speed is 5.2× batch 1, but each user gets 2.5× slower tokens. |
| Same, batch 16 | — | 14 + 32 = 46 GB | Does not fit. This is the page’s “more than the GPU has left”. |
| Llama-3-8B (GQA) fp16, batch 48 | 40 GB → 20 ms; 2,400 tok/s, 50 per user | ~16 GB weights + 48 × 0.5 GB | 4× smaller KV per token buys 48 sequences instead of 13, and 3.7× the total throughput at the same per-user speed. |
| Llama-2-7B INT4 weights, batch 18 | 39.5 GB → 19.75 ms; 911 tok/s | 3.5 GB weights + 36 GB KV | Quantizing weights frees 10.5 GB, which is 5 more sequences. The KV cache is still fp16, so the gain is 1.4×, not 4×. |
Read the per-user column. Bigger batches raise total throughput and lower cost per token, while each user’s stream gets slower. That is the latency-against-throughput knob from section 09, with numbers on it. At long context the KV cache, not the weights, sets both the batch ceiling and the step time. That is why GQA moves throughput more than INT4 weights do here. Real servers also become compute-bound at larger batches, so treat these numbers as upper limits.
Common mistakes
- Benchmarking with toy lengths
A load test with 128-token prompts and 128-token answers barely touches the KV cache, so it reports batch sizes and throughput that real 4K-token traffic can never reach (compare batch 13 above with the batch 32 the page says needs short contexts). Replay your real distribution of prompt and output lengths.
- Expecting weight quantization to shrink the KV cache
INT4 weights cut the weights, not the cache. In the table above, 4× smaller weights gave 1.4× the throughput, because 36 of the 39.5 GB read per step was still fp16 KV. Shrinking the cache needs GQA in the model, or a separate KV-cache quantization setting in the server, checked with its own evals.
- Watching throughput and ignoring TTFT under load
Time to first token includes time spent waiting in the queue. With continuous batching, a newly admitted request’s long prefill runs in the same steps as everyone else’s decode, so one 30K-token prompt can stall every stream on that GPU. Track p95 TTFT separately from tokens per second. Chunked prefill, which splits a long prompt across several steps, exists for this problem.
- Turning on speculative decoding everywhere
It pays when the GPU is idle waiting on memory: small batches and predictable text such as code. At large batches the GPU is already busy, so verifying the draft’s guesses is no longer free. At high temperature the draft is wrong more often. Either way it can end up slower than plain decoding. Measure the acceptance rate on your own traffic.
- Running the KV pool at 100%
PagedAttention hands out pages as sequences grow. When the pool runs out mid-generation, the scheduler has to preempt a running request, then swap its cache out or recompute it later. That is wasted GPU time and a latency spike for that user. Leave headroom and cap concurrent sequences or the maximum context length.
Where this shows up in production and interviews
- Open serving engines
vLLM, Hugging Face TGI, NVIDIA TensorRT-LLM and SGLang all build on the same ideas: continuous batching, a paged KV cache, quantized weights and speculative decoding. SGLang’s RadixAttention also shares the KV cache between requests that start with the same prefix.
- Prefix caching and API prices
When thousands of requests start with the same system prompt, the server can keep that prefix’s KV cache and skip its prefill. That cuts TTFT and compute. It is why the major API providers bill cached input tokens at a fraction of the normal input rate.
- Splitting prefill from decode
Prefill is compute-bound and decode is memory-bound, so mixing them on one GPU makes each slow the other down. Research systems such as DistServe and Splitwise run them on separate GPU pools and move the KV cache between them. That way each pool can be sized and tuned for one kind of work.
- The interview version
“Design an inference server for a 7B model.” Do the two formulas out loud: KV bytes per token, then how many sequences fit, then the bandwidth ceiling. State TTFT and per-token targets. Then choose levers based on what you are short of: continuous batching and paging for concurrency, GQA or KV quantization for memory, speculative decoding for latency at low load.
Check yourself
Llama-3-8B (128 KB of KV per token) serves 32K-token contexts with 24 GB free after weights. How many sequences fit?
128 KB × 32,768 tokens = 4 GB per sequence, so 6 fit in 24 GB. At 4K context the same GPU held 48. Context length divides your batch size directly, which is why long-context requests cost more to serve.
The draft model proposes 4 tokens and the big model accepts the first 2. How many tokens does this step produce?
3. The two accepted tokens, plus the big model’s own token at the first position it rejected, which it computed in the same verification pass. Even when nothing is accepted, the step still produces 1 token. So a bad draft never changes the output; it only wastes the draft’s time.
Users with 30K-token prompts wait 6 s for the first token, then text streams quickly. Which lever do you reach for: INT4 weights, speculative decoding, or prefix caching?
Prefix caching (and chunked prefill, or a shorter prompt through retrieval). The slow part is prefill, which is TTFT. Speculative decoding and smaller weights mainly speed up decode, and decode is already fine. If most of those 30K tokens are a shared document or system prompt, caching its KV removes most of the prefill.
INT4 cuts Llama-2-7B’s weights from 14 GB to 3.5 GB. How much faster is one stream, and how much faster is a full GPU?
One stream at short context: 2 TB/s ÷ 3.5 GB ≈ 571 tok/s against 143, so 4×. A full GPU at 4K context: 911 against 650 tok/s, only 1.4×, because most of each step now reads the fp16 KV cache. The answer to “how much faster?” depends on whether the weights or the KV cache are the bigger read.
Quick answers
Why is serving an LLM slow?
Generation is autoregressive and every token requires reading the whole model from GPU memory, so it's memory-bandwidth-bound, not compute-bound. The optimizations are all about moving less memory.
What is the KV cache?
Stored Key/Value vectors for every previous token so attention doesn't recompute them each step. It makes decode fast but grows with sequence length and batch size, dominating GPU memory.
What is continuous batching?
Adding and removing requests from the running batch every token step (vLLM), so a finished request is instantly replaced — keeping the GPU full and multiplying throughput.
What is quantization?
Storing weights in int8/int4 instead of 16-bit floats — less memory to move means faster generation, at a small, usually acceptable quality loss.
What is speculative decoding?
A small draft model guesses several tokens; the big model verifies them in one parallel pass. Correct guesses are free, cutting latency with no change to the output.
This idea in other formats
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The Prompting HandbookA friendly, hands-on field guide for everyday humans — learn the CRISP framework, spot bad prompts, practice with real recipes, play a drag-and-drop game, and test yourself with a quiz. No code required.Read →
- The Senior AI Engineer Interview Handbook60 questions across architecture, production incidents, agentic systems, RAG, evals, cost, safety, and leadership — what staff-level AI interviewers actually probe for.Read →
- The Transformers HandbookThe architecture behind every LLM, built up from scratch — tokens and embeddings, positional encoding, self-attention (query/key/value), multi-head attention, the transformer block (FFN, residuals, layer norm), and how a decoder-only model generates text autoregressively.Read →
- The Fine-Tuning HandbookWhen to fine-tune vs RAG vs prompting, full fine-tuning vs parameter-efficient methods, how LoRA and QLoRA make it cheap enough for a single GPU, why the data matters more than the method, catastrophic forgetting, and how to evaluate and decide.Read →
- The On-Device AI HandbookSmall models, everywhere: why 1–14B models got frontier-adjacent (distillation + textbook data), the napkin law of local inference (tokens/sec ≈ bandwidth ÷ bytes), quantization and the llama.cpp / GGUF / Ollama / MLX stack, the honest local-vs-cloud decision table, four hybrid patterns that ship, and the evals craft of choosing a small model that actually fits the device.Read →
- The GPU Fundamentals HandbookThe bottleneck is never where you think. SIMT and warps, the memory hierarchy from registers to HBM, arithmetic intensity and the roofline (compute-bound vs bandwidth-bound), where LLM workloads actually land, why FlashAttention was inevitable, the kernel stack from CUDA to Triton to torch.compile, and the multi-GPU interconnect story.Read →