{"slug": "continuous-batching-under-the-hood-what-actually-happens-inside-vllm-when-100-at", "title": "Continuous Batching Under the Hood: What Actually Happens Inside vLLM When 100 Requests Hit at Once", "summary": "A developer published a technical breakdown of how vLLM's V1 scheduler implements continuous batching, explaining that no persistent batch object exists inside modern LLM inference engines—instead, a scheduler recomputes batch membership between every token-generation step using waiting and running queues plus per-request num_computed_tokens cursors. The writeup traces how finished sequences are evicted and their KV cache memory reassigned to waiting requests within roughly 15 milliseconds, and contrasts iteration-level scheduling (from the Orca paper at OSDI 2022) with static request-level batching.", "body_md": "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.\n\nWhen developers first stand up an inference server for a large language model using that approach, throughput drops off a cliff.\n\nGenerative 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.\n\nIf you group those two requests into a classic static batch, two things go wrong immediately:\n\n`<pad>` tokens so the matrix dimensions line up.\nModern 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).\n\nHere is the exact mechanical breakdown of what happens inside the engine when 100 requests hit your server at once.\n\nIn a framework like PyTorch, a batch is usually a concrete Python object: a tensor with shape `(batch_size, seq_len, hidden_dim)`.\n\nIn modern LLM engines, **no persistent batch object exists**.\n\nInside 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:\n\n`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.\nEvery time the engine loop spins, the scheduler asks a specific question: *which requests get to advance right now, and by how many tokens?*\n\nIts central ledger is a dictionary:\n\n```\nnum_scheduled_tokens: dict[str, int] = {req_id: count}\n```\n\nIf 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`.\n\nThe 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.\n\nStatic batching schedules work at the **request level**: a batch is formed when requests enter, and it disbands only when every request finishes.\n\nContinuous batching schedules work at the **iteration level**: scheduling happens between individual token generation steps.\n\nMathematically, if $\\mathcal{B}_s$ is the set of requests running in step $s$:\n\n$$\\mathcal{B}_{s+1} = (\\mathcal{B}_s \\setminus \\mathcal{F}_s) \\cup \\mathcal{A}_s$$\n\nWhere:\n\n`<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.\n\n```\nStep s:   [ Req 1 (gen 9/10) ]  [ Req 2 (gen 44/500) ]  [ Req 3 (gen 120/120 - EOS) ]\n                                                                      |\n                                                                EVICTED & FREED\n                                                                      |\nStep s+1: [ Req 1 (gen 10/10) ] [ Req 2 (gen 45/500) ]  [ Req 4 (Prompt Chunk 1) ]\n```\n\nBecause 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.\n\nTo 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.\n\nWhen a request first arrives, the model must read the entire prompt and compute initial KV tensors for all prompt tokens.\n\nOnce 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.\n\n| Metric | Prefill Phase | Decode Phase | \n|---|---|---|\n| **Input Size** | Entire prompt ($N$ tokens) | 1 token per sequence | \n| **BLAS Operation** | GEMM (Matrix-Matrix) | GEMV (Matrix-Vector) | \n| **Bottleneck** | Compute (Tensor Cores) | Memory Bandwidth (HBM) | \n| **Arithmetic Intensity** | High ($O(\\text{prompt_length})$) | Low ($\\approx 1$ FLOP / byte) | \n| **Latency Metric** | Time to First Token (TTFT) | Inter-Token Latency (ITL) | \n\nIn naive continuous batching, when an engine batches running decodes together with a fresh 4,000-token prefill, a major problem arises: **the prefill bubble**.\n\nSuppose 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.\n\nSuddenly, User 33 submits a prompt containing a 6,000-token system prompt and legal document.\n\nIf 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.\n\nFor 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.\n\nTo solve the prefill bubble, modern engines like vLLM and TensorRT-LLM introduce **Chunked Prefill** (based on research from Sarathi and Split-Fuse).\n\nInstead 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).\n\nDuring every scheduling step, the engine fills the token budget using a strict two-stage process:\n\n`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:\n\n```\nnum_new_tokens = min(remaining_prompt_tokens, token_budget)\n```\n\nIn 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`.\n\nIn 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.\n\n```\nToken Budget: 2048 tokens\nRunning Decodes: 48 tokens (48 active users)\nRemaining Budget: 2000 tokens\n\nIncoming Request (3500 tokens):\nIteration 1:  [ 48 Decode Tokens ] + [ 2000 Tokens of Prompt A (Chunk 1) ]\nIteration 2:  [ 48 Decode Tokens ] + [ 1500 Tokens of Prompt A (Chunk 2) ] + [ 452 Tokens of Prompt B ]\nIteration 3:  [ 49 Decode Tokens (including Prompt A's first generated token) ]\n```\n\nChunked prefill does more than protect decode latency; it actually makes the GPU run faster overall.\n\nBecause 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.\n\nThe 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.\n\nAllocating 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.\n\nThis is where continuous batching links directly with **PagedAttention**.\n\nIn 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.\n\nUnder PagedAttention, GPU VRAM is partitioned into fixed-size physical blocks (typically 16 or 32 tokens per block).\n\nBefore the scheduler commits any token allocation (whether a 1-token decode or a 512-token prefill chunk), it calls:\n\n```\ncan_allocate = kv_cache_manager.allocate_slots(request, num_scheduled_tokens)\n```\n\nThe behavior differs between queues:\n\n`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.\nWhen active requests demand more memory blocks than physically exist in VRAM, the engine invokes **preemption**:\n\n`WAITING`. When memory clears up later, the engine simply re-prefills its prompt and continues.\nBecause continuous batching manages memory in tiny discrete blocks rather than large monolithic buffers, preemptions are rare under normal load.\n\nWhen configuring an engine like vLLM for high-concurrency production workloads, three scheduler settings dictate system performance:\n\n`--max-num-seqs` (Maximum Active Sequences)\nThis controls the maximum number of requests that can be in the `running` state simultaneously.\n\n`--max-num-batched-tokens` (Iteration Token Budget)\nThis is the total token cap (decodes + prefill chunks) permitted in a single forward pass.\n\n`--enable-chunked-prefill`\nIn 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.\n\nWhen you send a request to a modern LLM cluster:\n\nContinuous batching turns an unpredictable, variable-length text generation pipeline into a predictable, high-throughput streaming assembly line.", "url": "https://wpnews.pro/news/continuous-batching-under-the-hood-what-actually-happens-inside-vllm-when-100-at", "canonical_source": "https://dev.to/syed_anzar/continuous-batching-under-the-hood-what-actually-happens-inside-vllm-when-100-requests-hit-at-once-476e", "published_at": "2026-11-29 08:38:39+00:00", "updated_at": "2026-11-29 08:43:45.373405+00:00", "lang": "en", "topics": ["ai-infrastructure", "large-language-models", "machine-learning", "ai-tools"], "entities": ["vLLM", "TensorRT-LLM", "TGI", "PyTorch", "Orca", "OSDI 2022"], "also_reported_by": [], "takeaway": "Continuous batching schedules at the iteration level, recomputing the running set after every token so finished sequences are evicted and their KV cache pages reassigned within about 15 milliseconds, yielding 10x to 20x higher throughput than static batching.", "recommendation": {"advice": "Schedule LLM requests per token-generation step rather than per request, evicting finished sequences immediately and reassigning their KV cache pages to waiting requests to avoid idle slots.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/continuous-batching-under-the-hood-what-actually-happens-inside-vllm-when-100-at", "markdown": "https://wpnews.pro/news/continuous-batching-under-the-hood-what-actually-happens-inside-vllm-when-100-at.md", "text": "https://wpnews.pro/news/continuous-batching-under-the-hood-what-actually-happens-inside-vllm-when-100-at.txt", "jsonld": "https://wpnews.pro/news/continuous-batching-under-the-hood-what-actually-happens-inside-vllm-when-100-at.jsonld"}}