Scheduling and decoding
- Production
- 45 min
- Lesson 4 of 7 in Inference engineering
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:Model and kernel optimization
You will be able to
- Compare static, dynamic and continuous batching by what changes at each iteration, and say what continuous batching needs from the KV-cache manager.
- Explain prefill and decode interference with a worked number, and describe how a token budget in chunked prefill trades smooth streaming against the long prompt's first-token time.
- Use Little's law to bound sustainable load, and choose between queueing, priority, admission control and cancellation when demand exceeds capacity.
- Compute expected accepted tokens and the speedup of speculative decoding from acceptance rate, draft length and draft cost, explain why the output distribution is unchanged, and say when the gain disappears.
- Decide between chunked prefill on shared GPUs and separate prefill and decode pools using KV-transfer arithmetic and the cost of extra machines.
One long answer is being written, and four short ones wait behind it: an order status, a time, an address and a “thank you”.
Latency the cat strolls past the screen, stops to wash a paw, and is still ahead of the short ones.
Ananya looks at the clock. “Nobody is doing anything wrong,” she says. “That’s the problem.” How do you let the short ones through without stopping the long one?
Concept
Lessons 1 to 3 made one engine step cheaper. This lesson is about which work goes into each step, and in what order. That is the scheduler’s job. It decides which requests are in the batch, how many prompt tokens to process alongside the decoding ones, when to admit or reject a request, and, with speculative decoding, how many tokens to try per step. Poor scheduling wastes the hardware you just optimised, and it is where many users’ latency complaints come from.
Why It Matters
Two requests with the same model and hardware can have very different latency depending on the queue in front of them. The usual production complaints, “the stream froze for a second when someone sent a big document” and “p95 first-token time triples at peak”, are scheduling problems. The fixes (chunked prefill, admission control, priorities) are cheap compared with buying GPUs.
Mental Model
The scheduler is a dispatcher at the server with a fixed number of seats per trip. A trip serves every seat holder once. Static batching waits for a full vehicle and holds everyone until the slowest passenger arrives. Continuous batching lets passengers get off and on at every stop. Chunked prefill is cutting one very long passenger’s journey into short legs so the short trips keep running. Speculative decoding is sending a scout ahead to guess a few stops, then checking the guess in one trip.
Batching strategies
| Strategy | How it works | Problem |
|---|---|---|
| No batching | one request at a time | the GPU is mostly idle during memory-bound decode (lesson 1) |
| Static batching | wait for N requests, run until all finish | short requests wait for the longest; padding waste; waiting to fill a batch delays TTFT |
| Dynamic batching | batch whatever arrives in a time window, then run it as a static batch | still tied to the slowest request |
| ContinuousContinuous batchingScheduling work per decode step so finished requests leave a batch and new ones join immediately.Open the glossary entry (iteration-level) batching | re-form the batch at every decode step: finished sequences leave, waiting ones join | needs per-sequence cache management |
The Orca paper (Yu et al., OSDI 2022) introduced iteration-level scheduling: the scheduler runs one model iteration at a time instead of whole requests, so an early-finishing request returns at once and a new arrival does not wait for the whole batch. It also introduced selective batching, so that batching and per-iteration scheduling can coexist. The paper reports 36.9 times the throughput of NVIDIA’s FasterTransformer at the same latency on a 175-billion-parameter model, in its own setup. The mechanism is what matters: it is why modern engines handle mixed-length traffic well, and why it pairs with paged cache management (lesson 2), since sequences now start and end at arbitrary steps.
It is not free. A request that joins must be prefilled, and that prefill shares the step with everyone’s decode.
Prefill and decode interfere
A worked example. An 8B model on an H100, with peak dense BF16 of about 990 TFLOPS as in lesson 1. Prefill costs about FLOPs per token.
- A 16,000-token prompt: FLOPs, at least 259 ms at peak. Real engines are slower.
- A 200-token prompt: at least 3.2 ms.
If the scheduler runs the big prefill as one step, every running decode waits at least 259 ms for its next token, against an ITL of perhaps 5 to 15 ms. To users the stream freezes. The short prompts behind it fare worse: their first-token time rises from about 3 ms of compute to over 260 ms. This is head-of-line blockingHead-of-line blockingA long request at the front of a queue or batch delaying the short ones behind it, such as a large prefill stalling other users' first tokens or decode steps.Open the glossary entry, and the cause is the schedule, not the model.
Chunked prefillChunked prefillSplitting a long prompt's prefill into pieces so other users' decode steps keep running. It smooths streaming for others at some cost to the long prompt's first token.Open the glossary entry limits the work per step. The scheduler sets a token budget per iteration, fills it with one token for each running decode, and spends what is left on a chunk of the waiting prompt. Sarathi-Serve (Agrawal et al., 2024) describes the idea as splitting prefills into roughly equal chunks and adding new requests to a batch without pausing ongoing decodes (“stall-free scheduling”); it reports 2.6 to 3.7 times higher serving capacity than vLLM under tail-latency constraints on two setups, and up to 5.6 times for Falcon-180B with pipeline parallelism.
With a 2,048-token budget, the 16,000-token prompt takes eight steps. Each step’s compute is at least , so a running decode sees steps of about 33 ms during that time rather than one 259 ms stall.
| Aspect | One-step prefill | Chunked prefill, 2,048-token budget |
|---|---|---|
| Steps used by the 16,000-token prompt | 1 | 8 |
| Compute per step (at least) | 259 ms | about 33 ms |
| What running decodes experience | One stall of at least 259 ms | Steps of about 33 ms |
| Short prompts waiting behind it | 260 ms or more to first token | Served between chunks |
The budget is a trade. vLLM’s optimization guide (accessed 2026-10-21) states it plainly: a smaller budget gives better inter-token latency because decodes are interrupted less, and a larger budget gives better time to first token because prompts finish sooner. Chunked prefill does not make prefill faster. It protects other users’ decode, and the long prompt itself finishes a little later than if it had the engine to itself. In vLLM’s current engine it is on by default where possible.
Policies when demand exceeds capacity
Little’s law, the capacity check
Little’s lawLittle's lawIn a stable system, the average number of requests in flight equals the arrival rate times the average time each spends in the system (L = λW). It gives the most traffic a given concurrency limit can sustain.Open the glossary entry says that in a stable system the average number of requests in flight equals the arrival rate times the average time each spends in the system: . Rearranged, the most traffic a service can sustain is .
Tie it to lesson 2. Suppose the cache pool allows 49 concurrent 8,192-token sequences and a typical request holds its slot for 8 seconds (admission to last token, not counting time waiting in the queue). Then requests per second. At 8 requests per second the queue grows without limit, however well the batching works: the arrival rate exceeds the service rate. A longer queue only adds waiting time.
Choices
- First come, first served is simple and fair, and suffers head-of-line blocking from long requests.
- Priority and SLO-aware scheduling puts interactive traffic ahead of batch jobs, and can approximate shortest-job-first from predicted output length. Per-tenant quotas stop one customer from filling the pool.
- Admission control and backpressure. Cap running sequences and queue length, and reject early (HTTP 429 or 503, with a retry hint) once the queue would break the latency target. Rejecting some requests quickly beats serving all of them late, because goodput counts only requests that meet the target.
- Preemption frees cache when the pool is full (lesson 2). A common choice is to preempt the newest or lowest-priority sequence, which has the least sunk work.
- Cancellation on disconnect. When a client goes away, abort its generation so the cache and batch slot are freed. Otherwise abandoned requests keep burning capacity.
Streaming (server-sent events or similar) improves perceived latency, not total time. Slow consumers must have timeouts, or their open streams hold resources.
Speculative decoding
Decode is memory-bound at small batch (lesson 1): reading the weights costs the same whether the step scores one token or several. Speculative decodingSpeculative decodingA cheap drafter, often a small model, proposes several tokens and the large model verifies them in one pass. The output distribution is preserved, and the speed-up depends on how often drafts are accepted.Open the glossary entry uses the idle arithmetic. A cheap draft proposes tokens. The large target model scores all positions plus one more in a single forward pass. Tokens are accepted in order while they match what the target would have produced, and decoding resumes from the first mismatch.
The rule (Leviathan et al., 2022): accept a drafted token with probability , where is the target’s probability and the draft’s. On the first rejection, sample from the adjusted distribution and stop. The paper proves that tokens produced this way are distributed identically to sampling from the target alone, for any draft model. At temperature 0 the output equals greedy decoding. vLLM’s documentation says it is theoretically lossless up to the precision limits of hardware numerics and notes that batch size and floating-point effects can still cause small output variation (lesson 3). Speculative decoding is not lossy like quantization.
The speedup arithmetic
Let be the chance that a drafted token is accepted (assumed independent per token, which is an idealisation) and the time of one draft step relative to one target step. From the paper:
Worked examples, with illustrative and (the paper’s T5 experiments report c between 0.02 and 0.11):
| Expected tokens per step | Speedup | |||
|---|---|---|---|---|
| 0.8 | 4 | 0.05 | 3.36 | 2.80 |
| 0.5 | 4 | 0.05 | 1.94 | 1.61 |
| 0.75 | 5 | 0.10 | 3.29 | 2.19 |
Two lessons. Acceptance rate matters more than anything else: dropping from 0.8 to 0.5 cuts the speedup by about 40 percent. And has an optimum. For and the speedup rises with (1.71 at , 2.80 at 4, 3.09 at 8) and then falls (2.72 at 16), because later drafted tokens are rarely accepted but always cost draft time.
Why it stops helping at load
The speedup formula assumes verifying tokens costs about one decode step. That holds only while the step is memory-bound. A verification step for a batch of sequences processes tokens, so intensity is roughly for BF16 weights. On an H100 with ridge near 295, crosses it at . Past that, verification costs real compute and the extra tokens slow the step. vLLM’s page lists speculative decoding as aimed at medium-to-low load and memory-bound workloads, with smaller gains at high load, and says real gains depend on model family, traffic, hardware and sampling settings. Benchmark with your own traffic and watch the acceptance rate.
Where the drafts come from
| Method | Draft source | Notes |
|---|---|---|
| Separate draft model | a small model from the same family | needs a compatible tokenizer; one more model to serve |
| Medusa | extra decoding heads on the target, with tree attention | Medusa-1 (frozen backbone) reports over 2.2 times speedup; Medusa-2 trains jointly for 2.3 to 3.6 times and needs a special recipe |
| EAGLE | autoregression over the target’s second-to-top-layer features | reports 2.7 to 3.5 times latency speedup on a 70B chat model; needs a trained head |
| Multi-token prediction | modules trained into the base model | built-in drafting where a model ships it |
| N-gram or prompt lookup | copy spans already in the prompt | training-free; helps when output repeats the input, as in summarisation or code edits |
vLLM’s documentation (accessed 2026-10-21) says model-based methods give the largest latency reduction and that simpler methods give modest speedups without adding work at peak traffic. The speedups above are the papers’ own, on their models and hardware.
Prefill and decode disaggregation
Prefill is compute-bound and decode is bandwidth-bound, so one pool of GPUs must compromise on batch size, parallelism and scheduling. DisaggregationPrefill/decode disaggregationRunning prefill and decode on separate GPU pools so the two phases do not interfere. It costs more machines and KV transfer.Open the glossary entry runs them on separate pools. Prefill machines compute the cache and send it over a fast interconnect to decode machines. DistServe (Zhong et al., OSDI 2024) argues that colocation causes interference and couples resource planning, and reports serving about 7.4 times more requests or meeting about 12.6 times tighter latency targets than the systems it compared with. Splitwise (Patel et al., 2023) makes the same split and reports 1.4 times the throughput at 20 percent lower cost, or 2.35 times the throughput with the same cost and power budgets. Mooncake builds a cache-centred version for a production service (lesson 5 returns to engines).
The cost is the transfer. A 4,096-token context on the 70B model from lesson 2 is , or 10.7 gigabits. Over a 400 Gb/s link at full line rate that is about 27 ms; real transfers are slower than line rate. That is small against a 500 ms TTFT target and large against a 10 ms decode step. Add the operational price: two pools to size, a router that balances both, and wasted capacity when the traffic mix shifts.
When is it worth it? High volume, strict targets on both TTFT and ITL, long prompts and a fast interconnect. For a small deployment, chunked prefill gives most of the benefit with none of the machinery. That is a judgment, not a measurement.
Constrained decoding
To guarantee output that matches a JSON schema, regex or grammar, the engine computes at each step which tokens would keep the output valid and masks the rest to zero probability before sampling. Costs: computing the mask each step (XGrammar, Dong et al. 2024, reports splitting tokens into context-independent ones, checked in advance, and context-dependent ones, checked at run time, and overlapping grammar work with GPU execution, with up to 100 times speedup over earlier approaches), compile time for complex grammars, and mismatches between character-level grammars and token boundaries. vLLM supports xgrammar and guidance as backends and recommends describing the schema in the prompt too.
Valid is not correct: the content of a well-formed JSON object can still be wrong. If speculative decoding is also on, drafted tokens must pass the same mask.
Real-World Application
When streaming stutters, check scheduling before hardware. Find the longest prompts in the time window of the stutter, compute their prefill floor, and compare it with the ITL target. If it is an order of magnitude over, enable chunked prefill and tune the budget, then re-measure both TTFT and ITL. Next, compute the Little’s-law ceiling from your cache concurrency and typical latency, and compare it with peak arrival rate. If peak exceeds it, add admission control and capacity, not a bigger queue. Turn on speculative decoding only for low-concurrency, latency-sensitive services, and measure the acceptance rate.
Interview Perspective
Expect: “Static versus continuous batching: what changes each iteration?”, “Derive the speculative-decoding speedup”, “Why does it help less at batch 64?”, “Streaming freezes whenever someone submits a huge document. Root cause and fixes”, “When would you disaggregate?”. A strong answer gives the mechanism, one number, and the cost.
Common mistakes: saying a bigger batch always lowers latency; saying speculative decoding changes outputs; saying chunked prefill speeds prefill; forgetting cancellation on disconnect; treating disaggregation as always better than colocation with chunked prefill.
Provenance: Common industry pattern and Generated practice. These are standard serving topics for ML-infrastructure roles; none is verified for a named company.
Practice Questions
- Basic: Static versus continuous batching: what changes each iteration?
- Intermediate: Derive expected accepted tokens for and . Why does speculation help less at batch 64?
- Advanced: Users report streaming freezing for about a second whenever someone submits a huge document. Give the root cause and two fixes with trade-offs.
- Product-Company: Design scheduling for a platform that serves a chat product (TTFT target 500 ms) and nightly batch jobs on the same GPUs.
Activity
For a model and GPU of your choice, compute the prefill floor for a 200-token and a 32,000-token prompt (2P FLOPs per token over dense peak). Then choose a token budget and state what it does to the ITL of running decodes and to the long prompt’s TTFT. Finally compute the Little’s-law ceiling for a cache concurrency and request time you assume.
Homework
Write a one-page scheduling plan: batching mode, token budget, priorities and quotas, admission-control thresholds and the response code, cancellation, and whether you would enable speculative decoding, with your acceptance-rate assumption and the batch size at which you would turn it off.
Quick Revision
- Continuous batching re-forms the batch every step; finished sequences leave and waiting ones join.
- A big prefill in one step stalls every decode. Chunked prefill spreads it under a token budget.
- Smaller budget: smoother ITL. Larger budget: faster TTFT for long prompts. Prefill is not made faster.
- Little’s law: . Sustainable rate = . Beyond it, queues grow without bound.
- Admission control and early rejection raise goodput. Cancel abandoned requests.
- Speculative decoding: expected tokens ; speedup divides by . Same distribution. Gains shrink at high batch.
- Disaggregation adds a KV transfer and two pools; try chunked prefill first.
Check yourself
- Walk-through: Explain how speculative decoding can be faster yet produce the same distribution, and when you would turn it off.
- Variation: Explain chunked prefill and what you tune if TTFT for long prompts becomes too slow.
- Common misconception: “Speculative decoding is lossy like quantization.” With correct rejection sampling the output distribution is the target’s.
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Production Metrics (opens in a new tab)
The engine's own metrics, which let you watch queue length, time to first token and inter-token latency while tuning.
Automatic Prefix Caching (opens in a new tab)
A companion scheduling feature that also reduces prefill work.
Further reading
Mastering LLM Techniques: Inference Optimization (opens in a new tab)
A vendor overview that places batching and speculative decoding beside the other serving optimizations.
Research papers
The paged cache allocation that continuous batching depends on.
More for this module: Inference engineering resources
Practice
Test what you just read. Quizzes and cards are grouped by module: Inference engineering.
Check yourself16 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.