Module 2 · Model serving and inference scaling · Chapter 06 · Free
Batching and streaming: the latency budget of a token
- Generation has two phases: prefill reads the whole prompt at once, decode writes one token at a time.
- Users feel time to first token first. Averages over full responses hide that wait.
- Batching lifts throughput but can tax each user. Streaming cuts perceived wait, not total time.
The picture: a kitchen that cooks in batches. More plates per hour, but your plate may wait for the batch.
- Why prefill and decode cost differently, and what that means for capacity.
- Two latency numbers to track: time to first token and time per output token.
- The latency budget method: split a target across queue, prefill, decode and network.
- A worked 6 second copilot response, accounted for stage by stage.
- A broken serving config to debug: three faults, three fixes.
Copperline is a made up company. Ana, the support lead, tells Priya the copilot "feels slow". The dashboard disagrees: average full response time is an illustrative 4.1 seconds, inside target.
- Priya times it herself. Nothing appears for an illustrative 3.8 seconds, then text dumps all at once.
- Nobody measured time to first token, so the wait that users felt was invisible.
- Agents had started retyping answers by hand, so trust, not just seconds, was the cost.
The average was fine. The experience was not. The metric was wrong.
- Prefill and decode: two phases, two cost shapes.
- Time to first token versus time per output token.
- Batching: throughput up, individual latency at risk.
- Streaming, then the picture of one request.
- A latency budget worked in numbers, then a break-it lab.
Next: the two phases, and why one price tag cannot describe both.
Step 1: Prefill reads, decode writes
Token basics live in the AI engineering course chapter Tokens and context windows. This chapter starts where that one ends: what serving does with those tokens.
- Prefill: the engine processes the whole prompt in one pass and builds the KV cache. Cost grows with prompt length. Long prompts, slow starts.
- Decode: the engine produces one token, then the next, each step reading the cache. Cost grows with output length, one step per token.
- Operator view: prefill is compute heavy and parallel. Decode is memory heavy and serial. They stress the GPU in different ways.
Think of prefill as reading a brief, decode as writing the reply sentence by sentence. Where the picture breaks down:
- Reading scales with the brief. Writing scales with the reply. The two lengths rarely match.
- Unlike a person, the engine can interleave many requests between decode steps.
Next: two clocks, because the two phases end at different moments.
Step 2: Two clocks, TTFT and TPOT
- Time to first token (TTFT): queue wait plus prefill plus first decode step. This is when the user sees life.
- Time per output token (TPOT): the average gap between tokens during decode. This sets reading speed and total time.
- Total time is roughly TTFT plus TPOT times the remaining tokens. A long answer can have a great TTFT and still finish late.
Report both, at p95, not as one average. Chapter 4, "SLOs for AI services: latency, throughput and quality", builds SLOs on these numbers.
Next: batching, the trade that buys throughput with someone else's wait.
Step 3: Batching buys throughput, and charges latency
A GPU step costs almost the same whether it advances one sequence or many. So engines group requests into batches, and modern engines in this category, including vLLM, TensorRT-LLM and SGLang, add and remove sequences as they finish. That is continuous batching.
- Throughput rises: more tokens per second per GPU, lower cost per token.
- Individual latency can rise: your decode step now shares the GPU, and a long batch queue adds wait before prefill.
- The cap is memory: every active sequence holds KV cache. Too many sequences and the cache thrashes, preempting and recomputing work.
Batching is a bus, not a taxi: cheaper per rider, slower door to door. Where the picture breaks down:
- A bus runs a fixed route. A serving engine rebalances the batch on every step.
- Past the cache limit, adding riders does not slow the bus. It makes the engine redo work.
Next: streaming, which fixes the feeling without shortening the work.
Step 4: Streaming changes what the user feels
- Without streaming, the client waits for the full answer, then shows it at once. Perceived latency equals total time.
- With streaming, tokens go to the client as decode produces them. Perceived latency is close to TTFT, even though total time is unchanged.
- Streaming also surfaces failure early: a stalled stream is visible in seconds, not after a long silent wait.
Streaming is not a speedup. It is honest pacing. Budget and measure total time anyway, because exports, APIs and downstream steps still wait for the last token. The AI engineering course covers the product side in its latency and streaming chapter.
Predict first:
Users judge the wait to first visible progress. Text starting at 0.9 seconds feels responsive even when the full answer still takes 6 seconds to finish.
Next: the picture, one request against its budget.
Step 5: The picture, one request and its budget
Press Next to walk a request through the four budget stages.
- Before any compute, the request waits for a batch slot. Under load this is often the biggest TTFT term.
- Prefill reads the prompt and builds the KV cache. Long retrieved context makes this stage grow.
- Each step adds one token per sequence. TPOT times token count is most of the total time.
- With streaming, the user reads while decode continues. Without it, this stage delivers everything at the end.
Next: the budget method, with a 6 second response accounted for.
Step 6: Worked example, where did 6 seconds go?
One illustrative copilot request at Copperline: a 1,200 token prompt (question plus retrieved help text) and a 200 token answer. All numbers below are illustrative.
1. Set the budget first. Target: TTFT at most 1.0 second, total at most 6.0 seconds. Split it: queue 0.3s, prefill 0.6s, first token step 0.1s, decode 4.8s, network 0.2s. Sum: 0.3 + 0.6 + 0.1 + 4.8 + 0.2 = 6.0s.
2. Measure the actual request. Queue 1.4s, prefill 0.7s, decode 3.7s for 200 tokens, network 0.2s. Total: 1.4 + 0.7 + 3.7 + 0.2 = 6.0s. Same total, very different shape.
3. Read the two clocks. TTFT = 1.4 + 0.7 + about 0.02 = about 2.1s, over its 1.0s budget. TPOT = 3.7s / 200 tokens = 18.5 ms per token, inside budget.
4. Name the fault. Decode is healthy. The queue is 1.1s over budget: too many concurrent sequences for the cache and GPU, so requests wait. The fix targets admission and batch limits, not the model.
5. Check the feeling. With streaming off, the user saw nothing for 6.0s. With streaming on, first text at 2.1s, and after the queue fix, at about 1.0s.
A budget turns "it feels slow" into a stage, a number and an owner. That is the whole method: budget each stage, measure each stage, fix the stage that is over.
Next: the break-it lab, where the config itself is the incident.
Step 7: Break-it lab, debug the serving config
Why this exercise: most "slow model" tickets are config faults, not model faults. This one has exactly three planted faults. Find all three before you open the reveal.
Lab: This is the chapter's break-it config, live. This lab runs in your browser and needs JavaScript enabled.
- Each fault maps to one budget stage: streaming to perceived TTFT, sequences to queue and prefill, timeout to decode.
- None of the fixes needs a bigger GPU. All three are one line each.
Next: a field note, then the mix-ups.
Production teams commonly report that users judge chat tools on how fast text starts, not how fast it ends, which is why TTFT is a standard serving metric alongside total latency. Treat exact thresholds as workload specific: a coding agent and a support copilot can share an engine and still need different budgets.
Mix-ups to avoid
- "Average response time is fine, so latency is fine." Averages hide TTFT and the p95 tail. Measure both clocks, at p95.
- "Streaming makes generation faster." It does not. Total time is the same. Perceived wait drops because progress is visible.
- "Bigger batches are always better." Past the KV cache budget, batching causes preemption and makes latency worse.
- "A short timeout keeps the system healthy." Below p95 generation time, a timeout manufactures failures out of healthy requests.
- "Prefill and decode scale the same way." Prefill scales with prompt length, decode with output length. Size and tune them separately.
Chapter quiz
Five questions. Score 70% or more to mark this chapter complete.
Review this chapter in 5 minutes
Watch the whole chapter recapped: prefill versus decode, TTFT and TPOT, the staged latency budget, and three config faults to fix.
- Prefill processes the prompt in one pass and scales with prompt length. Decode emits one token per step and scales with output length.
- TTFT is queue plus prefill plus the first step. TPOT is the per token gap in decode. Report both at p95.
- Batching raises tokens per second per GPU. Past the KV cache budget it causes preemption and hurts latency.
- Streaming leaves total time unchanged and cuts perceived wait to about TTFT.
- Worked budget: 6.0s total hid a 1.4s queue against a 0.3s budget. Decode at 18.5 ms per token was healthy.
- Lab fixes: streaming on, max sequences under the cache budget, timeout above p95.
Decision rule: when a service feels slow, split the time into queue, prefill, decode and network, compare each with its budget, and fix only the stage that is over.
Review
Glossary
- Prefill
- The pass that processes the whole prompt and builds the KV cache. Example: a 1,200 token prompt read in one go.
- Decode
- Generating output one token per step. Example: 200 steps for a 200 token answer.
- KV cache
- Stored attention data reused across decode steps. Example: the memory each active sequence holds on the GPU.
- Time to first token
- Wait from request to first visible token. Example: queue plus prefill, about 1 second on target.
- Time per output token
- Average gap between tokens during decode. Example: 18.5 ms per token in the worked example.
- Batching
- Advancing many sequences in one GPU step. Example: 32 sequences sharing a decode step.
- Continuous batching
- Adding and removing sequences from the batch as requests arrive and finish. Example: a freed slot refilled mid generation.
- Streaming
- Sending tokens to the client as they are produced. Example: text appearing word by word in chat.
- Latency budget
- A target split across stages so each stage has an owner. Example: queue 0.3s, prefill 0.6s, decode 4.8s.
- Preemption
- Pausing or evicting a sequence to free cache, then recomputing it later. Example: restarts when sequences exceed cache.
Next: "Scaling inference: replicas and autoscaling on the right signal".