Post

vLLM v1 Deep Dive in 20000 words

A source-level and system-design walk through vLLM v1, from an OpenAI streaming request through AsyncLLM, ZMQ, continuous batching, KV cache, model execution, cancellation, SSE, and CUDA graphs

vLLM v1 Deep Dive in 20000 words

Introduction

This post traces what actually happens when you call LLM(...) and then llm.generate(...), with permalinks pinned to commit 6d0976970 of the vLLM repo.

We start with the online serving path: one stream=true OpenAI request from the socket to the GPU and back as SSE chunks. Parts 1–3 then use the offline LLM path — the synchronous “I have a script and some prompts, run them” API — to unpack the shared engine internals in more detail. Part 4 returns to the online server and traces the production code path end to end.

The online source trace is pinned to the immutable OSS v0.30.0 commit and was also verified interactively against a live vllm 0.30.0.0+cu130 process on a B300. Execution was followed from the FastAPI chat route through rendering, AsyncLLM.generate, ZMQ, EngineCore scheduling, output processing, and SSE serialization.

Part 0 — One Streaming Request End to End

Suppose a client sends:

1
2
3
4
5
6
7
8
9
10
11
POST /v1/chat/completions
Content-Type: application/json

{
  "model": "Qwen/Qwen3-30B-A3B-Instruct-2507-FP8",
  "messages": [
    {"role": "user", "content": "Explain paged attention"}
  ],
  "stream": true,
  "max_tokens": 128
}

The defining system-design problem is larger than “how does the model generate tokens?”:

How does a distributed inference service accept thousands of concurrent HTTP requests, continuously batch them onto a small number of GPUs, and stream independently ordered responses back without one slow client stalling the engine?

vLLM answers with a pipeline containing several explicit queue and process boundaries:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Client
  │ HTTP POST /v1/chat/completions
  ▼
FastAPI / Uvicorn
  │ validate JSON + Pydantic request
  ▼
OpenAIServingChat
  │ chat template + tokenization + SamplingParams
  ▼
AsyncLLM.generate()                         API process
  │ create per-request RequestOutputCollector
  │ msgspec serialize + ZMQ send
══════════════════════ process boundary ══════════════════════
  ▼
EngineCore
  │ waiting queue → running queue
  │ prefix-cache lookup + KV-block allocation
  │ continuous batching / token-budget scheduling
  ▼
GPUModelRunner
  │ mixed prefill + decode forward
  │ sample next tokens
  ▼
EngineCoreOutputs
══════════════════════ ZMQ back to API process ════════════════
  ▼
AsyncLLM background output handler
  │ incremental detokenization + stop checks
  │ per-request collector
  ▼
chat_completion_stream_generator()
  │ OpenAI JSON chunks
  │ data: {...}\n\n
  ▼
StreamingResponse → TCP → client

This diagram already exposes the central design choices:

  1. HTTP concurrency is separated from GPU scheduling. Uvicorn can have many request coroutines, but there is one shared engine scheduler deciding what tokens run next.
  2. One HTTP connection does not own a GPU batch. Every request is inserted into a global scheduling domain. Batches are rebuilt every iteration from all active requests.
  3. The engine process does not write HTTP. It emits token IDs and metadata. The frontend process performs incremental detokenization, OpenAI schema conversion, and SSE framing.
  4. Streaming is a delivery property, not a separate inference algorithm. The scheduler and model forward are the same for streaming and non-streaming requests. The difference is whether the frontend yields every incremental RequestOutput or accumulates until completion.
  5. There are two types of backpressure. GPU admission/scheduling protects compute and KV memory; per-request output coalescing protects the API process when a network client consumes more slowly than tokens are produced.

Four distinct latency measurements

For a streaming LLM API, “latency” is not one scalar.

MetricStartsEndsDominant components
Queueing latencyrequest acceptedfirst scheduled tokenadmission control, busy GPU, priorities
Time to first token (TTFT)request acceptedfirst content deltatokenization, queueing, prefix lookup, prefill, first sampling
Inter-token latency (ITL)token chunk Ntoken chunk N+1decode scheduling, one-token forward, sampling, frontend
End-to-end latencyrequest acceptedfinal [DONE]TTFT + all decode steps + network flushing

A useful approximation is:

\[TTFT \approx T_{render} + T_{queue} + T_{prefill} + T_{first\ sample}\]

and:

\[E2E \approx TTFT + \sum_{i=1}^{N-1} ITL_i + T_{finalize}\]

Prefix caching primarily reduces T_prefill. CUDA graphs primarily reduce per-step launch overhead inside ITL. Continuous batching improves throughput and utilization but can increase an individual request’s queueing or ITL under heavy load. Those are different knobs.

Where a streaming request first enters Python

The route is create_chat_completion in api_router.py.

The core handler is intentionally thin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@router.post("/v1/chat/completions", ...)
@with_cancellation
@load_aware_call
async def create_chat_completion(request, raw_request):
    handler = chat(raw_request)
    generator = await handler.create_chat_completion(request, raw_request)

    if isinstance(generator, ChatCompletionResponse):
        return JSONResponse(...)

    return StreamingResponse(
        content=with_sse_keep_alive(generator, keep_alive_interval),
        media_type="text/event-stream",
    )

This route does four jobs:

  1. FastAPI validates the JSON body into ChatCompletionRequest.
  2. It fetches the long-lived OpenAIServingChat object from app state.
  3. It asks the handler for either a complete response or an async generator.
  4. For streaming, it hands that generator to Starlette’s StreamingResponse.

The route itself never runs the model and never loops over tokens.

Cancellation begins before inference

The @with_cancellation decorator races two tasks:

1
2
3
4
5
6
handler_task = asyncio.create_task(handler_func(...))
cancellation_task = asyncio.create_task(listen_for_disconnect(request))
done, pending = await asyncio.wait(
    [handler_task, cancellation_task],
    return_when=asyncio.FIRST_COMPLETED,
)

If the client disconnects while request preprocessing is still happening, the handler task is cancelled. Once a StreamingResponse has been returned, Starlette takes responsibility for monitoring the socket. If the stream generator is cancelled later, AsyncLLM.generate() catches CancelledError/GeneratorExit and sends an abort to EngineCore.

That full propagation path matters operationally:

1
2
3
4
5
6
TCP disconnect
  → cancel HTTP coroutine
  → close async result generator
  → AsyncLLM.abort(request_id)
  → ZMQ ABORT request
  → scheduler releases request + KV blocks

Without it, abandoned browser tabs and timed-out upstream services would leave zombie decode requests consuming GPU cycles and KV cache.

SSE is a protocol adapter over incremental engine output

Server-Sent Events are simply UTF-8 records separated by a blank line:

1
2
3
4
5
6
7
8
9
data: {"id":"chatcmpl-...","choices":[{"delta":{"role":"assistant"}}]}

data: {"id":"chatcmpl-...","choices":[{"delta":{"content":"Paged"}}]}

data: {"id":"chatcmpl-...","choices":[{"delta":{"content":" attention"}}]}

data: {"id":"chatcmpl-...","choices":[{"finish_reason":"stop"}]}

data: [DONE]

The first chunk establishes the assistant role. Later chunks carry content, reasoning, tool-call deltas, token IDs, and optional logprobs. A terminal chunk carries the finish reason. If usage reporting is requested, a final empty-choice chunk carries prompt/completion token counts before [DONE].

SSE is one-way and HTTP-friendly, making it simpler than WebSockets for standard token streaming. The tradeoff is that client-to-server updates require another request, and proxies may close an idle stream. vLLM’s with_sse_keep_alive wrapper addresses idle proxy timeouts with optional SSE comment frames:

1
2
: keep-alive

SSE clients ignore comments, but load balancers see bytes on the connection.

Streaming does not imply one token per network packet

Inside AsyncLLM, every request owns a RequestOutputCollector. It stores at most one pending output object:

1
2
3
4
if self.output is None:
    self.output = output
elif output_kind == DELTA:
    self.output.add(output, aggregate=True)

If the engine produces several deltas before the HTTP coroutine consumes the previous one, they are merged. This is a deliberate bounded-buffer design:

  • memory does not grow without limit for a slow client;
  • the GPU-side engine does not wait on socket writes;
  • the client may receive multiple generated tokens in one SSE chunk.

So the semantic guarantee is ordered incremental text, not exactly one token per chunk.

System-design takeaway: isolate the high-throughput producer from slow consumers with bounded per-request buffers. Decide explicitly whether to block, drop, merge, or spill when the consumer falls behind. vLLM merges token deltas.

A first debugging exercise

The fastest way to understand the online path is to stop at the route and follow one request through the immutable OSS sources:

  1. api_router.create_chat_completion
  2. OpenAIServingChat._create_chat_completion
  3. OnlineRenderer.render_chat
  4. AsyncLLM.generate
  5. AsyncLLM.add_request / _add_request
  6. AsyncMPClient.add_request_async
  7. EngineCoreRequestType.ADD over ZMQ into the EngineCore busy loop

At the API breakpoint inspect:

1
2
3
4
5
6
7
request.messages
request.stream
request.max_tokens
request.temperature
request.top_p
request.tools
raw_request.headers

Then step until engine_inputs and sampling_params exist. The original chat messages have become token IDs plus scheduler/model parameters. That is the frontend/backend contract.

Part 1 — The Six-Layer Architecture

vLLM v1 stacks six layers from the user-facing API down to the GPU:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
┌─────────────────────────────────────────────────────────────────────────────┐
│ LAYER 1: LLM (vllm/entrypoints/llm.py)                          MAIN process│
│   User-facing API: LLM(model=...).generate(prompts, sampling_params)        │
│   Owns: tokenizer, request_counter, llm_engine                              │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │ holds
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ LAYER 2: LLMEngine (vllm/v1/engine/llm_engine.py)               MAIN process│
│   Synchronous batch driver around EngineCore.                               │
│   Owns: input_processor, output_processor, engine_core (an EngineCoreClient)│
└─────────────────────────────────────────────────────────────────────────────┘
                                    │ holds
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ LAYER 3: EngineCoreClient (vllm/v1/engine/core_client.py)       MAIN process│
│   Abstract IPC client. Three concrete subclasses:                           │
│     • InprocClient — runs EngineCore in *this* process (debug only)         │
│     • SyncMPClient — for offline LLM (multiprocess, blocking)               │
│     • AsyncMPClient — for AsyncLLM / OpenAI server                          │
└─────────────────────────────────────────────────────────────────────────────┘
                              ┌─────┘
                              │ owns the spawn lifecycle and the input/output
                              │ ZMQ sockets; everything below runs in a
                              │ DIFFERENT process spawned via mp "spawn" context
                              ▼
═══════════════════════════════ PROCESS BOUNDARY ═══════════════════════════════
                              ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ LAYER 4: EngineCoreProc (vllm/v1/engine/core.py)               EngineCore   │
│   Wraps EngineCore with a busy loop polling the input zmq socket.           │
│   Owns: input_queue, output_queue, scheduler, model_executor                │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │ holds
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ LAYER 5: Executor (vllm/v1/executor/...)                       EngineCore   │
│   Abstracts TP/PP fan-out:                                                  │
│     • UniprocExecutor — TP=1 PP=1 (no extra subprocesses)                   │
│     • MultiprocExecutor — spawns one Worker subprocess per TP rank          │
└─────────────────────────────────────────────────────────────────────────────┘
                                    │ holds
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ LAYER 6: Worker / GPUModelRunner (vllm/v1/worker/gpu_worker.py)             │
│   The actual GPU rank. Owns the model weights, KV-cache pool,               │
│   InputBatch, Sampler, LogitsProcessors, CUDA graphs.                       │
└─────────────────────────────────────────────────────────────────────────────┘

The key thing this picture buys you: everything above the dashed line lives in your Python script’s process. Everything below lives in a separate spawned process. The boundary is ZMQ. Layer 3 is the abstraction that decides whether to fork or stay in-process.

🧠 Why two processes? Originally vLLM was single-process. The split was added in v1 because serving (where many requests overlap) wants the model loop running on its own thread of control, free of GIL contention with HTTP / streaming code. The downside for the offline path is that every llm.generate(...) pays a per-call IPC cost — fine when you batch a lot of work into one call, not great when you make many small calls.

For TP=1 (single GPU) with LLM(...), exactly one extra subprocess is spawned: the EngineCoreProc. The model weights, KV cache, sampler, and any custom LogitsProcessors live inside that subprocess. With TP > 1, the MultiprocExecutor would fan out further into TP-many Worker subprocesses, each holding a model shard.

LayerClassFile:line
1LLMvllm/entrypoints/llm.py:212
2LLMEnginevllm/v1/engine/llm_engine.py:50
3EngineCoreClientvllm/v1/engine/core_client.py:69
3SyncMPClientcore_client.py:716
3AsyncMPClientcore_client.py:887
4EngineCorevllm/v1/engine/core.py:92
4EngineCoreProcvllm/v1/engine/core.py:802
5UniprocExecutoruniproc_executor.py
5MultiprocExecutormultiproc_executor.py
6Workervllm/v1/worker/gpu_worker.py

Part 2 — Initialization: From LLM(...) to “ready”

What actually happens when you write llm = LLM("Llama-3.1-8B-Instruct")?

Wall time on a typical setup (H100 80GB, 1.7B-parameter model, gpu_memory_utilization=0.72, enforce_eager=False): about 14-15 seconds end-to-end, dominated by model weight loading + CUDA graph capture. Bigger models, slower NFS, or enforce_eager=False (which triggers torch.compile) push it higher.

Let’s walk it phase by phase.

Phase 1 — Caller-process construction

LLM.__init__ parses arguments into EngineArgs and calls LLMEngine.from_engine_args(...):

1
self.llm_engine = LLMEngine.from_engine_args(...)

Inside LLMEngine.__init__ the caller-process construction does three notable things, all before any subprocess is spawned:

1
2
3
4
5
6
7
8
9
10
# vllm/v1/engine/llm_engine.py:93,96,104
self.input_processor = InputProcessor(self.vllm_config, renderer)        # main process
self.output_processor = OutputProcessor(...)                             # main process
self.engine_core = EngineCoreClient.make_client(                         # spawns!
    multiprocess_mode=multiprocess_mode,
    asyncio_mode=False,
    vllm_config=vllm_config,
    executor_class=executor_class,
    log_stats=log_stats,
)

InputProcessor owns the tokenizer and validates incoming prompts. It stays in the caller process; every LLMEngine.add_request will hit it.

OutputProcessor also stays in the caller process. It owns one RequestState per active request, with a LogprobsProcessor and IncrementalDetokenizer attached. Per-request streaming output construction happens here.

The third line is the magic one: constructing engine_core is what triggers the subprocess spawn.

Phase 2 — Client dispatch

EngineCoreClient.make_client is a tiny dispatcher:

1
2
3
4
5
6
7
8
# vllm/v1/engine/core_client.py:88-103
if asyncio_mode and not multiprocess_mode:
    raise NotImplementedError(...)
if multiprocess_mode and asyncio_mode:
    return AsyncMPClient(...)        # OpenAI server / AsyncLLM
if multiprocess_mode and not asyncio_mode:
    return SyncMPClient(...)         # offline LLM — our path
return InprocClient(...)             # debug / dev only — same process

For the offline LLM(...) path this returns a SyncMPClient, which calls MPClient.__init__ as super().__init__(). That constructor:

  1. Sets up two ZMQ sockets in the main process (core_client.py:511-533):
    • input_socket — caller pushes EngineCoreRequests here
    • output_socket — caller pulls EngineCoreOutputs from here
  2. Calls launch_core_engines(...) which is where the subprocess is born.
  3. Waits for ready-handshake on the input socket (core_client.py:577-595) — every spawned EngineCore must send back an EngineCoreReadyResponse before the client returns.

Phase 3 — The Spawn Site

This is the bit worth knowing precisely. launch_core_engines constructs a CoreEngineProcManager, whose constructor at utils.py:101-135 reads:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# vllm/v1/engine/utils.py:101-133
def __init__(self, ..., vllm_config, executor_class, log_stats, ...):
    context = get_mp_context()           # ← returns spawn context
    common_kwargs = {
        "vllm_config": vllm_config,
        "executor_class": executor_class,
        ...
    }
    from vllm.v1.engine.core import EngineCoreProc

    self.processes: list[BaseProcess] = []
    for index in range(local_engine_count):
        ...
        self.processes.append(
            context.Process(                                       # ← THIS LINE
                target=EngineCoreProc.run_engine_core,             # ← target fn
                name="EngineCore",
                kwargs=common_kwargs | {"dp_rank": ..., ...},
            )
        )

That context.Process(...) call at utils.py:128-133 is the spawn site — the line that creates the EngineCore subprocess.

get_mp_context() is at vllm/utils/system_utils.py:168 and returns multiprocessing.get_context("spawn") by default (controlled by env var VLLM_WORKER_MULTIPROC_METHOD). Its preceding helper _maybe_force_spawn forces spawn under conditions like CUDA-already-initialized — so for any GPU inference path, spawn is effectively always used.

🔥 Spawn semantics matter Spawned children re-import everything from clean Python state. Runtime monkey-patches you’ve made in the parent process do NOT propagate to the child. The child does inherit the parent’s environment variables.

The canonical place to inject behavior into a spawned child is a sitecustomize.py on PYTHONPATH — Python’s site module loads it at every interpreter startup, before the user’s imports. Combined with an env-var gate (which the child inherits from the parent), this gives you a clean way to install a per-process patch only when you opt in.

If you’ve ever wondered why some patches “work in test but not in production” — it’s often this. You patched the parent; vLLM ran in the spawned child.

Phase 4 — In the spawned child: run_engine_core

The new process’s entry point is EngineCoreProc.run_engine_core at core.py:1060. This is a static function, NOT a method. That’s deliberate: spawn semantics make unpickling self-references awkward, so vLLM passes only kwargs across the boundary and reconstructs the object in the child.

1
2
3
4
5
6
7
8
9
10
# vllm/v1/engine/core.py:1060
def run_engine_core(*args, dp_rank: int = 0, local_dp_rank: int = 0, **kwargs):
    # Ensure HF transformer config can serialize after spawning
    maybe_register_config_serialize_by_value()
    ...
    set_process_title("EngineCore")
    ...
    engine_core = EngineCoreProc(*args, engine_index=dp_rank, **kwargs)
    ...
    engine_core.run_busy_loop()  # never returns until shutdown

Phase 5 — EngineCoreProc.__init__ → EngineCore.__init__

EngineCoreProc.__init__ sets up input_queue / output_queue (in-process Python queues feeding the busy loop), performs the ZMQ handshake with the parent, then calls super().__init__(...) — which is the heavy EngineCore.__init__.

EngineCore.__init__ does the actual model bring-up. The interesting parts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# vllm/v1/engine/core.py (abbreviated)
class EngineCore:
    def __init__(self, vllm_config, executor_class, log_stats, ...):
        load_general_plugins()                                   # 1) plugins

        self.vllm_config = vllm_config
        self.log_stats = log_stats

        # 2) Build executor (which loads the model)
        self.model_executor = executor_class(vllm_config)        # core.py:116

        # 3) Profile peak memory + allocate KV cache pool
        kv_cache_config = self._initialize_kv_caches(vllm_config)  # core.py:131

        # 4) Build scheduler
        Scheduler = vllm_config.scheduler_config.get_scheduler_cls()
        self.scheduler = Scheduler(...)                          # core.py:140

Each step is doing real work:

Step 2 (the executor) is what actually loads the model. For TP=1 it’s UniprocExecutor — no further spawning. For TP > 1 it’s MultiprocExecutor which spawns N Worker subprocesses, one per TP rank. The Executor wraps GPUModelRunner which holds the actual nn.Module, KV cache pages, InputBatch, Sampler, LogitsProcessors, and CUDA graphs.

Step 3 is the slow one — let’s zoom in.

Phase 5b — KV cache profiling and allocation

_initialize_kv_caches is the most architecturally interesting part of init:

1
2
3
4
5
6
# vllm/v1/engine/core.py:231-282 (abbreviated)
def _initialize_kv_caches(self, vllm_config):
    kv_cache_specs = self.model_executor.get_kv_cache_specs()        # 1
    available_gpu_memory = self.model_executor.determine_available_memory()  # 2
    kv_cache_configs = get_kv_cache_configs(...)                     # 3
    self.model_executor.initialize_from_config(kv_cache_configs)     # 4
  1. get_kv_cache_specs — query each layer’s KV-cache shape requirements (head dim, num heads, dtype, block size). Different layer types have different needs (attention vs Mamba vs grouped query etc.).
  2. determine_available_memory — runs a profiling forward pass on a fake max-batch input to measure peak GPU memory consumed by activations and intermediate buffers. Subtracts from gpu_memory_utilization × free_GPU_memory to determine the budget for KV cache. This is why you sometimes see brief memory spikes during init: that’s the profile.
  3. get_kv_cache_configs — given the budget and the per-layer specs, compute optimal block sizes and counts. May reduce max_model_len if the requested length doesn’t fit; the reduced value is propagated back to the caller in the ready handshake.
  4. initialize_from_config — actually allocate the KV cache pool, run a warmup forward, and capture CUDA graphs. The Capturing CUDA graphs ... 100% [N/N] lines you see in vLLM startup logs are step 4.

After this returns, EngineCore.__init__ continues to step 4 (build the Scheduler) and logs the now-famous line:

1
init engine (profile, create kv cache, warmup model) took 14.62 s (compilation: 3.10 s)

Phase 6 — Ready handshake back to caller

After EngineCore.__init__ returns, EngineCoreProc sends an EngineCoreReadyResponse (msgspec-encoded) back through input_socket to the parent’s MPClient. The parent has been polling at core_client.py:579-595 with VLLM_ENGINE_READY_TIMEOUT_S timeout (default 600s).

When the response arrives, MPClient._apply_ready_response syncs back any auto-adjusted config — notably a reduced max_model_len if KV-cache auto-fitting decided the requested length wouldn’t fit. This is worth knowing: if you ask for max_model_len=32768 but the KV pool only fits 20480 tokens, the engine quietly reduces it and updates the caller’s config.

Phase 7 — Final wiring and return

Before returning, MPClient.__init__ at core_client.py:641-665 spawns a daemon thread MPClientEngineMonitor that polls subprocess liveness. If the EngineCore subprocess dies unexpectedly, the thread sets resources.engine_dead=True, causing all subsequent add_request / get_output calls in the parent to raise EngineDeadError. This is the mechanism that gives you a clean error rather than a hang when the GPU side crashes.

MPClient.__init__ returns. LLMEngine.__init__ continues, runs get_supported_tasks() (round-trips to EngineCore via the now-live ZMQ pipes), and finalizes its state. Control returns to LLM.__init__, which sets up model_config, engine_class, renderer, input_processor shortcuts.

LLM(...) returns. The subprocess is alive, idle in run_busy_loop, waiting for the first add_request.

Wall-clock breakdown

Approximate timing for a 1.7B-parameter model on a H100 80GB:

phaseest. mswhat’s happening
Caller init + spawn fork-exec~500Python interpreter startup, vllm imports
Plugin loading + executor_class(...)~3000model weight load, torch.compile cache hit
determine_available_memory (peak profile)~1000one forward pass on max batch
initialize_from_config (KV alloc + CUDA graphs)~4000piecewise + full CUDA graphs captured
Ready-handshake + scheduler init + warmup~6000torch.compile transform, cudagraph profiling
Total~14,500matches “init engine … took ~14.5 s”

The init cost is one-time per LLM(...) instance. Across all subsequent llm.generate(...) calls, the subprocess stays alive. It only dies when your LLM object is garbage-collected (which triggers MPClient.shutdown).

Part 3 — Runtime: One llm.generate(...) Call

After init, calling llm.generate(prompts, sampling_params) is the hot path. Let’s trace it.

The high-level flow is: caller adds N requests → engine processes them → caller collects N RequestOutputs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
caller process                                EngineCore subprocess
─────────────────                             ──────────────────────
LLM.generate(prompts, params)
 ↓
LLM._add_completion_requests
 ↓ (loop over N)
LLM._add_request
 ↓
LLMEngine.add_request                         (via ZMQ, send_multipart)
 ├─ InputProcessor.process_inputs    ──────▶  EngineCore.add_request
 ├─ OutputProcessor.add_request                  ↓
 └─ engine_core.add_request                   self.scheduler.waiting.append
                                                 ↓
LLMEngine._run_engine                         busy loop: schedule → forward → sample
 └─ while has_unfinished_requests:               ↓
   LLMEngine.step                             EngineCoreOutputs ──▶ output_socket
    └─ engine_core.get_output       ◀──────  (via ZMQ, recv_multipart)
       └─ Connection.wait + zmq.recv
   OutputProcessor.process_outputs
    ├─ detokenizer.update
    ├─ logprobs_processor.update_from_output
    └─ make_request_output

Step 1 — Caller-side: rendering and per-Request fan-out

Entry: LLM.generate → LLM._run_completion → LLM._add_completion_requests.

_add_completion_requests calls _render_and_add_requests, which loops over the N prompts and calls _add_request for each, which calls LLMEngine.add_request.

Inside LLMEngine.add_request:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# vllm/v1/engine/llm_engine.py:209-285 (abbreviated)
def add_request(self, request_id, prompt, params, ...):
    # 1) Tokenize (no-op if caller passed pre-tokenized prompt)
    request = self.input_processor.process_inputs(...)             # llm_engine.py:241

    # 2) Register output state (RequestState, LogprobsProcessor, IncrementalDetokenizer)
    n = params.n if isinstance(params, SamplingParams) else 1
    if n == 1:
        self.output_processor.add_request(request, prompt_text, None, 0)
        self.engine_core.add_request(request)                      # zmq send to subprocess
        return req_id

    # 3) Parallel sampling (n>1): fan out to N child requests
    parent_req = ParentRequest(request)
    for idx in range(n):
        request_id, child_params = parent_req.get_child_info(idx)
        child_request = request if idx == n - 1 else copy(request)
        child_request.request_id = request_id
        child_request.sampling_params = child_params
        self.output_processor.add_request(child_request, prompt_text, parent_req, idx)
        self.engine_core.add_request(child_request)                # one zmq send per child!
    return req_id

Two things are worth noting:

Parallel sampling is just N independent Requests. SamplingParams(n=k) fans out at the LLMEngine.add_request layer into K child requests, each with sampling_params.n=1. The Scheduler, KVCacheManager, Sampler, and OutputProcessor downstream see K completely independent Requests. There is no MultiRowReq primitive in v1: one Request always means one InputBatch row. Prefix caching dedupes the prompt KV across the children, but the per-Request orchestration is still K-fold.

Each engine_core.add_request is a ZMQ round-trip. Internally it’s EngineCoreClient.add_request → _send_input → zmq.send_multipart(...). Per-call cost is small (microseconds), but it multiplies by N.

Step 2 — In the subprocess: input dispatch

EngineCoreProc.run_busy_loop in the spawned child polls input_socket, deserializes via msgspec, and routes by EngineCoreRequestType:

EngineCore.add_request builds an internal Request, runs update_block_hashes (computes prefix-cache keys for the prompt), and pushes to self.scheduler.waiting.

Step 3 — Scheduler iteration

Scheduler.schedule runs once per engine iteration, immediately before model_executor.execute_model. Its output is the exact batch that the workers execute.

Where continuous batching is actually implemented

There is no class named ContinuousBatcher, and there is no web-server timer that waits to accumulate requests. Continuous batching emerges from the EngineCore.step() loop calling Scheduler.schedule() again before every model execution. In OSS v0.30:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# vllm/v1/engine/core.py
def step(self):
    if not self.scheduler.has_requests():
        return {}, False

    scheduler_output = self.scheduler.schedule(...)
    future = self.model_executor.execute_model(
        scheduler_output,
        non_block=True,
    )
    model_output = future.result()
    return self.scheduler.update_from_output(
        scheduler_output,
        model_output,
    )

Scheduler.schedule() then rebuilds the batch from current state:

1
2
3
4
5
6
7
1. Create a fresh per-iteration token budget.
2. Schedule eligible requests already in `running`.
3. Use the remaining sequence, token, encoder, LoRA, and KV budgets
   to promote requests from `waiting`.
4. Execute exactly that new SchedulerOutput.
5. Apply sampled tokens and finished states.
6. Repeat.

Suppose requests A, B, and C decode in one iteration:

1
iteration 41: [A decode, B decode, C decode]

If B finishes and D arrives before the next scheduling decision:

1
iteration 42: [A decode, C decode, D prefill chunk]

That replacement of finished work at iteration boundaries is continuous batching. The “batch” is not a long-lived object; it is the latest SchedulerOutput.

This is different from a fixed size-or-time batcher:

Fixed request batchingvLLM continuous batching
wait until batch size or timeoutschedule whenever the engine reaches its next iteration
one request occupies a slot until the whole batch finishesfinished requests leave immediately
usually homogeneous request phaseone output can mix prefill and decode tokens
batch size is an inputrequest count emerges from token/KV constraints

The main tuning knobs are therefore not “batch timeout” and “target request count.” They are defined in SchedulerConfig:

Code/config knobWhat it limitsMain tradeoff
max_num_batched_tokensinput tokens in one iterationthroughput and prefill progress vs ITL
max_num_scheduled_tokensscheduler-issued tokens, including special casesprotects execution shape and speculative-decode accounting
max_num_seqsactive sequence slotsconcurrency vs KV/cache and per-request overhead
long_prefill_token_thresholdone long request’s prefill tokens per steplong-prompt TTFT vs decode fairness
enable_chunked_prefillwhether a prompt can consume partial remaining budgetutilization/fairness vs more scheduling boundaries

Code-level takeaway: continuous batching is implemented by the repeated EngineCore.step() → Scheduler.schedule() loop. Running requests retain state in paged KV blocks, while waiting requests can enter the next iteration as soon as token, sequence, and KV budgets permit.

The scheduler does not directly choose “N requests”

This is the most important point: there is no code equivalent to batch_size = 18. The request count is an output of greedy admission under several constraints.

The two main configured limits are initialized here:

1
2
3
4
5
6
# vllm/v1/core/sched/scheduler.py:104-110
self.max_num_running_reqs = self.scheduler_config.max_num_seqs
self.max_num_scheduled_tokens = (
    self.scheduler_config.max_num_scheduled_tokens
    or self.scheduler_config.max_num_batched_tokens
)

max_num_batched_tokens limits tokens processed in one iteration, while max_num_seqs limits how many requests may be admitted into self.running.

At the beginning of every step, vLLM creates a fresh token budget:

1
2
3
# vllm/v1/core/sched/scheduler.py:365-370
num_scheduled_tokens = {}
token_budget = self.max_num_scheduled_tokens

The resulting batch satisfies roughly:

[ \text{scheduled request count} = \left|\texttt{num_scheduled_tokens}\right| ]

[ \sum_r \texttt{num_scheduled_tokens}[r] \le \texttt{max_num_scheduled_tokens} ]

but the exact count also depends on KV-cache space, prefix-cache hits, request ordering, LoRA/encoder constraints, and whether prefill chunking is enabled. This is a greedy FCFS/priority scheduler, not a bin-packing optimizer that searches for the maximum-cardinality batch.

One unified “token deficit” model

The scheduler explicitly says there is no fundamental prefill/decode distinction. Each Request has tokens that exist and tokens that have already been computed; scheduling tries to close that deficit (source):

1
2
3
4
5
num_new_tokens = (
    request.num_tokens_with_spec
    + request.num_output_placeholders
    - request.num_computed_tokens
)

For ordinary decode, the deficit is normally one token. For an uncached prefill, it can be the entire prompt. For a prefix-cache hit, it is only the uncached suffix.

Pass 1: keep existing running requests moving

vLLM schedules self.running first (source). For each running Request it:

  1. computes the token deficit,
  2. caps it by long_prefill_token_threshold,
  3. caps it by the remaining token_budget,
  4. caps it so the sequence cannot exceed max_model_len.

It then asks the KV-cache manager to allocate slots (source). If allocation fails, it preempts requests until either space becomes available or the current request itself has been evicted.

1
2
3
4
# vllm/v1/core/sched/scheduler.py:512-518
scheduled_running_reqs.append(request)
num_scheduled_tokens[request_id] = num_new_tokens
token_budget -= num_new_tokens

That subtraction is the mechanism that indirectly limits how many additional requests can enter this iteration.

Pass 2: admit waiting requests into the remaining budget

Only after processing running requests does vLLM inspect self.waiting (source):

1
2
3
4
while (self.waiting or self.skipped_waiting) and token_budget > 0:
    if len(self.running) == self.max_num_running_reqs:
        break
    request = request_queue.peek_request()

This is where the sequence-count limit matters: max_num_seqs prevents more requests from being promoted into running. It is not necessarily equal to the number executed in the current step—some already-running requests may be temporarily unschedulable.

For a new Request, prefix-cache matching happens before the scheduler decides num_new_tokens.

When a Request is constructed, vLLM hashes every complete token block (Request.update_block_hashes, get_request_block_hasher). Each block hash includes the previous block’s hash, the current block’s token IDs, and relevant extra keys such as LoRA, multimodal inputs, prompt embeddings, or cache salt (hash_block_tokens). The parent hash makes this a chain: a block matches only when the entire prefix leading to it also matches.

During scheduling, vLLM calls kv_cache_manager.get_computed_blocks(request). That method limits the maximum hit to request.num_tokens - 1, because even a fully cached prompt must recompute its final position to produce logits (source):

1
2
3
4
5
6
7
max_cache_hit_length = request.num_tokens - 1
computed_blocks, num_new_computed_tokens = (
    self.coordinator.find_longest_cache_hit(
        request.block_hashes,
        max_cache_hit_length,
    )
)

For an ordinary full-attention model, the coordinator converts matched blocks back into a token count (source). The actual longest-prefix scan is:

1
2
3
4
5
6
7
# vllm/v1/core/single_type_kv_cache_manager.py:446-457
for block_hash in block_hashes[:max_num_blocks]:
    cached_block = block_pool.get_cached_block(block_hash, kv_cache_group_ids)
    if cached_block:
        computed_blocks.append(cached_block)
    else:
        break

See the full implementation in FullAttentionManager.find_longest_cache_hit. It stops at the first miss because later chained hashes cannot be valid if an earlier prefix block is absent.

The lookup itself is a hash-table query in BlockPool.get_cached_block. Newly completed full blocks enter that table through BlockPool.cache_full_blocks.

Back in schedule, local and externally loaded cache hits are added together, then subtracted from the Request’s token count:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# vllm/v1/core/sched/scheduler.py:639-689
num_computed_tokens = (
    num_new_local_computed_tokens
    + num_external_computed_tokens
)
num_new_tokens = request.num_tokens - num_computed_tokens

if 0 < long_prefill_token_threshold < num_new_tokens:
    num_new_tokens = long_prefill_token_threshold

if not enable_chunked_prefill and num_new_tokens > token_budget:
    break

num_new_tokens = min(num_new_tokens, token_budget)

For example, if a 1,000-token prompt has 800 tokens represented by matched full blocks, this iteration schedules only 200 tokens. Matching is block granular, so a final partial block—and sometimes a complete final block—must be recomputed.

The break is significant. With chunked prefill disabled, a prompt that does not fit in the remaining budget is not partially scheduled, and vLLM stops admitting more waiting requests in that pass. With chunked prefill enabled, min(..., token_budget) lets it consume the remaining budget as a partial prefill.

The request still needs enough physical KV capacity. vLLM calls allocate_slots; if it returns None, admission stops even if the numerical token and sequence budgets have room.

Once admitted, the Request moves to running, its token allocation is recorded, and the budget decreases (source):

1
2
3
4
self.running.append(request)
num_scheduled_tokens[request_id] = num_new_tokens
token_budget -= num_new_tokens
request.status = RequestStatus.RUNNING

How priority flows from HTTP to the scheduler

Priority is request metadata carried across every layer; it is not a separate paid-tier queue hidden in the API server.

For an OpenAI request, the serving layer’s _get_priority reads either the HTTP header or the request field:

1
2
3
4
5
6
7
8
9
10
11
12
# vllm/entrypoints/generate/base/serving.py
PRIORITY_HEADER = "X-Vllm-Priority"

def _get_priority(request, raw_request) -> int:
    if raw_request is not None:
        value = raw_request.headers.get(PRIORITY_HEADER)
        if value is not None:
            try:
                return int(value)
            except ValueError:
                pass
    return request.priority

OpenAIServingChat passes it into AsyncLLM.generate(...), input processing copies it into EngineCoreRequest, and EngineCore constructs:

1
2
request.priority = priority
request.arrival_time = arrival_time or time.time()

It only changes scheduling when the server is launched with the --scheduling-policy option:

1
vllm serve MODEL --scheduling-policy priority

The default is FCFS. In priority mode the PriorityRequestQueue is a heap. Request ordering is implemented by Request.__lt__:

1
2
3
4
5
6
7
# vllm/v1/request.py
def __lt__(self, other):
    if self.priority != other.priority:
        return self.priority < other.priority
    if self.arrival_time != other.arrival_time:
        return self.arrival_time < other.arrival_time
    return self.request_id < other.request_id

So smaller integers run earlier; arrival time breaks ties. The final request ID comparison makes ordering deterministic when timestamps match.

Priority affects two concrete scheduler decisions:

  1. PriorityRequestQueue.peek_request() selects the best waiting request for admission.
  2. Under KV allocation pressure, the scheduler chooses a running victim with the largest (priority, arrival_time) tuple — the numerically lowest priority and, within that tier, the newest request.
1
2
3
4
preempted_req = max(
    self.running,
    key=lambda r: (r.priority, r.arrival_time),
)

But this policy is not a complete multi-tenant QoS system:

  • there is no built-in quota, reserved capacity, or per-customer token bucket;
  • there is no priority aging in Request.__lt__, so a continuous stream of higher-priority work can starve lower tiers;
  • a newly arrived high-priority request does not automatically interrupt a running decode at that instant; preemption is tied to scheduler/KV allocation pressure;
  • priority values supplied by clients must not be trusted directly in a public service.

A production gateway should authenticate the caller, overwrite X-Vllm-Priority, enforce per-tier quotas, and reserve capacity if the paid-tier SLA must survive free-tier overload. vLLM’s priority heap then implements the GPU-local ordering policy.

Tradeoff: strict priority protects high-value traffic but can create starvation and poor aggregate efficiency. Weighted queues or priority aging belong above vLLM unless implemented in a custom scheduler.

What chunked prefill changes in code

For a waiting request, the scheduler computes the uncached token deficit. The chunked-prefill admission branch then decides whether partial progress is legal:

1
2
3
4
5
6
7
if (
    not self.scheduler_config.enable_chunked_prefill
    and num_new_tokens > request_token_budget
):
    break

num_new_tokens = min(num_new_tokens, request_token_budget)

With chunking disabled, one prompt that does not fit can stop later waiting requests from entering that pass. This preserves whole-prefill execution but can create head-of-line blocking.

With chunking enabled, the prompt consumes only the remaining budget and stays active for a later iteration. long_prefill_token_threshold can cap even a large available chunk:

1
2
if 0 < threshold < num_new_tokens:
    num_new_tokens = threshold

The core tradeoff is:

1
2
3
4
5
6
7
larger prefill chunk
  → fewer scheduler boundaries and faster completion for that prompt
  → more competition with decode, potentially worse ITL

smaller prefill chunk
  → finer-grained interleaving with decode and better fairness
  → more iterations, launch overhead, and later TTFT for the long prompt

This is the code-level mechanism behind “protect decode from prefill bursts.” Prefill/decode disaggregation provides stronger isolation, but chunking is the first, much cheaper intervention.

A concrete production-shaped example

Suppose:

1
2
3
4
max_num_batched_tokens = 16,384
max_num_seqs           = 1,024
chunked prefill        = disabled
running requests       = 0

After prefix-cache lookup, 18 waiting requests require a total of 16,117 prompt tokens. The scheduler admits all 18:

1
remaining token budget = 16,384 - 16,117 = 267

If the next waiting prompt needs 900 uncached tokens, it does not fit. Because chunked prefill is disabled, the scheduler breaks instead of scheduling 267 tokens from it. The forward batch therefore contains 18 requests, not because 18 was selected explicitly, but because the nineteenth request failed the next greedy admission test.

On a later mixed iteration, the same algorithm might first schedule 18 running decode requests at one token each, then use the remaining 16,366-token budget for new prefills. This is how a trace annotation such as execute_context_14(13747)_generation_18(18) arises: one scheduler output contains 14 context requests/13,747 context tokens plus 18 generation requests/18 generation tokens.

The final answer is num_scheduled_tokens

After both passes, vLLM verifies the invariants (source):

1
2
3
total_num_scheduled_tokens = sum(num_scheduled_tokens.values())
assert total_num_scheduled_tokens <= self.max_num_scheduled_tokens
assert len(self.running) <= self.max_num_running_reqs

It packages the per-request mapping into SchedulerOutput, then EngineCore.step passes that object directly to the model executor.

One subtle bookkeeping detail: after constructing the output, the scheduler advances each Request’s num_computed_tokens by the scheduled amount (source). The GPU has not completed yet; this is scheduler-side planned state. If speculative tokens are rejected, update_from_output corrects the count later.

What happens when KV capacity is exhausted

The scheduler has multiple independent capacity gates:

GateEnforced byProtects
queued request countAsyncLLM.check_admission()API-process memory and bounded overload
queued prefill tokensAsyncLLM.check_admission()TTFT target
per-step token budgetScheduler.schedule()GPU work per iteration
active sequence countmax_num_seqsmodel-runner/KV concurrency
physical KV blocksKVCacheManager.allocate_slots()GPU memory correctness

A request can fit under the numerical token and sequence limits but still fail KV allocation. For a new waiting request, the scheduler calls allocate_slots:

1
2
3
4
5
6
7
8
9
10
new_blocks = self.kv_cache_manager.allocate_slots(
    request,
    num_new_tokens,
    new_computed_blocks=new_computed_blocks,
    full_sequence_must_fit=self.scheduler_reserve_full_isl,
    ...
)

if new_blocks is None:
    break

With scheduler_reserve_full_isl=True, the scheduler checks that the full input sequence can fit rather than admitting only the first prefill chunk. This is a conservative anti-thrashing policy: slightly lower nominal utilization can avoid admitting long prompts that repeatedly consume work but can never hold their required input KV.

For an already-running request that needs another block and cannot allocate it, the scheduler may preempt a running victim. _preempt_request():

1
2
3
4
5
self._free_request_blocks(request)
request.status = RequestStatus.PREEMPTED
request.num_computed_tokens = 0
request.num_preemptions += 1
self.waiting.prepend_request(request)

This is recompute-style preemption, not free suspension. The active KV allocation is released and scheduler progress resets. When the request resumes, some work may be recovered through prefix-cache hits, but preemption can still increase TTFT/ITL and waste GPU cycles.

Two nuances matter:

  1. Priority mode selects a lower-priority running victim under allocation pressure; FCFS mode selects from the end of the running list.
  2. Failure to allocate a new waiting request normally stops admission for that pass; a high-priority arrival does not automatically evict a running low-priority request merely because it arrived.

Tradeoff: maximizing KV occupancy raises concurrency until there is no headroom for sequence growth. Near saturation, preemption and recomputation can make throughput and tail latency worse even while memory utilization looks excellent.

Step 4 — Forward + sampling

GPUModelRunner.execute_model runs the forward pass on the assembled batch. Input prep is at _prepare_inputs which flattens scheduled requests into the (total_tokens, ...) GPU input tensor — one InputBatch row per Request, with num_scheduled_tokens tokens per row (typically 1 in decode, len(prompt) in prefill).

The forward pass produces (num_rows, vocab) logits. Sampler.forward runs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# vllm/v1/sample/sampler.py:68-143 (abbreviated)
def forward(self, logits, sampling_metadata, ...):
    # 1) raw logprobs (if requested)
    if num_logprobs is not None:
        if logprobs_mode == "raw_logprobs":
            raw_logprobs = self.compute_logprobs(logits)

    # 2) Apply non-argmax-invariant LogitsProcessors (incl. user-provided)
    logits = self.apply_logits_processors(logits, ...)

    # 3) Sample (greedy / temperature / top-k / top-p)
    sampled, processed_logprobs = self.sample(logits, sampling_metadata)

    # 4) Gather top-K logprobs for output
    logprobs_tensors = self.gather_logprobs(raw_logprobs, num_logprobs, ...)

    return SamplerOutput(sampled_token_ids=sampled.unsqueeze(-1), ...)

The order is important: logprobs are computed before user LogitsProcessors run by default. If you’re masking the logit space (e.g., constrained decoding), you almost certainly want to set logprobs_mode="processed_logprobs" on LLM(...) — otherwise the reported logprobs reflect the unmasked distribution and downstream top-K may return tokens your mask would have forbidden.

Step 4b — Custom LogitsProcessors

vLLM v1’s LogitsProcessor base lives at vllm/v1/sample/logits_processor/interface.py. It exposes two methods:

1
2
3
4
5
6
7
8
9
# vllm/v1/sample/logits_processor/interface.py
class LogitsProcessor(ABC):
    @abstractmethod
    def update_state(self, batch_update: "BatchUpdate | None") -> None:
        """Called when batch composition changes (rows added/removed/moved)."""

    @abstractmethod
    def apply(self, logits: torch.Tensor) -> torch.Tensor:
        """Called every forward pass. logits is (batch_size, vocab). May modify in-place."""

For per-request logic, vLLM provides AdapterLogitsProcessor as a convenience subclass:

1
2
3
4
5
6
7
8
class AdapterLogitsProcessor(LogitsProcessor):
    def apply(self, logits):
        for req_idx, req_lp in self.req_info.items():
            req_logits = logits[req_idx]
            new_logits = req_lp(req_logits)
            if new_logits is not req_logits:
                logits[req_idx] = new_logits
        return logits

You implement new_req_logits_processor(params) returning a (output_ids, logits_row) -> logits_row callable. The Adapter pattern dispatches it per-row internally.

LogitsProcessors are wired via LLM(..., logits_processors=[CustomLogitsProcessorClass]). The class is instantiated once per Worker (in the EngineCore subprocess); per-request state lives in the instance and gets populated via update_state callbacks when new requests join the batch.

Step 4c — Mixed batches: prefill + decode in one forward, and sample_tokens

A question that confuses everyone reading a vLLM v1 trace: you see an iteration annotated execute_context_1(4)_generation_5(5) and ask — does a single forward really run prefill and decode at the same time? Yes. vLLM v1 has no separate “prefill engine” and “decode engine”; continuous batching folds both into one execute_model call. The annotation is literally telling you the mix: 1 request prefilling (4 prompt tokens) + 5 requests decoding (5 tokens, 1 each) in this forward.

How the two phases get flattened into one batch. The scheduler is phase-agnostic — num_scheduled_tokens[req_id] is just “how many tokens this request contributes this step” (its remaining prompt chunk in prefill, 1 in decode). _prepare_inputs concatenates every scheduled request’s tokens into one 1-D input_ids of length total_num_scheduled_tokens, and builds query_start_loc — the cumulative-sum boundaries (cu_seqlens) that mark where each request’s slice starts:

1
2
3
4
5
6
# vllm/v1/worker/gpu_model_runner.py:1888-1894 (abbreviated)
self.query_start_loc.np[0] = 0
self.query_start_loc.np[1 : num_reqs + 1] = cu_num_tokens   # prefix sum of per-req token counts
# e.g. prefill A=4 tok, then 5 decodes of 1 tok ->
#   input_ids  : [a0 a1 a2 a3 | b0 | c0 | d0 | e0 | f0]   (length 9)
#   query_start_loc: [0, 4, 5, 6, 7, 8, 9]

From the GEMMs’ point of view there is no “prefill vs decode” — the linear and MoE layers just matmul [total_tokens, hidden]; the M dimension is the total token count, a mix of the 4 prefill tokens and 5 decode tokens. The only layer that needs to know the boundaries is attention, which runs in varlen mode: query_start_loc + seq_lens + the paged block tables let one FlashAttention/FlashInfer kernel give the prefill request a causal mask over its 4 new tokens (attending to its cached prefix) and give each decode request a single query attending to all of its cached KV — in the same kernel launch. That is the whole trick: flatten everything, let varlen attention respect the per-request boundaries, and the rest of the network is phase-blind.

Where decode and prefill actually diverge: the LM head. A prefill request that contributed 4 tokens does not need 4 rows of logits — only its last position predicts the next token. So after the transformer stack, vLLM gathers just the final row of each request before the (expensive) vocab projection:

1
2
3
4
5
6
# vllm/v1/worker/gpu_model_runner.py:2037 — one logits row per request
logits_indices = query_start_loc[1:] - 1     # [3, 4, 5, 6, 7, 8]  (last token of each slice)

# vllm/v1/worker/gpu_model_runner.py:4070-4071 — slice THEN project
sample_hidden_states = hidden_states[logits_indices]      # [num_reqs, hidden], not [total_tokens, hidden]
logits = self.model.compute_logits(sample_hidden_states)  # LM head only on num_reqs rows

So no matter how prefill-heavy the forward is, compute_logits and the sampler always see exactly num_reqs rows (here 6) — one candidate position per request.

Why execute_model and sample_tokens are split. In v1’s V2 runner the forward and the sampling are two separate worker entry points (gpu_worker.py:748 — this is the gpu_worker.py(774): sample_tokens frame you see in a 0.22 trace; the line moved a little across patches):

1
2
3
4
5
6
7
# vllm/v1/worker/gpu_worker.py:748-751, 813-814
def sample_tokens(self, grammar_output):
    return self.model_runner.sample_tokens(grammar_output)   # -> gpu_model_runner.py:4124

...
with self.annotate_profile(scheduler_output):                # <- emits "execute_context_..._generation_..."
    output = self.model_runner.execute_model(scheduler_output)

execute_model launches the forward and compute_logits, stashes the result in self.execute_model_state, and returns None without sampling. sample_tokens then runs the Sampler (greedy / top-k / top-p) on those num_reqs logit rows and produces the ModelRunnerOutput. The split exists for async scheduling: once the forward is launched the engine can already build the next step’s inputs on the CPU while the GPU is busy, then come back to collect the sampled tokens — overlapping host-side scheduling with device compute.

The annotation itself is built in annotate_profile, which wraps the execute_model call (so the string scopes the forward, not the sampling). The counts come from compute_iteration_details, which buckets each scheduled request — context (prefill: output tokens still 0, including an in-flight chunked-prefill chunk) vs generation (decode):

1
2
3
4
5
6
7
# vllm/v1/utils.py:470-502 (abbreviated)
for req_id, num_tokens in scheduler_output.num_scheduled_tokens.items():
    if scheduler_output.scheduled_cached_reqs.is_context_phase(req_id) or req_id in new_req_ids:
        num_context_requests += 1;    num_context_tokens += num_tokens      # prefill
    else:
        num_generation_requests += 1; num_generation_tokens += num_tokens   # decode
# -> "execute_context_{ctx_reqs}({ctx_tokens})_generation_{gen_reqs}({gen_tokens})"

What you actually see in the profile. Per scheduler step there are two adjacent regions:

  1. execute_context_X(a)_generation_Y(b) — the fused forward. Inside it, per layer: one varlen attention kernel covering both phases, then the big projection/MoE GEMMs with M = a + b (here 9), then the TP all-reduce.
  2. sample_tokens — a small tail: the LM-head GEMM on num_reqs rows plus the sampler kernels (softmax / top-k / top-p / multinomial or argmax). It is tiny relative to the dozens of transformer layers, regardless of batch shape.

Read the annotation as the compute profile of that step:

AnnotationWhat it isGEMM MBound byAll-reduce kernel
context_0(0)_generation_N(N)pure decodeN (small)memory bandwidthtrtllm_allreduce_fusion (decode cudagraph)
context_M(big)_generation_0(0)pure / chunked prefilllargecomputemultimem_all_reduce (eager)
context_1(4)_generation_5(5)mixed (this example)4+5=9mixedusually the eager path — a prefill token in the batch breaks the pure-decode cudagraph shape

That last row is why a mixed step shows the multimem_all_reduce / larger-M-GEMM signature rather than the decode-only trtllm_allreduce_fusion fused kernel: the decode cudagraph is captured for a uniform query_len == 1 batch, and the moment one request contributes >1 token the runner falls off that captured shape and replays the eager path. (See the CUDA graph discussion in Part 4 for why the captured shapes are decode-only.)

And one practical corollary for the reward-model case: with prefix caching on, context_* counts only the uncomputed tokens, so a 9K-token judge prompt that is a near-total cache hit shows up as context_1(4) — a tiny prefill tail batched alongside whatever decodes are in flight — not the cold context_1(~9000) you’d see on the first, cache-missing call.

Aside — KV cache and prefix caching: the same blocks, deduped

Not a forward-pass stage. Unlike Steps 4–4c, this isn’t a phase that runs in sequence (it doesn’t happen “after sample_tokens”). The KV cache is the data structure the Step 4c forward reads from and writes into every iteration; prefix caching is a dedup layer over it. It’s pulled out here as a standalone aside because the same blocks are touched throughout the forward, not at one point in the timeline.

A common question: is prefix caching a separate cache from the KV cache? No. Prefix caching is not a second store — it is a hash-based dedup-and-reuse layer over the exact same PagedAttention KV blocks. Understanding that one fact explains both how the unified prefill+decode forward reads/writes KV and why the context_1(4) cache-hit forward above is so cheap.

The KV cache is a pool of fixed-size blocks. vLLM v1 carves GPU memory into a BlockPool of KVCacheBlocks — each block holds the K and V for a fixed number of tokens (the block size, e.g. 16). A KVCacheBlock is mostly block_id (its physical slot in the pool), ref_cnt, and an optional _block_hash. Free blocks live in a free_block_queue in eviction (LRU) order. There is one physical pool; “KV cache” and “prefix cache” are two views of it.

How a forward writes KV — slot_mapping. Every request owns a block_table: an ordered list of the physical block_ids holding its tokens’ KV. When the runner prepares a step, it computes a slot_mapping — for each new token in the flattened batch, the exact physical slot (block_id * block_size + offset) where that token’s freshly-computed K/V must be written (compute_slot_mapping). Inside the model, after attention computes K/V for the batch, the reshape_and_cache_flash kernel scatters them into those slots. This is phase-agnostic: a prefill request contributing 4 new tokens writes 4 slots, a decode request contributing 1 token writes 1 slot — the same flattened slot_mapping, the same kernel, in the same forward.

How a forward reads KV — block_table + varlen attention. The attention kernel takes the per-request block_table and seq_lens (alongside the query_start_loc boundaries from Step 4c) and runs in paged, varlen mode: for each request it gathers K/V from that request’s blocks and applies the right mask — a prefill query attends causally over [its already-cached prefix blocks] + [its new tokens]; a decode query (1 token) attends to all of its blocks. One kernel launch serves the whole mixed batch; the block tables are what let prefill and decode coexist, because each request reads only its own blocks regardless of how many new tokens it brought.

Prefix caching is the dedup on those blocks. Two things make it work:

  1. Registration. When a request fills a block completely, vLLM hashes the block’s token ids (chained with the previous block’s hash, so the hash encodes the whole prefix up to here) and registers hash -> block in cached_block_hash_to_block (cache_full_blocks).
  2. Lookup. A new request’s get_computed_blocks hashes its prompt blocks and calls find_longest_cache_hit. Every hash that matches an existing block means “this prefix is already in the KV pool” — so the request’s block_table is pointed at those existing physical blocks (their ref_cnt is incremented; nothing is copied), and those tokens are marked already computed.

allocate_slots then only allocates new blocks for the uncomputed tail. So a 9K-token judge prompt whose prefix is cached contributes its shared blocks by reference and schedules only the few uncached tokens for compute — that is precisely the context_1(4) forward: 4 new tokens prefilled, while the attention kernel still reads the ~9K cached tokens out of the shared blocks via the block table. (vLLM recomputes the last token even on a full hit — max_cache_hit_length = num_tokens - 1 — because it needs that position’s logits to sample.)

This is why the reward workload (256 jobs × 4 summaries sharing an ~8K job/résumé prefix) is so much cheaper than it looks: the shared prefix is computed once, its full blocks are hash-registered, and the other three summaries of that job reuse the identical physical blocks — ref_cnt bumps, no recompute. Turning prefix caching off doesn’t free a separate cache; it just disables the hash lookup, forcing every summary to recompute and re-store that 8K prefix into fresh blocks (4× the prefill work). Eviction is the same pool’s LRU: when a cached block’s ref_cnt hits zero it goes back on the free_block_queue and can be reclaimed (and its hash entry dropped) when memory is needed.

Step 5 — Result emission

After Sampler returns, the engine builds EngineCoreOutputs (a list of EngineCoreOutput structs, one per Request) containing new_token_ids + new_logprobs (a LogprobsLists of NumPy arrays). msgspec-serialized and pushed to the output socket.

Step 6 — Caller: get_output + OutputProcessor

Back in the caller process, LLMEngine.step calls engine_core.get_output():

1
2
3
4
5
# vllm/v1/engine/core_client.py:786-796
def get_output(self):
    outputs = self.outputs_queue.get()  # blocks on Connection.wait + zmq.recv
    ...
    return outputs

This is where most of the wall-clock time goes for short-generation workloads: waiting on IPC. The actual compute happens in the subprocess; the caller just blocks on Connection.wait until it arrives.

Once outputs land, OutputProcessor.process_outputs loops over the N EngineCoreOutput entries and per-Request:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# vllm/v1/engine/output_processor.py:572-687 (abbreviated)
def process_outputs(self, engine_core_outputs, ...):
    request_outputs = []
    for engine_core_output in engine_core_outputs:
        req_state = self.request_states[req_id]

        # 1) IterationStats updates
        self._update_stats_from_output(req_state, engine_core_output, ...)

        # 2) Streamed-text detokenization + stop-string check
        stop_string = req_state.detokenizer.update(new_token_ids, ...)

        # 3) Logprobs accumulation (decodes top-K token IDs to strings!)
        req_state.logprobs_processor.update_from_output(engine_core_output)

        # 4) Build user-facing RequestOutput
        request_output = req_state.make_request_output(...)
        request_outputs.append(request_output)

    return OutputProcessorOutput(request_outputs=request_outputs, ...)

There’s a non-obvious cost in step 3: _update_sample_logprobs calls convert_ids_list_to_tokens which calls tokenizer.decode([tok]) once per logprob entry to populate Logprob.decoded_token:

1
2
3
4
5
6
7
8
9
# vllm/tokenizers/detokenizer_utils.py:83
def convert_ids_list_to_tokens(tokenizer, token_ids):
    token_str_lst = []
    for token_id in token_ids:
        token_str = tokenizer.decode([token_id])
        if token_str is None:
            token_str = ""
        token_str_lst.append(token_str)
    return token_str_lst

If you request many logprobs per position (e.g. logprobs=200 for analysis or constrained-decoding workflows), this dominates OutputProcessor wall time — N requests × K logprobs × M positions HF tokenizer calls per step. For workflows that read only Logprob.logprob numerical values and discard Logprob.decoded_token, this is wasted work.

Part 4 — The Production Online Path (vllm serve)

Part 0 gave the high-level request journey. This section follows the actual vLLM v1 source through the deeper design questions:

  • Which process owns each responsibility?
  • Where is admission control performed?
  • How does one engine output channel feed thousands of HTTP streams?
  • What happens when the browser disconnects?
  • Can a slow client stall GPU execution?
  • Where would we scale the API tier, engine tier, or data-parallel replicas?

The source links below are permanent references into the OSS v0.30.0 commit, which matches the architecture used for the live trace.

4.1 Startup: CLI, API process, EngineCore, workers

The modern command is:

1
2
3
vllm serve Qwen/Qwen3-30B-A3B-Instruct-2507-FP8 \
  --host 0.0.0.0 \
  --port 8000

The single-API-server startup path begins in ServeSubcommand.cmd and continues through the api_server.entry launch functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
vllm/entrypoints/cli/serve.py
ServeSubcommand.cmd()
  │
  └── uvloop.run(run_server(args))
          │
          ├── setup_server()                 bind listening socket
          │
          └── run_server_worker()
                  │
                  ├── build_async_engine_client()
                  │     ├── AsyncEngineArgs.from_cli_args()
                  │     ├── create_engine_config()
                  │     └── AsyncLLM.from_vllm_config()
                  │            ├── create AsyncMPClient
                  │            ├── launch/connect EngineCore
                  │            └── create OutputProcessor
                  │
                  └── build_and_serve()
                        ├── engine_client.get_supported_tasks()
                        ├── build_app()
                        ├── init_app_state()
                        └── serve_http() / Uvicorn

The API process owns:

  • socket and HTTP lifecycle;
  • JSON/Pydantic validation;
  • model-facing chat rendering and tokenization;
  • request IDs, tracing headers, priorities, and routing metadata;
  • incremental detokenization and OpenAI response formatting;
  • each client’s async stream.

The EngineCore process owns:

  • the authoritative waiting/running request state;
  • KV-cache block accounting;
  • prefix-cache matching;
  • scheduling and token budgets;
  • calls to the model executor;
  • generation progress and finished-request cleanup.

Executor workers own the actual model execution on the configured devices. With tensor, pipeline, data, or expert parallelism, the exact worker topology changes, but the API/EngineCore contract does not: the frontend submits EngineCoreRequest objects and receives EngineCoreOutputs.

This process isolation is not cosmetic. Python HTTP and tokenization work can create event-loop jitter and hold the GIL. Engine scheduling needs a tight, predictable loop. Keeping them separate also creates a failure and scaling boundary: API servers can be replicated or restarted without embedding all HTTP concerns in the scheduler.

4.2 App construction creates long-lived serving objects

build_and_serve() first asks the engine which tasks the model supports, then builds the FastAPI application and calls init_app_state().

The resulting app.state contains long-lived objects, with generation handlers constructed by init_generate_state():

1
2
3
4
5
6
engine_client
openai_serving_models
openai_serving_chat
openai_serving_completion
renderer
tokenizer

The route does not reconstruct tokenizers or serving handlers per request. Those objects are initialized once and shared by all request coroutines in that API process.

The chat endpoint is registered by the OpenAI chat router.

and fetches the handler with:

1
2
def chat(request: Request) -> OpenAIServingChat | None:
    return request.app.state.openai_serving_chat

That is a useful general service pattern: immutable or internally synchronized heavyweight components belong in process-level state; request-specific mutable state belongs in the coroutine or a per-request object.

4.3 The route is thin, but its decorators are important

The endpoint implementation is conceptually:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@router.post(
    "/v1/chat/completions",
    dependencies=[Depends(validate_json_request)],
)
@with_cancellation
@load_aware_call
async def create_chat_completion(
    request: ChatCompletionRequest,
    raw_request: Request,
):
    handler = chat(raw_request)
    generator = await handler.create_chat_completion(request, raw_request)

    if isinstance(generator, ChatCompletionResponse):
        return JSONResponse(...)

    return StreamingResponse(
        content=with_sse_keep_alive(generator, keep_alive_interval),
        media_type="text/event-stream",
    )

Each layer has a distinct role:

LayerResponsibilityWhy it belongs here
validate_json_requestreject unsupported content types or malformed JSONfail before expensive preprocessing
Pydantic modelvalidate OpenAI request fieldstyped API contract
load_aware_calltrack endpoint load around the handlerload balancing and observability
with_cancellationcancel work if the peer disconnects earlyavoid orphaned preprocessing/generation
route bodyselect serving object and response typeHTTP adaptation only

One subtle point: with_cancellation protects the period before the route returns the StreamingResponse. After that, Starlette owns the stream and disconnect monitoring. The cancellation chain still reaches the engine because closing the response cancels the async generator.

4.4 Rendering is the frontend/backend contract

The main serving path is OpenAIServingChat._create_chat_completion(), which first calls:

1
conversation, engine_inputs = await self.render_chat_request(request)

The online renderer converts an API-shaped request into an engine-shaped request. Depending on model and request type, this can include:

  • validating that the requested model or LoRA adapter exists;
  • normalizing the conversation;
  • applying the model’s chat template;
  • tokenizing the rendered prompt;
  • processing multimodal inputs;
  • resolving generation-prompt and continuation behavior;
  • constructing EngineInput.

This boundary is worth emphasizing. EngineCore should not know that the caller used the OpenAI chat schema, Cohere schema, a completion endpoint, or an internal RPC schema. It receives tokenized model input and generation parameters.

After rendering, the serving layer creates a stable external request ID:

1
request_id = f"chatcmpl-{self._base_request_id(raw_request, request.request_id)}"

It also resolves:

  • effective model/adapter name;
  • prompt length and legal maximum output length;
  • SamplingParams or beam-search parameters;
  • tracing headers;
  • request priority;
  • session ID;
  • optional explicit data-parallel rank.

The maximum generation length is constrained by model context:

1
max_tokens <= max_model_len - effective_prompt_length

This is frontend validation because it can reject impossible work before consuming scheduler and KV-cache capacity.

Boundary distinction: API validation answers “is this request meaningful?” Admission control answers “can the service accept this work now?” Scheduling answers “which accepted tokens execute in this iteration?”

4.5 stream=true selects a consumer, not a different engine

The serving layer always obtains an engine result generator:

1
2
3
4
5
6
7
8
result_generator = self.engine_client.generate(
    engine_input,
    sampling_params,
    request_id,
    priority=...,
    data_parallel_rank=...,
    session_id=...,
)

Then it chooses how to consume it:

1
2
3
4
5
6
7
8
if request.stream:
    return self.chat_completion_stream_generator(
        request, result_generator, ...
    )

return await self.chat_completion_full_generator(
    request, result_generator, ...
)

Both branches submit the same engine request and receive the same sequence of RequestOutput objects.

  • Streaming converts each available delta to SSE.
  • Non-streaming consumes the sequence internally and returns one final JSON document.

This means enabling streaming improves perceived latency and avoids holding the whole answer before delivery, but it does not reduce prefill cost, decode cost, or KV-cache usage.

4.6 AsyncLLM.generate: one collector per request

AsyncLLM.generate() is an async generator.

Its core loop is:

1
2
3
4
5
6
7
8
q = await self.add_request(request_id, prompt, sampling_params, ...)

finished = False
while not finished:
    out = q.get_nowait() or await q.get()
    finished = out.finished
    if out is not STREAM_FINISHED:
        yield out

add_request() and _add_request() perform several important operations:

  1. Reject immediately if the engine is dead.
  2. Process raw inputs asynchronously when tokenization or multimodal work could block the event loop.
  3. Assign the internal request ID.
  4. Lazily start the shared background output-handler task.
  5. Create a per-request RequestOutputCollector.
  6. Register request state with OutputProcessor.
  7. Send the request to EngineCore.

Registration occurs before the first awaited send:

1
2
self.output_processor.add_request(request, ..., queue)
await self.engine_core.add_request_async(request)

That ordering avoids a race where an extremely fast engine result arrives before the frontend knows which collector should receive it.

For n > 1, vLLM can fan the logical request into child requests while sharing the parent collector. This is why response choices have stable indexes even though each choice may progress independently.

4.7 Admission control and scheduling are separate gates

AsyncLLM.check_admission() runs before the request is sent over ZMQ:

1
2
3
4
5
6
7
max_num_reqs = self.scheduler_config.max_num_queued_reqs
if current_requests + n > max_num_reqs:
    raise QueueOverflowError()

max_queued_tokens = self.scheduler_config.max_num_queued_tokens
if current_prefill_tokens >= max_queued_tokens:
    raise MaxQueuedTokensError()

Both errors become HTTP 503 so a load balancer or client can retry another replica. The two limits protect different things:

LimitCountsPurpose
max_num_queued_reqsunfinished sequences; n > 1 consumes multiple slotscoarse bounded queue
max_num_queued_tokensprompt tokens still considered in prefillTTFT-oriented backlog bound

The token limit is more model-aware than request count. A rough configuration from the source documentation is:

[ \texttt{max_num_queued_tokens} \approx \text{target queueing seconds} \times \text{aggregate prefill tokens/sec} ]

The accounting intentionally overestimates backlog: partial-prefill progress and prefix-cache hits are not visible in the API process until prefill completes. That can reject slightly earlier than necessary, but the error is in the safe direction for TTFT.

This is still not a complete public API rate limiter. It has no account-level quota or billing tier. Those belong at the gateway; this gate protects the current vLLM deployment’s real-time capacity.

Once accepted, EngineCore passes the request to the scheduler. The scheduler decides when it actually executes based on:

  • available KV-cache blocks;
  • max_num_batched_tokens;
  • maximum concurrent sequence count;
  • priorities and scheduling policy;
  • prefix-cache matches;
  • preemption/resume state;
  • chunked-prefill constraints;
  • data/pipeline/expert-parallel coordination.

This produces three conceptually different states:

1
2
3
Rejected     request never entered the engine
Waiting      accepted, but not selected in this iteration
Running      selected and owns active scheduler/KV state

Production systems need metrics for all three. GPU utilization alone cannot tell whether latency is caused by HTTP overload, admission rejection, scheduler queueing, prefix misses, or slow model execution.

Overload tradeoff: an unbounded queue converts overload into enormous latency. A bounded token-aware queue converts it into explicit rejection, preserving useful work and tail latency for admitted requests.

4.8 ZMQ is the API/engine process boundary

For the multiprocess path, AsyncMPClient.add_request_async() serializes an EngineCoreRequest and sends it over a ZMQ multipart socket:

1
2
3
async def add_request_async(self, request):
    request.client_index = self.client_index
    await self._send_input(EngineCoreRequestType.ADD, request)

The message includes a request type plus encoded frames. ZMQ is used here as a local or remote process transport with asynchronous sockets and multipart, potentially zero-copy frames.

The reverse channel carries EngineCoreOutputs. A dedicated socket task:

1
2
3
frames = await output_socket.recv_multipart(copy=False)
outputs = decoder.decode(frames)
outputs_queue.put_nowait(outputs)

Why not have every HTTP coroutine own an RPC call that waits for its result? Because generation is iterative and globally batched. One engine step may advance request A, B, and C; the next may advance B, C, and D. The natural wire format is therefore a stream of batched engine events, followed by demultiplexing in the API process.

4.9 EngineCore: accept messages, schedule, execute, publish

The EngineCore busy loop processes input and engine steps.

At a high level:

1
2
3
while running:
    self._process_input_queue()
    self._process_engine_step()

Input messages are dispatched by type:

1
2
3
4
ADD      → scheduler.add_request(...)
ABORT    → remove request and free its state
UTILITY  → health/config/cache operations
WAKEUP   → interrupt a blocked poll

An engine step then follows the path already explored in Parts 2 and 3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Scheduler.schedule()
  → allocate/reuse KV blocks
  → select mixed prefill/decode tokens
  → produce SchedulerOutput

ModelExecutor.execute_model()
  → prepare model inputs
  → run eager or captured CUDA-graph forward
  → sample tokens

EngineCore
  → update request state
  → package EngineCoreOutput
  → publish to output queue/socket

The most important online implication is that an HTTP request is not scheduled once. It is reconsidered every engine iteration. A long decode is a sequence of small scheduling decisions, which is what permits continuous batching, preemption, fairness policies, and newly arrived work.

4.10 The reverse path: one output handler, many request streams

AsyncLLM._run_output_handler() starts one background coroutine for all requests:

1
2
3
while True:
    outputs = await engine_core.get_output_async()
    processed = output_processor.process_outputs(outputs.outputs, ...)

OutputProcessor.process_outputs():

  1. Finds frontend request state by request ID.
  2. Appends new token IDs.
  3. Incrementally detokenizes only the new suffix.
  4. Checks stop strings and finish conditions.
  5. Updates prompt/sample logprobs when requested.
  6. Builds RequestOutput.
  7. Places it in that request’s collector.
  8. Removes completed request state.

The concurrency topology is:

1
2
3
4
                       ┌─ collector A → HTTP coroutine A
EngineCoreOutputs ─────┼─ collector B → HTTP coroutine B
                       ├─ collector C → HTTP coroutine C
                       └─ collector D → HTTP coroutine D

There is one shared engine-output reader because the socket is naturally batched. There is one collector per external request because HTTP clients make progress independently.

The output handler processes large output batches in chunks and explicitly yields to the asyncio loop between chunks. This prevents a burst of engine outputs from monopolizing the API event loop and delaying new HTTP requests or socket writes.

4.11 Slow clients and bounded output coalescing

The RequestOutputCollector is not an unbounded asyncio.Queue. It has one pending output slot plus an event:

1
2
3
class RequestOutputCollector:
    output = None
    ready = asyncio.Event()

When a delta arrives and the previous delta has not yet been consumed, vLLM merges them:

1
self.output.add(output, aggregate=True)

This design has an important consequence:

1
2
engine generates:       ["The"] [" quick"] [" brown"] [" fox"]
slow client consumes:   ["The quick brown"] [" fox"]

Ordering and text are preserved, but chunk boundaries are not. That is exactly what an OpenAI-compatible stream should promise.

An unbounded queue would let a client with a tiny receive window accumulate thousands of Python objects. A blocking queue would couple GPU progress to the slowest network consumer. Coalescing is the middle ground: bounded memory and continued engine progress, at the cost of coarser chunks.

At very large scale, this does not eliminate all slow-client cost. The API process still holds:

  • the HTTP connection;
  • request/response metadata;
  • detokenizer and parser state;
  • one pending merged output;
  • kernel socket buffers.

Therefore API-server connection count and egress bandwidth can become scaling constraints even when GPU capacity is sufficient.

4.12 Turning RequestOutput into OpenAI SSE

chat_completion_stream_generator() consumes the per-request engine generator:

1
2
3
4
5
async for res in result_generator:
    for output in res.outputs:
        delta_text = output.text
        ...
        yield f"data: {chunk.model_dump_json(...)}\n\n"

The generator has more responsibility than simply wrapping text:

  • emit the initial assistant-role chunk;
  • preserve indexes for n > 1;
  • stream content, reasoning, or tool-call deltas;
  • attach logprobs or token IDs when requested;
  • suppress hidden reasoning metadata;
  • map internal stop reasons to OpenAI finish reasons;
  • report continuous or final usage;
  • convert generation failures into streaming error events;
  • finish with data: [DONE]\n\n.

Incremental parsing matters for reasoning and tool calls. A raw token sequence might gradually form structured content such as:

1
{"name":"search","arguments":"{\"query\":\"paged attention\"}"}

The parser must preserve partial state across chunks and emit only fields that are valid at that point. This is another reason response formatting belongs in the frontend rather than in GPU workers.

4.13 Keepalive comments protect quiet streams

There can be a long gap before the first model token:

  • the request waits behind other work;
  • a long prompt requires prefill;
  • remote KV transfer is in progress;
  • a pipeline stage is delayed.

Some load balancers interpret an idle HTTP stream as dead. The SSE keepalive wrapper races the next generator item against a timer and emits:

1
2
: keep-alive

when the timer wins. Because this is an SSE comment, conforming clients ignore it while network intermediaries observe activity.

The heartbeat interval should be lower than the smallest idle timeout in the path:

1
client ← CDN/LB ← ingress/proxy ← API server

Heartbeats do not solve total request timeouts. The upstream must also permit the maximum expected queueing plus generation duration.

4.14 Cancellation and abort are resource-management features

The full disconnect path is:

1
2
3
4
5
6
7
8
9
client disconnects
  → Starlette cancels StreamingResponse iteration
  → chat stream generator closes
  → AsyncLLM.generate receives CancelledError/GeneratorExit
  → AsyncLLM.abort(request_id)
  → OutputProcessor removes frontend state
  → AsyncMPClient sends ABORT over ZMQ
  → EngineCore/scheduler removes request
  → KV blocks become reusable

generate() also aborts on unexpected frontend errors. Engine-death errors are different: if the core has already failed, there is nothing healthy to abort, so the error propagates.

This is not just cleanup hygiene. At high QPS, even a small abandoned-request rate can consume a significant fraction of decode capacity because decode requests are long-lived relative to ordinary web requests.

One operational metric worth adding is:

1
aborted_generated_tokens / total_generated_tokens

It estimates GPU work that did not reach a client. A high value can indicate aggressive upstream timeouts, users cancelling slow responses, or an unhealthy queueing policy.

4.15 Scaling the service: three different bottlenecks

An LLM endpoint has at least three independently scalable resources:

TierResourceTypical bottleneckScale signal
API frontendCPU, connections, egresstokenization, JSON/SSE, open socketsevent-loop lag, CPU, connections, network
Engine replicascheduler + KV capacityqueueing, KV exhaustionwaiting requests, KV usage, TTFT
Model workersGPU compute/interconnectprefill/decode kernels, collectivesGPU time, ITL, throughput

Adding API processes helps when frontend CPU or connection handling is saturated. It does not create more KV cache or GPU compute.

The CLI makes frontend scaling explicit. ServeSubcommand.cmd() selects api_server_count according to the data-parallel load-balancing mode:

1
2
3
4
5
external LB       → usually one API server; external router selects rank
hybrid LB         → API servers for local DP ranks
internal LB       → defaults API-server count to full DP size
multi-port LB     → supervisor exposes rank-oriented ports
headless          → zero API servers

More API processes increase HTTP/tokenization/SSE capacity. They still target the same engine fleet and therefore do not multiply model throughput by themselves.

Model parallelism is not replica scale-out

Tensor parallelism, pipeline parallelism, and expert parallelism split one model execution across devices. The GPUs cooperate on one engine step and usually share one logical scheduling/KV-capacity domain.

Data parallelism creates multiple EngineCore replicas with independent request queues and KV caches. That is the knob that adds independent serving capacity:

1
2
TP=8, DP=1  → one model replica sharded across eight GPUs
TP=4, DP=2  → two independent replicas, four GPUs each

The second topology can serve two independent batches, but only if the model fits and performs well at TP=4. Reducing TP may increase per-replica latency; increasing DP may fragment prefix caches. Scale decisions therefore require measured throughput at the target TTFT/ITL, not simply “more GPUs.”

Internal DP routing in code

For internal load balancing, the DPCoordinator collects each engine’s:

1
[waiting request count, running request count, KV-cache usage]

and publishes snapshots to frontends, normally on an approximately 100 ms cadence. DPLBAsyncMPClient.get_core_engine_for_request() then chooses a rank. If the request carries an explicit data_parallel_rank, that decision wins. Otherwise the current implementation computes a load score:

1
2
3
4
5
6
7
8
inflight = self.engine_inflight[engine]
score = max(
    self.client_count * inflight,
    waiting + running,
)

if waiting:
    score += waiting * 6.0 * max(0.0, kv_cache_usage - 0.5)

It picks the minimum score, increments a local waiting estimate immediately, and rotates the starting index to remove deterministic tie bias.

Every term addresses a real race or bottleneck:

  • waiting + running uses coordinator state from all API clients;
  • local inflight spreads a burst before the next coordinator snapshot;
  • the KV-pressure penalty avoids sending more work to a queue that is unlikely to drain because memory is nearly full;
  • rotating tie order approximates round-robin when replicas are equally idle.

This is substantially better than blind round-robin, but it is still an estimate. Request count does not capture a 100-token prompt versus a 100,000-token prompt, and the score does not directly include output-length estimates, adapter affinity, or prefix-cache locality.

Potential production extensions include:

SignalBenefitTradeoff
queued prompt tokensbetter prefill-cost estimaterequires fresh cross-process accounting
expected output tokensbetter decode occupancy estimateclient value is uncertain or manipulable
prefix hash affinityhigher cache hit ratehotspots and sticky imbalance
adapter/model affinityavoids load/eviction costcan strand capacity
oldest queue ageprotects tail latencymay route to a less efficient replica

External load-balancing mode moves this decision to the gateway. The frontend’s _get_data_parallel_rank can read X-data-parallel-rank, but then the gateway must own health, compatibility, overload, and locality policy.

Autoscaling is outside the hot scheduler loop

The scheduler can reject, queue, preempt, and route among existing ranks. It cannot make a multi-minute model cold start disappear. An orchestrator should scale on sustained queue age, prompt/output token demand, KV pressure, and measured throughput, while vLLM’s bounded admission handles the immediate burst.

Scaling takeaway: API processes scale connections; TP/PP/EP make one replica fit or execute; DP adds independent schedulers and KV pools; the external orchestrator adds or removes replicas slowly.

4.16 Failure domains and error propagation

The main failure domains are:

  1. One HTTP request fails. Return a normal JSON or streaming error; other requests continue.
  2. One API process fails. Its connections terminate. Engine requests owned by that client must be cleaned up or detected as orphaned.
  3. EngineCore fails. The shared output handler receives an exception, propagates it to all live collectors, and the API server becomes unhealthy.
  4. One model worker fails. Distributed execution generally invalidates the engine replica; retry should happen at a higher-level router on another healthy replica.

The background output handler treats core-output failure as global:

1
2
except Exception as e:
    output_processor.propagate_error(e)

Every waiting generate() task is awakened with the failure instead of hanging forever. This is a critical reliability property for any fan-out/fan-in async architecture: terminal producer failure must be broadcast to all consumers.

Retries require care. Retrying before any bytes are sent is straightforward. After partial SSE output, transparent retry may duplicate or diverge from text the client already saw. Production gateways commonly retry connection/setup failures but do not silently restart a partially emitted generation unless the protocol includes resumable generation semantics.

4.17 Observability: carry one identity across every boundary

A request ID should connect:

1
2
3
4
5
6
7
8
edge access log
  → API route timing
  → render/tokenize timing
  → scheduler queueing
  → prefix-cache hit/miss
  → prefill/decode execution
  → output serialization
  → final usage / finish reason

Useful per-request timestamps include:

1
2
3
4
5
6
7
8
t0  HTTP request accepted
t1  rendering/tokenization complete
t2  submitted to EngineCore
t3  first scheduled
t4  first token generated
t5  first SSE chunk written
t6  final token generated
t7  [DONE] written

From these:

1
2
3
4
5
6
frontend preprocessing = t2 - t0
engine queueing         = t3 - t2
model TTFT              = t4 - t3
network/frontend TTFT   = t5 - t4
decode duration         = t6 - t4
finalization/egress     = t7 - t6

Only measuring t7 - t0 hides whether a regression came from tokenization, queueing, model kernels, detokenization, JSON serialization, or the network.

4.18 System-design tradeoff matrix

RequirementvLLM mechanismTradeoff / failure modeScaling implication
High GPU utilizationcontinuous batching and iteration-level schedulingrequests interfere through queueing and token budgetadd replicas or tune batch/token limits
Low TTFTprefix caching, chunked prefill, admission controlcache locality can conflict with load balanceroute with both load and prefix affinity
Low ITLdecode batching, CUDA graphs, optimized attention/MoElarger batches improve throughput but may hurt latencyseparate latency and throughput pools
Many concurrent clientsasync HTTP and per-request collectorsAPI CPU, sockets, and egress can saturate firstscale API processes independently
Bounded memory for slow clientsmerge pending delta outputschunks may contain multiple tokenspreserve semantic order, not chunk size
Fast disconnect cleanupcancellation → engine abortraces around partially emitted responsesmonitor abort rate and wasted tokens
Proxy-safe streamingSSE keepalive commentsdoes not override absolute timeoutalign heartbeat and proxy timeout policy
Process isolationAPI process ↔ ZMQ ↔ EngineCoreserialization and IPC overheadenables independent frontend scaling
Failure visibilitypropagate engine error to all collectorsone core failure affects all attached streamshealth-check and fail over by replica
OpenAI compatibilityfrontend schema and stream adapterAPI features add CPU/parser complexitykeep engine protocol schema-agnostic
Multi-tenant fairnesspriorities, token budgets, admission policiesstarvation or priority abusequotas and per-tenant queue metrics
Horizontal GPU scaledata-parallel replicas and routingcache fragmentation and imbalanceload-aware, locality-aware router

4.19 Online and offline converge on the same core

 Offline LLMOnline AsyncLLM
CallerPython processHTTP/RPC client
API styleblocking batch callasync per-request generator
Input arrivalknown listcontinuous, concurrent arrivals
Output deliveryreturn after completionincremental stream or final JSON
Client transportin-process PythonHTTP + SSE
Core transportsynchronous clientasynchronous multiprocess client
Schedulingsame v1 schedulersame v1 scheduler
KV cachesame block managersame block manager
Model runnersame GPU runnersame GPU runner
CUDA graphssame captured graph poolsame captured graph pool

This is why studying the offline path was still useful: it exposes the engine without HTTP concurrency. The online server adds four major mechanisms around the same core:

  1. request rendering and API compatibility;
  2. async admission and request lifecycle;
  3. multiplexed IPC plus per-request output demultiplexing;
  4. streaming, cancellation, and network backpressure.

4.20 CUDA graphs are captured at startup, not per request

CUDA graphs are still captured inside the model-worker initialization path described in Part 2. They are not captured by FastAPI, AsyncLLM.generate(), or the SSE generator.

1
2
3
4
5
6
7
8
9
10
11
12
server startup
  → create EngineCore/model executor
  → load model
  → determine KV-cache capacity
  → compile/warm up model
  → capture configured graph shapes
  → mark server ready

request hot path
  → scheduler chooses this iteration's shape
  → model runner selects matching captured graph when eligible
  → replay graph

--enforce-eager skips graph replay and is useful when first learning or debugging the Python path. It generally trades lower startup complexity and better debuggability for higher launch overhead at runtime.

A runtime profile of an already-ready server captures graph replays, not the one-time graph capture. This is why offline and online GPU traces can look nearly identical after the request reaches EngineCore.

4.21 A practical live-debugging sequence

For a source-level walkthrough, use eager mode first so CUDA-graph capture does not complicate the initial trace. Attach a debugger to the API process and set breakpoints in this order:

  1. api_router.create_chat_completion
  2. OpenAIServingChat._create_chat_completion
  3. AsyncLLM.add_request and _add_request
  4. AsyncMPClient.add_request_async
  5. AsyncLLM._run_output_handler
  6. OutputProcessor.process_outputs
  7. chat_completion_stream_generator

Because EngineCore is a separate process, stepping into the scheduler requires a second debugger attach to that process. Do not expect “step into” across ZMQ to jump process boundaries automatically.

At each boundary, inspect the representation change:

1
2
3
4
5
6
7
8
9
ChatCompletionRequest
  → conversation + EngineInput
  → EngineCoreRequest
  → SchedulerOutput
  → model token IDs
  → EngineCoreOutput
  → RequestOutput with incremental text
  → ChatCompletionStreamResponse
  → SSE bytes

These representation changes form a compact map of the serving architecture: each conversion exists to isolate an API, process, scheduling, model-execution, or transport responsibility.

Part 5 — Sizing the GPU Fleet

The GPU count is not derived from QPS alone. A request with a 100-token prompt and 20-token output is not equivalent to one with a 20,000-token prompt and 2,000-token output. Capacity planning has two separate decisions:

  1. How many GPUs form one model replica? This is the TP/PP topology needed to fit the weights and meet single-replica latency.
  2. How many independent replicas are required? This is the DP count needed for throughput, KV-cache concurrency, failures, and traffic bursts.

The final relationship is approximately:

[ \text{Total GPUs} = \text{GPUs per replica} \times \text{number of DP replicas} ]

5.1 First make one replica fit

For a dense model, the first-order weight-memory estimate is:

[ M_{\text{weights}} \approx N_{\text{parameters}} \times \text{bytes per parameter} ]

For example, 70B BF16 weights require roughly:

[ 70 \times 10^9 \times 2 \approx 140\text{ GB} ]

before allocator overhead, temporary buffers, CUDA graphs, activations, and KV cache. With tensor and pipeline parallelism, the rough per-GPU weight share is:

[ M_{\text{weights/GPU}} \approx \frac{M_{\text{weights}}}{TP \times PP} ]

This is only a fit estimate. Tensor parallelism introduces collectives on every layer; pipeline parallelism introduces stage bubbles and load-balance concerns. The smallest topology that fits is not necessarily the fastest topology.

vLLM exposes the topology through ParallelConfig:

1
2
3
4
tensor_parallel_size
pipeline_parallel_size
data_parallel_size
enable_expert_parallel

For a conventional dense deployment:

1
2
GPUs per replica = TP × PP
Total GPUs        = TP × PP × DP

Do not multiply by EP again automatically. Expert parallelism usually maps the experts across ranks already present in the distributed world. The exact MoE topology depends on how TP, DP, and EP groups are constructed.

5.2 Weight memory is not the serving-memory budget

After loading the model, vLLM profiles non-KV memory and assigns the remaining budget to KV cache. The relevant source paths are CacheConfig.gpu_memory_utilization and GPUWorker.determine_available_memory().

The conceptual budget is:

[ M_{\text{KV available}} \approx M_{\text{GPU target}} - M_{\text{weights}} - M_{\text{peak activations}} - M_{\text{CUDA graphs}} - M_{\text{runtime overhead}} ]

where:

[ M_{\text{GPU target}} = \texttt{gpu_memory_utilization} \times M_{\text{physical GPU}} ]

This is why increasing gpu_memory_utilization can increase concurrency but also reduce the safety margin for memory spikes, graph capture, communication buffers, or memory-accounting error.

The startup logs report the resulting KV capacity. That measured capacity is more reliable than estimating from total GPU memory alone.

5.3 Translate traffic into token demand

Let:

  • (\lambda): target request rate in requests/second;
  • (P): prompt tokens per request;
  • (O): generated tokens per request;
  • (H): token-weighted prefix-cache hit fraction.

Then:

[ D_{\text{prefill}} = \lambda \times \mathbb{E}[P(1-H)] ]

[ D_{\text{decode}} = \lambda \times \mathbb{E}[O] ]

These are different workloads:

  • prefill processes many tokens from each newly admitted request;
  • decode repeatedly advances active sequences by one or a few tokens;
  • prefix caching reduces prefill work but does not remove decode work.

Use a token-weighted cache hit rate:

[ H = \frac{\text{cached prompt tokens}} {\text{total prompt tokens}} ]

Request-level hit rate can be misleading. A 90% hit on a 100-token prompt saves less compute than a 50% hit on a 20,000-token prompt.

Also include:

  • n > 1 output choices;
  • retries and aborted generations;
  • speculative-decoding acceptance;
  • multimodal encoder work;
  • LoRA or model-mix effects;
  • cold-cache versus warm-cache traffic.

5.4 Measure one replica at the target latency

The most reliable unit of capacity is:

Maximum arrival rate one replica sustains while meeting the required P95/P99 TTFT, ITL, error-rate, and memory limits.

Use vllm bench serve or an equivalent trace replay with the production distributions of:

  • prompt length;
  • output length;
  • arrival process and burstiness;
  • cacheable prefixes;
  • sampling settings;
  • adapters and models;
  • streaming cancellations.

For each offered request rate, record:

1
2
3
4
5
6
7
8
achieved request throughput
prompt token throughput
output token throughput
P50/P95/P99 TTFT
P50/P95/P99 ITL
queue time
KV-cache utilization
preemptions and rejected requests

Do not use the highest rate that avoids an OOM. Use the highest rate that still meets the latency objective. Maximum throughput commonly occurs beyond the point where tail latency is acceptable.

If one replica sustains (\lambda_{\text{replica,SLO}}) requests/second for the representative workload, the measured compute lower bound is:

[ R_{\text{load}} = \left\lceil \frac{\lambda_{\text{target}}} {\lambda_{\text{replica,SLO}}} \right\rceil ]

5.5 Use token throughput as a sanity check

If only isolated prefill and decode benchmarks are available, estimate the fraction of one replica consumed by each phase:

[ \rho_{\text{prefill}} = \frac{D_{\text{prefill}}} {C_{\text{prefill,replica}}} ]

[ \rho_{\text{decode}} = \frac{D_{\text{decode}}} {C_{\text{decode,replica}}} ]

For an aggregated prefill/decode replica, a first-order compute estimate is:

[ R_{\text{compute}} \approx \left\lceil \rho_{\text{prefill}} + \rho_{\text{decode}} \right\rceil ]

The sum is only an approximation: continuous batching, memory-bandwidth reuse, collectives, and prefill/decode interference are nonlinear. A mixed trace replay should replace this estimate before production deployment.

For disaggregated serving, size the pools separately:

[ R_{\text{prefill pool}} = \left\lceil \rho_{\text{prefill}} \right\rceil \qquad R_{\text{decode pool}} = \left\lceil \rho_{\text{decode}} \right\rceil ]

and include the latency and bandwidth cost of transferring KV cache between them.

5.6 Check the independent KV-concurrency bound

For a conventional transformer, KV memory per cached token across the model is approximately:

[ m_{\text{KV/token}} = 2 \times L \times H_{\text{KV}} \times D_{\text{head}} \times S ]

where (L) is the layer count, (H_{\text{KV}}) the number of KV heads, (D_{\text{head}}) the head dimension, and (S) bytes per cache element. TP usually shards this storage across ranks, while the exact layout depends on the attention architecture and cache dtype.

Little’s Law gives a concurrency estimate:

[ C_{\text{active}} \approx \lambda \times \mathbb{E}[W_{\text{active}}] ]

where (W_{\text{active}}) is time spent admitted to the engine, not time in an external rejected queue.

For roughly uniform generation progress, average cached tokens per active request are approximately:

[ T_{\text{active}} \approx \mathbb{E}[P] + \frac{\mathbb{E}[O]}{2} ]

Therefore a rough cluster KV demand is:

[ M_{\text{KV demand}} \approx C_{\text{active}} \times T_{\text{active}} \times m_{\text{KV/token}} ]

In practice, use vLLM’s measured KV-token capacity and apply both limits:

1
2
3
4
5
effective sequences per replica
  = min(
      max_num_seqs,
      KV token capacity / average active cached tokens
    )

Then:

[ R_{\text{KV}} = \left\lceil \frac{C_{\text{active}}} {C_{\text{active per replica}}} \right\rceil ]

The no-headroom lower bound is:

[ R_{\text{base}} = \max(R_{\text{load}}, R_{\text{KV}}) ]

5.7 Add headroom and failure capacity

Running continuously at the measured limit leaves no room for:

  • burst traffic;
  • request-length variance;
  • cache-cold periods;
  • one replica restarting;
  • background model loading;
  • traffic imbalance;
  • performance regressions.

If the target steady-state utilization is (u), use:

[ R_{\text{production}} = \left\lceil \frac{R_{\text{base}}}{u} \right\rceil ]

For example, (u=0.70) reserves approximately 30% headroom. Then verify the failure requirement separately:

1
2
3
4
Can the remaining fleet still meet the SLO after losing:
  one replica?
  one node?
  one rack or zone?

GPU startup can take minutes, so reactive autoscaling is not immediate overload protection. Keep warm capacity and use the bounded admission controls in SchedulerConfig to protect the surviving fleet.

5.8 Worked example

Assume the measured workload is:

1
2
3
4
5
6
7
8
9
target arrival rate                 12 requests/s
average prompt                      2,000 tokens
token-weighted prefix-cache hit     60%
average output                      300 tokens
average active engine time          8 s
one replica topology                TP=8, PP=1
measured SLO capacity per replica   3.2 requests/s
effective active capacity           180 requests/replica
steady-state utilization target     70%

Token demand:

[ D_{\text{prefill}} = 12 \times 2000 \times (1-0.60) = 9{,}600\text{ prompt tokens/s} ]

[ D_{\text{decode}} = 12 \times 300 = 3{,}600\text{ output tokens/s} ]

Measured load bound:

[ R_{\text{load}} = \left\lceil \frac{12}{3.2} \right\rceil = 4 ]

Active-concurrency estimate:

[ C_{\text{active}} = 12 \times 8 = 96 ]

[ R_{\text{KV}} = \left\lceil \frac{96}{180} \right\rceil = 1 ]

Therefore:

[ R_{\text{base}}=\max(4,1)=4 ]

With 70% target utilization:

[ R_{\text{production}} = \left\lceil \frac{4}{0.70} \right\rceil = 6\text{ replicas} ]

Each replica uses eight GPUs:

[ \text{Total GPUs} = 6 \times 8 = \boxed{48} ]

This is not a universal recommendation; every numeric capacity in the example is hypothetical. The method is the reusable part:

1
2
3
4
5
6
fit one replica
  → measure mixed-workload SLO capacity
  → check token demand
  → check KV concurrency
  → add burst and failure headroom
  → multiply replicas by GPUs per replica

5.9 Map the estimate back to vLLM knobs

Capacity decisionvLLM controlWhat it changes
GPUs per replicatensor_parallel_size, pipeline_parallel_sizemodel fit, communication, single-replica latency
Replica countdata_parallel_sizeindependent schedulers, KV pools, and throughput
KV capacitygpu_memory_utilization, cache dtypeconcurrent cached tokens
Per-step workmax_num_batched_tokensthroughput versus TTFT/ITL interference
Active sequencesmax_num_seqsconcurrency and model-runner overhead
Long-prompt fairnesslong_prefill_token_threshold, chunked prefillprefill progress versus decode ITL
Overload protectionmax_num_queued_reqs, max_num_queued_tokensbounded queueing, not additional capacity
Frontend CPU/connectionsapi_server_countHTTP capacity, not GPU capacity

Changing these knobs changes the measured operating point, so capacity planning is iterative. Tune, benchmark again, and size from the resulting latency-throughput frontier rather than from theoretical FLOPS.

Summary: A Mental Model

A useful mental model for vLLM v1:

  • A frontend/backend process boundary connected by ZMQ. Frontend-side: validate, render, tokenize, submit EngineCoreRequest, detokenize, and format output. Engine-side: schedule, execute, sample, and emit EngineCoreOutput. Distributed executors may add more worker processes below EngineCore.
  • Six layers, with a clean boundary at layer 3/4. Everything above the boundary is Python orchestration; everything below is GPU-driving + scheduler bookkeeping.
  • HTTP streams do not own GPU batches. The scheduler rebuilds a continuous batch every iteration from all eligible requests in one engine replica.
  • One output channel, one collector per request. The API process demultiplexes batched engine outputs and coalesces pending deltas so a slow client cannot create an unbounded output queue.
  • Cancellation is capacity management. A disconnected SSE stream propagates an abort to the scheduler so GPU work stops and KV blocks are released.
  • One Request = one row. Parallel sampling fans out to N independent Requests at the LLMEngine layer; the engine has no concept of “one Request, N rows”.
  • Init is one-time. ~14 s for a typical model — model load, KV profiling, CUDA graph capture, ready handshake. Then the subprocess stays alive across all generate calls.
  • Spawn semantics gate every patch. Anything you want to take effect in EngineCore needs to be installed via sitecustomize.py + env-var gate, not runtime monkey-patch in the parent.

If you remember these points, the rest of vLLM v1’s behavior makes sense when you encounter it. The codebase is large but the architecture is clean.

Happy hacking.

This post is licensed under CC BY 4.0 by the author.