Pidoku

Processes and Wires

Module 16 Lesson 16.d 50 min Difficulty 2/5

Prerequisites 16.c


Before you start: words you need#

WordPlain meaning
GILCPython’s global interpreter lock: only one thread of a process runs Python code at any moment.
SocketAn endpoint for sending bytes between processes, on one machine or across a network.
ZeroMQ (ZMQ)A library that gives sockets useful patterns (send to a named peer, fan-in, publish). vLLM uses it between the API server and the engine core.
msgpackA compact binary format for structured data, like JSON but smaller and faster to encode.
Shared memoryA region of RAM that several processes map at once, so one can write and others read without copying through the kernel.
Ring bufferA fixed array of slots used in a circle: the writer fills the next slot, readers follow behind, and slots are reused.
RankThe number of one worker inside a group of workers, starting at 0.
Busy loopA loop that checks for work again immediately instead of sleeping, trading CPU for lower latency.

1. What is it?#

A running vLLM server is several operating-system processes, not one. Python runs only one thread of Python code at a time per process, so vLLM puts each job that must not wait for another into its own process: text handling in the API server, decisions in the engine core, and arithmetic in one worker per GPU. They are joined by two kinds of wire. Between the API server and the engine core runs ZeroMQ carrying msgpack messages. Between the engine core and its workers runs a shared-memory ring buffer.

Knowing which wire carries what tells you how many CPU cores to give the server, why it dies as a unit, and where a slow request is spending its time. Read from the v0.32.0 source; facts checked on 13 November 2026.

flowchart LR
  subgraph API["API server process"]
    direction TB
    IN[":i-network: <b>ROUTER socket</b><br/><small>binds; sends requests</small>"]
    OUT[":i-network: <b>PULL socket</b><br/><small>receives outputs</small>"]
  end
  subgraph CORE["Engine core process"]
    direction TB
    T1[":i-activity: <b>Input thread</b><br/><small>DEALER socket, decode</small>"] --> Q1[("input_queue")]
    Q1 --> LOOP[":i-recycle: <b>Busy loop</b><br/><small>schedule, execute, update</small>"]
    LOOP --> Q2[("output_queue")]
    Q2 --> T2[":i-activity: <b>Output thread</b><br/><small>encode, PUSH socket</small>"]
  end
  subgraph WK["Worker processes"]
    direction TB
    W0[":nvidia: <b>Worker rank 0</b><br/><small>GPU 0</small>"]
    W1[":nvidia: <b>Worker rank 1</b><br/><small>GPU 1</small>"]
  end
  IN -->|"ADD / ABORT / UTILITY"| T1
  T2 -->|"EngineCoreOutputs"| OUT
  LOOP -->|"shared-memory<br/>broadcast queue"| W0
  LOOP --> W1
  W0 -->|"response queue"| LOOP
  class IN,OUT,T1,T2 io
  class Q1,Q2 memory
  class LOOP queue
  class W0,W1 compute

2. Why does it exist?#

Suppose everything lived in one process. While the server tokenised a 100,000-token prompt, the scheduler could not schedule and the GPU would sit idle. While the scheduler ran, no response could be streamed. The GIL turns every slow CPU job into a pause for every other job.

Splitting by process gives each job its own interpreter and its own lock. The price is that data must now cross process boundaries, and the two wires are vLLM’s answer to doing that cheaply: token IDs only (never text) to the engine core, and a lock-free broadcast to the workers.


3. Simple analogy#

A newsroom. Reporters (the API server) take calls from the public and write short coded notes. They drop the notes into the editor’s inbox tray (ZeroMQ). The editor (engine core) never answers the phone; an assistant empties the tray onto the desk (input thread), and another carries finished pages out (output thread), so the editor only ever decides. The editor pins one plan per hour on a corkboard that every printer can see (shared-memory broadcast); each printer ticks its own box when it has read it, and the editor cannot reuse that pin until every box is ticked.


4. Tiny example: counting the processes#

Start a server on four GPUs with vllm serve <model> -tp 4 and list its processes:

Shell
ps -eo pid,args | grep -E "VLLM::|vllm serve" | grep -v grep

You will see the vllm serve process itself (the one API server), VLLM::EngineCore, and four VLLM::Worker_TP0 … VLLM::Worker_TP3: six in all. With a single GPU you would see only two, because the worker then runs inside the engine core process. The rest of this lesson explains why each one exists and what travels between them.


5. Technical explanation#

Who runs where#

ProcessTitle in psCountJobWhat it must never wait for
API serverthe vllm serve command line; VLLM::APIServer_<i> when there are severalA, which defaults to DPHTTP, chat templates, tokenising, media loading, detokenising, streamingThe GPU
Launcherthe vllm serve command line1 when A > 1; it only supervisesStart and watch the others—
Engine coreVLLM::EngineCore (or VLLM::EngineCore_DP<rank>)DP, default 1Scheduling, KV block accountingTokenising or network clients
WorkerVLLM::Worker, with suffixes such as _TP0, _PP1, _DP2one per GPU, DP × PP × TP; none with a single GPUBuild tensors, run the model, sampleAnything
DP coordinatorVLLM::DPCoordinator1 when DP > 1 (internal load balancing, or any MoE model)Balance load across engine cores—

TP, PP and DP are the tensor-, pipeline- and data-parallel sizes (19.a). The titles need the setproctitle package, which vLLM installs; the VLLM prefix can be changed with VLLM_PROCESS_NAME_PREFIX.

The single-GPU case is special: with a world size of 1 the executor backend is uni (UniProcExecutor), which calls the worker as an ordinary object inside the engine core process. Any larger world size uses mp (MultiprocExecutor), one process per GPU.

warning

The engine core runs a busy loop: when there is work it never sleeps. Give the server fewer physical CPU cores than it has busy jobs and the engine core gets descheduled by the operating system in the middle of a step, which shows up as throughput loss with the GPU under-used. The project’s sizing rule is A + DP + N + (1 if DP > 1) physical cores for N GPUs (so at least 2 + N), and twice that in vCPUs when hyper-threading is on. In containers, check the CPU limit, not the node size.

Wire 1: API server and engine core#

ZeroMQ gives sockets a few useful shapes. vLLM uses four of them on this wire:

SocketWho owns itBehaviour used
ROUTERAPI server, bindsSends each message to a specific engine, chosen by the engine’s identity
DEALEREngine core, connectsIts identity is the engine index, 2 bytes little-endian
PUSHEngine core, one per API serverSends outputs to exactly the API server that owns the request
PULLAPI serverReceives them

With everything on one machine the address is a Unix-domain path, ipc://<VLLM_RPC_BASE_PATH>/<uuid>, where the base path defaults to the system temp directory. When engines live on other nodes it is TCP.

The first message on the wire goes the “wrong” way. A ROUTER socket cannot address a peer it has never heard from, so on start-up each engine core’s input thread sends a ready response to every API server. It carries facts the API server needs, which may differ from what was configured: the maximum model length after any auto-fitting, the number of GPU blocks, the block size, the KV cache capacity in tokens, max_num_seqs, max_num_batched_tokens and the vLLM version. Only then can requests flow.

Every request message is two or more frames:

frame 0   the engine identity          (ROUTER uses it to route; it is stripped on arrival)
frame 1   one byte: the request type
frame 2+  the msgpack-encoded body; large tensors travel as extra zero-copy frames

The type byte is defined in vllm/v1/engine/__init__.py:

Python
class EngineCoreRequestType(enum.Enum):
    ADD = b"\x00"            # a new request
    ABORT = b"\x01"          # a list of request IDs to cancel
    START_DP_WAVE = b"\x02"  # data-parallel coordination
    UTILITY = b"\x03"        # call a method on the engine core and return its result
    EXECUTOR_FAILED = b"\x04"  # internal sentinel: a worker died
    WAKEUP = b"\x05"           # internal sentinel: wake the queue during shutdown

UTILITY is a small remote-procedure-call mechanism: the body is (client_index, call_id, method_name, args), the engine core calls the named method on itself, and the result travels back tagged with the same call_id. Loading a LoRA adapter, resetting the prefix cache, putting the engine to sleep and profiling all use it.

What is in a request#

The body of an ADD is an EngineCoreRequest. Text never crosses this wire; the engine core is a tokens-in, tokens-out machine. Abridged:

Python
class EngineCoreRequest(msgspec.Struct, array_like=True, omit_defaults=True, gc=False):
    request_id: str
    prompt_token_ids: list[int] | None
    mm_features: list[MultiModalFeatureSpec] | None   # processed images, audio
    sampling_params: SamplingParams | None
    pooling_params: PoolingParams | None              # for embedding models
    arrival_time: float
    lora_request: LoRARequest | None
    cache_salt: str | None                            # isolates the prefix cache
    data_parallel_rank: int | None
    prompt_embeds: torch.Tensor | None = None
    client_index: int = 0                             # which API server sent it
    current_wave: int = 0
    priority: int = 0
    ...
    external_req_id: str | None = None                # the ID the client sent

Three options on that class declaration are performance decisions:

  • array_like=True encodes the struct as a msgpack array, not a map. Field names are never sent; position identifies the field. (That is why new fields are always appended at the end.)
  • omit_defaults=True drops trailing fields that hold their default.
  • gc=False tells Python’s garbage collector not to track these objects. A server holds thousands of them, and tracking them makes every collection pause longer.

The engine core does one more thing at start-up for the same reason: it calls freeze_gc_heap() to mark everything allocated so far as permanent, so the garbage collector never scans the model’s Python objects again.

What comes back#

One EngineCoreOutputs per engine step, holding one EngineCoreOutput per request that made progress. Abridged:

Python
class EngineCoreOutput(msgspec.Struct, array_like=True, omit_defaults=True, gc=False):
    request_id: str
    new_token_ids: list[int]
    new_logprobs: LogprobsLists | None = None
    finish_reason: FinishReason | None = None   # STOP, LENGTH, ABORT, ERROR, REPETITION
    stop_reason: int | str | None = None
    events: list[EngineCoreEvent] | None = None # QUEUED, SCHEDULED, PREEMPTED + timestamps
    prefill_stats: PrefillStats | None = None   # includes cached-token counts
    num_nans_in_logits: int = 0                 # > 0 means the output is corrupted
    ...

finish_reason is an integer on the wire (FinishReason is an IntEnum, for compactness) and a word in the API. STOP and LENGTH are the ones clients see every day. ERROR is a retryable internal failure, always turned into HTTP 500. REPETITION ends a request whose output has fallen into a repeating loop. The events list is how latency metrics are built: the engine core stamps each state change with its own clock, and the API server computes queue time and prefill time from the differences (19.c).

Inside the engine core: two threads and a loop#

Socket I/O and serialisation release the GIL, so they can overlap with the GPU. The engine core exploits that with two helper threads. The comment in EngineCoreProc.__init__ says so:

Python
# Background Threads and Queues for IO. These enable us to
# overlap ZMQ socket IO with GPU since they release the GIL,
# and to overlap some serialization/deserialization with the
# model forward pass.
# Threads handle Socket <-> Queues and core_busy_loop uses Queue.
  • The input thread (process_input_sockets) receives frames, decodes msgpack, and does the per-request preparation there too (preprocess_add_request): it builds the scheduler’s Request object and computes the prompt’s block hashes for prefix caching. That work overlaps with the forward pass of the step in progress.
  • The output thread (process_output_sockets) encodes results and sends them, reusing its byte buffers between steps instead of allocating new ones.
  • The main thread only ever touches two in-memory queues. It never blocks on a socket.

An abort gets special handling. It is placed on both the ordinary input queue and a separate aborts_queue, and the main loop drains the second one right after each forward pass. A cancelled request therefore stops consuming GPU one step later, not after everything queued ahead of it has been handled. (Aborting twice is harmless; the scheduler’s abort is idempotent.)


6. Under the hood: the engine core to worker wire#

Workers are on the same machine as their engine core (or its leader node), and with tensor parallelism every worker must receive the same schedule at the same moment. That is a broadcast, and vLLM implements it as a ring buffer in shared memory (ShmRingBuffer, wrapped by MessageQueue, in vllm/distributed/device_communicators/shm_broadcast.py): one writer, N readers, no locks.

+-------------------------------+------------------------------------+
| chunk 0 | chunk 1 | ... | chunk | meta 0 | meta 1 | ... | meta      |
+-------------------------------+------------------------------------+
  max_chunks × max_chunk_bytes     max_chunks × (1 + n_readers) bytes

each meta = [ written | reader0 | reader1 | ... ]   one byte per flag

The writer may reuse a chunk only when it is unwritten or every reader has marked it read. A reader may read a chunk when written is 1 and its own flag is 0. The writer’s order is fixed: clear written, write the data, clear the reader flags, then set written. Because there is a single writer and each reader touches only its own flag byte, no mutex is needed.

Each message is (method_name, args, kwargs, output_rank): an instruction to call a method on the worker object. The worker’s whole main loop is:

Python
def worker_busy_loop(self):
    """Main busy loop for Multiprocessing Workers."""
    assert self.rpc_broadcast_mq is not None
    while True:
        self._execute_worker_rpc(self.rpc_broadcast_mq.dequeue(indefinite=True))

Every worker executes the call, but only the worker whose rank equals output_rank sends a reply (or all of them, when output_rank is None). For execute_model that is the first tensor-parallel worker of the last pipeline stage. All tensor-parallel ranks compute the same sampled tokens, so one answer is enough.

A chunk holds 16 MiB by default (VLLM_MQ_MAX_CHUNK_BYTES_MB); a larger message is flagged as overflow and sent through a ZeroMQ side channel. If the engine core waits more than 300 seconds for a reply (VLLM_EXECUTE_MODEL_TIMEOUT_SECONDS), it treats the executor as failed.

They live and die together#

There is no partial failure by default:

  • If a worker dies, the executor’s monitor thread notices, an EXECUTOR_FAILED item is put on the engine core’s input queue, and the busy loop raises.
  • If the engine core dies, its output thread’s last act is to send the literal bytes ENGINE_CORE_DEAD to every API server. Each API server marks itself errored; every pending and future request fails with EngineDeadError, and /health returns 503.

The intended recovery is to restart the whole server, which is what a Kubernetes liveness probe on /health does (19.e). v0.32.0 also has an opt-in fault-tolerance mode (--enable-fault-tolerance, off by default; it requires external data-parallel load balancing and one API server) aimed at recovering from a failed data-parallel engine core instead of restarting everything.

Start methods#

Child processes are started with fork by default (VLLM_WORKER_MULTIPROC_METHOD), which is fast but unsafe once CUDA has been initialised in the parent. So:

  • when started as vllm serve, vLLM controls the main process and switches to spawn;
  • when used as a library, it uses fork, unless it detects CUDA (or XPU) already initialised, a Ray actor, --numa-bind or WSL, in which case it switches to spawn and logs a warning naming the reason.

This is why a script that uses the LLM class should put its code under if __name__ == "__main__":. With spawn, the child re-imports your script, and unguarded code would start a second engine from inside the first.

The broadcast in Go#

The flag protocol, for one writer and two readers:

Go
package main

import "fmt"

const readers = 2

type chunk struct {
	data    string
	written byte
	read    [readers]byte
}

type ring struct {
	chunks   []chunk
	writeIdx int
	readIdx  [readers]int
}

// canWrite: the chunk was never written, or every reader has consumed it.
func (c *chunk) canWrite() bool {
	if c.written == 0 {
		return true
	}
	for _, f := range c.read {
		if f == 0 {
			return false
		}
	}
	return true
}

func (r *ring) enqueue(msg string) bool {
	c := &r.chunks[r.writeIdx]
	if !c.canWrite() {
		return false // a slow reader is holding the writer back
	}
	c.written = 0 // order matters: clear, write, reset readers, then publish
	c.data = msg
	c.read = [readers]byte{}
	c.written = 1
	r.writeIdx = (r.writeIdx + 1) % len(r.chunks)
	return true
}

func (r *ring) dequeue(id int) (string, bool) {
	c := &r.chunks[r.readIdx[id]]
	if c.written == 0 || c.read[id] == 1 {
		return "", false
	}
	c.read[id] = 1 // each reader writes only its own flag: no lock needed
	r.readIdx[id] = (r.readIdx[id] + 1) % len(r.chunks)
	return c.data, true
}

func main() {
	r := &ring{chunks: make([]chunk, 2)}

	fmt.Println("enqueue step-1:", r.enqueue("execute_model(step 1)"))
	fmt.Println("enqueue step-2:", r.enqueue("execute_model(step 2)"))
	fmt.Println("enqueue step-3:", r.enqueue("execute_model(step 3)"), "<- ring is full")

	m, _ := r.dequeue(0)
	fmt.Println("worker 0 got:", m)
	fmt.Println("enqueue step-3:", r.enqueue("execute_model(step 3)"), "<- worker 1 has not read chunk 0")

	m, _ = r.dequeue(1)
	fmt.Println("worker 1 got:", m)
	fmt.Println("enqueue step-3:", r.enqueue("execute_model(step 3)"), "<- now every reader is done with it")
}

Output:

enqueue step-1: true
enqueue step-2: true
enqueue step-3: false <- ring is full
worker 0 got: execute_model(step 1)
enqueue step-3: false <- worker 1 has not read chunk 0
worker 1 got: execute_model(step 1)
enqueue step-3: true <- now every reader is done with it

The last three lines are the important ones: the writer is blocked by the slowest reader. In vLLM the writer then waits, and every 60 seconds (VLLM_RINGBUFFER_WARNING_INTERVAL) logs “No available shared memory broadcast block found in 60 seconds”. If you see that message outside startup, one worker is stuck (often a hung GPU or a collective waiting for a peer) and the others are waiting for it. During startup it can simply mean a worker is still compiling.


7. Performance implications#

This program answers the sizing question for any topology: how many processes you will see, and how many cores the project’s rule asks for.

Go
package main

import "fmt"

type topology struct {
	name       string
	tp, pp, dp int
	apiServers int // 0 means "use the default", which is the data-parallel size
}

func main() {
	cases := []topology{
		{name: "1 GPU", tp: 1, pp: 1, dp: 1},
		{name: "4 GPUs, one big model (-tp 4)", tp: 4, pp: 1, dp: 1},
		{name: "8 GPUs, -tp 2 -dp 4", tp: 2, pp: 1, dp: 4},
		{name: "8 GPUs, 8 replicas (-dp 8)", tp: 1, pp: 1, dp: 8},
		{name: "8 GPUs, -dp 8, 2 API servers", tp: 1, pp: 1, dp: 8, apiServers: 2},
	}
	fmt.Printf("%-31s %4s %4s %4s %8s %6s %5s %6s %6s\n",
		"deployment", "API", "lnch", "eng", "workers", "coord", "ps", "cores", "vCPUs")
	for _, c := range cases {
		api := c.apiServers
		if api == 0 {
			api = c.dp
		}
		launcher := 0 // with several API servers, the `vllm serve` process only supervises
		if api > 1 {
			launcher = 1
		}
		gpus := c.dp * c.pp * c.tp
		workers := gpus
		if gpus == 1 {
			workers = 0 // one GPU: the worker runs inside the engine core process
		}
		coord := 0
		if c.dp > 1 {
			coord = 1
		}
		inPs := api + launcher + c.dp + workers + coord
		// The docs' sizing rule: one physical core per busy job, one GPU = one job.
		cores := api + c.dp + gpus + coord
		fmt.Printf("%-31s %4d %4d %4d %8d %6d %5d %6d %6d\n",
			c.name, api, launcher, c.dp, workers, coord, inPs, cores, 2*cores)
	}
}

Output:

deployment                       API lnch  eng  workers  coord    ps  cores  vCPUs
1 GPU                              1    0    1        0      0     2      3      6
4 GPUs, one big model (-tp 4)      1    0    1        4      0     6      6     12
8 GPUs, -tp 2 -dp 4                4    1    4        8      1    18     17     34
8 GPUs, 8 replicas (-dp 8)         8    1    8        8      1    26     25     50
8 GPUs, -dp 8, 2 API servers       2    1    8        8      1    20     19     38

The -tp 2 -dp 4 row reproduces the docs’ worked example of 17 processes needing cores (the idle launcher is not counted). Other consequences:

  • The API server is the first CPU bottleneck under many short streaming requests, because it tokenises, detokenises and serialises JSON for every token. With data parallelism there are DP of them by default; --api-server-count changes that.
  • Serialisation is per step, not per token per request. One EngineCoreOutputs carries every request’s new tokens, so the wire cost grows with batch size much more slowly than the number of messages would suggest.
  • The broadcast lets the engine core run ahead of its workers by up to the number of chunks in the ring, which is what async scheduling (17.d) relies on.

8. Production implications#

  • Size CPU by the formula above, in physical cores, and check container CPU limits. CPU starvation looks like a slow GPU.
  • Any process dying kills the server on purpose. Liveness probes on /health and a restart policy are the recovery path.
  • “No available shared memory broadcast block found” after startup means a stuck worker; collect py-spy dump stacks from every VLLM::Worker process before restarting.
  • /dev/shm must be large enough in containers (--ipc=host or a larger --shm-size, 16.b).
  • Scripts that embed the LLM class need the if __name__ == "__main__": guard.

9. Common mistakes#

  1. Counting one process per GPU plus one. With one GPU there are two processes; with data parallelism there are also several API servers, a launcher and a coordinator.
  2. Giving a vLLM pod two vCPUs. The engine core alone wants a full physical core.
  3. Expecting one failed worker to be survivable. By default the whole server goes down.
  4. Searching ps only for VLLM::. A single API server keeps its vllm serve command line as its title.
  5. Reading a startup “no available block” warning as a hang. Compilation can legitimately keep a worker busy for minutes.

10. Hands-on exercise#

  1. On a machine running vLLM, run ps -eo pid,args | grep -E "VLLM::|vllm serve" and count the processes. Does the count match the ps column of the sizing program?
  2. In the sizing program, add a case for 16 GPUs with -tp 8 -dp 2. How many vCPUs does that node need at minimum?
  3. In the ring buffer program, change the ring to 4 chunks and enqueue 5 messages before any reader runs. Which enqueue fails, and what does that say about how far ahead of its workers an engine core can get?
  4. Find _get_output_rank in vllm/v1/executor/multiproc_executor.py. With TP=4, PP=2, which rank replies?

11. Interview questions#

  1. Why does vLLM use separate processes instead of threads for the API server and engine core?
  2. Why does the engine core send the first message to the API server, and not the other way round?
  3. What three options on EngineCoreRequest’s class declaration make it cheaper to send and hold?
  4. With tensor parallelism of 4, how many workers execute execute_model and how many reply?
  5. Why is an abort put on two queues?
  6. How does a shared-memory ring buffer with one writer and several readers avoid locks?

12. Further reading#

Checked on 13 November 2026, against the v0.32.0 tag.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in