If you come from traditional deep learning, your mental model of batching is straightforward. You gather $N$ inputs, pad them with zeros so their dimensions match, pack them into a tensor, and push that tensor through your model in a single forward pass.
When developers first stand up an inference server for a large language model using that approach, throughput drops off a cliff.
Generative language models do not work like ResNet or BERT. In an LLM, requests arrive asynchronously. One user sends a 50-word prompt and wants a 10-word reply. Another user uploads a 3,000-word documentation file and asks for an 800-word summary.
If you group those two requests into a classic static batch, two things go wrong immediately:
<pad> tokens so the matrix dimensions line up.
Modern inference engines like vLLM, TensorRT-LLM, and TGI achieve 10x to 20x higher throughput because they throw static batching out the window. They use an architecture called Continuous Batching (originally introduced as iteration-level scheduling by the Orca paper at OSDI 2022).
Here is the exact mechanical breakdown of what happens inside the engine when 100 requests hit your server at once.
In a framework like PyTorch, a batch is usually a concrete Python object: a tensor with shape (batch_size, seq_len, hidden_dim).
In modern LLM engines, no persistent batch object exists.
Inside the scheduler loop of vLLM V1, a batch is simply a transient calculation made right before each GPU forward pass. What actually persists in memory are two queues and a collection of cursors:
waiting: A FIFO queue of new requests that have arrived but have not yet executed on the GPU.running: A list of active requests currently generating tokens. num_computed_tokens: A per-request cursor tracking how many tokens the model has processed into the Key-Value (KV) cache.
Every time the engine loop spins, the scheduler asks a specific question: which requests get to advance right now, and by how many tokens?
Its central ledger is a dictionary:
num_scheduled_tokens: dict[str, int] = {req_id: count}
If a request is actively generating text, count is 1. If a request is running a chunked prompt, count might be 512. If a request is blocked waiting for memory, count is 0.
The batch exists only for the duration of a single forward pass kernel execution. The moment the forward pass finishes, the scheduler recomputes membership from scratch.
Static batching schedules work at the request level: a batch is formed when requests enter, and it disbands only when every request finishes.
Continuous batching schedules work at the iteration level: scheduling happens between individual token generation steps.
Mathematically, if $\mathcal{B}_s$ is the set of requests running in step $s$:
$$\mathcal{B}_{s+1} = (\mathcal{B}_s \setminus \mathcal{F}_s) \cup \mathcal{A}_s$$
Where:
<eos> token or hit their max token limit. Their completed text is streamed immediately to the user via Server-Sent Events (SSE), and their KV cache memory is freed.
Step s: [ Req 1 (gen 9/10) ] [ Req 2 (gen 44/500) ] [ Req 3 (gen 120/120 - EOS) ]
|
EVICTED & FREED
|
Step s+1: [ Req 1 (gen 10/10) ] [ Req 2 (gen 45/500) ] [ Req 4 (Prompt Chunk 1) ]
Because the scheduler regains control after every token, a sequence that finishes is evicted within 15 milliseconds. Its slot and its memory pages are immediately assigned to a waiting request. No slot sits idle.
To understand why continuous batching gets complicated in production, you have to look at the hardware reality of GPU execution. An LLM performs two completely different computational workloads during its lifetime.
When a request first arrives, the model must read the entire prompt and compute initial KV tensors for all prompt tokens.
Once the prompt is ingested, the model generates one new token per step. To generate token $T+1$, it reads token $T$ and attends to all previous KV pairs.
| Metric | Prefill Phase | Decode Phase |
|---|---|---|
| Input Size | Entire prompt ($N$ tokens) | 1 token per sequence |
| BLAS Operation | GEMM (Matrix-Matrix) | GEMV (Matrix-Vector) |
| Bottleneck | Compute (Tensor Cores) | Memory Bandwidth (HBM) |
| Arithmetic Intensity | High ($O(\text{prompt_length})$) | Low ($\approx 1$ FLOP / byte) |
| Latency Metric | Time to First Token (TTFT) | Inter-Token Latency (ITL) |
In naive continuous batching, when an engine batches running decodes together with a fresh 4,000-token prefill, a major problem arises: the prefill bubble.
Suppose your engine is currently running decode loops for 32 active users. Each token generation step takes 25 milliseconds. The users see smooth streaming text at 40 tokens per second.
Suddenly, User 33 submits a prompt containing a 6,000-token system prompt and legal document.
If the engine runs that entire 6,000-token prefill in the next forward pass, compute time spikes. Instead of taking 25ms, that single forward pass takes 650ms.
For the 32 decoding users, their text stream freezes for two-thirds of a second. This phenomenon is an Inter-Token Latency (ITL) spike. In high-concurrency systems, back-to-back long prefills completely destroy the interactive experience for existing users.
To solve the prefill bubble, modern engines like vLLM and TensorRT-LLM introduce Chunked Prefill (based on research from Sarathi and Split-Fuse).
Instead of treating a prompt as an indivisible block of work, the scheduler establishes a global token budget per iteration, governed by the configuration parameter max_num_batched_tokens (typically set to 2,048 or 4,096 tokens).
During every scheduling step, the engine fills the token budget using a strict two-stage process:
1 token allocated from the budget. If you have 64 running sequences, 64 tokens are deducted from your budget.token_budget = max_batched_tokens - 64) is allocated to pending requests in the If a new request arrives with a 3,000-token prompt, but the remaining token budget is only 1,500 tokens, the scheduler does not reject or postpone the request. It slices it:
num_new_tokens = min(remaining_prompt_tokens, token_budget)
In this iteration, the model computes the first 1,500 tokens of the prompt and writes their key-value pairs into physical KV cache blocks. The request is immediately added to the running queue with a flag is_prefill_chunk = True.
In the next iteration, the remaining 1,500 prompt tokens are scheduled. Only after the final chunk finishes does the request transition to autoregressive token generation.
Token Budget: 2048 tokens
Running Decodes: 48 tokens (48 active users)
Remaining Budget: 2000 tokens
Incoming Request (3500 tokens):
Iteration 1: [ 48 Decode Tokens ] + [ 2000 Tokens of Prompt A (Chunk 1) ]
Iteration 2: [ 48 Decode Tokens ] + [ 1500 Tokens of Prompt A (Chunk 2) ] + [ 452 Tokens of Prompt B ]
Iteration 3: [ 49 Decode Tokens (including Prompt A's first generated token) ]
Chunked prefill does more than protect decode latency; it actually makes the GPU run faster overall.
Because the decode phase is memory-bandwidth bound and tensor cores sit idle waiting for weights to transfer from HBM, piggybacking a 512-token or 1,024-token prefill chunk onto those decodes utilizes the idle compute cores.
The GPU loads the model weights once, executes the memory-bound decodes, and simultaneously feeds the compute-bound prefill chunk through the tensor cores. You get free prompt processing without degrading decode latency.
Allocating tokens in the scheduler is only half the battle. A request cannot run unless physical GPU memory exists to store its attention keys and values.
This is where continuous batching links directly with PagedAttention.
In naive systems, engines pre-allocated contiguous memory for the worst-case maximum sequence length (e.g. 4,096 tokens). If a user only generated 50 tokens, the remaining 4,046 slots sat completely wasted.
Under PagedAttention, GPU VRAM is partitioned into fixed-size physical blocks (typically 16 or 32 tokens per block).
Before the scheduler commits any token allocation (whether a 1-token decode or a 512-token prefill chunk), it calls:
can_allocate = kv_cache_manager.allocate_slots(request, num_scheduled_tokens)
The behavior differs between queues:
allocate_slots returns None (meaning the GPU memory watermark is reached), the scheduler executes a clean break. New requests wait safely in the queue outside the GPU.
When active requests demand more memory blocks than physically exist in VRAM, the engine invokes preemption:
WAITING. When memory clears up later, the engine simply re-prefills its prompt and continues.
Because continuous batching manages memory in tiny discrete blocks rather than large monolithic buffers, preemptions are rare under normal load.
When configuring an engine like vLLM for high-concurrency production workloads, three scheduler settings dictate system performance:
--max-num-seqs (Maximum Active Sequences)
This controls the maximum number of requests that can be in the running state simultaneously.
--max-num-batched-tokens (Iteration Token Budget)
This is the total token cap (decodes + prefill chunks) permitted in a single forward pass.
--enable-chunked-prefill
In vLLM V1, chunked prefill is enabled by default. If you run custom pipelines or older engine versions, ensure this flag is explicitly enabled. Without it, long prompts will cause periodic 500ms+ stutter in all concurrent active streams.
When you send a request to a modern LLM cluster:
Continuous batching turns an unpredictable, variable-length text generation pipeline into a predictable, high-throughput streaming assembly line.