Precise prefix-cache routing on TPU¶
Use this guide when many requests share long prefixes (system prompts, multi-turn chat, RAG) and the optimized baseline's estimate of what each pod caches is not good enough. Each vLLM pod publishes KV-cache events over ZMQ, the router subscribes to every pod and indexes resident blocks, and it tokenizes each prompt through vLLM's render endpoints to look up exact blocks. Chapter 20 compares the approximate and precise indexes.
Every pod streams its KV events to the router all the time, so the router's index knows which blocks each pod holds. Per request, the router renders the prompt to token IDs on any Ready pod, looks the blocks up, and sends the request to a pod that already holds them.
Prerequisites¶
- The optimized baseline prerequisites (TPU node pools, boot disk, repository, CRDs, namespace, Secret). The router also reads
HF_TOKENto reach gated tokenizers. -
One of the guide's TPU configurations:
ACCELERATOR_TYPEModel Layout Status tpu/v6Qwen/Qwen3-32B2 replicas x 8 chips ( 2x4, TP=8), 16k context,--block-size=256community tpu/v7Qwen/Qwen3.5-397B-A17B-FP82 replicas x 4 chips ( 2x2x1, DP=2 x TP=4, EP)community tpu/v5pQwen/Qwen3-32B2 replicas x 4 chips ( 2x2x1, TP=4), vLLM 0.29validated nightly The TPU7x overlay uses DP=2 x TP=4 to exercise per-rank KV events with few ranks; the tuned Qwen3.5-397B layout is in Model recipes.
Steps¶
1. Set the environment and deploy the router¶
export REPO_ROOT=$(realpath $(git rev-parse --show-toplevel))
export GUIDE_NAME=precise-prefix-cache-routing
export NAMESPACE=llm-d-precise-prefix-cache-routing
export MONITORING=false
export MONITORING_VALUES=
export ENGINE_VALUES=
export ACCELERATOR_TYPE=tpu/v6 # tpu/v5p, tpu/v6 or tpu/v7
export MODEL_SERVER=vllm
export INFRA_PROVIDER=gke
export MODEL=Qwen/Qwen3-32B
source ${REPO_ROOT}/guides/env.sh
export ROUTER_BASE_VALUES="${REPO_ROOT}/guides/recipes/router/base.values.yaml"
export ROUTER_VALUES="${REPO_ROOT}/guides/${GUIDE_NAME}/router/${GUIDE_NAME}.values.yaml"
helm install ${GUIDE_NAME} \
${ROUTER_STANDALONE_CHART} \
-f ${ROUTER_BASE_VALUES} \
${MONITORING_VALUES} \
-f ${ROUTER_VALUES} \
${ENGINE_VALUES} \
-n ${NAMESPACE} --version ${ROUTER_CHART_VERSION}
The release name must be ${GUIDE_NAME}: the InferencePool selector matches a guide label that pairs with it. Two settings must agree between router and model servers:
- Block size.
blockSizeTokensof theprecise-prefix-cache-producerequals vLLM--block-size, 64 by default. On v6e,--block-size=64runs out of SMEM on TorchTPU, so thetpu/v6overlay sets 256 androuter/tpu-v6e.values.yamlsetsblockSizeTokens: 256; add that file as one more-fvalues file after${ROUTER_VALUES}. - Model. The
token-producermodelNamein the router values isQwen/Qwen3-32B. Ontpu/v7, set it to${MODEL}before installing: the render call lands on the model servers, which reject a mismatched model.
Run one router replica: the token load scorer's in-flight accounting is per process, and the KV index is not safe to split across replicas.
Check: the EPP pod is Running and kubectl logs -n ${NAMESPACE} deploy/${GUIDE_NAME}-epp shows no ZMQ subscription or token-producer errors once step 2 is done.
2. Deploy the model servers¶
kubectl apply -n ${NAMESPACE} \
-k ${REPO_ROOT}/guides/${GUIDE_NAME}/modelserver/${ACCELERATOR_TYPE}/${MODEL_SERVER}/${INFRA_PROVIDER}/
Every overlay starts vLLM with --kv-events-config and exposes the per-pod ZMQ socket on port 5556; vLLM overlays also bind port 5559 with a replay buffer of the last 10,000 event batches, which a restarted router uses to rebuild its index. Nothing else is needed for rendering: the router calls /v1/*/render on a Ready pod of the pool, round-robin. The TPU overlays run vLLM 0.29, which exposes render without --enable-scale-out.
Check: all model server pods Running and ready.
3. Check rendering on every pod¶
export IP=$(kubectl get service ${GUIDE_NAME}-epp -n ${NAMESPACE} -o jsonpath='{.spec.clusterIP}')
export POD_IPS=$(kubectl get pods -n ${NAMESPACE} -l llm-d.ai/guide=${GUIDE_NAME} -o jsonpath='{.items[*].status.podIP}')
kubectl run render-check --rm -i --restart=Never \
--image=${CURL_TEST_IMAGE} \
--namespace="${NAMESPACE}" \
--env="POD_IPS=${POD_IPS}" \
--env="MODEL=${MODEL}" \
-- /bin/sh -c 'test -n "${POD_IPS}" || { echo "FAIL: no model server pods"; exit 1; }
for ip in ${POD_IPS}; do
R=$(curl -sS -X POST "http://${ip}:8000/v1/completions/render" -H "Content-Type: application/json" -d "{\"model\": \"${MODEL}\", \"prompt\": \"render check\", \"max_tokens\": 1}")
echo "${R}" | grep -q "\"token_ids\"" || { echo "FAIL: ${ip}: ${R}"; exit 1; }
echo "OK: ${ip}"
done'
Check: one OK: <ip> line per pod and exit 0.
4. Send test requests¶
kubectl run curl-test --rm -i --restart=Never \
--image=${CURL_TEST_IMAGE} \
--namespace="${NAMESPACE}" \
--env="IP=${IP}" \
--env="MODEL=${MODEL}" \
-- /bin/sh -c 'curl -sS -X POST "http://${IP}/v1/completions" -H "Content-Type: application/json" -d "{\"model\": \"${MODEL}\", \"prompt\": \"How are you today?\"}"'
The guide also sends an Anthropic Messages request (/v1/messages, rendered natively on vLLM 0.29) and a Responses request (/v1/responses). On the TPU overlays, vLLM 0.29 has no /v1/responses/render, so the router's auto mode falls back to the deprecated legacy render, which does not guarantee token parity: some precise matches are lost for Responses traffic.
Check: a completion returns.
5. Verify that the router itself renders¶
The render check above calls the pods directly, so it passes even when the router's own render calls fail (requests then return 200, routed without cache information). Grant the check pod read access to the router's /metrics, then compare the render counters across one request:
kubectl create clusterrole ${GUIDE_NAME}-metrics-reader \
--verb=get --non-resource-url=/metrics \
--dry-run=client -o yaml | kubectl apply -f -
kubectl create clusterrolebinding ${GUIDE_NAME}-metrics-reader \
--clusterrole=${GUIDE_NAME}-metrics-reader \
--serviceaccount=${NAMESPACE}:default \
--dry-run=client -o yaml | kubectl apply -f -
kubectl run router-render-check --rm -i --restart=Never \
--image=${CURL_TEST_IMAGE} \
--namespace="${NAMESPACE}" \
--env="IP=${IP}" \
--env="MODEL=${MODEL}" \
--env="GUIDE_NAME=${GUIDE_NAME}" \
-- /bin/sh -c 'TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
metrics() { curl -sSf -o /tmp/metrics -H "Authorization: Bearer ${TOKEN}" "http://${GUIDE_NAME}-epp:9090/metrics" || { echo "FAIL: cannot read the router metrics"; exit 1; }; }
count() { awk -v re="$1" "\$0 ~ re {s += \$NF} END {print s + 0}" /tmp/metrics; }
SUCCEEDED="^llm_d_epp_token_producer_render_duration_seconds_count.*result=\"success\""
FAILED="^llm_d_epp_token_producer_render_failures_total"
metrics; OK0=$(count "${SUCCEEDED}"); FAIL0=$(count "${FAILED}")
curl -sS -o /dev/null -w "request: HTTP %{http_code}\n" -X POST "http://${IP}/v1/completions" -H "Content-Type: application/json" -d "{\"model\": \"${MODEL}\", \"prompt\": \"router render check\", \"max_tokens\": 1}"
metrics; OK1=$(count "${SUCCEEDED}"); FAIL1=$(count "${FAILED}")
echo "router renders: $((OK1 - OK0)) succeeded, $((FAIL1 - FAIL0)) failed"
test $((OK1 - OK0)) -ge 1 && test "${FAIL1}" = "${FAIL0}" || { echo "FAIL: the router did not render the request"; exit 1; }'
Check: router renders: 1 succeeded, 0 failed (or more succeeded) and exit 0.
6. Verify precise routing¶
Send the optimized baseline's 10 shared-prefix requests (Optimized baseline, step 5), but 3 s apart: add sleep 3 after each curl inside the loop. The gap passes the router's 2 s speculative-index TTL, so each request routes on the KV events of the one before it. Then read each pod's counters with the same loop as that step.
Check: one pod reports most of the 10 requests and its hit share is large. On the router side, compare llm_d_epp_prefix_predicted_cached_tokens_sum / llm_d_epp_prefix_prompt_tokens_sum with the pods' vllm:prefix_cache_hits_total / vllm:prefix_cache_queries_total: with a complete index they track each other closely. A clearly higher pod share means the index is missing blocks.
7. Run it in production¶
- Alert when a serving pod's
llm_d_epp_kv_cache_events_messages_received_totalrate is zero, whenllm_d_epp_kv_cache_events_zmq_errors_totalrises, or whenllm_d_epp_kv_cache_events_pool_queue_depthkeeps growing (raisekvEventsConfig.concurrency).llm_d_epp_kv_cache_events_active_subscribersequals the pod count by construction, so it is not a health check. - Watch
llm_d_epp_token_producer_render_failures_totalandllm_d_epp_token_producer_render_duration_seconds: every request is rendered before routing, so render latency is part of TTFT. Each attempt is capped at 2 s (vllm.endpointDiscovery.attemptTimeout). - After a router restart, logs show
Requesting proactive replay on connectthenReplay completeper pod. Blocks stored before the replay window stay out of the index until evicted and stored again, and everything built on them too, so fix a broken pod's configuration before restarting the router (kubectl rollout restart -n ${NAMESPACE} deploy/${GUIDE_NAME}-epp).
Check: the alert expressions return data in Prometheus (Observability).
8. Clean up¶
kubectl delete -n ${NAMESPACE} -k ${REPO_ROOT}/guides/${GUIDE_NAME}/modelserver/${ACCELERATOR_TYPE}/${MODEL_SERVER}/${INFRA_PROVIDER}
helm uninstall ${GUIDE_NAME} -n ${NAMESPACE}
kubectl delete clusterrolebinding ${GUIDE_NAME}-metrics-reader --ignore-not-found=true
kubectl delete clusterrole ${GUIDE_NAME}-metrics-reader --ignore-not-found=true
kubectl delete namespace ${NAMESPACE}
Check: the namespace and both cluster-scoped RBAC objects are gone.
Troubleshooting¶
| Symptom | Cause | Fix |
|---|---|---|
| Requests spread evenly, hit rates near zero | The router gets no KV events or cannot tokenize | Rerun steps 3 and 5; check --block-size equals blockSizeTokens; read the EPP logs |
| v6e pods fail at startup with SMEM errors | --block-size=64 on TorchTPU |
Keep the overlay's 256 and set blockSizeTokens: 256 in the router |
| Render rejected for the model | token-producer modelName differs from MODEL (TPU7x) |
Set modelName to ${MODEL} and reinstall the router |
| One pod's event rate is zero while it serves | Wrong port or topic | Pod exposes 5556 (and 5559); its --kv-events-config topic matches kvEventsConfig.topicFilter |
| Hit share on pods far above the router's prediction | Index incomplete after a restart | Wait for replay; prefixes older than the window return only after eviction |
| Responses requests match less often | Legacy render fallback on vLLM 0.29 | Expected on the TPU overlays |
