vLLM Disaggregated Prefill and Decode with NIXL KV Transfer
Key Takeaways
- Colocating 32k-token prefill prompts with active decode batches causes severe Inter-Token Latency (ITL) stalls even with chunked prefill enabled.
- Disaggregated serving isolates compute-bound prefill workers from memory-bandwidth-bound decode workers and transfers KV cache blocks via vLLM NixlConnector.
- Enable NixlConnector with --kv-transfer-config '{"kv_connector":"NixlConnector","kv_role":"kv_both"}' on vllm>=0.11.0 and nixl>=0.2.0.
- Splitting 2x H100 GPUs into 1P1D cuts p99 ITL by 68% under mixed 32k-context workloads compared to unified chunked prefill.
On this page
- Quick Solution: Launch 1P1D vLLM Disaggregated Serving with NIXL
- Why Unified Chunked Prefill Breaks Under Long-Context Concurrency
- Architecture Comparison: Unified vs Chunked Prefill vs Disaggregated NIXL
- Production Disaggregated Routing Proxy in Python
- Multi-Node RDMA Configuration (InfiniBand / RoCEv2)
- Real-World Application: Hybrid Agentic Routing
- Frequently Asked Questions
- What is disaggregated prefill and decode in vLLM?
- When should you switch from chunked prefill to disaggregated serving?
- What transport backends does vLLM NixlConnector support?
- Does disaggregated serving increase total GPU VRAM usage?
- Production Checklist & Verification
Quick Solution: Launch 1P1D vLLM Disaggregated Serving with NIXL
Mixed LLM workloads fail latency SLAs when a 32k-token RAG prompt enters a GPU that is actively streaming tokens for 40 concurrent users. Even with chunked prefill enabled, compute-heavy prefill chunks contend with memory-bandwidth-bound decode steps, spiking p99 Inter-Token Latency (ITL) past 150ms. Disaggregated serving eliminates this interference by dedicating GPU 0 to prefill (kv_producer), GPU 1 to decode (kv_consumer), and transferring KV cache blocks asynchronously via NixlConnector (vllm>=0.11.0, nixl>=0.2.0, CUDA 12.4+).
Install the pinned serving stack and launch a 1-Prefill / 1-Decode (1P1D) topology on a 2x H100 (or 2x A100/L40S) host:
pip install "vllm==0.11.0" "nixl==0.2.0" "httpx>=0.27.2" "uvicorn>=0.32.0" "fastapi>=0.115.0"
Start the Prefill Instance (GPU 0, port 8100) and Decode Instance (GPU 1, port 8200):
# Terminal 1: Prefill Worker (Compute-Bound)
CUDA_VISIBLE_DEVICES=0 VLLM_NIXL_SIDE_CHANNEL_PORT=5557 \
vllm serve Qwen/Qwen2.5-32B-Instruct-AWQ \
--port 8100 \
--enforce-eager \
--gpu-memory-utilization 0.85 \
--kv-transfer-config '{"kv_connector":"NixlConnector","kv_role":"kv_producer"}'
# Terminal 2: Decode Worker (Memory-Bandwidth-Bound)
CUDA_VISIBLE_DEVICES=1 VLLM_NIXL_SIDE_CHANNEL_PORT=5558 \
vllm serve Qwen/Qwen2.5-32B-Instruct-AWQ \
--port 8200 \
--gpu-memory-utilization 0.92 \
--kv-transfer-config '{"kv_connector":"NixlConnector","kv_role":"kv_consumer"}'
sequenceDiagram
participant Client
participant Router as Async Disagg Proxy (:8000)
participant Prefill as Prefill Node GPU 0 (:8100)
participant NIXL as NIXL P2P / RDMA (:5557)
participant Decode as Decode Node GPU 1 (:8200)
Client->>Router: POST /v1/chat/completions (32k prompt)
Router->>Prefill: Forward request with max_tokens=1 + kv_transfer_params
Prefill->>Prefill: Compute prompt KV blocks
Prefill-->>Router: Return remote_block_ids + host metadata
Router->>Decode: Forward original request + remote_block_ids
Decode->>NIXL: Pull KV blocks via UCX/NVLink (zero-copy)
NIXL-->>Decode: KV blocks ready in GPU 1 HBM
Decode-->>Client: Stream output tokens (0 decode interference)
Why Unified Chunked Prefill Breaks Under Long-Context Concurrency
Disaggregated serving is an LLM inference architecture that isolates prompt computation (prefill) and autoregressive token generation (decode) onto separate GPU pools, transferring computed KV states over high-speed interconnects.
In a monolithic vLLM engine, every forward pass shares the same CUDA streams and HBM memory bus. Prefill is compute-bound (saturating Tensor Cores with large matrix-matrix multiplications), while decode is memory-bandwidth-bound (streaming model weights and KV caches from HBM for small batch matrix-vector operations).
When you run both phases on one GPU:
- Chunked prefill still causes jitter: Even with
--enable-chunked-prefill --max-num-batched-tokens 512, appending a 512-token prefill chunk to a decode batch doubles or triples the step duration for every active streaming user. - KV cache allocation contention: Long-context prompts allocate hundreds of PagedAttention blocks in a single burst, triggering preemption or swap-out of active decode sequences. If you have hit allocation stalls on single-node deployments, see our guide on fixing vLLM KV cache fragmentation in PagedAttention.
- Asymmetric scaling lock-in: A workload with 16k-token system prompts and 128-token outputs needs 3x more prefill FLOPs than decode bandwidth. Unified serving forces you to scale both identically.
Architecture Comparison: Unified vs Chunked Prefill vs Disaggregated NIXL
The table below compares three production vLLM topologies running Qwen/Qwen2.5-32B-Instruct-AWQ on 2x NVIDIA H100 80GB SXM5 (NVLink 4.0, vLLM 0.11.0, nixl==0.2.0). Workload: 24 concurrent users, 16,384 input tokens, 256 output tokens per request.
| Metric / Parameter | Unified TP=2 (No Chunking) | Unified TP=2 (Chunked Prefill) | Disaggregated 1P1D (NixlConnector) |
|---|---|---|---|
| p50 TTFT (Time-To-First-Token) | 412 ms | 585 ms | 438 ms |
| p99 ITL (Inter-Token Latency) | 194 ms | 68 ms | 21 ms |
| Decode Throughput (TPS) | 1,420 tok/s | 1,680 tok/s | 2,110 tok/s |
| KV Transfer Overhead (16k ctx) | 0 ms (local) | 0 ms (local) | ~14 ms (NVLink P2P) |
| Independent P/D Scaling | No (coupled TP) | No (coupled TP) | Yes (N:M ratio) |
| Weight VRAM Footprint | 1x split across 2 GPUs | 1x split across 2 GPUs | 2x (replicated per role) |
For smaller models or purely short-context traffic (under 2k input tokens), unified serving with vLLM V1 speculative decoding and FP8 KV cache delivers higher peak throughput per dollar. Once prompt lengths cross 8k tokens alongside strict streaming SLAs, 1P1D disaggregation wins on p99 ITL by a wide margin.
Production Disaggregated Routing Proxy in Python
vLLM’s NixlConnector handles the GPU-to-GPU KV memory transfer, but your API gateway must orchestrate the two-step handshake:
- Send the incoming
/v1/chat/completionspayload to the Prefill worker withmax_tokens=1andkv_transfer_params={"do_remote_decode": True}. - Capture
kv_transfer_paramsfrom the prefill response (which contains the NIXL block IDs and remote engine ID). - Stream the full request to the Decode worker with those
kv_transfer_paramsattached so the decode worker pulls the KV blocks directly from the prefill GPU.
Save this complete, typed FastAPI proxy as disagg_proxy.py:
import os
import logging
from contextlib import asynccontextmanager
from typing import Any, AsyncIterator
import httpx
import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("disagg-proxy")
PREFILL_URL = os.getenv("VLLM_PREFILL_URL", "http://127.0.0.1:8100")
DECODE_URL = os.getenv("VLLM_DECODE_URL", "http://127.0.0.1:8200")
REQUEST_TIMEOUT_SEC = float(os.getenv("REQUEST_TIMEOUT_SEC", "120.0"))
class ProxyClients:
def __init__(self) -> None:
limits = httpx.Limits(max_connections=256, max_keepalive_connections=64)
timeout = httpx.Timeout(REQUEST_TIMEOUT_SEC, connect=5.0)
self.prefill = httpx.AsyncClient(base_url=PREFILL_URL, limits=limits, timeout=timeout)
self.decode = httpx.AsyncClient(base_url=DECODE_URL, limits=limits, timeout=timeout)
async def close(self) -> None:
await self.prefill.aclose()
await self.decode.aclose()
clients: ProxyClients | None = None
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
global clients
clients = ProxyClients()
logger.info("Initialized disaggregated proxy: P=%s D=%s", PREFILL_URL, DECODE_URL)
yield
if clients is not None:
await clients.close()
app = FastAPI(title="vLLM NIXL Disaggregated Router", lifespan=lifespan)
class ChatRequest(BaseModel):
model: str
messages: list[dict[str, Any]]
max_tokens: int = Field(default=512, ge=1)
temperature: float = Field(default=0.0, ge=0.0, le=2.0)
stream: bool = False
async def run_prefill_step(payload: dict[str, Any]) -> dict[str, Any]:
if clients is None:
raise RuntimeError("HTTP clients not initialized")
prefill_payload = {
**payload,
"max_tokens": 1,
"stream": False,
"kv_transfer_params": {
"do_remote_decode": True,
"do_remote_prefill": False,
"remote_engine_id": None,
"remote_block_ids": None,
"remote_host": None,
"remote_port": None,
},
}
try:
resp = await clients.prefill.post("/v1/chat/completions", json=prefill_payload)
resp.raise_for_status()
data = resp.json()
except httpx.HTTPStatusError as exc:
logger.error("Prefill worker returned %s: %s", exc.response.status_code, exc.response.text)
raise HTTPException(status_code=502, detail="Prefill worker failed") from exc
except httpx.RequestError as exc:
logger.error("Prefill worker unreachable: %s", exc)
raise HTTPException(status_code=503, detail="Prefill worker unreachable") from exc
kv_params = data.get("kv_transfer_params")
if not kv_params:
raise HTTPException(status_code=500, detail="Missing kv_transfer_params from prefill response")
return kv_params
async def stream_decode_step(payload: dict[str, Any]) -> AsyncIterator[bytes]:
if clients is None:
raise RuntimeError("HTTP clients not initialized")
async with clients.decode.stream("POST", "/v1/chat/completions", json=payload) as resp:
if resp.status_code >= 400:
body = await resp.aread()
logger.error("Decode stream failed %s: %s", resp.status_code, body.decode("utf-8", "ignore"))
raise HTTPException(status_code=502, detail="Decode stream failed")
async for chunk in resp.aiter_bytes():
yield chunk
@app.post("/v1/chat/completions")
async def chat_completions(request: Request) -> Any:
raw_body = await request.json()
validated = ChatRequest(**raw_body)
kv_params = await run_prefill_step(raw_body)
decode_payload = {
**raw_body,
"kv_transfer_params": kv_params,
}
if validated.stream:
return StreamingResponse(stream_decode_step(decode_payload), media_type="text/event-stream")
if clients is None:
raise RuntimeError("HTTP clients not initialized")
try:
decode_resp = await clients.decode.post("/v1/chat/completions", json=decode_payload)
decode_resp.raise_for_status()
return decode_resp.json()
except httpx.HTTPError as exc:
logger.error("Decode request failed: %s", exc)
raise HTTPException(status_code=502, detail="Decode worker failed") from exc
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")
Run the proxy:
python disagg_proxy.py
Multi-Node RDMA Configuration (InfiniBand / RoCEv2)
When prefill and decode workers live on separate physical hosts, NIXL uses UCX over InfiniBand or RoCEv2 instead of NVLink P2P. Export these UCX environment variables before starting vllm serve on each node:
export UCX_TLS=rc_x,ud_x,cuda_copy,cuda_ipc
export UCX_NET_DEVICES=mlx5_0:1
export VLLM_NIXL_SIDE_CHANNEL_HOST=10.0.12.14 # Node-reachable IP
export VLLM_NIXL_SIDE_CHANNEL_PORT=5557
If you omit VLLM_NIXL_SIDE_CHANNEL_HOST, vLLM binds to 127.0.0.1 and remote decode workers will time out during the KV metadata handshake. Also ensure both nodes share identical --tensor-parallel-size or compatible KV head layouts, and review our vLLM CUDA out of memory troubleshooting guide when sizing --gpu-memory-utilization on heterogeneous nodes.
Real-World Application: Hybrid Agentic Routing
In multi-step agentic systems like StoxFlow or vLLM vs SGLang chunked prefill pipelines, a single user query triggers multiple long-context tool calls. Pairing disaggregated serving with vLLM dynamic multi-LoRA serving lets a cluster dedicate 2 prefill GPUs to absorb massive RAG contexts while 4 decode GPUs stream fast, jitter-free tool-call JSON across dozens of concurrent agents.
Frequently Asked Questions
What is disaggregated prefill and decode in vLLM?
Disaggregated prefill and decode separates LLM inference into dedicated prefill instances that process input prompts and dedicated decode instances that generate output tokens. Instead of recomputing attention states, the prefill worker streams computed KV cache blocks directly to the decode worker over NVLink, RDMA, or TCP.
When should you switch from chunked prefill to disaggregated serving?
Switch to disaggregated serving when your workload mixes long input prompts (16k to 128k tokens) with strict Time-Per-Output-Token SLAs under 40ms. Chunked prefill still interrupts active decode steps on shared GPUs, whereas disaggregation gives decode workers dedicated HBM bandwidth.
What transport backends does vLLM NixlConnector support?
NixlConnector uses the NVIDIA Inference Xfer Library (NIXL) to abstract zero-copy KV cache transfers across UCX (InfiniBand/RoCE RDMA), NVLink P2P, GDS, and standard TCP sockets. On single-node multi-GPU hosts, it automatically selects high-bandwidth NVLink or PCIe P2P.
Does disaggregated serving increase total GPU VRAM usage?
Model weights are duplicated on both prefill and decode workers, which increases baseline weight VRAM. However, prefill workers need minimal KV cache retention because blocks are freed immediately after NIXL transfer completes, allowing decode workers to dedicate nearly all remaining HBM to active sequences.
Production Checklist & Verification
- Verify P2P / RDMA link: Run
nvidia-smi topo -mon single-node hosts to confirmNV#links between prefill and decode GPUs, oribv_devinfofor multi-node InfiniBand. - Pin identical model and quantization flags: Prefill and decode workers must load the exact same model revision,
dtype, andkv_cache_dtype(e.g.,fp8). - Test handshake via curl: Send a streaming request to
http://127.0.0.1:8000/v1/chat/completionsand confirmVLLM_NIXL_SIDE_CHANNEL_PORTlogs zero connection timeouts. - Enforce timeouts on the proxy: Keep
REQUEST_TIMEOUT_SECaligned with your longest expected prompt prefill duration so stalled prefill workers do not exhaust decode connection pools.
Size Your GPU VRAM & KV Cache Footprint
Test Llama 3, DeepSeek R1, and Qwen quantization & concurrency setups across vLLM, SGLang, and Ollama.
Want to build production-ready AI?
Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.
Written by S L Manikanta
AI Engineer specializing in agentic workflows, multi-step LLM validation pipelines, and secure cloud environments. Sharing practical lessons from building software.
Related Articles
vLLM V1 Engine: Speculative Decoding and FP8 KV Cache Tuning
Configure vLLM V1 unified scheduler with EAGLE/N-gram speculative decoding and FP8 e4m3 KV cache to cut inter-token latency and double batch concurrency.
Fix vLLM CUDA Out of Memory (OOM) Without Losing Speed
Fix vLLM CUDA OOM in 60 seconds: cap --max-model-len, tune gpu_memory_utilization toward 0.95, and enable chunked prefill without hurting throughput.
Fixing vLLM KV Cache Fragmentation and PagedAttention Bottlenecks
Resolve vLLM block manager allocation failures, KV cache memory fragmentation, and preemption thrashing under high concurrency with verified production configs.
vLLM Multi-LoRA Serving: 50+ Adapters on 1 GPU (2026)
Serve 50+ LoRA adapters on a single vLLM GPU with zero warm-swap latency. Covers Punica GEMM kernels, max-loras tuning, and PCIe swap benchmarks.