Scheduling and decoding

  • Production
  • 45 min
  • Lesson 4 of 7 in Inference engineering
  • Last verified

Open slides(33 slides)

Before you start

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

StrategyHow it worksProblem
No batchingone request at a timethe GPU is mostly idle during memory-bound decode (lesson 1)
Static batchingwait for N requests, run until all finishshort requests wait for the longest; padding waste; waiting to fill a batch delays TTFT
Dynamic batchingbatch whatever arrives in a time window, then run it as a static batchstill 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) batchingre-form the batch at every decode step: finished sequences leave, waiting ones joinneeds 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 2P2P FLOPs per token.

  • A 16,000-token prompt: 2×8×109×16,000=2.56×10142 \times 8 \times 10^{9} \times 16{,}000 = 2.56 \times 10^{14} 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 2×8×109×2,048=33 ms2 \times 8 \times 10^{9} \times 2{,}048 = 33\ \text{ms}, so a running decode sees steps of about 33 ms during that time rather than one 259 ms stall.

AspectOne-step prefillChunked prefill, 2,048-token budget
Steps used by the 16,000-token prompt18
Compute per step (at least)259 msabout 33 ms
What running decodes experienceOne stall of at least 259 msSteps of about 33 ms
Short prompts waiting behind it260 ms or more to first tokenServed between chunks
Diagram: Each iteration gathers one token per running decode and tops the batch up with a chunk of a waiting prompt until the budget is full.

One iteration with a token budget

Running decodes: 1 token each

Mixed batch

Chunk of a waiting prompt: fills the rest of the budget

Forward pass

New tokens and cache updates

Diagram summary: Each iteration gathers one token per running decode and tops the batch up with a chunk of a waiting prompt until the budget is full. One forward pass handles the mix, and the loop repeats.

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: L=λ×WL = \lambda \times W. Rearranged, the most traffic a service can sustain is λmax⁡=concurrency limitmean time per request\lambda_{\max} = \dfrac{\text{concurrency limit}}{\text{mean time per request}}.

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 λmax⁡=49/8≈6.1\lambda_{\max} = 49 / 8 \approx 6.1 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.

Diagram: With 49 cache slots and each request holding a slot for 8 seconds, the server can sustain only about 6.1 requests per second.

arrival rate exceeds service rate

Arrivals: 8 requests per second

Queue

Service: 49 slots ÷ 8 s per request
= 6.1 requests per second

Queue grows without limit

Fix: reject early, add capacity,
or shorten the time per request

Diagram summary: With 49 cache slots and each request holding a slot for 8 seconds, the server can sustain only about 6.1 requests per second. At 8 per second the queue grows without bound, however good the batching, so the answer is admission control or more capacity.

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.
Diagram: When demand exceeds capacity, admission control rejects requests early rather than serving everyone late.

no

yes

interactive

batch

New request

Queue short enough to meet
the latency target?

Reject early: 429 or 503 with a retry hint

Interactive or batch?

High-priority queue

Low-priority queue

Run; cancel on client disconnect

Diagram summary: When demand exceeds capacity, admission control rejects requests early rather than serving everyone late. Admitted requests are prioritised by type, interactive ahead of batch, and an abandoned request is cancelled so it stops using cache and batch slots.

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 γ\gamma tokens. The large target model scores all γ\gamma 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 xx with probability min⁡(1,p(x)/q(x))\min(1, p(x) / q(x)), where pp is the target’s probability and qq the draft’s. On the first rejection, sample from the adjusted distribution norm(max⁡(0,p−q))\mathrm{norm}(\max(0, p - q)) 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.

Diagram: A cheap draft proposes several tokens and the target verifies them all in one pass.

Draft proposes 4 tokens

Target scores all 4 positions
plus one more, in one forward pass

Accept in order while they match:
e.g. tokens 1 to 3 accepted

First rejection: sample the target's
corrected token and stop

Next step starts after the accepted tokens

Diagram summary: A cheap draft proposes several tokens and the target verifies them all in one pass. Tokens are accepted in order until the first mismatch, where the target supplies its own token. The output distribution is the same as the target alone, and each pass yields several tokens when the draft is good.

The speedup arithmetic

Let α\alpha be the chance that a drafted token is accepted (assumed independent per token, which is an idealisation) and cc the time of one draft step relative to one target step. From the paper:

expected tokens per target step=1−αγ+11−α\text{expected tokens per target step} = \frac{1 - \alpha^{\gamma+1}}{1 - \alpha} speedup=1−αγ+1(1−α)(γc+1)\text{speedup} = \frac{1 - \alpha^{\gamma+1}}{(1 - \alpha)(\gamma c + 1)}

Worked examples, with illustrative α\alpha and cc (the paper’s T5 experiments report c between 0.02 and 0.11):

α\alphaγ\gammaccExpected tokens per stepSpeedup
0.840.053.362.80
0.540.051.941.61
0.7550.103.292.19

Two lessons. Acceptance rate matters more than anything else: dropping α\alpha from 0.8 to 0.5 cuts the speedup by about 40 percent. And γ\gamma has an optimum. For α=0.8\alpha = 0.8 and c=0.05c = 0.05 the speedup rises with γ\gamma (1.71 at γ=1\gamma = 1, 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 γ+1\gamma + 1 tokens costs about one decode step. That holds only while the step is memory-bound. A verification step for a batch of BB sequences processes (γ+1)×B(\gamma + 1) \times B tokens, so intensity is roughly (γ+1)×B(\gamma + 1) \times B for BF16 weights. On an H100 with ridge near 295, γ=4\gamma = 4 crosses it at B≈59B \approx 59. 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

MethodDraft sourceNotes
Separate draft modela small model from the same familyneeds a compatible tokenizer; one more model to serve
Medusaextra decoding heads on the target, with tree attentionMedusa-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
EAGLEautoregression over the target’s second-to-top-layer featuresreports 2.7 to 3.5 times latency speedup on a 70B chat model; needs a trained head
Multi-token predictionmodules trained into the base modelbuilt-in drafting where a model ships it
N-gram or prompt lookupcopy spans already in the prompttraining-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).

Diagram: A router sends each request to a prefill pool.

KV-cache transfer over fast link

Router

Prefill pool: tuned for first-token time

Decode pool: large batches, tuned for ITL

Stream tokens

Diagram summary: A router sends each request to a prefill pool. The finished KV-cache moves over a fast link to a decode pool, which runs large batches and streams the tokens.

The cost is the transfer. A 4,096-token context on the 70B model from lesson 2 is 4,096×320 KiB≈1.34 GB4{,}096 \times 320\ \text{KiB} \approx 1.34\ \text{GB}, 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 α=0.7\alpha = 0.7 and γ=3\gamma = 3. 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: L=λWL = \lambda W. Sustainable rate = concurrency÷time per request\text{concurrency} \div \text{time per request}. Beyond it, queues grow without bound.
  • Admission control and early rejection raise goodput. Cancel abandoned requests.
  • Speculative decoding: expected tokens (1−αγ+1)/(1−α)(1 - \alpha^{\gamma+1}) / (1 - \alpha); speedup divides by (γc+1)(\gamma c + 1). 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.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

Research papers

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.

0 of 16 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveCompare static, dynamic and continuous batching by what changes at each iteration, and say what continuous batching needs from the KV-cache manager.

  1. Question 1 of 16A batch of 8 starts together. Three requests finish at step 40; the other five run to step 200, and new requests are waiting. What happens to the three freed slots?

    Choose one answer.

  2. Question 2 of 16Continuous batching has sequences starting and ending at arbitrary steps. What does this ask of memory management?

    Choose one answer.

  3. Question 3 of 16Which are properties of continuous (iteration-level) batching? Select all that apply.

    Choose all that apply.

ObjectiveExplain 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.

  1. Question 4 of 16A 13B model processes a 10,000-token prompt on a GPU with 500 dense TFLOPS. Counting 2P FLOPs per token, what is the minimum prefill time at peak?

    Choose one answer.

  2. Question 5 of 16Streaming freezes for about half a second each time a user submits a very large document, and then recovers. What is the most likely cause and fix?

    Choose one answer.

  3. Question 6 of 16An operator raises the per-iteration token budget for chunked prefill from 1,024 to 8,192. What should they expect?

    Choose one answer.

  4. Question 7 of 16Which statements about chunked prefill are correct? Select all that apply.

    Choose all that apply.

ObjectiveUse Little's law to bound sustainable load, and choose between queueing, priority, admission control and cancellation when demand exceeds capacity.

  1. Question 8 of 16A service can hold 30 concurrent sequences, and a typical request holds its slot for 12 seconds from admission to last token. What is the most arrival rate it can sustain?

    Choose one answer.

  2. Question 9 of 16Peak arrival is 4 requests per second and the service ceiling is 2.5. Latency targets are being missed. What is the best response?

    Choose one answer.

  3. Question 10 of 16Which actions raise goodput when a service is overloaded? Select all that apply.

    Choose all that apply.

ObjectiveCompute 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.

  1. Question 11 of 16Speculative decoding uses acceptance rate α = 0.6, draft length γ = 3 and draft cost ratio c = 0.1. What is the approximate speedup?

    Choose one answer.

  2. Question 12 of 16What is true of the output distribution under speculative decoding with correct accept and reject sampling?

    Choose one answer.

  3. Question 13 of 16On an H100 (ridge near 295 FLOP per byte), a service uses γ = 3 drafts and a batch of 128. Why does speculative decoding gain little there?

    Choose one answer.

  4. Question 14 of 16A summarization service wants a speculative method that needs no extra trained model or heads and works because outputs often repeat phrases from the input. Which fits?

    Choose one answer.

ObjectiveDecide between chunked prefill on shared GPUs and separate prefill and decode pools using KV-transfer arithmetic and the cost of extra machines.

  1. Question 15 of 16An 8B model has a cache of 1.07 GB for an 8,192-token context. Moved over a 200 Gb/s link at full line rate, how long does the transfer take?

    Choose one answer.

  2. Question 16 of 16A small team runs one model on two nodes and sees stuttering streams when long prompts arrive. Which step should come first?

    Choose one answer.