This document is relevant for: Trn2, Trn3
Tutorial: Serve vLLM Neuron in production with llm-d on Amazon EKS#
This tutorial deploys vLLM Neuron on Amazon EKS behind llm-d. llm-d is a production serving layer for vLLM. It schedules each request on the servers of a deployment. In this tutorial, the deployment is disaggregated. At the end, you have two prefill servers and one decode server behind the llm-d router. Then you verify that the decode server reads the KV cache over NIXL. You also verify that the router sends a request to the prefill server that holds its cached prefix.
Overview#
The deployment in this tutorial uses these llm-d production serving features:
llm-d has more production serving features, for example wide expert parallelism, tiered prefix caching, flow control, and workload autoscaling. This tutorial does not deploy them. See Next steps.
This tutorial uses Qwen/Qwen3-8B as the example model. You can use the same
procedure for another model that vLLM Neuron can serve in a disaggregated
deployment. For each new model, do the checks in
Verify the deployment. Some values depend on your deployment. The
Configuration rules section gives the rules and the
values.
Disaggregated prefill and decode#
The prefill servers compute the KV cache of the prompt. The decode server reads this KV cache over NIXL and generates the tokens. It does not compute the prompt again. The P/D sidecar in the decode pod sends each request first to the selected prefill server, then to the decode server.
KV-cache-aware routing#
A KV-cache-aware router tracks the KV cache blocks that each prefill server holds. For each request, it gives a higher score to a prefill server with a longer match of cached blocks. A repeated prefix then skips the prefill computation of the cached blocks.
A round-robin router selects the server with the cached prefix only one time in N, where N is the number of prefill servers. A KV-cache-aware router selects it each time that the servers have the same load.
The router also scores the queue length of each server. The prefill profile
in router-values.yaml sets a weight for each score. This tutorial uses the
weight 2 for the prefix score and the weight 1 for the queue score. A higher
prefix weight makes the router prefer the cached prefix more. With these
weights, a server with the cached prefix and a much longer queue can lose the
request to a server with a shorter queue.
The llm-d router builds its index from the KV events of vLLM. Each prefill
server publishes a BlockStored event when it stores a KV cache block and a
BlockRemoved event when it removes one. The router subscribes to these events.
The router does not guess the cache contents from the prompt text.
Components#
The router has two parts: Envoy and the endpoint picker (EPP). The llm-d chart deploys them in one pod.
Component |
Image |
Function |
|---|---|---|
Envoy |
|
Receives the client request. Asks the endpoint picker (EPP) for a target. |
Endpoint picker (EPP) |
|
Keeps an index of the KV blocks from the KV events of the prefill servers. Gets the token IDs of the prompt from a prefill server. Selects a prefill server and a decode server. |
Prefill server |
vLLM Neuron DLC |
Computes the KV cache of the prompt. Publishes KV events. |
Decode server |
vLLM Neuron DLC |
Reads the KV cache from the prefill server over NIXL and generates tokens. |
P/D sidecar |
|
Runs in the decode pod. Sends the prefill request to the selected prefill server, then sends the decode request to the local decode server. |
You deploy the prefill pods and the decode pod. The decode pod includes the P/D sidecar.
Request flow#
The client sends a request to Envoy.
Envoy sends the request to the EPP.
The EPP gets the token IDs of the prompt from a prefill server, through the
prefill-renderService.The EPP scores each prefill server by its cached prefix and its queue length. It selects the prefill server with the highest score. It also selects the decode server with the shortest queue.
Envoy sends the request to the P/D sidecar of the decode pod. The request carries the selected prefill server in the
x-llm-d-prefiller-host-portheader.The sidecar sends the prefill request to the selected prefill server.
The sidecar sends the decode request to the local decode server. The decode server reads the KV cache from the prefill server and generates the tokens.
The sidecar sends the response to the client through Envoy.
Prerequisites#
An Amazon EKS cluster with these node groups:
Three Trainium nodes for the prefill servers and the decode server, one node for each server. This tutorial uses
trn3.48xlargenodes. For a different instance type, change the device counts and the tensor parallel size in the manifests.One CPU node for the router. The router pod requests 2 vCPUs and 3 GiB of memory. Give the node the label
role=router:kubectl label node <router-node-name> role=router.
Trainium nodes that use the Amazon EKS optimized accelerated AMI for Neuron. This AMI has the Neuron driver.
EFA on the Trainium nodes, set up as in Amazon EKS: Elastic Fabric Adapter. Each node needs one EFA interface on each network card, the EFA software, and a security group that allows all traffic to and from itself. Put the Trainium nodes in one subnet. The KV cache moves between the nodes over EFA.
The Neuron device plugin and the EFA device plugin on the cluster. See Install the device plugins.
The Gateway API Inference Extension CRDs, version v1.6.2. See Install the Inference Extension CRDs.
kubectl, Helm 3.8 or later, and Python 3 with therequestspackage on your workstation.envsubston your workstation. Thegettextpackage supplies this command. The manifests use it to set the container image.The vLLM Neuron Deep Learning Container (DLC) from
public.ecr.aws/neuron/pytorch-inference-vllm-neuronx. See Set the container image and the llm-d version.A model that vLLM Neuron supports for disaggregated inference. See Disaggregated inference: 1P1D and xPyD. This tutorial uses
Qwen/Qwen3-8Bas the example. This model is not gated, so the servers download it without a Hugging Face token.
For a gated model, create a Kubernetes secret with your Hugging Face token. Then
add an HF_TOKEN entry from this secret to the env list of each server
container.
Configuration rules#
Apply these rules to every deployment. A wrong value in rules 1 to 5 or 9 does not stop the deployment. The servers start, and requests can succeed. But the router does not follow the cache, the decode server reads the wrong KV cache, or some requests fail.
Rules 1, 2, 3, 6, and 9 are for KV-cache-aware routing. Rules 4, 5, and 8 are for disaggregated prefill and decode. Rule 7 is for all servers in the pool.
Set
blockSizeTokensof the router to the token span of one engine hash block. This value is the engine--block-sizemultiplied by the decode context parallel size. If the engine does not use decode context parallelism, use the--block-sizevalue. This formula applies to a model with one KV cache group. For a model with more than one KV cache group, the span is the--prefix-match-unitvalue, or the greatest common divisor of the block sizes of the groups. The example model in this tutorial has one KV cache group. With a different value, the router can skip some KV events, and the index can keep blocks that the server removed. Some cached prefixes then do not match. Use the same value to get a one-to-one map between the engine blocks and the index blocks.Set the KV events endpoint to
tcp://*:<port>. The router connects to each prefill server to receive its KV events, so each prefill server must listen on the port. vLLM listens when the endpoint contains*or::. With an IPv4 address, for exampletcp://0.0.0.0:5557or the IP address of the pod, vLLM connects to that address and does not listen. vLLM gives no error, and the router receives no events. SetsocketPortof the router to the same port.Set
prefixMatchInfoProducerName: precise-prefix-cache-produceron the prefix cache scorer. Without this parameter, the scorer uses the approximate prefix producer. The approximate producer estimates the cache contents from the prompts that the router sent before, and ignores the KV events.Set
deciders.prefill: always-disagg-pd-deciderondisagg-profile-handler. A Neuron decode server does not compile the prefill graphs, so it cannot serve a full request. Without a prefill decider, the router turns off disaggregation and sends each request to the decode server alone. Theprefix-based-pd-deciderof the upstream examples also sends some requests to the decode server alone.Give each prefill server a unique
engine_idin--kv-transfer-config. The NIXL connector of vLLM identifies a remote server by itsengine_idonly. If two prefill servers use the same ID, the decode server reads the KV cache of the wrong server.Make sure that the prefill servers serve the render endpoint. The EPP calls
/v1/completions/renderon a prefill server to get the token IDs of a prompt. vLLM 0.29 serves this endpoint by default, and it does not accept the--enable-scale-outflag. vLLM 0.30 and later serve the endpoint only with--enable-scale-out. The prefill manifest selects the flag from the vLLM version in the image, so it works with each DLC tag.Use one port for all servers in the InferencePool. The EPP makes one endpoint for each pod IP and each target port of the pool. If the prefill servers and the decode pod use different ports, the EPP sends requests to ports that do not serve them. This tutorial uses port 8000: the prefill servers listen on 8000, and the P/D sidecar of the decode pod listens on 8000. The decode server listens on 8200 in the decode pod.
Turn off TLS on the P/D sidecar. The sidecar serves TLS by default. The Envoy configuration of the llm-d chart connects to the servers over plain HTTP. This tutorial sets
--secure-serving=falseon the sidecar.Use the served model name in the KV events topic. The topic of each prefill server is
kv@<pod IP>:<port>@<model>. The index puts this model name in each stored block key. The router uses themodelfield of the request for the lookup keys. If the two names are different, the index finds no match, and the router gives no error.
Values for the example in this tutorial. The block size and the model name depend on your model. Use the other values as they are. If you change a port, change it in each location that the rules give.
Value |
Example |
Rule |
|---|---|---|
|
|
1 |
Decode context parallel size |
|
1 |
|
|
1 |
KV events endpoint |
|
2 |
|
|
2 |
Served model name (topic and request |
|
9 |
To use a different model, change the model name in prefill.yaml,
decode.yaml, and modelName of router-values.yaml. Also change it in each
request and command of this tutorial.
Prepare the cluster#
Install the device plugins#
If the cluster already has the Neuron device plugin and the EFA device plugin,
run the command at the end of this section first. If each Trainium node shows
the Neuron devices and the EFA devices, skip the install. If not, add your
instance types to the instance type list of the installed plugin, for example
with helm upgrade. Do not install a second copy of a plugin.
Find the instance types of your Trainium nodes:
kubectl get nodes -L node.kubernetes.io/instance-type
In the two helm install commands that follow, replace trn3.48xlarge with a
list of instance types from this output.
Install the Neuron device plugin. The neuronInstances value selects the nodes
that run the plugin. The value replaces the default list of the chart, so give
all of the instance types of the Neuron nodes on the cluster.
The chart installs a node problem detector in the neuron-healthcheck-system
namespace. The chart does not create this namespace. Create the namespace before
you install the chart.
kubectl create namespace neuron-healthcheck-system
helm install neuron oci://public.ecr.aws/neuron/neuron-helm-chart \
--version 1.11.2 \
--namespace kube-system \
--set-json 'neuronInstances=["trn3.48xlarge"]' \
--wait
Note
The Neuron device plugin sets NEURON_LOGICAL_NC_CONFIG in each pod. On Trn2
and Trn3 it sets 2, unless the node is configured for LNC 1. On a node with the
default setting, the servers in this tutorial run at LNC 2, and
--tensor-parallel-size 8 uses 16 physical NeuronCores. See
LNC on Kubernetes.
Install the EFA device plugin. The supportedInstanceLabels.values value also
replaces the default list of the chart, so give all of the instance types of the
EFA nodes on the cluster. The default list does not include Trn3 instance types,
so this value is necessary on Trn3.
helm repo add eks https://aws.github.io/eks-charts
helm repo update eks
helm install efa eks/aws-efa-k8s-device-plugin \
--version v0.5.35 \
--namespace kube-system \
--set-json 'supportedInstanceLabels.values=["trn3.48xlarge"]' \
--wait
Make sure that each Trainium node shows the Neuron devices and the EFA devices:
kubectl get nodes -o custom-columns='NODE:.metadata.name,NEURON:.status.allocatable.aws\.amazon\.com/neuron,EFA:.status.allocatable.vpc\.amazonaws\.com/efa'
Each Trainium node must show a number in the NEURON column and in the EFA
column. Each number must be equal to or more than the number of devices that one
prefill pod or the decode pod requests. The CPU node shows <none>. If a
Trainium node shows <none>, make sure that its instance type is in
neuronInstances and in supportedInstanceLabels.values.
Install the Inference Extension CRDs#
The router finds the servers through an InferencePool resource. Install the
CRDs:
kubectl apply --server-side -f \
https://github.com/kubernetes-sigs/gateway-api-inference-extension/releases/download/v1.6.2/manifests.yaml
The router runs in standalone mode, with Envoy in the EPP pod. It does not need the Gateway API CRDs or a Gateway controller.
Create the namespace#
kubectl create namespace llmd
Set the container image and the llm-d version#
The server manifests in this tutorial read the container image from the
VLLM_NEURON_IMAGE environment variable. Find the current tag of the vLLM
Neuron DLC in the
vLLM Inference NeuronX DLC list.
Then set the variable in the shell that you use to apply the manifests:
export VLLM_NEURON_IMAGE="public.ecr.aws/neuron/pytorch-inference-vllm-neuronx:<tag>"
Replace <tag> with the tag from the DLC list.
Set the llm-d version in the same shell. The decode manifest and the Helm
commands read it from the LLMD_VERSION environment variable:
export LLMD_VERSION="v1.0.0"
The router configuration in this tutorial is for llm-d v1.0.0. Before you set a later version, read its release notes. A new version can change the configuration format or the plugin names.
Set both variables in each terminal that you use.
The kubectl apply commands of the server manifests use envsubst with a
variable list, for example envsubst '${VLLM_NEURON_IMAGE}'. This command
replaces only the variables in the list. The container commands use other
variables, for example $MODEL, that the pod sets when it starts. Do not run
envsubst without the variable list, because it replaces these variables with
empty values.
Deploy the prefill servers#
Each prefill server computes the KV cache of the prompt for the decode server. It also publishes its KV events and serves the render endpoint for the EPP. Create one pod for each prefill server.
In this tutorial, each pod requests all of the Neuron devices and EFA devices of one node. This configuration does not need the Neuron scheduler extension.
Note
To put more than one server on a node, request part of the Neuron devices in each pod. Then install the Neuron scheduler extension. Without the extension, the device plugin can refuse an allocation of part of a node.
Save this manifest as prefill.yaml:
apiVersion: v1
kind: Pod
metadata:
name: prefill-0
namespace: llmd
labels:
app: vllm-neuron
llm-d.ai/role: prefill
spec:
restartPolicy: Never
containers:
- name: vllm
image: ${VLLM_NEURON_IMAGE}
command: ["/bin/bash", "-c"]
args:
- |
SCALE_OUT="$(python3 -c 'from importlib.metadata import version; v = tuple(int(x) for x in version("vllm").split(".")[:2]); print("--enable-scale-out" if v >= (0, 30) else "")')"
exec vllm serve "$MODEL" \
--port 8000 \
--tensor-parallel-size 8 \
--max-model-len 8192 \
--block-size 32 \
$SCALE_OUT \
--kv-events-config '{"enable_kv_cache_events": true, "publisher": "zmq", "endpoint": "tcp://*:5557", "topic": "kv@'"$POD_IP"':5557@'"$MODEL"'"}' \
--kv-transfer-config '{"kv_connector": "NeuronNixlConnector", "kv_role": "kv_producer", "kv_buffer_device": "cuda", "engine_id": "'"$ENGINE_ID"'", "kv_connector_extra_config": {"backends": ["LIBFABRIC"]}}'
env:
- { name: MODEL, value: Qwen/Qwen3-8B }
- { name: ENGINE_ID, value: prefill-0 }
- { name: POD_IP, valueFrom: { fieldRef: { fieldPath: status.podIP } } }
- { name: VLLM_NIXL_SIDE_CHANNEL_HOST, valueFrom: { fieldRef: { fieldPath: status.podIP } } }
- { name: VLLM_NIXL_SIDE_CHANNEL_PORT, value: "5600" }
- { name: VLLM_HTTP_TIMEOUT_KEEP_ALIVE, value: "120" }
- { name: HF_HOME, value: /cache/hf }
ports:
- { containerPort: 8000, name: http }
- { containerPort: 5557, name: kv-events }
- { containerPort: 5600, name: nixl }
resources:
limits:
aws.amazon.com/neuron: 16
vpc.amazonaws.com/efa: 16
readinessProbe:
httpGet: { path: /health, port: 8000 }
periodSeconds: 15
failureThreshold: 400
volumeMounts:
- { name: cache, mountPath: /cache }
- { name: dshm, mountPath: /dev/shm }
volumes:
- name: cache
hostPath: { path: /mnt/vllm-cache, type: DirectoryOrCreate }
- name: dshm
emptyDir: { medium: Memory, sizeLimit: 64Gi }
The important settings are:
image: ${VLLM_NEURON_IMAGE}— thekubectl applycommand replaces this value with the image that you set in Set the container image and the llm-d version.--kv-events-config— publishes the KV events on port 5557 with the ZMQ publisher. The endpointtcp://*:5557makes the server listen on the port (rule 2). The topic has the formatkv@<address>@<model>. The router subscribes to topics that start withkv@. The<model>value must equal the served model name (rule 9).SCALE_OUT— adds--enable-scale-outwhen the vLLM version in the image is 0.30 or later. The prefill server then serves the render endpoint (rule 6). When the variable is empty, the command gets no extra argument.kv_role: kv_producer— the prefill server keeps the KV cache of a request until the decode server reads it over NIXL.engine_id— a unique NIXL ID for each prefill server (rule 5).VLLM_NIXL_SIDE_CHANNEL_HOSTandVLLM_NIXL_SIDE_CHANNEL_PORT— the decode server connects to the pod IP on port 5600 to get the NIXL metadata of the prefill server.kv_buffer_device: cuda— on Neuron, this value means the Neuron device memory. vLLM Neuron accepts only this value. Do not change it.VLLM_HTTP_TIMEOUT_KEEP_ALIVE=120— keeps idle HTTP connections open for 120 seconds. The vLLM default is 5 seconds. The P/D sidecar and the EPP keep their idle connections for 90 seconds. With the default, the server can close a connection at the same time as a client reuses it, and the request fails.
Create the first prefill server:
: "${VLLM_NEURON_IMAGE:?Set VLLM_NEURON_IMAGE first}" && \
envsubst '${VLLM_NEURON_IMAGE}' < prefill.yaml | kubectl apply -f -
Create the second prefill server. This command changes the pod name and the
ENGINE_ID value to prefill-1:
envsubst '${VLLM_NEURON_IMAGE}' < prefill.yaml | sed 's/prefill-0/prefill-1/g' | kubectl apply -f -
Create a Service for the render endpoint of the prefill servers. The
token-producer URL in the router configuration uses the name, the namespace
and the port of this Service:
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Service
metadata:
name: prefill-render
namespace: llmd
spec:
selector:
app: vllm-neuron
llm-d.ai/role: prefill
ports:
- { name: http, port: 8000, targetPort: 8000 }
EOF
Deploy the decode server#
The decode pod has two containers: the decode server and the P/D sidecar. The sidecar listens on port 8000, which is the port of the InferencePool (rule 7). The decode server listens on port 8200.
Save this manifest as decode.yaml:
apiVersion: v1
kind: Pod
metadata:
name: decode-0
namespace: llmd
labels:
app: vllm-neuron
llm-d.ai/role: decode
spec:
restartPolicy: Never
containers:
- name: vllm
image: ${VLLM_NEURON_IMAGE}
command: ["/bin/bash", "-c"]
args:
- |
exec vllm serve "$MODEL" \
--port 8200 \
--tensor-parallel-size 8 \
--max-model-len 8192 \
--block-size 32 \
--kv-transfer-config '{"kv_connector": "NeuronNixlConnector", "kv_role": "kv_consumer", "kv_buffer_device": "cuda", "kv_connector_extra_config": {"backends": ["LIBFABRIC"]}}'
env:
- { name: MODEL, value: Qwen/Qwen3-8B }
- { name: VLLM_NIXL_SIDE_CHANNEL_HOST, valueFrom: { fieldRef: { fieldPath: status.podIP } } }
- { name: VLLM_NIXL_SIDE_CHANNEL_PORT, value: "5600" }
- { name: VLLM_HTTP_TIMEOUT_KEEP_ALIVE, value: "120" }
- { name: HF_HOME, value: /cache/hf }
ports:
- { containerPort: 8200, name: vllm }
resources:
limits:
aws.amazon.com/neuron: 16
vpc.amazonaws.com/efa: 16
readinessProbe:
httpGet: { path: /health, port: 8200 }
periodSeconds: 15
failureThreshold: 400
volumeMounts:
- { name: cache, mountPath: /cache }
- { name: dshm, mountPath: /dev/shm }
- name: pd-sidecar
image: ghcr.io/llm-d/llm-d-router-disagg-sidecar:${LLMD_VERSION}
args:
- --port=8000
- --model-server-port=8200
- --kv-connector=nixlv2
- --secure-serving=false
ports:
- { containerPort: 8000, name: http }
volumes:
- name: cache
hostPath: { path: /mnt/vllm-cache, type: DirectoryOrCreate }
- name: dshm
emptyDir: { medium: Memory, sizeLimit: 64Gi }
The important settings are:
--secure-serving=false— the sidecar serves plain HTTP (rule 8).kv_role: kv_consumer— the decode server reads the KV cache from the prefill servers. The manifest does not setengine_id, so vLLM gives the decode server a unique ID.No
--kv-events-config— the decode server does not publish KV events. ThepodLabelSelectorvalue in the router configuration keeps the router from subscribing to the decode pod.VLLM_HTTP_TIMEOUT_KEEP_ALIVE=120— the sidecar also reuses idle connections to the decode server.
Create the decode server:
: "${LLMD_VERSION:?Set LLMD_VERSION first}" && \
envsubst '${VLLM_NEURON_IMAGE} ${LLMD_VERSION}' < decode.yaml | kubectl apply -f -
Wait until all three pods are ready. The first start downloads the model. Each start compiles the graphs again, because the compile cache is in the container. The start time depends on the model and on the compile time of the graphs.
kubectl wait --namespace llmd --for=condition=Ready pod \
-l app=vllm-neuron --timeout=60m
Make sure that each prefill server serves the render endpoint (rule 6):
for pod in prefill-0 prefill-1; do
kubectl exec --namespace llmd "$pod" -c vllm -- python3 -c "
import json, urllib.request
body = json.dumps({'model': 'Qwen/Qwen3-8B', 'prompt': 'Hello'}).encode()
request = urllib.request.Request('http://127.0.0.1:8000/v1/completions/render', data=body, headers={'Content-Type': 'application/json'})
print('$pod', urllib.request.urlopen(request, timeout=30).status)"
done
The output must show 200 for each prefill server. An HTTP Error 404 means
that the server does not serve the render endpoint. Make sure that rule 6 is
met.
Deploy the router#
Install the router with the official llm-d chart
oci://ghcr.io/llm-d/charts/llm-d-router-standalone, at the version in
LLMD_VERSION. The chart version also selects the EPP image. The
values file below gives the EPP configuration. The configuration turns on
disaggregated prefill and decode and KV-cache-aware routing.
Save this file as router-values.yaml:
router:
modelServers:
matchLabels:
app: vllm-neuron
targetPorts:
- number: 8000
epp:
resources:
requests: { cpu: "1", memory: 2Gi }
limits: { memory: 4Gi }
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions: [{ key: role, operator: In, values: [router] }]
pluginsConfigFile: epp-config.yaml
pluginsCustomConfig:
epp-config.yaml: |
apiVersion: llm-d.ai/v1
kind: EndpointPickerConfig
plugins:
- type: endpoint-notification-source
- type: token-producer
parameters:
modelName: Qwen/Qwen3-8B
vllm:
url: http://prefill-render.llmd.svc.cluster.local:8000
- type: precise-prefix-cache-producer
parameters:
tokenProcessorConfig:
blockSizeTokens: 32
indexerConfig:
kvBlockIndexConfig:
enableMetrics: true
kvEventsConfig:
topicFilter: "kv@"
engineType: vllm
discoverPods: true
podDiscoveryConfig:
socketPort: 5557
podLabelSelector: "llm-d.ai/role=prefill"
- type: prefix-cache-scorer
parameters:
prefixMatchInfoProducerName: precise-prefix-cache-producer
- type: queue-scorer
- type: prefill-filter
- type: decode-filter
- type: max-score-picker
- type: always-disagg-pd-decider
- type: disagg-profile-handler
parameters:
deciders:
prefill: always-disagg-pd-decider
dataLayer:
sources:
- pluginRef: endpoint-notification-source
extractors:
- pluginRef: precise-prefix-cache-producer
schedulingProfiles:
- name: prefill
plugins:
- pluginRef: prefill-filter
- pluginRef: prefix-cache-scorer
weight: 2
- pluginRef: queue-scorer
weight: 1
- pluginRef: max-score-picker
- name: decode
plugins:
- pluginRef: decode-filter
- pluginRef: queue-scorer
weight: 1
- pluginRef: max-score-picker
proxy:
failOpen: false
resources:
requests: { cpu: "1", memory: 1Gi }
limits: { memory: 2Gi }
The important settings are:
modelName— set this value to the served model name.blockSizeTokens: 32— equals the engine--block-size(rule 1).socketPort: 5557— the router subscribes to the KV events of each prefill pod on this port. It must equal the port of the publisher.podLabelSelector— limits the KV event subscriptions to the pods with the labelllm-d.ai/role=prefill. The decode server does not publish KV events.prefixMatchInfoProducerName— makes the scorer use the index of the KV events (rule 3).always-disagg-pd-decider— sends every request through a prefill server (rule 4).failOpen: false— Envoy rejects a request when the EPP is not available. With the chart defaulttrue, Envoy skips the EPP and sends the request to any server in the InferencePool. If the request goes to the decode pod, it has no prefill server. The decode server cannot serve this request (rule 4). Withfalse, requests fail while the EPP restarts.weight— the weights of the scorers in theprefillprofile. See KV-cache-aware routing.resources— the router pod requests 2 vCPUs. The chart defaults request 12 vCPUs for the EPP and Envoy together. Increase the values for a high request rate.
Install the router:
: "${LLMD_VERSION:?Set LLMD_VERSION first}" && \
helm install llmd oci://ghcr.io/llm-d/charts/llm-d-router-standalone \
--version "$LLMD_VERSION" --namespace llmd -f router-values.yaml
kubectl wait --namespace llmd --for=condition=Available deployment/llmd-epp --timeout=10m
The chart creates the EPP deployment with an Envoy container, the
InferencePool resource, and the llmd-epp Service. Envoy listens on port 8081
of the Service.
Send a request#
The llmd-epp Service is a ClusterIP Service, so it is available only in the
cluster. Forward a local port to it:
kubectl port-forward --namespace llmd service/llmd-epp 8081:8081
In a second terminal, send a request:
curl -s http://localhost:8081/v1/completions \
-H "Content-Type: application/json" \
-d '{"model": "Qwen/Qwen3-8B", "prompt": "The capital of France is", "max_tokens": 16, "temperature": 0}'
The model field must equal the served model name. A different name gives a
404 response.
The response is a JSON object. The text field of the first item in choices
holds the generated text. Keep the port-forward command running. The checks
in the next section also use port 8081.
Verify the deployment#
A correct response does not prove that each feature works. Do these checks in this order. Each check finds a different failure. Check 1 verifies disaggregated prefill and decode. Checks 2 to 5 verify KV-cache-aware routing.
1. Make sure that the decode server reads the KV cache over NIXL#
The decode server counts the prompt tokens by their source. It also counts the NIXL transfers. This shell function reads these metrics from inside the decode pod:
kv_metrics() {
kubectl exec --namespace llmd decode-0 -c vllm -- \
python3 -c "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8200/metrics').read().decode())" \
| grep -E '^vllm:(prompt_tokens_by_source_total|nixl_bytes_transferred_count|nixl_num_failed_transfers_total)'
}
Read the metrics, send one request through the router, and read the metrics again. The random prefix makes sure that no server holds the prompt in its cache:
kv_metrics
PROMPT="$(python3 -c "import uuid; print(uuid.uuid4().hex + ' ' + 'The quick brown fox jumps over the lazy dog. ' * 99)")"
curl -s http://localhost:8081/v1/completions -H "Content-Type: application/json" \
-d "$(python3 -c 'import json, sys; print(json.dumps({"model": sys.argv[1], "prompt": sys.argv[2], "max_tokens": 16}))' \
Qwen/Qwen3-8B "$PROMPT")" > /dev/null
kv_metrics
Compare the two outputs:
Metric |
Expected change |
Meaning |
|---|---|---|
|
Increases by approximately the number of prompt tokens |
The decode server reads the KV cache of the prompt from the prefill server. |
|
Increases by a few tokens at most, not by the number of prompt tokens |
The decode server does not compute the prompt again. |
|
Stays the same |
The decode server does not have the prompt in its own prefix cache. The random prefix makes sure of this. |
|
Increases |
The decode server completes NIXL transfers. This value counts transfers, not bytes. In this tutorial, it increases by one transfer for each tensor parallel rank. |
|
Stays at 0 |
No NIXL transfer fails. |
Make sure that the P/D sidecar receives the KV transfer data from each prefill response. This command must give no output:
kubectl logs --namespace llmd decode-0 -c pd-sidecar | grep -E "missing 'kv_transfer_params'|prefill request failed"
2. Make sure that the EPP subscribes to the KV events of each prefill server#
Each prefill server must listen on the KV events port. This command checks the KV events port of each prefill server:
for pod in prefill-0 prefill-1; do
kubectl exec --namespace llmd "$pod" -c vllm -- \
python3 -c "import socket; socket.create_connection(('127.0.0.1', 5557), 2); print('$pod listening')"
done
If the connection fails, check the endpoint of --kv-events-config (rule 2).
Make sure that the EPP subscribes to each prefill server:
kubectl logs --namespace llmd deployment/llmd-epp -c epp | grep 'Connected subscriber socket'
The output must show Connected subscriber socket for the IP address of each
prefill server. podLabelSelector limits the subscriptions to the prefill
pods, because the decode server does not publish KV events. The output has
two lines. To see the IP address of each pod, run
kubectl get pods --namespace llmd -o wide.
3. Make sure that the EPP uses the KV event index#
The EPP writes its configuration to the log when it starts. Make sure that the prefix cache scorer names the precise producer:
kubectl logs --namespace llmd deployment/llmd-epp -c epp | grep -o 'prefixMatchInfoProducerName[^,]*' | head -1
The output must contain precise-prefix-cache-producer.
4. Make sure that the index receives blocks and finds matches#
The metrics endpoint of the EPP accepts only a Kubernetes bearer token with
permission to read /metrics. Create a service account with this permission:
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: ServiceAccount
metadata: { name: metrics-reader, namespace: llmd }
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata: { name: llmd-metrics-reader }
rules:
- nonResourceURLs: ["/metrics"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata: { name: llmd-metrics-reader }
roleRef: { apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: llmd-metrics-reader }
subjects:
- { kind: ServiceAccount, name: metrics-reader, namespace: llmd }
EOF
Keep the port forward on port 8081 open. In a third terminal, forward the metrics port of the EPP:
kubectl port-forward --namespace llmd service/llmd-epp 9090:9090
This shell function reads the index counters from the metrics endpoint of the EPP:
index_counters() {
curl -s -H "Authorization: Bearer $(kubectl create token metrics-reader --namespace llmd)" \
http://localhost:9090/metrics \
| grep -E '^llm_d_epp_kv_cache_index_(admissions|lookup_requests|lookup_hits)_total'
}
Read the counters, send the same prompt two times, and read the counters again. The prompt must be longer than one block. With the Qwen3 tokenizer, this prompt has 991 tokens and fills 30 full blocks of 32 tokens:
index_counters
PROMPT="$(python3 -c "print('The quick brown fox jumps over the lazy dog. ' * 99)")"
for i in 1 2; do
curl -s http://localhost:8081/v1/completions -H "Content-Type: application/json" \
-d "$(python3 -c 'import json, sys; print(json.dumps({"model": sys.argv[1], "prompt": sys.argv[2], "max_tokens": 1}))' \
Qwen/Qwen3-8B "$PROMPT")" > /dev/null
done
index_counters
The first request stores the 30 blocks. The second request finds the 30 blocks in the index. Compare the two outputs. For a prompt that the servers did not receive before, the counters change by these values:
Counter |
Expected change |
Meaning |
|---|---|---|
|
Increases by 30 |
The index receives a |
|
Increases by 30 |
The index finds the cached blocks of the second request. |
|
Increases by 2 |
The EPP looks up each request that has a minimum of one full block. A shorter prompt has no lookup. |
The exact numbers depend on the length of the prompt and on the tokenizer. The counters start at 0 again when the EPP pod restarts.
The cached_tokens value in the response is 0, also for a cache hit. The P/D
sidecar copies this value from the prefill response. The prefill server reports
the value only with --enable-prompt-tokens-details. Use the counters of the
EPP.
If the function gives no output, run the curl command without grep to see
the response. A 401 response means that the request has no valid token. Make
sure that the metrics-reader service account exists. A 403 response means that the token does not have permission to read /metrics. Make sure that the ClusterRoleBinding exists.
If admissions_total stays at 0, the router receives no events. Check the
publisher endpoint (rule 2) and socketPort.
If lookup_requests_total increases and lookup_hits_total stays at 0, the
lookup keys do not match the stored keys. Check the model name in the KV events
topic (rule 9) and blockSizeTokens (rule 1).
5. Make sure that the router selects the prefill server that holds the prompt#
This check proves the routing decision. For each trial, the script sends a new prompt directly to one prefill server, selected at random. Only that server then holds the prompt in its cache. Then the script sends the same prompt through the router, and reads the logs of the prefill servers to find the server that the router selected.
A KV-cache-aware router selects the server that holds the prompt in all trials. With two prefill servers, a router that ignores the cache selects it in about half of the trials.
Note
Put the prompt in the cache of a known server first. A prompt that you send two times through the router does not prove the routing. With one request at a time on an idle deployment, the router often selects the same server for both requests, also when it ignores the cache.
The script needs the requests package and kubectl access to the cluster.
Save this script as check_routing.py:
"""Put each prompt in the cache of a random prefill server, then send it through the router.
Usage: python3 check_routing.py <router-url> <model> <trials>
"""
import random
import subprocess
import sys
import uuid
import requests
URL, MODEL, TRIALS = sys.argv[1], sys.argv[2], int(sys.argv[3])
PREFILLS = ["prefill-0", "prefill-1"]
PRIME = (
"import json, sys, urllib.request; "
"body = json.dumps({'model': sys.argv[1], 'prompt': sys.argv[2], 'max_tokens': 1}).encode(); "
"urllib.request.urlopen(urllib.request.Request('http://127.0.0.1:8000/v1/completions', "
"data=body, headers={'Content-Type': 'application/json'}), timeout=600)"
)
def counts() -> dict[str, int]:
"""Return the number of completion requests in the log of each prefill server."""
result = {}
for pod in PREFILLS:
log = subprocess.run(
["kubectl", "logs", "--namespace", "llmd", pod, "-c", "vllm"],
capture_output=True, text=True, check=True,
).stdout
result[pod] = log.count('"POST /v1/completions HTTP/1.1" 200')
return result
def prime(pod: str, prompt: str) -> None:
"""Send the prompt directly to one prefill server, so that only this server caches it."""
subprocess.run(
["kubectl", "exec", "--namespace", "llmd", pod, "-c", "vllm", "--",
"python3", "-c", PRIME, MODEL, prompt],
check=True, capture_output=True,
)
def send(prompt: str) -> str:
"""Send one request through the router and return the prefill server that served it."""
before = counts()
reply = requests.post(
f"{URL}/v1/completions",
json={"model": MODEL, "prompt": prompt, "max_tokens": 1, "temperature": 0},
timeout=600,
)
reply.raise_for_status()
after = counts()
served = [pod for pod in PREFILLS if after[pod] > before[pod]]
if len(served) != 1:
sys.exit(f"Expected a new request on 1 prefill server, found {len(served)}. Send no other requests during the check.")
return served[0]
same = 0
for _ in range(TRIALS):
prompt = f"{uuid.uuid4().hex} " + "The quick brown fox jumps over the lazy dog. " * 100
target = random.choice(PREFILLS)
prime(target, prompt)
routed = send(prompt)
same += routed == target
print(f"primed={target} routed={routed}")
print(f"The router chose the primed prefill server in {same} of {TRIALS} trials.")
Run the script. The script reads the full logs of the prefill servers for each request, so 20 trials can take several minutes.
python3 check_routing.py http://localhost:8081 Qwen/Qwen3-8B 20
The output is similar to this:
primed=prefill-1 routed=prefill-1
primed=prefill-0 routed=prefill-0
...
The router chose the primed prefill server in 20 of 20 trials.
For a comparison, copy router-values.yaml to router-values-nocache.yaml. In the copy, remove the - pluginRef: prefix-cache-scorer line and its weight: 2 line from the prefill profile. Upgrade the router:
: "${LLMD_VERSION:?Set LLMD_VERSION first}" && \
helm upgrade llmd oci://ghcr.io/llm-d/charts/llm-d-router-standalone \
--version "$LLMD_VERSION" --namespace llmd -f router-values-nocache.yaml
kubectl rollout status --namespace llmd deployment/llmd-epp --timeout=10m
The upgrade replaces the EPP pod, so the port forwards on port 8081 and port 9090 stop. A kubectl port-forward command can continue to run after it stops forwarding. Stop each command and start it again. Then run the script again. The router then ignores the cache. It selects the primed server in about half of the trials. This router does not select a server at random. On an idle deployment, it can send most requests to the same prefill server. The result is about half because the script primes a random server in each trial.
Restore the KV-cache-aware router:
: "${LLMD_VERSION:?Set LLMD_VERSION first}" && \
helm upgrade llmd oci://ghcr.io/llm-d/charts/llm-d-router-standalone \
--version "$LLMD_VERSION" --namespace llmd -f router-values.yaml
kubectl rollout status --namespace llmd deployment/llmd-epp --timeout=10m
Start the port forwards on port 8081 and port 9090 again. The index of the new EPP is empty, so the counters start at 0.
Troubleshooting#
Symptom |
Cause |
Action |
|---|---|---|
In check 1, |
The decode server cannot read the KV cache from the prefill server. |
Make sure that EFA is set up and that the NIXL port is open between the pods. Give each prefill server a unique |
Requests succeed, but check 5 gives about half of the trials |
The scorer uses the approximate producer, or the index is empty. |
Do checks 3 and 4. Set |
|
The model name in the KV events topic does not equal the |
Use the served model name in the topic (rule 9). Set |
|
The publisher does not listen, or the router uses the wrong port. |
Use |
A short prompt or a repeated prompt fails |
The decider sends the request to the decode server alone. |
Use |
The decode server reads the wrong KV cache, or a KV cache read fails |
Two prefill servers use the same |
Give each prefill server a unique |
The EPP logs a tokenizer error, or the render endpoint returns |
The prefill server does not serve the render endpoint. |
On vLLM 0.30 and later, the prefill servers need |
A prefill server stops with |
The vLLM version is earlier than 0.30. |
Remove the flag. The render endpoint is on by default (rule 6). |
Requests through Envoy fail, and the sidecar logs a TLS handshake error |
The sidecar serves TLS, and Envoy uses plain HTTP. |
Set |
The request returns |
The |
Use the served model name in the request. |
The EPP pod stays in |
No node has the label |
Read the events in |
A pod fails with |
The pod requests part of a node. |
Request all of the Neuron devices of the node, or install the Neuron scheduler extension. |
Limitations#
The P/D sidecar logs
warning: SSRF protection is disabledat start. The sidecar sends the prefill request to the host in thex-llm-d-prefiller-host-portheader, and it does not check this host. Use a Kubernetes network policy so that only the router can reach port 8000 of the decode pod. On Amazon EKS, a network policy has an effect only when network policy enforcement is on in the Amazon VPC CNI.Port 8000 of the prefill servers, port 8200 of the decode server, the KV events port (5557), and the NIXL port (5600) have no authentication. Use a network policy so that only the pods of this deployment can reach these ports.
The router is in standalone mode. For a Gateway API deployment, use the
llm-d-router-gatewaychart. The EPP configuration in this tutorial does not change.The decode server cannot serve a full request. Keep at least one prefill server ready.
The EPP keeps the KV block index in memory. When the EPP pod restarts, the index is empty. The router then does not know the blocks that the prefill servers already hold, until the servers store the blocks again.
Clean up#
Stop the kubectl port-forward commands. Remove the router, the servers, and the metrics reader:
helm uninstall llmd --namespace llmd
kubectl delete namespace llmd
kubectl delete clusterrolebinding llmd-metrics-reader
kubectl delete clusterrole llmd-metrics-reader
kubectl label node <router-node-name> role-
The last command removes the role=router label from the router node. These
commands keep the Inference Extension CRDs and the device plugins, because other workloads can use them. The model files stay in /mnt/vllm-cache on each Trainium node. If you created the Trainium nodes for this tutorial, delete them to stop the charges.
Next steps#
llm-d has more production serving features than this tutorial deploys. For example, llm-d has guides for wide expert parallelism, tiered prefix caching, flow control, and workload autoscaling. This tutorial does not cover these features. See the llm-d guides and the llm-d website.