Prefix cache-aware routing in precise mode
Prefix cache-aware routing in precise mode is designed for generative AI inference scenarios. It tracks the distribution of the KV Cache in the inference engine based on KV Cache events and dynamically routes requests to the optimal compute node. This significantly improves the serving efficiency of large language model (LLM) services. This document describes how to use the Gateway with Inference Extension component to implement prefix cache-aware routing in precise mode.
Background
vLLM
vLLM is a framework designed for efficient and user-friendly construction of LLM inference services. It supports various large language models, including Qwen, and optimizes inference efficiency through techniques like PagedAttention, dynamic batch inference (Continuous Batching), and model quantization.
KV cache
vLLM automatic prefix caching
vLLM supports an automatic prefix caching (APC) feature. APC caches the KV Cache of requests that vLLM has already processed. If a new request shares the same prefix with a historical request, the existing KV Cache can be reused. This allows the new request to skip the KV Cache computation for the shared prefix, accelerating the processing of LLM inference requests.
Precise vs. estimation mode
Prefix cache-aware routing in precise mode is a load balancing strategy that works as follows:
Each vLLM workload reports its cached KV Cache block information to the Gateway with Inference Extension via event messages. By tracking the KV Cache information for each vLLM workload, the gateway can dispatch an incoming request to the vLLM workload with the highest cache hit rate based on the request's content. This approach maximizes the prefix cache hit rate and reduces request response time. Evaluate whether this approach is suitable for your business scenario.
Similar to prefix cache-aware routing in estimation mode, the goal of precise mode is to leverage the inference service framework's prefix caching mechanism to maximize the prefix cache hit rate.
-
Prefix cache-aware routing in precise mode directly receives KV Cache block distribution information, which allows it to determine the KV Cache status more accurately and maximize the prefix cache hit rate. However, this requires the inference service to use the vLLM v0.10.0 framework or later and to configure KV Cache event reporting parameters at startup.
-
Prefix cache-aware routing in estimation mode is decoupled from the inference engine but cannot precisely track the KV Cache distribution.
To use prefix cache-aware routing in precise mode, your inference service must be built with the vLLM v0.10.0 or later framework. You must also specify KV Cache event-related parameters in the vLLM startup parameters. For details, see the examples in this document.
Prerequisites
-
Create an ACK managed cluster with a GPU node pool. You can also install the ACK Virtual Node component in the ACK managed cluster to use ACK with ACS GPU Compute Power.
This document uses the Qwen-32B model service as an example, which requires more than 64 GB of GPU memory. We recommend using the ecs.gn8is-2x.8xlarge instance type. For ACK Virtual Node, we recommend the GU8TF card type.
-
You have installed Gateway with Inference Extension version 1.4.0-aliyun.3 or later and selected the Enable Gateway API Inference Extension option. For instructions, see Install the Gateway with Inference Extension component.
Deploy model service
Step 1: Prepare the Qwen3-32B model files
-
Download the Qwen3-32B model from ModelScope.
Ensure git-lfs is installed. If not, run
yum install git-lfsorapt-get install git-lfs. See Installing Git Large File Storage for other methods.git lfs install GIT_LFS_SKIP_SMUDGE=1 git clone https://www.modelscope.cn/Qwen/Qwen3-32B.git cd Qwen3-32B/ git lfs pull -
Upload the model files to an OSS bucket.
See Install ossutil.
ossutil mkdir oss://<YOUR-BUCKET-NAME>/Qwen3-32B ossutil cp -r ./Qwen3-32B oss://<YOUR-BUCKET-NAME>/Qwen3-32B -
Create a persistent volume (PV) named
llm-modeland a persistent volume claim (PVC). See Use ossfs 1.0 to create a statically provisioned volume.-
Create
llm-model.yaml. Defines a Secret, a statically provisioned PV, and a PVC.apiVersion: v1 kind: Secret metadata: name: oss-secret stringData: akId: <YOUR-OSS-AK> # The AccessKey ID used to access OSS akSecret: <YOUR-OSS-SK> # The AccessKey secret used to access OSS --- apiVersion: v1 kind: PersistentVolume metadata: name: llm-model labels: alicloud-pvname: llm-model spec: capacity: storage: 30 Gi accessModes: - ReadOnlyMany persistentVolumeReclaimPolicy: Retain csi: driver: ossplugin.csi.alibabacloud.com volumeHandle: llm-model nodePublishSecretRef: name: oss-secret namespace: default volumeAttributes: bucket: <YOUR-BUCKET-NAME> # The name of the bucket. url: <YOUR-BUCKET-ENDPOINT> # The Endpoint information, such as oss-cn-hangzhou-internal.aliyuncs.com. otherOpts: "-o umask=022 -o max_stat_cache_size=0 -o allow_other" path: <YOUR-MODEL-PATH> # In this example, the path is /Qwen3-32B/. --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: llm-model spec: accessModes: - ReadOnlyMany resources: requests: storage: 30 Gi selector: matchLabels: alicloud-pvname: llm-model -
Apply the manifest to create the Secret, PV, and PVC.
kubectl create -f llm-model.yaml
-
Step 2: Deploy vLLM inference service
-
Create a vllm.yaml file.
The following table describes key startup parameters and environment variables.
Parameter
Description
--kv-events-config
Specifies the configuration for publishing KV Cache events. The value must be a valid JSON string or individually passed JSON keys.
Example:
{"enable_kv_cache_events":true,"publisher":"zmq","endpoint":"tcp://epp-default-qwen-inference-pool.envoy-gateway-system.svc.cluster.local:5557","topic":"kv@${POD_IP}@Qwen3-32B"}Details:
-
endpoint: Specifies the ZMQ server endpoint for the inference extension. The endpoint must be in the format
tcp://epp-<InferencePool namespace>-<InferencePool name>.envoy-gateway-system.<cluster domain>:5557. For example, if you create anInferencePoolnamedqwen-inference-poolin thedefaultnamespace, the endpoint is set totcp://epp-default-qwen-inference-pool.envoy-gateway-system.svc.cluster.local:5557. -
The naming convention for the topic is
kv@${POD_IP}@<served model name>. In this example, because vLLM specifies the--served-model-name Qwen3-32Bstartup parameter, the topic is set tokv@${POD_IP}@Qwen3-32B.
--prefix-caching-hash-algo
The algorithm for calculating the KV Cache prefix cache block hash must be specified as
sha256_cbor_64bit.--block-size
The number of tokens stored in each KV Cache prefix cache block. In this example, this is set to
64.PYTHONHASHSEED
The seed used for the Python hash algorithm. It must be a non-zero value. In this example, it is set to
42. -
-
Deploy the vLLM inference service.
kubectl create -f vllm.yaml
Deploy inference routing
Step 1: Deploy inference routing policy
-
Create an inference-policy.yaml file.
# An InferencePool enables inference routing for the workload. apiVersion: inference.networking.x-k8s.io/v1alpha2 kind: InferencePool metadata: name: qwen-inference-pool spec: targetPortNumber: 8000 selector: app: qwen3 --- # An InferenceTrafficPolicy defines the traffic policy applied to the InferencePool. apiVersion: inferenceextension.alibabacloud.com/v1alpha1 kind: InferenceTrafficPolicy metadata: name: inference-policy spec: poolRef: name: qwen-inference-pool profile: single: # Specifies that the backend inference service is a single-instance vLLM deployment. trafficPolicy: # Specifies the load balancing policy for the inference service. prefixCache: mode: tracking # Enables KV Cache-aware load balancing. trackingConfig: indexerConfig: tokenProcessorConfig: blockSize: 64 # Must be consistent with the --block-size startup parameter of vLLM. hashSeed: 42 # Must be consistent with the PYTHONHASHSEED environment variable of vLLM. model: Qwen/Qwen3-32B # Specifies the official name of the model on ModelScope. -
Deploy the inference routing policy.
kubectl apply -f inference-policy.yaml
Step 2: Deploy gateway and routing rules
-
Create an inference-gateway.yaml file. This file defines the gateway, the gateway routing rule, and the backend timeout policy.
apiVersion: gateway.networking.k8s.io/v1 kind: Gateway metadata: name: inference-gateway spec: gatewayClassName: ack-gateway listeners: - name: http-llm protocol: HTTP port: 8080 --- apiVersion: gateway.networking.k8s.io/v1 kind: HTTPRoute metadata: name: inference-route spec: parentRefs: - name: inference-gateway rules: - matches: - path: type: PathPrefix value: /v1 backendRefs: - name: qwen-inference-pool kind: InferencePool group: inference.networking.x-k8s.io --- apiVersion: gateway.envoyproxy.io/v1alpha1 kind: BackendTrafficPolicy metadata: name: backend-timeout spec: timeout: http: requestTimeout: 24h targetRef: group: gateway.networking.k8s.io kind: Gateway name: inference-gateway -
Deploy the gateway and routing rules.
kubectl apply -f inference-gateway.yaml
Step 3: Verify routing rules
-
Create round1.txt and round2.txt. Both TXT files contain the same
content. Sequentially use round1.txt and round2.txt as the body of an LLM request and check the logs of the inference extension to verify that the prefix cache-aware routing feature of precise mode is working.round1.txt:
echo '{"max_tokens":24,"messages":[{"content":"Hi, here'\''s some system prompt: hi hi hi hi hi hi hi hi hi hi.For user 3, here are some other context: hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi.I would like to test your intelligence. for this purpose I would like you to play zork. you can interact with the game by typing in commands. I will forward these commands to the game and type in any response. are you ready?","role":"user"}],"model":"Qwen3-32B","stream":true,"stream_options":{"include_usage":true},"temperature":0}' > round1.txtround2.txt:
echo '{"max_tokens":3,"messages":[{"content":"Hi, here'\''s some system prompt: hi hi hi hi hi hi hi hi hi hi.For user 3, here are some other context: hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi.I would like to test your intelligence. for this purpose I would like you to play zork. you can interact with the game by typing in commands. I will forward these commands to the game and type in any response. are you ready?","role":"user"},{"content":"Hi there! It looks like you're setting up a fun test. I'm ready to play Zork! You can","role":"assistant"},{"content":"% zork\nWelcome to Dungeon. This version created 11-MAR-91.\nYou are in an open field west of a big white house with a boarded\nfront door.\nThere is a small mailbox here.\n>","role":"user"},{"content":"Great!","role":"assistant"},{"content":"Opening the mailbox reveals:\n A leaflet.\n>","role":"user"}],"model":"Qwen3-32B","stream":true,"stream_options":{"include_usage":true},"temperature":0}' > round2.txt -
Get the public IP of the gateway.
export GATEWAY_IP=$(kubectl get gateway/inference-gateway -o jsonpath='{.status.addresses[0].value}') -
Send two requests to simulate a multi-turn conversation.
curl -X POST $GATEWAY_IP:8080/v1/chat/completions -H 'Content-Type: application/json' -d @./round1.txt curl -X POST $GATEWAY_IP:8080/v1/chat/completions -H 'Content-Type: application/json' -d @./round2.txt -
Check the logs to confirm that prefix-based load balancing has taken effect.
kubectl logs deploy/epp-default-qwen-inference-pool -n envoy-gateway-system|grep "handled"Expected output:
2025-08-19T10:16:12Z LEVEL(-2) requestcontrol/director.go:278 Request handled {"x-request-id": "00d5c24e-b3c8-461d-9848-7bb233243eb9", "model": "Qwen3-32B", "resolvedTargetModel": "Qwen3-32B", "criticality": "Critical", "model": "Qwen3-32B", "targetModel": "Qwen3-32B", "endpoint": "{NamespacedName:default/qwen3-779c54544f-9c4vz Address:10.0.0.5 Labels:map[app:qwen3 pod-template-hash:779c54544f]}"} 2025-08-19T10:16:19Z LEVEL(-2) requestcontrol/director.go:278 Request handled {"x-request-id": "401925f5-fe65-46e3-8494-5afd83921ba5", "model": "Qwen3-32B", "resolvedTargetModel": "Qwen3-32B", "criticality": "Critical", "model": "Qwen3-32B", "targetModel": "Qwen3-32B", "endpoint": "{NamespacedName:default/qwen3-779c54544f-9c4vz Address:10.0.0.5 Labels:map[app:qwen3 pod-template-hash:779c54544f]}"}The output shows the gateway forwards both requests to the same workload, confirming that prefix cache-aware routing in precise mode is working correctly.