AI Infrastructure

Continuous Batching

Continuous batching (also called iteration-level scheduling or in-flight batching) is an LLM serving technique where the scheduler rebuilds the batch after every decoding step, so finished requests leave immediately and waiting requests join mid-flight instead of everyone waiting for the longest sequence in a fixed batch. It is the default scheduling strategy in vLLM, SGLang, TensorRT-LLM, and Hugging Face Transformers.

Continuous batching is the scheduling trick that makes it economical to serve a large language model to many users at once. Instead of grouping requests into a fixed batch and running that batch until its longest response is done, a continuously batching server re-forms the batch at every decoding step: a request that just emitted its end-of-sequence token leaves right away, and a request that just arrived takes its seat on the very next step. Because LLM responses vary wildly in length (a one-word answer and a 2,000-token essay can arrive in the same second), this single change is the difference between a GPU that spends most of its time computing padding and one that is almost always doing useful work. It is why every serious inference engine, from vLLM to SGLang, TensorRT-LLM, and now Hugging Face Transformers itself, uses it by default.

You will also see it called iteration-level scheduling (the name used in the Orca paper that introduced it), in-flight batching (NVIDIA’s term in TensorRT-LLM), or dynamic batching in looser usage, although that last name usually refers to a weaker, request-level technique covered below.

Why ordinary batching wastes the GPU

Generating text with a transformer happens in two phases. Prefill processes the whole prompt in one parallel forward pass and fills the KV cache. Decode then produces one token per forward pass, each step reading every weight in the model just to emit a single token per sequence. A single decode step for one user is badly memory-bandwidth-bound: the GPU streams tens of gigabytes of weights to do a sliver of arithmetic. Batching fixes that by letting one pass over the weights serve many sequences at once, so the cost of moving weights is shared.

The naive way to batch is static batching: collect B requests, pad them to the same length, and call generate() on the group. The batch finishes only when its longest member finishes. Every sequence that ended early keeps occupying its slot, computing padding tokens that are thrown away, and every new request that arrived in the meantime waits in a queue until the whole batch drains.

# Scenario: an offline job that summarizes support tickets in fixed groups of 8.
# This is static batching: generate() returns only when ALL 8 are done.
from transformers import AutoTokenizer, AutoModelForCausalLM

tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B", padding_side="left")
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-4B", device_map="auto")

tickets = load_tickets()            # list[str], hundreds of them
for i in range(0, len(tickets), 8):
    group = tickets[i : i + 8]
    inputs = tok(group, return_tensors="pt", padding=True).to(model.device)
    # If one ticket needs a 400-token summary and seven need 40,
    # those seven slots sit idle for ~360 steps.
    out = model.generate(**inputs, max_new_tokens=400)
    save(tok.batch_decode(out, skip_special_tokens=True))

Two costs compound here. Utilization: the fraction of slot-steps doing real work drops as the spread of output lengths grows. Latency: a short request that lands in a batch with a long one pays the long one’s latency, and a request arriving just after a batch starts waits for the entire batch before it can even begin. Anyscale’s benchmark illustrated the scale of the problem: serving OPT-13B on a single A100, continuous batching in vLLM delivered up to 23x the throughput of naive Hugging Face serving while also lowering median latency, with the caveat that the measurement includes PagedAttention’s memory savings, not batching alone.

How continuous batching works

The idea comes from Orca (Yu et al., OSDI 2022). Its insight was that a generative model’s natural unit of work is not the request but the iteration: one forward pass that advances every active sequence by one token. If the scheduler makes its decisions at that granularity, a newly arrived request only has to wait for a single iteration before it can be considered, and a finished one can be evicted the moment it emits its stop token. Orca reported up to 36.9x throughput over NVIDIA FasterTransformer on GPT-3 175B at the same latency.

flowchart LR
    Q[Waiting queue]:::data --> S{Scheduler<br/>every step}:::process
    S -->|admit if slot + KV memory free| B[Running batch]:::default
    B --> F[One forward pass<br/>+1 token per sequence]:::process
    F --> C{Sequence hit EOS<br/>or max tokens?}:::process
    C -->|yes| R[Return response,<br/>free slot and KV blocks]:::output
    C -->|no| B
    R --> S
    classDef default fill:#ffffff,stroke:#4338CA,stroke-width:2px,color:#0F172A,rx:8px,ry:8px;
    classDef data    fill:#EEF0F7,stroke:#0D9488,stroke-width:2px,color:#0F172A,rx:8px,ry:8px;
    classDef process fill:#F7F8FC,stroke:#6366F1,stroke-width:2px,color:#0F172A,rx:8px,ry:8px;
    classDef output  fill:#4338CA,stroke:#4338CA,stroke-width:2px,color:#ffffff,rx:8px,ry:8px;

There is one obvious objection: sequences in the same step are at different positions with different context lengths, so how can they share one forward pass? Orca’s answer was selective batching. Most of a transformer layer (the QKV projections, the MLP, layer norms) operates token by token, so tokens from different sequences can simply be concatenated into one flat tensor and pushed through those matmuls together. Only attention needs to know which tokens belong to which sequence, so attention is computed per sequence (today, by a varlen or paged attention kernel that takes a list of sequence boundaries). This “flatten everything, split only for attention” layout is still how modern engines build a step.

Stripped of memory management and kernels, the scheduler loop looks like this:

# Scenario: the core loop of a toy inference server, showing iteration-level
# scheduling. model.step() runs ONE forward pass over the flattened batch.
from collections import deque

waiting: deque[Request] = deque()   # filled by the HTTP handler as users arrive
running: list[Request] = []
MAX_SEQS = 64

while True:
    # 1. Admit new requests into free slots BEFORE this step, not after a batch ends.
    while waiting and len(running) < MAX_SEQS and kv_pool.can_fit(waiting[0]):
        req = waiting.popleft()
        kv_pool.allocate(req)
        running.append(req)          # its prompt is prefilled inside this step

    if not running:
        wait_for_new_requests(); continue

    # 2. One forward pass: prefill tokens for new arrivals + 1 decode token for the rest.
    next_tokens = model.step(running)

    # 3. Evict finished sequences immediately; their slots are reusable next step.
    still_running = []
    for req, tok in zip(running, next_tokens):
        req.output.append(tok)
        if tok == EOS or len(req.output) >= req.max_tokens:
            req.respond()            # stream/return to the user right now
            kv_pool.free(req)
        else:
            still_running.append(req)
    running = still_running

Static, dynamic, and continuous batching compared

Static batchingDynamic (request-level) batchingContinuous batching
When the batch is formedFixed group, chosen up frontWhen B requests arrive or a timeout firesRe-formed at every decoding step
When a short request returnsWhen the longest in its batch finishesWhen the longest in its batch finishesAs soon as it emits its own stop token
When a new request can startAfter the current batch drainsAfter the current batch drainsOn the next step (one iteration of wait)
Padding wasteHigh, grows with length varianceHigh, grows with length varianceNear zero
Typical homeOffline scripts, model.generate()Classic model servers (e.g. Triton dynamic batcher for non-generative models)vLLM, SGLang, TensorRT-LLM, TGI, Transformers generate_batch

Dynamic batching fixes the arrival side (you no longer wait to collect a full batch by hand) but not the departure side, which is where generative workloads bleed most of their capacity.

Interactive: static vs. continuous batching

The widget below replays the same 20 requests through both schedulers. Each colored bar is one request occupying a slot for as many decode steps as its response needs; striped gray is a slot that is held but doing nothing useful (padding in static batching). The two knobs are the ones that matter most in practice: how many slots the server runs in parallel, and how uneven the response lengths are.

Interactive: watch idle slots appear and disappear

Simplified model: 20 requests queued at t = 0, each needing a fixed number of decode steps; prefill cost is ignored. Drag length variance up and watch static batching's striped waste grow while continuous batching stays packed, then change the slot count to see how the gap scales.

With variance at zero every request is the same length, so the two schedules are identical: continuous batching has nothing to recover. The gap opens as soon as lengths diverge, which is the normal state of any chat or agent workload. Notice also that mean latency improves even more than total time, because short requests no longer wait for long batch-mates.

The memory side: why PagedAttention made it practical

Scheduling is only half the problem. Every running sequence needs its own KV cache, and that cache grows by one entry per layer per generated token. Early servers reserved a contiguous chunk of memory sized for the maximum possible length of each request, so most of the reserved space sat empty and fragmented, capping how many sequences could be in the batch at once. Continuous batching wants the batch to be as large as memory allows, so wasted KV memory directly limits its benefit.

PagedAttention (Kwon et al., the paper that introduced vLLM) solved this by storing the KV cache in fixed-size blocks allocated on demand, like virtual memory pages, with a per-sequence block table telling the attention kernel where each block lives. A sequence takes exactly the blocks it needs, freed blocks go straight back to the pool, and the scheduler’s admission test becomes simply “are there enough free blocks?”. The vLLM paper reports 2 to 4x higher throughput than prior state-of-the-art systems at the same latency. Since then, block-level KV management and continuous batching have been effectively inseparable: prefix caching and SGLang’s RadixAttention both build on the same block pool so that requests sharing a system prompt can share blocks too.

When memory does run out mid-generation (sequences grow, and the scheduler admitted them optimistically), the engine preempts some requests: it frees their blocks and later either swaps them back from CPU memory or recomputes them from scratch. vLLM V1 defaults to recomputation. Frequent preemption is the signal that your batch limits are set too high for your memory.

Prefill and decode in the same step: chunked prefill and the token budget

Continuous batching introduces a new tension. When a request joins, its whole prompt has to be prefilled, and a 30,000-token prompt is an enormous forward pass. If the scheduler runs that prefill as one step, every decoding user in the batch freezes until it finishes, a hiccup the Sarathi-Serve authors call a generation stall. If it postpones the prefill until the batch quiets down, the new user’s time to first token (TTFT) balloons.

Chunked prefill, from Sarathi-Serve (Agrawal et al., OSDI 2024), splits long prompts into fixed-size chunks and mixes one chunk into each step alongside the ongoing decodes, a scheme the paper calls stall-free scheduling. Each step then has a predictable cost, bounded by a token budget: the maximum number of tokens (prefill chunk tokens plus one per decoding sequence) processed in a single forward pass. Sarathi-Serve reported up to 2.6x higher serving capacity for Mistral-7B and 2.8x for Yi-34B under latency SLOs.

# Scenario: a RAG assistant where some users paste 20-page documents while others
# are mid-conversation. We want chats to keep streaming smoothly while long
# prompts are ingested in the background, chunk by chunk.
from vllm import LLM, SamplingParams

llm = LLM(
    model="Qwen/Qwen3-8B",
    max_num_seqs=128,            # cap on concurrent sequences in a step
    max_num_batched_tokens=2048, # small budget: smoother inter-token latency for chatters,
                                 # long prompts get chunked across more steps (slower TTFT)
    enable_chunked_prefill=True, # already the default in vLLM V1; shown for clarity
)

prompts = [long_doc_question] + short_chat_turns     # mixed workload
outs = llm.generate(prompts, SamplingParams(max_tokens=256))
for o in outs:
    print(o.outputs[0].text[:80])

vLLM’s tuning guide states the trade-off plainly: smaller max_num_batched_tokens values (for example 2048) give better inter-token latency because fewer prefill tokens slow down each decode step, while larger values give better time to first token because more of each prompt is processed per step; for raw throughput, especially with smaller models on large GPUs, the docs recommend going above 8192. The same knobs exist under different names in every engine:

EngineMax concurrent sequencesPer-step token budgetNotes
vLLM (V1)--max-num-seqs--max-num-batched-tokensChunked prefill always on when possible; decodes scheduled first
SGLang--max-running-requests--chunked-prefill-sizePaired with RadixAttention prefix sharing
HF Transformersmax_requests_per_batchmax_batch_tokens (default 8192)Set via ContinuousBatchingConfig; FIFO or prefill_first scheduler
TensorRT-LLMmax_batch_sizemax_num_tokensCalled “in-flight batching”

Taken to its logical end, the prefill/decode tension leads to prefill-decode disaggregation: instead of interleaving the two phases on one GPU pool, run them on separate pools and ship the KV cache between them. Disaggregation does not replace continuous batching, though; each pool still continuously batches its own phase.

Using continuous batching in practice

If you serve through vLLM, SGLang, TensorRT-LLM, or TGI, continuous batching is already on; your job is to send requests concurrently so the scheduler has something to pack, and to set the limits above. The most common mistake is a client that sends requests one at a time in a loop, which leaves a continuously batching server running a batch of one.

The Transformers v5 line also ships continuous batching natively, which is handy for offline evaluation and data generation without standing up a server:

# Scenario: generating 5,000 synthetic Q&A pairs for an eval set on one GPU.
# generate_batch() runs a continuous-batching scheduler with a paged KV cache.
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
from transformers.generation import ContinuousBatchingConfig

model_id = "Qwen/Qwen3-4B"
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, attn_implementation="flash_attention_2", dtype=torch.bfloat16, device_map="cuda"
)

prompts = [f"Write one tricky question about topic #{i} and answer it." for i in range(5000)]
inputs = [tok.encode(p) for p in prompts]          # token id lists, no padding needed

gen_cfg = GenerationConfig(max_new_tokens=256, do_sample=False, eos_token_id=tok.eos_token_id)
cb_cfg = ContinuousBatchingConfig(max_batch_tokens=16384, scheduler_type="fifo")

outputs = model.generate_batch(
    inputs=inputs, generation_config=gen_cfg, continuous_batching_config=cb_cfg
)
for req_id, out in list(outputs.items())[:3]:      # results keyed by request id
    print(req_id, tok.decode(out.generated_tokens, skip_special_tokens=True)[:80])

To check that your deployment is actually benefiting, load-test with realistic concurrency and length variance rather than one prompt repeated:

# Scenario: before launch, measure TTFT and throughput at increasing concurrency
# against an OpenAI-compatible endpoint (vLLM / SGLang / TGI all expose one).
import asyncio, time
from openai import AsyncOpenAI

client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")

async def one(prompt: str, max_tokens: int):
    t0 = time.perf_counter(); ttft = None; n = 0
    stream = await client.chat.completions.create(
        model="Qwen/Qwen3-8B", messages=[{"role": "user", "content": prompt}],
        max_tokens=max_tokens, stream=True,
    )
    async for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            ttft = ttft or time.perf_counter() - t0
            n += 1
    return ttft, n

async def run(concurrency: int):
    t0 = time.perf_counter()
    jobs = [one(f"Explain concept {i} briefly.", 50 + (i * 37) % 400) for i in range(concurrency)]
    res = await asyncio.gather(*jobs)
    wall = time.perf_counter() - t0
    toks = sum(n for _, n in res)
    p50_ttft = sorted(t for t, _ in res)[len(res) // 2]
    print(f"c={concurrency:4d}  tokens/s={toks / wall:8.1f}  p50 TTFT={p50_ttft:.2f}s")

for c in (1, 8, 32, 128):
    asyncio.run(run(c))

Throughput should climb steeply with concurrency until you hit the memory or max-num-seqs ceiling, then flatten while TTFT starts to rise; that knee is your practical capacity per replica.

What’s New (2025–2026)

  • vLLM V1 made the token budget the core abstraction. The V1 scheduler no longer distinguishes “prefill steps” from “decode steps”; it hands each request a share of a fixed per-step token budget, so chunked prefill, prefix caching, and speculative decoding all fit into one continuous-batching loop. Chunked prefill is enabled by default whenever possible, and pending decodes are scheduled before any prefill work.
  • Continuous batching moved into Hugging Face Transformers itself. The v5 line ships generate_batch(), a persistent ContinuousBatchingManager, and a ContinuousBatchingConfig with a paged KV pool, FIFO and prefill_first schedulers, prefix caching (on by default for full-attention models), CUDA graphs, and async batching that overlaps CPU batch preparation with GPU compute. transformers serve builds on the same manager to expose an OpenAI-compatible endpoint.
  • Scheduling policy is getting its own research line. A 2026 study (arXiv:2610.15899) built a continuous-batching testbench on Hugging Face models and compared eight lightweight scheduling policies across 1,152 GPU, model, scheduler, and workload combinations using ShareGPT-derived traffic, asking how much of the latency-throughput frontier can be won by smarter admission and ordering rules alone, without new kernels or learned schedulers.
  • Frontier open-weight releases now ship with batching limits in their serving recipes. Mistral Large 4’s model card, for example, sets SGLang’s --max-running-requests 64 (default 48 if omitted) and tells users short on GPU memory to lower --max-num-seqs in vLLM: a reminder that on a 1-trillion-parameter model, the KV cache left over after loading weights is what decides how many users one node can continuously batch.
  • Disaggregated serving became mainstream at large scale, splitting prefill and decode across pools (prefill-decode disaggregation) while keeping continuous batching inside each pool.

Limits and when it matters less

Continuous batching is close to free, but it is not magic. It does nothing for a single user at a time, where batch size is one regardless of scheduler; for that, look at speculative decoding and quantization. Its gains shrink when outputs are uniform in length (classification, fixed-length extraction), which the widget’s zero-variance setting shows. Larger batches raise throughput but also raise per-token latency, because each step does more work, so latency-sensitive products cap batch size deliberately. And because admission is limited by free KV memory, long-context workloads can starve the batch: a handful of 500K-token sessions can consume the cache that would otherwise hold hundreds of short chats, which is why KV cache optimization techniques (quantized caches, MLA, sliding windows) translate directly into bigger continuous batches and lower cost per token.

How to Use: Serve a model with continuous batching in vLLM and tune its two main knobs

python
# Scenario: a team chatbot that gets bursts of 50+ concurrent users.
# vLLM always uses continuous batching; you tune how big each step can get.
#
# Shell:
#   vllm serve Qwen/Qwen3-8B \
#     --max-num-seqs 128 \             # max requests in one decode step
#     --max-num-batched-tokens 8192 \  # token budget per step (prefill + decode)
#     --gpu-memory-utilization 0.90    # how much VRAM the KV cache pool may take

import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")

async def ask(i: int) -> str:
    r = await client.chat.completions.create(
        model="Qwen/Qwen3-8B",
        messages=[{"role": "user", "content": f"Give me tip #{i} for writing SQL."}],
        max_tokens=64 + 32 * (i % 6),   # deliberately uneven output lengths
    )
    return r.choices[0].message.content

async def main():
    # 64 requests in flight at once: the server's scheduler slots each one
    # into the running batch the moment a slot frees up.
    answers = await asyncio.gather(*(ask(i) for i in range(64)))
    print(len(answers), "answers")

asyncio.run(main())

Ready to build?

Leverage AI technologies to build your product stack

Superteams can help you build, deploy and launch AI application stacks using open source technologies — from architecture through to production.

Talk to Superteams