Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

Download this lesson and two more on LLM serving (EPUB)

On this page

12.3 Continuous Batching: Request Scheduling and Chunked Prefill

Three requests are generating tokens together. One finishes after two decode iterations; another needs six. Must a fourth request wait four more iterations before it can use the freed slot? Continuous batching lets the scheduler admit it at the next iteration boundary, provided token and KV-cache budgets allow it.

Section 12.2 explained where growing KV state is stored. This section explains which requests get to compute next. Reusable memory blocks help admission, but a memory allocator alone does not choose an execution schedule.

1. Follow Six Requests Through Three Slots

Use the same authored workload throughout this section: requests A–F have 4, 2, 6, 3, 5 and 2 remaining decode tokens. All six are queued before execution, three slots are available, and each scheduled request produces one token per iteration. Prefill has been excluded so that we can isolate the admission rule. These are iteration counts, not measured milliseconds.

In the static policy used here, A, B and C form one group. A completed request may return its result and release memory; the restriction is that no replacement joins until that entire group finishes. A particular implementation may mask finished rows or compact them. Neither behavior makes memory retention or dummy computation an inherent requirement of static admission.

The continuous policy admits waiting requests into freed slots at every boundary. The table shows who runs in each iteration. A check mark means that request finishes at the end of that iteration; its replacement can first run in the next row.

IterationStatic: slots 1 / 2 / 3Continuous: slots 1 / 2 / 3
1A / B / CA / B / C
2A / B ✓ / CA / B ✓ / C
3A / — / CA / D / C
4A ✓ / — / CA ✓ / D / C
5— / — / CE / D ✓ / C
6— / — / C ✓E / F / C ✓
7D / E / FE / F ✓ / —
8D / E / F ✓E / — / —
9D ✓ / E / —E ✓ / — / —
10— / E / —All requests finished
11— / E ✓ / —All requests finished

B finishes at iteration 2. Continuous batching runs D in that slot at iteration 3; static batching starts D at iteration 7. The same 22 decode tokens finish in 9 rather than 11 iterations. This does not establish a GPU speedup: iteration duration changes with batch composition, context lengths and kernels. Even the continuous schedule has empty slots once the waiting queue runs out.

Explore the Completion Boundaries

Open iteration 3. Which policy has started D? At iteration 7, D has just started in one schedule and already finished in the other. The cards show the end of each iteration, including requests that just finished. Step 0 shows the queue before admission.

Six requests share three slots. All requests arrive before decoding starts. Prefill is omitted. Each card shows the end of this iteration. The remaining token count includes tokens still to be generated for both queued and active requests.

Before execution: all requests queued

Static batching

Finished 0/6 · Queued 6 · Tokens left 22

Slot 1Not admitted yet
Slot 2Not admitted yet
Slot 3Not admitted yet

Queue: A, B, C, D, E, F

Workload finishes at iteration 11

Continuous batching

Finished 0/6 · Queued 6 · Tokens left 22

Slot 1Not admitted yet
Slot 2Not admitted yet
Slot 3Not admitted yet

Queue: A, B, C, D, E, F

Workload finishes at iteration 9

Starting decode targets (tokens per request): A=4 · B=2 · C=6 · D=3 · E=5 · F=2

Hand-authored teaching workload. Iterations are not milliseconds or GPU utilization. Token/KV budgets, arrival timing, prefill, communication and scheduler costs are omitted. Empty slots after completion are not wasted computation.

2. Admission Needs More Than a Free Slot

Orca studied scheduling at iteration granularity instead of waiting for a whole request group to finish [1]. In ordinary autoregressive decoding, one scheduled decode step produces one new token per request. Prefill chunks can produce no output token until the prompt is complete; speculative decoding can produce multiple accepted tokens. An iteration is therefore a scheduling unit, not universally “one token for every active request.”

At a boundary, the scheduler accounts for completed or cancelled requests, retains unfinished state, and selects the next work. Releasing a request’s KV references need not immediately free physical blocks that other requests or a prefix cache still reference. Admission must satisfy the request limit, token budget, available KV capacity and scheduling policy.

Let BB be the iteration’s input-token budget, DD the number of scheduled ordinary decode requests, and PP the number of scheduled prefill tokens. In a simplified policy where each decode consumes one input-token position,

D+P≤B.D+P\le B.

This is a work budget, not the total tokens stored in the KV cache. A request decoding one token may already retain thousands of context tokens. An apparently free request slot can remain unusable when KV capacity is exhausted. Conversely, an empty queue leaves spare capacity no policy can fill.

3. Why Prefill Changes the Latency Trade-off

Prefill processes prompt tokens and builds their KV state. Many prompt positions can run in parallel within a forward pass. After the final prompt position, its logits can be used to sample the first output token. Subsequent decode steps extend the sequence using cached state.

Long prefills often have high arithmetic intensity; small-batch decode often spends much of its time reading weights and KV state. Batch size, context length, architecture and kernel design can change either bottleneck. Decode includes projections, attention and other operations; it is not universally a single GEMV that cannot use Tensor Cores.

If a shared execution pool runs a long prefill before serving existing decode requests, their next token is delayed. Time to first token (TTFT) includes a new request’s queueing and prompt processing up to its first delivered token. Inter-token latency (ITL) measures gaps between successive delivered tokens of an ongoing response. Improving one does not automatically improve the other. Measurements should state whether they are taken at the server or client, since delivery can add delay.

4. Chunked Prefill: Reserve Work, Then Measure Time

SARATHI partitions prefill work into chunks and combines prefill with decode work in its batching design [2]. Chunking provides scheduling boundaries inside a long prompt. It does not make the prompt free or guarantee smooth streaming.

For a small numerical example, set B=10B=10 and reserve three token positions for three ongoing decodes. A 20-token prompt can use the remaining seven positions per iteration:

IterationDecode input tokensPrefill input tokensPrompt tokens still unprocessed
13713
2376
3360

This assumes all three decodes remain active and enough KV memory is available. The prompt reaches its final position in iteration 3, when its first output token can be sampled. The first two chunks do not each produce a user-visible token. Increasing the token budget can finish the prompt sooner, but may lengthen the steps experienced by existing decodes. Token counts alone do not predict milliseconds.

As of 2026-11-25, vLLM’s V1 optimization documentation describes prioritizing decode work and using the remaining max_num_batched_tokens budget for prefills, splitting prefills that do not fit [3]. It distinguishes this token budget from the request limit max_num_seqs. Record the engine version and effective settings; the example above is an arithmetic model, not a recommended production configuration.

Read a Shared Execution Timeline

The following existing timeline uses invented time units. Compare “Unified serving” and “Chunked prefill”: the first existing decode ends at 66 versus 20, while the new prompt’s prefill completes at 60 versus 78. The same amount of prefill work is rearranged. Earlier service for an existing response comes with later completion of the new prompt in this schedule. These are authored timings, not measured TTFT or a prediction for a specific GPU.

P: prefill · D1–D3: existing decodes · KV: state handoff · New: new request decode

Shared pool
P
D1
D2
D3

In this schedule, existing decodes wait for the large prefill.

2026-10-18 · Generation method: hand-authored teaching schedules in invented units. These are not hardware measurements or speedup predictions. Disaggregation also adds a resource pool.

The timeline serializes labeled blocks to explain ordering; it is not a kernel-level depiction of SARATHI’s mixed batch. The “Disaggregated” option introduces another resource pool and a KV handoff, which the disaggregated-serving example in §12.5 examines. It is not an equal-resource speed comparison.

5. Run the Decode-Only Schedule

Deliberately simplified CPU simulation using the Python standard library. It reproduces the first table with FIFO admission and fixed remaining decode lengths. All requests arrive before execution and are treated as decode-ready. It omits prefill, real token sampling/EOS, KV allocation, token budgets, cancellation, priority/fairness, concurrency and GPU timing. It does not simulate serving latency or claim production readiness.

from collections import deque


def schedule(requests, capacity=3, continuous=True):
    """Decode-only FIFO model; requests are (ID, remaining_decode_tokens)."""
    waiting = deque(requests)
    if type(capacity) is not int or capacity <= 0:
        raise ValueError("capacity must be a positive integer")
    if any(type(length) is not int or length <= 0 for _, length in waiting):
        raise ValueError("decode lengths must be positive integers")
    if len({name for name, _ in waiting}) != len(waiting):
        raise ValueError("request IDs must be unique")
    active = [None] * capacity
    trace, finished = [], {}
    while waiting or any(request is not None for request in active):
        # A static group admits replacements only when its survivors are gone.
        if continuous or all(request is None for request in active):
            for slot in range(capacity):
                if active[slot] is None and waiting:
                    name, length = waiting.popleft()
                    active[slot] = [name, length]
        iteration = len(trace) + 1
        trace.append(tuple(request[0] if request else "-" for request in active))
        for slot, request in enumerate(active):
            if request is not None:
                request[1] -= 1  # one decode token for this active request
                if request[1] == 0:
                    finished[request[0]] = iteration
                    active[slot] = None  # reusable at the next boundary
    return trace, finished


requests = [("A", 4), ("B", 2), ("C", 6), ("D", 3), ("E", 5), ("F", 2)]
static, static_end = schedule(requests, continuous=False)
continuous, continuous_end = schedule(requests, continuous=True)
assert (len(static), len(continuous)) == (11, 9)
assert static_end == {"A": 4, "B": 2, "C": 6, "D": 9, "E": 11, "F": 8}
assert continuous_end == {"A": 4, "B": 2, "C": 6, "D": 5, "E": 9, "F": 7}
assert static[2] == ("A", "-", "C")
assert continuous[2] == ("A", "D", "C")
print(f"static={len(static)}, continuous={len(continuous)} iterations")
for iteration, slots in enumerate(continuous, start=1):
    print(iteration, " ".join(slots))

Expected output:

static=11, continuous=9 iterations
1 A B C
2 A B C
3 A D C
4 A D C
5 E D C
6 E F C
7 E F -
8 E - -
9 E - -

The completion assertions distinguish the admission policies, and the loop stops as soon as the final request finishes. There is no extra empty “GPU iteration.” Empty input returns an empty trace; zero capacity and nonpositive decode lengths are rejected. Change a remaining length or capacity, then explain which request can enter sooner before running it again.

6. Validate a Scheduler on the Workload You Serve

Replay a representative arrival trace with prompt/output lengths and burst patterns preserved. Hold the model, hardware, precision and quality settings fixed. Compare throughput within the declared latency budget, alongside TTFT and ITL distributions, queue time, KV occupancy, preemptions, cancellations and errors. Split long and short prompts and low and high load; a good average can hide starvation or tail-latency failures.

Save the request trace identifier, model/runtime versions, scheduler configuration and admission limits with the results. Reject a change that exceeds a predeclared tail-latency or error threshold, even if tokens per second rises. Keep the previous configuration available for rollback. Section 12.4 on speculative decoding studies another way to change work per iteration: verifying several candidate tokens together.

Quizzes

Quiz 1: B finishes at iteration 2. When does D first run under the two policies? At iteration 3 under continuous admission, after B’s slot is released. Under the defined static policy, D waits until A, B and C have all finished at iteration 6, then starts at 7. The difference is admission timing; static admission does not inherently forbid releasing B’s memory.

Quiz 2: Why do 9 versus 11 iterations not prove the same wall-clock speedup? Iterations can differ in batch composition, context lengths and execution time. The example excludes prefill, KV limits and scheduler costs. Measure matched workloads; occupied slots are not a GPU-utilization measurement.

Quiz 3: With a ten-token budget and three ongoing decodes, how is a 20-token prompt processed? Under the stated policy it receives 7, 7 and 6 prefill positions over three iterations. Its first output token can be sampled when the final prompt position is processed. Seven available input positions do not mean only seven KV positions are needed: prior context remains stored.

Quiz 4: Can a smaller prefill chunk improve ITL while worsening TTFT? Yes. It can reduce the work placed ahead of an existing response’s next decode, but the new prompt may require more scheduled chunks or wait longer for its share. The effect depends on load and kernels; both latency distributions must be measured.

Quiz 5: Why can a continuous batch still have an empty slot while requests are waiting? Token or KV capacity may be exhausted, or admission priorities may defer the waiting work. A request-count slot is only one constraint. When the queue itself empties, no scheduler can keep every slot occupied.

References

  1. Yu, G.-I., Jeong, J. S., Kim, G.-W., Kim, S., & Chun, B.-G. (2022). Orca: A Distributed Serving System for Transformer-Based Generative Models. OSDI 2022.
  2. Agrawal, A., Panwar, A., Mohan, J., Kwatra, N., Gulavani, B. S., & Ramjee, R. (2023). SARATHI: Efficient LLM Inference by Piggybacking Decodes with Chunked Prefills. arXiv:2308.16369.
  3. vLLM contributors. Optimization and Tuning: Chunked Prefill. Documentation checked 2026-11-25. Official documentation.