Slides · Production: cost, serving and observability
LLM inference and serving
1 / 30
LLM inference and serving
Why decode is slow, why memory caps how many users fit on a GPU, and what each speed-up costs you.
Concept
The servers are idle, yet the queue grows
- On sale day the dashboard shows servers that are not working hard, and the queue keeps growing.
- If compute is not the limit, something else is: memory bandwidth and memory capacity.
- Even if you never self-host, these ideas explain provider behaviour: why long prompts delay the first token, why long answers take so long, why prompt caching exists.
By the end you can:
- Explain why decode is bandwidth-bound and why KV-cache memory caps concurrency.
- Read serving metrics and map a symptom to a cause.
- Match each speed-up technique to the bottleneck it attacks and the cost it adds.
- Decide between a hosted API and self-hosting with a break-even estimate.
Concept
Mental model: a narrow straw and a bus
- A GPU is a very fast calculator with a narrow straw to its memory. One token for one user drains the straw, because all the weights must pass the calculator for every token.
- Batching is a bus: one trip through the weights serves many riders, so the cost of the trip is shared.
- Each rider carries a bag (their KV-cache) that takes a seat’s worth of memory. The bus fills up from bags before it fills up from riders.
- A good scheduler lets riders get on and off at every stop instead of waiting for the whole route.
Compare
Two phases, two bottlenecks
| Aspect | Prefill | Decode |
|---|---|---|
| What happens | The whole prompt is processed in parallel | One new token per step, reusing stored keys and values |
| Limited mainly by | Compute | Memory bandwidth: moving weights, keys and values to the chip |
| Shows up as | Time to first token | Time between tokens |
| Grows with | Prompt length and load | Output length |
- NVIDIA’s inference-optimization post calls decode a memory-bound operation: the speed of moving weights, keys, values and activations from memory dominates its latency.
- Two scarce resources follow: bandwidth limits decode speed, capacity limits how many requests are in flight.
Diagram
One server, end to end
Math
Why decode has a speed ceiling
max tokens per second (one stream)=bytes read per stepmemory bandwidthbytes read per step≈number of parameters×bytes per parameter| Symbol | Meaning |
|---|---|
| memory bandwidth | Bytes the GPU can move per second (assumed 3,000 GB/s, illustrative) |
| parameters | 13 billion in this example |
| bytes per parameter | 2 for 16-bit, 1 for 8-bit, 0.5 for 4-bit |
| Weight precision | Weights read per step | Upper bound for one stream |
|---|---|---|
| 16-bit | 13×109×2=26 GB | 263,000≈115 tokens/s |
| 8-bit | 13 GB | about 231 tokens/s |
| 4-bit | 6.5 GB | about 462 tokens/s |
- The bound ignores KV-cache reads and other overheads, so real speeds are lower.
- More arithmetic power with the same bandwidth leaves the bound unchanged.
Worked example
Batching shares the weight read
Same 26 GB model, same 3,000 GB/s (illustrative). Each decode step reads the weights once, however many requests are in the batch.
| Requests per step | Weight reads per step | Tokens produced per step | Ceiling on aggregate tokens/s (weights only) |
|---|---|---|---|
| 1 | 26 GB | 1 | about 115 |
| 8 | 26 GB | 8 | about 923 |
- The ceiling for 8 requests is 268×3,000.
- The real gain is smaller: each request also reads its own KV-cache, compute eventually becomes the limit, and every request holds memory. That is the next slide.
Math
KV-cache memory per token
KV bytes per token=2×L×Hkv×dhead×bKV bytes per request=KV bytes per token×nseq| Symbol | Meaning |
|---|---|
| 2 | One key and one value per head |
| L | Number of transformer layers |
| Hkv | Key and value heads. Fewer than query heads with grouped-query attention (GQA) |
| dhead | Size of each head |
| b | 2 for 16-bit |
- NVIDIA’s post writes the same per-token size with nheads×dhead and notes that the total grows linearly with batch size and sequence length.
- MQA and GQA reduce the number of key-value heads. NVIDIA notes MQA can cost accuracy and that GQA balances multi-head and multi-query attention.
Worked example
Worked example: how many requests fit?
Illustrative plan: an 80 GiB GPU, 90 percent usable (72 GiB), 7B model in 16-bit (about 13 GiB of weights), 32 layers, head_dim 128, 4,096-token requests.
| Layout | Per token | Per 4,096-token request | KV pool (72−13=59 GiB) |
|---|---|---|---|
| 32 KV-heads | 2×32×32×128×2=524,288 B (0.5 MiB) | 2 GiB | 259=29.5, so 29 requests |
| 8 KV-heads (GQA) | 2×32×8×128×2=131,072 B (0.125 MiB) | 0.5 GiB | 0.559=118 requests |
- Same GPU, same weights, four times the concurrency, from one architecture choice.
- When the pool is full, new requests queue. The vLLM guide says it may also preempt and recompute running requests, which can hurt end-to-end latency.
- So “how many users fit on one GPU” is mostly a KV-cache question.
Check yourself
Check: how long a context can you afford?
A 40 GiB GPU is 90 percent usable and holds 10 GiB of weights. The model has 24 layers, 8 KV-heads, head_dim 128 and 16-bit values. Product wants 100 requests in flight at once. What is the longest context per request the KV pool allows? And how many 16,384-token requests fit?
Answer
Per token: 2×24×8×128×2=98,304 bytes. The pool is 40×0.9−10=26 GiB. For 100 requests each gets 0.26 GiB, which is 98,3040.26×230≈2,839 tokens. A 16,384-token request holds 1.5 GiB, so 1.526=17.3, which is 17 requests. Concurrency and context length trade directly against each other.
Compare
Four metrics, four questions
| Metric | Question it answers | What moves it |
|---|---|---|
| TTFT | How long until the first token? | Queueing plus prefill; prompt length and load |
| Inter-token latency (ITL, time per output token) | How smooth is the stream? | Decode speed, memory bandwidth, batch pressure |
| Throughput | How many tokens per second across all users? | Batching, utilization. A cost metric |
| Goodput | How much work meets the promised targets? | Throughput minus the requests that miss TTFT or ITL limits |
- A common definition of goodput is the rate of requests that meet your latency targets.
- DistServe’s stricter version: the highest request rate a GPU can sustain while a target share of requests meets both the first-token limit and the per-output-token limit. Its abstract reports staying within the limits for more than 90 percent of requests.
Worked example
Worked example: more traffic is not more goodput
Using the simple definition, goodput=request rate×share that meets both targets. One illustrative server under rising load:
| Load (requests/s) | Share meeting both targets | Goodput |
|---|---|---|
| 5 | 98% | 5×0.98=4.90 |
| 10 | 92% | 10×0.92=9.20 |
| 15 | 70% | 15×0.70=10.50 |
| 20 | 45% | 20×0.45=9.00 |
- Throughput keeps rising with load, but goodput peaks at 15 requests per second and then falls.
- Past the peak you serve more requests and more of them miss the promise.
- Goodput is how you tune: raise load until the share meeting the targets starts to fall, and stop near the peak.
Diagram
From symptom to cause
- Typical fixes. High TTFT: prefix cache, chunked prefill, more replicas. High ITL: quantize, speculative decoding, smaller model. High cost: continuous batching, paged KV, route easy traffic to a small model.
- The vLLM guide describes a chunked-prefill budget as a trade: smaller values give better ITL, larger values give better TTFT.
Check yourself
Check: fast but costly
A self-hosted deployment meets its TTFT and ITL targets at every hour. Yet cost per million tokens is far above plan, and GPU utilization sits near 25 percent because requests arrive one or two at a time. Which branch of the triage tree are you on, and what do you try?
Answer
Both latency checks pass, so you are on the throughput-and-cost branch. The GPU is mostly idle, so the batch is small and the fixed hourly price is spread over few tokens. Options: send several models or tenants to shared replicas so batches fill, scale down to fewer GPUs, or move the low-volume traffic to a hosted API. More decode speed-ups would not help, because latency is not the problem.
Worked example
Continuous batching: toy timeline
Three slots. Requests A, B, C need 2, 5, 3 decode steps. D needs 2 steps and is waiting. A dot is an idle slot.
| Step | Static: slot 1 | slot 2 | slot 3 | Continuous: slot 1 | slot 2 | slot 3 |
|---|---|---|---|---|---|---|
| 1 | A | B | C | A | B | C |
| 2 | A | B | C | A | B | C |
| 3 | · | B | C | D | B | C |
| 4 | · | B | · | D | B | · |
| 5 | · | B | · | · | B | · |
| 6 | D | · | · | |||
| 7 | D | · | · |
- Static batching holds the group until the longest request (B) finishes, so D completes at step 7.
- Continuous (in-flight) batching rebuilds the batch at every step, so D takes A’s freed slot and completes at step 4.
- The Anyscale post reports, against naive batching on OPT-13B and one A100 40GB in 2023, up to 23x for vLLM (continuous batching plus its own memory optimizations) and 8x for continuous batching in Ray Serve and text-generation-inference. One benchmark in one setting.
- Catch: under heavy load a request can wait longer for a slot.
Sources[4] How continuous batching enables 23x throughput in LLM inference while reducing p50 latency[1] Mastering LLM Techniques: Inference Optimization
Diagram
PagedAttention and prefix caching
- The vLLM paper’s abstract reports near-zero KV-cache waste and 2 to 4 times the throughput of the systems it compared with (FasterTransformer, Orca) at the same latency.
- vLLM’s automatic prefix caching hashes full blocks, reuses matching leading blocks, and does not change model outputs. It saves prefill work, not decode.
Sources[5] Efficient Memory Management for Large Language Model Serving with PagedAttention[6] Automatic Prefix Caching
Worked example
Chunked prefill
A 12,000-token prompt can hold the GPU through one long prefill while other users’ decode steps wait.
| Time slice | Without chunking (one long pass) | With chunked prefill |
|---|---|---|
| 1 | Long prompt prefill | Prefill chunk 1 plus others’ decode |
| 2 | Prefill continues; others wait | Prefill chunk 2 plus others’ decode |
| 3 | Prefill ends; others finally get a token | Prefill chunk 3 plus others’ decode |
- Others’ streams keep flowing on the right. The cost is a slightly later first token for the long prompt.
- The vLLM guide says chunked prefill is on by default where possible in its V1 engine and prioritizes decode requests. A smaller per-step token budget favours ITL, a larger one favours TTFT.
Concept
Quantization: smaller numbers, smaller reads
- Store weights (sometimes activations too) in 8-bit or 4-bit formats.
- A 13B model’s weights go from about 26 GB at 16-bit to about 13 GB or 6.5 GB (plus some overhead for scaling factors). Decode reads fewer bytes, and more memory is free for KV-cache.
- Cost: NVIDIA’s post names two error sources, rounding and clipping, as the price of fewer bits.
- Weights are easier to quantize than activations, which tend to contain outliers.
- Speed-up depends on kernels and hardware. Choose the format by testing on your own evaluation set, not by default.
Diagram
Speculative decoding
- Leviathan et al. report 2x to 3x faster decoding on T5-XXL compared with the standard T5X implementation, with identical outputs (ICML 2023).
- With the standard sampler, vLLM’s page calls the method theoretically lossless up to hardware numeric precision (a variant that relaxes verification is not), and recommends measuring on your own traffic.
- The speed-up depends on how often the draft is right.
Sources[7] Fast Inference from Transformers via Speculative Decoding[8] Speculative Decoding
Compare
Speculative decoding and load
The vLLM page rates methods by traffic level (page viewed 2026-10-23). Three rows:
| Method | Low QPS (latency focused) | High QPS (throughput focused) |
|---|---|---|
| Draft model | High gain | Medium gain |
| EAGLE | High gain | Medium to high gain |
| N-gram | Low to medium gain | Medium gain |
- The page positions it as a latency tool for memory-bound serving at lighter to moderate load.
- For the model-based methods in the full table (EAGLE, MTP, draft models) the rating at high QPS is lower than at low QPS. The simpler n-gram and suffix methods are rated Medium at high QPS, and the page describes their speedups as modest but without extra work at peak load.
- Model-based methods also add a second component to run.
Source[8] Speculative Decoding
Compare
Three more levers
| Aspect | FlashAttention | Parallelism | Prefill and decode disaggregation |
|---|---|---|---|
| Attacks | Memory traffic inside attention | A model too big for one GPU; throughput | Interference between phases |
| How | Tiles stay in fast on-chip memory, fewer reads and writes of main GPU memory | Tensor parallelism shards each layer; data parallel replicas add throughput | Run prefill and decode on separate pools |
| Output | Exact, not an approximation | Unchanged | Unchanged |
| Cost | Benefit depends on the implementation you run | Tensor parallelism needs fast links between GPUs | More machines, KV transfer, scheduling |
- DistServe reports serving up to 7.4x more requests, or meeting up to 12.6x tighter latency targets, than the systems it compared against, in its own tests. Do not quote it as a general speed-up.
Sources[9] FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness[3] DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving[2] Optimization and Tuning
Compare
Technique to bottleneck to cost
| Technique | Attacks | Cost or catch |
|---|---|---|
| Continuous batching | Idle slots, low throughput | Per-request latency can rise at high load |
| PagedAttention | KV fragmentation, small batches | Engine complexity |
| Prefix caching | Repeated prefill of shared prompts | Only identical prefixes; cache memory |
| Chunked prefill | Long prompts stalling others’ decode | Slightly slower first token for the long prompt |
| Quantization | Memory size and bandwidth | Some quality loss; kernel and hardware support vary |
| Speculative decoding | Decode latency at low to medium load | Extra component; for model-based methods the vLLM rating drops at high load |
| FlashAttention | Attention memory traffic | None on output |
| Disaggregation | Phase interference | More machines, KV transfer |
Sources[1] Mastering LLM Techniques: Inference Optimization[2] Optimization and Tuning[6] Automatic Prefix Caching[8] Speculative Decoding
Check yourself
Check: pick two techniques
A self-hosted assistant serves a few users at a time. Single-stream speed is the complaint: time between tokens is high even on short prompts. Name two techniques that attack this, and say which of them risks changing answers.
Answer
Quantization shrinks the bytes read per decode step and raises the bandwidth ceiling, but rounding and clipping can change answers, so test it on your own tasks. Speculative decoding targets decode latency at low to medium load and, with the standard sampler, keeps the large model’s output distribution. Continuous batching or a bigger batch would not help here, because with few users there is little to share.
Worked example
Self-host or API: it is about utilization
Illustrative: a GPU costs 2 dollars per hour and your engine sustains 1,000 output tokens per second across users.
tokens per hour at full load=1,000×3,600=3,600,000cost per million tokens=million tokens per hour×utilizationhourly price| GPU use | Tokens per hour | Cost per million tokens |
|---|---|---|
| 100% | 3,600,000 | 3.62≈$0.56 |
| 30% | 1,080,000 | 1.082≈$1.85 |
- Break-even against an API priced at $1.00 per million (invented): u0.5556=1.00, so utilization u must reach about 56 percent.
- An idle GPU still costs money. An API bill follows usage.
- This leaves out failover capacity, engineers’ time and the quality gap between an open model and a frontier one.
Check yourself
Check: how fast must the GPU be?
A GPU costs 4.00 dollars per hour. A hosted API offers a comparable model at 2.50 dollars per million tokens. You expect 50 percent utilization. What full-load throughput, in output tokens per second, must the engine sustain for self-hosting to cost no more than the API?
Answer
To tie, the GPU must deliver 2.504.00=1.6 million tokens in an hour at the price of that hour. At 50 percent utilization the actual tokens equal half of full-load tokens, so full load must be 3.2 million tokens an hour, which is 3,6003,200,000≈889 tokens per second. Below that throughput, or at lower utilization, the API is cheaper on this arithmetic alone (failover capacity and engineering time not included).
Compare
Decision factors
| Factor | Favours self-hosting | Favours a hosted API |
|---|---|---|
| Volume | Steady and high | Spiky or low |
| Utilization | Can keep GPUs busy | Often idle |
| Data residency | Strict rules | No rule that blocks a provider |
| Control | Need to fine-tune or control the model | Prompting is enough |
| Team | Can run a serving stack | Small team |
| Capability | An open model is good enough | Need the strongest available model |
- A common hybrid: self-host the bulk, keep an API fallback for overflow and hard cases.
- Before committing, estimate break-even with your own prices and measured throughput.
Concept
Common mistakes
- “A bigger batch always lowers latency.” It raises throughput; per-request latency can get worse.
- “Quantization is free.” It trades quality for memory and speed.
- Confusing a response cache with the KV-cache. One skips the model; the other stores keys and values inside it.
- Claiming speculative decoding changes outputs. Done correctly, it does not.
- Comparing a self-hosted price at full load with an API price. Use the utilization you will really see.
Summary
Recap
- Prefill sets TTFT. Decode sets inter-token latency and is memory-bandwidth-bound.
- KV-cache memory caps concurrency. GQA shrinks it. A full pool means queueing or preemption.
- Continuous batching and PagedAttention raise throughput; prefix caching cuts repeated prefill work (and so TTFT), while chunked prefill smooths other users’ streams at a small first-token cost for the long prompt.
- Quantization trades quality for speed and memory. Speculative decoding, with the standard sampler, keeps the output distribution. Measure both on your own traffic.
- Self-hosting wins on utilization and loses on idle time and operations.
References
References & Sources (1 of 2)
Mastering LLM Techniques: Inference Optimization (opens in a new tab)
Shashank Verma, Neal Vaidya2023Article
https://developer.nvidia.com/blog/mastering-llm-techniques-inference-optimization/
Used for Decode is memory-bound; KV-cache size formula and linear growth; MQA and GQA reduce key-value heads; in-flight batching; quantization costs (rounding and clipping) and why weights are easier than activations.
Optimization and Tuning (opens in a new tab)
vLLM project2026Documentation
https://docs.vllm.ai/en/latest/configuration/optimization.html
Used for KV-cache shortage can trigger preemption and recomputation that hurts latency; chunked prefill budget trades ITL against TTFT; tensor, pipeline and data parallelism.
Yinmin Zhong, Shengyu Liu, Junda Chen, Jianbo Hu, et al.2024OSDI 2024Paper
arXiv 2401.09670 (opens in a new tab)https://www.usenix.org/conference/osdi24/presentation/zhong-yinmin
Used for Goodput as the rate served within both TTFT and time-per-output-token limits; disaggregating prefill and decode, with its reported 7.4x and 12.6x results.
Cade Daniel, Chen Shen, Eric Liang, Richard Liaw2023Article
https://www.anyscale.com/blog/continuous-batching-llm-inference
Used for Reported results versus naive batching in one 2023 setting (OPT-13B, one A100 40GB): up to 23x for vLLM, which pairs continuous batching with its own memory optimizations, and 8x for continuous batching in Ray Serve and text-generation-inference; iteration-level scheduling.
Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, et al.2023Preprint
arXiv 2309.06180 (opens in a new tab)https://arxiv.org/abs/2309.06180
Used for PagedAttention and vLLM: near-zero KV-cache waste and 2 to 4 times throughput versus FasterTransformer and Orca at the same latency.
References
References & Sources (2 of 2)
Automatic Prefix Caching (opens in a new tab)
vLLM project2026Documentation
https://docs.vllm.ai/en/stable/design/prefix_caching/
Used for Automatic prefix caching hashes full KV blocks, reuses matching prefixes, and does not change model outputs.
Fast Inference from Transformers via Speculative Decoding (opens in a new tab)
Yaniv Leviathan, Matan Kalman, Yossi Matias2023ICML 2023 (PMLR 202)Paper
arXiv 2211.17192 (opens in a new tab)https://proceedings.mlr.press/v202/leviathan23a.html
Used for Speculative decoding gives 2x to 3x acceleration on T5-XXL with identical outputs.
Speculative Decoding (opens in a new tab)
vLLM project2026Documentation
https://docs.vllm.ai/en/latest/features/speculative_decoding/
Used for Speculative decoding targets medium-to-low QPS, memory-bound workloads; method-by-load rating table; lossless up to hardware numerics; advice to measure on your own traffic.
FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (opens in a new tab)
Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, et al.2022NeurIPS 2022Paper
arXiv 2205.14135 (opens in a new tab)https://proceedings.neurips.cc/paper_files/paper/2022/hash/67d57c32e20fd0a7a302cb81d36e40d5-Abstract-Conference.html
Used for FlashAttention is an exact attention algorithm that uses tiling to cut reads and writes between GPU main memory and on-chip memory.
Keys: ← → move, Home End first and last, F full screen.