An SRE's guide to deploying Large Language Models, Part 5: routing, observing and scaling it
Part 4 ended with one vLLM pod, on one GPU node that Karpenter created for it, answering requests through a port-forward. That’s a model server, and it isn’t a service yet. In this part we add what turns it into one. First we look at routing, which is how we make smart use of the loaded models and get the most cache hits out of them: an endpoint picker and a gateway, exposed through a load balancer. Then we test the whole request path and set up observability, including a simulation you can run on a laptop. Then we use what we see to make the deployment autoscale, and finally we look at tiered KV caching to keep more prefixes around.
You need the result of part 4 to follow along: the cluster, and the chart installed with only the model switched on, with a pod that answers on /v1/models. The code for both parts is in the same examples folder, the one named after part 4, which this part continues. The tools are the same too. Terraform stopped at AWS, Karpenter and the load balancer controller in part 4, so everything here is Helm: the upstream charts, each with a values file from the examples, and the layers of our own chart that we kept switched off so far, which are routing, observability and autoscaling. The section numbers in this part start again at 1, and a reference to a section of part 4 says so.
1. Routing: the endpoint picker and Envoy AI Gateway
Our vLLM pod now answers over port-forward, which is all one pod needs. With several pods, something has to decide which pod gets which request. First we look at why that’s hard for an LLM and how the endpoint picker solves it, including how it scores pods. Then we look at the gateway that calls the picker and install it, and finally we create the resources, raw YAML first and templates after.
Part 1 ended on the sentence that the unit of work is a token and not a request, and the consequence shows up the moment you have more than one replica. One request is a 200-token question and another is a 100,000-token agent transcript. One lands on a pod whose KV cache is nearly full and another on a pod that already holds its system prompt. A load balancer that treats them as interchangeable sends them wherever the wheel points next.
The problem with a normal load balancer
Round robin and least-connections were designed for requests that cost roughly the same and carry no memory. LLM requests break both assumptions:
- They differ in cost by orders of magnitude, so equal request counts mean unequal load.
- A pod’s waiting queue and its KV cache fill up independently of how many connections it has.
- The pod that served a prompt a moment ago still holds that prompt’s KV blocks, which is a reason to send the next request with the same prefix back to it.
Everything a good router needs to know lives inside the model servers, and it changes every few milliseconds. Think of a restaurant host: one who hands out tables in turn is round robin, and a good one knows which tables are full.
The endpoint picker
The Kubernetes SIG that owns the Gateway API added an extension for exactly this problem, the Gateway API Inference Extension. It introduces a resource called an InferencePool. An InferencePool is like an EndpointSlice, the Kubernetes object that lists the pod addresses behind a Service, except that it lists all the vLLM pods that match a label selector. The pool’s main consumer is the endpoint picker, usually shortened to EPP, and the pool points at it. As the name says, the picker chooses one of the vLLM pods as the target for each request. The whole purpose is to give you a component you can put in your routing layer to decide smartly where each request goes.
In Envoy, for example, you reach it through an external-processing filter. The gateway parks each request and sends its headers and body to the picker over gRPC, the picker answers with the address of one pod, and the gateway forwards the request to that pod directly. Pool membership comes from the Kubernetes API and not from the proxy: the picker watches the pool and its pods, and admits a pod only when its Ready condition is true. A pod that is still streaming its weights is simply not a candidate.
The interesting part is how the picker chooses, so let’s dissect the one we use. It’s the production-grade picker from the llm-d router project, which is where the Gateway API Inference Extension project moved it in its v1.6.0 release. The extension itself now keeps the API and a minimal conformance picker. We use llm-d router v1.0.0 and Inference Extension v1.6.2.
What a picker knows decides how good it is. A common summary says it scrapes metrics off every vLLM pod and sends the request to the pod with the best prefix-cache hit. The first half is true and the second half is not.
The three signals
The picker learns about the pool through three paths, and only the first one touches the pods.
The first is a scrape. Every 50 milliseconds by default, the picker does an HTTP GET of /metrics on every pod in the pool, which comes to 20 scrapes a second per pod. It keeps exactly five vLLM series from the response: vllm:num_requests_waiting, vllm:num_requests_running, vllm:kv_cache_usage_perc, vllm:lora_requests_info and vllm:cache_config_info. That’s load, and only load. The picker does not read vLLM’s prefix-cache hit counters.
The second is the picker’s own bookkeeping, and it’s where prefix awareness comes from by default. The picker turns each prompt into an estimate of its tokens (about four bytes of text per token, so it needs no tokenizer) and hashes them in chained blocks. The block size matters, and our values set autoTune: true, so the picker reads it from each pod’s vllm:cache_config_info series. For this hybrid model that’s the 1,600-token attention block from section 3 of part 4, the one the Setting attention block size to 1600 tokens line in the startup log announces. So the picker hashes in blocks of 1,600 tokens. The number 64 is only the fallback before the first scrape, and the floor: anything smaller is raised to 64. After every pick, the picker records in a per-pod in-memory LRU which pod just received which block hashes. The next request with the same beginning is scored against that table, and the pods are never asked.
A block matches only if all 1,600 of its tokens are identical. A request that shares a 1,000-token system prompt with an earlier one and then diverges starts with a different first block, so it’s a miss. One that shares 1,700 tokens matches the first block. That’s the same line vLLM draws in section 3 of part 4, so the picker and vLLM agree about where a hit can land. The token count is an estimate, so the line is approximate. To check the number on your own pods, read the block_size label of vllm:cache_config_info on a pod’s /metrics, and if it isn’t 1600, trust the pod and not this post.
The third is vLLM publishing its own cache events, so the picker knows which blocks are resident. It’s called precise prefix-cache routing. It’s opt-in, it needs extra flags on vLLM and a tokenize call per request, and for this model we leave it off. Its own subsection below explains how to turn it on and why we don’t.
Scoring
The picker scores every candidate and takes the highest. Before it scores anything, a hidden filter runs. It’s added to every scheduling profile by default, which is why you won’t find it in our values, and it removes pods whose waiting queue is above 5 or whose KV usage is above 0.8, unless that would remove all of them. Three scorers then do the work, and each returns a number between 0 and 1:
- The queue scorer compares the waiting queues of the candidates. A pod scores the longest queue minus its own, divided by the longest minus the shortest. The shortest queue scores 1, the longest scores 0, and if all queues are equal everybody scores 1.
- The KV-cache scorer returns one minus the pod’s KV usage.
- The prefix scorer returns the number of the prompt’s blocks the index says the pod holds, divided by the number of blocks in the prompt.
The final score is the weighted sum, each weight times its scorer’s score. The built-in weights are queue 2, KV cache 2 and prefix 3, and ours are queue 2, KV cache 3 and prefix 1. Let’s see what that difference does with one request and three pods.
The request is a 12,800-token agent transcript, which is 8 blocks of 1,600 tokens. This is what the picker knows about the pods:
| Pod | Requests waiting | KV usage | Blocks of the prompt in the index |
|---|---|---|---|
| A | 0 | 0.20 | 0 of 8 |
| B | 3 | 0.45 | 8 of 8 |
| C | 4 | 0.75 | 4 of 8 |
Nobody is over the filter’s limits (queue 5, KV usage 0.8), so all three stay candidates. Each scorer turns its column into a score. The longest queue is 4 and the shortest is 0:
| Pod | Queue score | KV score | Prefix score |
|---|---|---|---|
| A | (4 - 0) / (4 - 0) = 1.00 | 1 - 0.20 = 0.80 | 0 / 8 = 0.00 |
| B | (4 - 3) / (4 - 0) = 0.25 | 1 - 0.45 = 0.55 | 8 / 8 = 1.00 |
| C | (4 - 4) / (4 - 0) = 0.00 | 1 - 0.75 = 0.25 | 4 / 8 = 0.50 |
Now the weights. With ours, queue 2, KV cache 3 and prefix 1:
| Pod | Queue 2 x score + KV 3 x score + prefix 1 x score | Total |
|---|---|---|
| A | 2 x 1.00 + 3 x 0.80 + 1 x 0.00 = 2.00 + 2.40 + 0.00 | 4.40 |
| B | 2 x 0.25 + 3 x 0.55 + 1 x 1.00 = 0.50 + 1.65 + 1.00 | 3.15 |
| C | 2 x 0.00 + 3 x 0.25 + 1 x 0.50 = 0.00 + 0.75 + 0.50 | 1.25 |
Pod A wins. With the stock weights, queue 2, KV cache 2 and prefix 3, the same three pods score differently:
| Pod | Queue 2 x score + KV 2 x score + prefix 3 x score | Total |
|---|---|---|
| A | 2 x 1.00 + 2 x 0.80 + 3 x 0.00 = 2.00 + 1.60 + 0.00 | 3.60 |
| B | 2 x 0.25 + 2 x 0.55 + 3 x 1.00 = 0.50 + 1.10 + 3.00 | 4.60 |
| C | 2 x 0.00 + 2 x 0.25 + 3 x 0.50 = 0.00 + 0.50 + 1.50 | 2.00 |
Now pod B wins. B holds the whole transcript in its cache, but it has three requests waiting and its KV cache is nearly half full. With the stock weights the prefix vote of 3 outweighs everything B is bad at, so the request goes to B. With ours it goes to the idle pod A, which prefills the transcript from scratch. We pay for that prefill on purpose, and the next subsection explains why.
Weights as an exchange rate
The weights are the part we don’t leave to a default, because they’re an exchange rate between three different currencies: waiting requests, KV cache and cache reuse. Take two pods with equal queues, one warm for the prompt and one idle with a KV usage of 0.10. The warm pod keeps winning while its KV usage stays below the idle pod’s usage plus the ratio of the prefix weight to the KV weight, times the share of the prompt it holds. For a full match, the stock ratio is 3 over 2, which is more than any KV gap can be, and a prefix weight of 3 is bigger than the whole range of the KV score. So memory pressure can never outvote a full prefix match.
I measured this on the picker image with two stand-in pods that only expose vLLM’s metrics. With the stock weights the warm pod still got everything at a KV usage of 0.79 and nothing at 0.85, because only the hidden filter stops it. With weights of 2, 3 and 1 the ratio is 1 over 3, so the choice should flip at 0.10 plus 1/3, which is 0.43, and it flipped between a warm-pod KV usage of 0.43 and 0.44.
The same arithmetic explains something that happened to me in production. On an older router, with the prefix weight at 3 and the KV weight at 2, a popular prompt prefix stuck to the pod that held it. By the formula above, nothing short of the hidden filter could move it, so traffic piled onto that one pod while the others sat idle, until its KV cache was close to full. The fix was to raise the KV weight from 2 to 3 and lower the prefix weight from 3 to 1. With those weights the choice flips once the warm pod is about a third fuller than an idle one, where before it never flipped.
It was also hard to see on the dashboards. The pool-averaged metrics I was autoscaling on stayed calm, because the other pods were idle. As an illustration, with made-up numbers and not a measurement: one pod at a KV usage of 0.75 and two idle pods at 0.05 average out to 0.28, which is nowhere near any threshold you’d put on an average, while that one pod is a few points from where the filter starts hiding it. That’s the best argument for scaling on the worst pod and not only on the average, which is what we do in section 3.
There’s a second reason to keep the prefix weight low for this model. The index records where requests went, not what vLLM can actually reuse. On a hybrid model, vLLM needs the recurrent state behind a prefix as well, and by default it saves that state only at checkpoints. So a match in the picker is an upper bound on a hit in vLLM. That comes from reading vLLM’s source and not from a measurement, but it points the same way as the production lesson.
Envoy AI Gateway
The picker needs a gateway to call it, and the gateway has to understand that a request to /v1/chat/completions carries a model name in its body. That’s the job of Envoy AI Gateway. It builds on Envoy Gateway, the controller that turns Gateway API resources into Envoy proxy configuration, and adds a second controller on top, so we run two controllers. One naming note, because you’ll see both names: from v1.2.0 the project is called Agent Router, but the API group, the charts and the images keep the old names, and so does this post.
The split between the planes is what matters. In the control plane, Envoy Gateway watches GatewayClass, Gateway and HTTPRoute, and the AI Gateway controller watches its own resources and generates the HTTP routes and proxy extensions for them. In the data plane, the Envoy pod gains an extra container once the first route exists: an external-processing sidecar called ai-gateway-extproc that reads the request body, finds the model name and writes it into a header.
Following one request through it:
- The client sends an OpenAI-style call with a
modelin the body. - The sidecar reads that model and sets the header
x-ai-eg-model, overwriting any value the client tried to send, so the model always comes from the body. - The route matches on that header.
- The route’s backend is the
InferencePool, so the picker runs next and returns a pod address. - On the way back, the sidecar reads the token usage and records it.
Of the six custom resources in this release, we use one in the request path: AIGatewayRoute, plus the Gateway API ones around it. AIServiceBackend and BackendSecurityPolicy are for external providers and upstream credentials, GatewayConfig tunes the sidecar, and MCPRoute and QuotaPolicy are out of scope here.
Installing the gateway stack
Terraform stops at the cluster, Karpenter and the AWS Load Balancer Controller. Everything in the gateway stack is Kubernetes, so it’s plain Helm with the charts’ own values files. The install order is where the documentation and reality part ways. Following the documented order, Envoy Gateway with the InferencePool add-on never becomes Ready, because the cluster role that lets it read InferencePool objects ships with the AI Gateway chart. The order that works is:
- The InferencePool CRDs (Inference Extension v1.6.2). They go first because the AI Gateway controller decides at startup whether to watch InferencePools, and it needs the CRD to exist at that moment.
- Gateway API v1.6.1 and the Envoy Gateway CRDs (v1.9.3).
- The AI Gateway CRDs, then the AI Gateway controller (v1.2.0).
- Envoy Gateway v1.9.3 last, with its own CRDs switched off (
crds.enabled=false) because step 2 installed them.
Run these from the platform folder of the examples, which holds the two values files that step 4 reads:
# 1. InferencePool CRDs (Gateway API Inference Extension v1.6.2)
kubectl apply -f https://github.com/kubernetes-sigs/gateway-api-inference-extension/releases/download/v1.6.2/manifests.yaml
# 2. Gateway API v1.6.1 and the Envoy Gateway CRDs, rendered from the Envoy Gateway v1.9.3 CRD chart
helm template eg-crds oci://docker.io/envoyproxy/gateway-crds-helm --version v1.9.3 \
--set crds.gatewayAPI.enabled=true --set crds.envoyGateway.enabled=true | kubectl apply --server-side --force-conflicts -f -
# 3. AI Gateway CRDs, then the AI Gateway controller (v1.2.0)
helm upgrade -i aieg-crd oci://docker.io/envoyproxy/ai-gateway-crds-helm --version v1.2.0 \
--namespace envoy-ai-gateway-system --create-namespace
helm upgrade -i aieg oci://docker.io/envoyproxy/ai-gateway-helm --version v1.2.0 \
--namespace envoy-ai-gateway-system
# 4. Envoy Gateway last, with the AI Gateway values and the InferencePool add-on
helm upgrade -i eg oci://docker.io/envoyproxy/gateway-helm --version v1.9.3 \
--namespace envoy-gateway-system --create-namespace --set crds.enabled=false \
-f envoy-gateway-values.yaml -f envoy-gateway-values-addon.yaml
The two values files are copies of the ones in the AI Gateway v1.2.0 repository (manifests/envoy-gateway-values.yaml and examples/inference-pool/envoy-gateway-values-addon.yaml). The base file is the minimal Envoy Gateway configuration that every AI Gateway install needs. It sets the controller name that our GatewayClass will use, turns on the Backend and EnvoyPatchPolicy APIs, and registers the AI Gateway controller as an extension manager, with its service address and port 1063. The AI Gateway needs that hook to fine-tune the Envoy configuration that Envoy Gateway generates (listeners, routes, clusters and secrets). The add-on is the part for model servers:
# platform/envoy-gateway-values-addon.yaml
# Vendored from https://raw.githubusercontent.com/envoyproxy/ai-gateway/v1.2.0/examples/inference-pool/envoy-gateway-values-addon.yaml (tag v1.2.0)
# Copyright Envoy AI Gateway Authors
# SPDX-License-Identifier: Apache-2.0
# The full text of the Apache license is available in the LICENSE file at
# the root of the repo.
# This addon file adds InferencePool support to Envoy Gateway.
# Use this in combination with the base envoy-gateway-values.yaml:
#
# helm upgrade -i eg oci://docker.io/envoyproxy/gateway-helm \
# --version v0.0.0-latest \
# --namespace envoy-gateway-system \
# --create-namespace \
# -f ../../manifests/envoy-gateway-values.yaml \
# -f envoy-gateway-values-addon.yaml
#
# You can also combine with rate limiting:
# -f ../../manifests/envoy-gateway-values.yaml \
# -f ../token_ratelimit/envoy-gateway-values-addon.yaml \
# -f envoy-gateway-values-addon.yaml
config:
envoyGateway:
# GAIE conformance test required Envoy Gateway namespaced mode
provider:
type: Kubernetes
kubernetes:
deploy:
type: GatewayNamespace
extensionManager:
# Enable InferencePool custom resource support
backendResources:
- group: inference.networking.k8s.io
kind: InferencePool
version: v1
It makes Envoy Gateway deploy each proxy into the namespace of its Gateway (GatewayNamespace), and it registers InferencePool as a backend resource type that the extension manager understands.
The router chart
The router itself ships as a Helm chart, oci://ghcr.io/llm-d/charts/llm-d-router-gateway, version v1.0.0. It creates the InferencePool and the picker with its Service, so there’s nothing for us to template. We only write values:
# k8s/epp-values.yaml
# Helm values for the llm-d router chart (oci://ghcr.io/llm-d/charts/llm-d-router-gateway, version v1.0.0).
# Install with the release name qwen38-27b-nvfp4 in the namespace llm: the chart then creates the InferencePool and the
# endpoint picker Service under that name, which is what the AIGatewayRoute refers to.
router:
modelServers:
matchLabels:
app: qwen38-27b-nvfp4 # the label on the vLLM pods
targetPorts:
- number: 8000
epp:
# The chart's default request (8 CPUs and 8 GiB) is sized for a pool of about a hundred pods, because the picker
# scrapes every pod many times a second. A pool of a few pods needs far less.
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
memory: 2Gi
pluginsConfigFile: "balanced-plugins.yaml"
pluginsCustomConfig:
balanced-plugins.yaml: |
apiVersion: llm-d.ai/v1
kind: EndpointPickerConfig
plugins:
- type: queue-scorer
- type: kv-cache-utilization-scorer
- type: approx-prefix-cache-producer
parameters:
autoTune: true # take LRU capacity (num_gpu_blocks) from the scraped vllm:cache_config_info
blockSizeTokens: 64 # used when auto-tune has no scrape yet; values below 64 are clamped up to 64
lruCapacityPerServer: 31250
- type: prefix-cache-scorer # reads the match info the producer wrote; the weight below is its vote
- type: max-score-picker
schedulingProfiles:
- name: default
plugins:
- pluginRef: queue-scorer
weight: 2
- pluginRef: kv-cache-utilization-scorer
weight: 3
- pluginRef: prefix-cache-scorer
weight: 1
- pluginRef: max-score-picker
monitoring:
prometheus:
auth:
enabled: true # the default: /metrics needs a bearer token (see the metrics section)
Four parts matter:
matchLabelsandtargetPortsare the pool’s selector: the label on our vLLM pods and the port they serve on, 8000.resourcesreplaces the chart’s default request of 8 CPUs and 8 GiB. That default is sized for a pool of about a hundred pods, because the picker scrapes every pod 20 times a second and the idle CPU grows with the pod count. It wouldn’t even schedule on our 4 vCPU system nodes. A pool of a few pods needs far less, so we ask for 500m and 512 Mi and cap memory at 2 Gi. The router’s sizing notes put the cost at about 7.5 cores for a hundred pods, plus 0.5 to 1 core per request per second for large agentic prompts, so watch the picker’s CPU as traffic grows.pluginsCustomConfigholds the picker’s own config file, andpluginsConfigFilesays which one to use. The plugins are the scorers from above, and the scheduling profile gives the weights we settled on: queue 2, KV cache 3, prefix 1.autoTunetakes the block size and the LRU capacity from the scrapedvllm:cache_config_info, which for this model means 1,600-token blocks andnum_gpu_blocksentries per pod.blockSizeTokensandlruCapacityPerServerare only the fallbacks before the first scrape, and values ofblockSizeTokensbelow 64 are clamped up to 64.monitoring.prometheus.auth.enabledkeeps the picker’s/metricsbehind a bearer token, which is the default. The next section sets up the account that reads it.
The config is read only at startup and parsed strictly, so a typo is a crash loop and not a silent default. That’s what you want: you find out at once. The install is one command:
helm upgrade -i qwen38-27b-nvfp4 oci://ghcr.io/llm-d/charts/llm-d-router-gateway \
--version v1.0.0 --namespace llm --create-namespace -f epp-values.yaml
The release name is the model name on purpose. The chart derives the InferencePool name from it, and our route refers to the pool by that name.
One more thing about running the picker is the failure mode. The InferencePool has a failureMode field that is meant to say what the gateway does when it can’t reach the picker. The API default is FailClose, which returns an error, and the llm-d chart sets FailOpen, which llm-d’s documentation describes as the proxy routing straight to the model servers when the picker is gone. Envoy AI Gateway doesn’t read that field, though. In v1.2.0 it builds the picker’s ext_proc filter with FailureModeAllow: false (in internal/extensionserver/inferencepool.go), and the pool’s upstream cluster takes its destination from the picker’s answer, so there is no list of endpoints to fall back to. With this gateway, a picker that is down or restarting fails the requests for that model. So the picker is part of the serving path. Alert on llm_d_epp_ready_endpoints and on the picker pod, keep it off nodes that get interrupted, and look at llm-d’s documentation on running two replicas with leader election, whose switchover takes 10 to 30 seconds. Then check what your own gateway does by reading the filter’s failure_mode_allow in Envoy’s config_dump.
Optional: precise prefix-cache routing
The default index is the picker’s diary of where it sent each prompt, and it assumes that pod still holds the cache. Precise routing replaces the diary with facts. Every vLLM pod publishes an event whenever it stores or evicts a cache block, over a ZMQ socket (events on port 5556, replay on port 5559). The picker dials every Ready pod, listens, and keeps an index of which blocks each pod holds, so it forgets what was evicted too. The pods bind the sockets and nothing connects to the picker. After a restart, the picker asks each pod to replay its recent events, and vLLM keeps the last 10,000 batches for that.
Two more pieces come with it. To get the exact token IDs of a prompt, the picker calls the /v1/*/render endpoint of a Ready pod before routing, and that endpoint exists only when vLLM runs with --enable-scale-out. And the picker has to hash with the block size vLLM uses.
Turning it on takes two commands. The first changes the vLLM pods: vllm.kvEvents.enabled adds --enable-scale-out, a --kv-events-config, a POD_IP variable and the two container ports. The arguments change, so the pods roll and each one reloads the model. The second moves the router to the precise values, with the same release name:
helm upgrade llm-serving ./helm/llm-serving --namespace llm -f terraform-values.yaml \
--set vllm.kvEvents.enabled=true
helm upgrade qwen38-27b-nvfp4 oci://ghcr.io/llm-d/charts/llm-d-router-gateway \
--version v1.0.0 --namespace llm -f epp-values-precise.yaml
Here are the precise values:
# k8s/epp-values-precise.yaml
# OPTIONAL. Helm values for the llm-d router chart (oci://ghcr.io/llm-d/charts/llm-d-router-gateway, version v1.0.0):
# precise prefix-cache routing for Qwen3.8-27B (hybrid model, vLLM attention block of 1,600 tokens). Use it instead of
# epp-values.yaml, with the same release name (qwen38-27b-nvfp4) and namespace (llm), and turn on vllm.kvEvents in the
# llm-serving chart so the vLLM pods publish the events the picker listens to.
router:
modelServers:
matchLabels:
app: qwen38-27b-nvfp4 # the label on the vLLM pods
targetPorts:
- number: 8000
epp:
# The chart's default request (8 CPUs and 8 GiB) is sized for a pool of about a hundred pods, because the picker
# scrapes every pod many times a second. A pool of a few pods needs far less.
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
memory: 2Gi
replicas: 1 # the KV index lives in this process; one replica (a restart rebuilds it from replay)
pluginsConfigFile: "precise-plugins.yaml"
pluginsCustomConfig:
precise-plugins.yaml: |
apiVersion: llm-d.ai/v1
kind: EndpointPickerConfig
plugins:
- type: token-producer # tokenizes every prompt by calling vLLM's /v1/*/render on a Ready pod
parameters:
modelName: qwen38-27b-nvfp4 # the served model name, not the S3 path
vllm:
endpointDiscovery:
attemptTimeout: 2s # cap one render attempt so the retry on another pod still fits
- type: endpoint-notification-source
- type: precise-prefix-cache-producer
parameters:
tokenProcessorConfig:
blockSizeTokens: 1600 # MUST equal the attention block size vLLM logs at startup
hashAlgorithm: xxh64 # the router's own key hash; it does not have to match vLLM's
speculativeIndexing: true # seed the index for 2 s after a pick, until vLLM confirms with an event
indexerConfig:
kvBlockIndexConfig:
enableMetrics: true
kvEventsConfig:
engineType: vllm
topicFilter: "kv@"
concurrency: 8
discoverPods: true # the picker dials every Ready pod of the pool
podDiscoveryConfig:
socketPort: 5556 # vLLM's PUB socket (--kv-events-config endpoint)
replaySocketPort: 5559 # vLLM's replay ROUTER socket (replay_endpoint)
- type: queue-scorer
- type: kv-cache-utilization-scorer
- type: prefix-cache-scorer
parameters:
prefixMatchInfoProducerName: precise-prefix-cache-producer # without this line the scorer silently uses the approximate index
- type: max-score-picker
dataLayer:
sources:
- pluginRef: endpoint-notification-source
extractors:
- pluginRef: precise-prefix-cache-producer
schedulingProfiles:
- name: default
plugins:
- pluginRef: queue-scorer
weight: 2
- pluginRef: kv-cache-utilization-scorer
weight: 3
- pluginRef: prefix-cache-scorer
weight: 1
- pluginRef: max-score-picker
monitoring:
prometheus:
auth:
enabled: true # the default: /metrics needs a bearer token (see the metrics section)
Three lines matter:
blockSizeTokens: 1600must equal the attention block size vLLM logs at startup. UnlikeautoTune, this config doesn’t learn it, so re-read the log after any change of KV dtype, MTP or vLLM version. With the guide’s default of 64, a 1,000-token prefix counts as a hit, although vLLM can’t reuse it.prefixMatchInfoProducerName: precise-prefix-cache-produceron the prefix scorer tells it to read the precise index. Without this line the config still loads, and the scorer silently keeps using the approximate one.modelNamein the token producer is the served model name and not the S3 path. The name vLLM publishes events under (the chart builds it frommodel.name) and the name clients send must be the same. A mismatch gives no error: the events arrive and nothing ever matches.
The file also sets replicas: 1, because the index lives inside the picker process, and keeps the weights at queue 2, KV cache 3 and prefix 1. To see whether it works, watch four series on the picker’s /metrics. llm_d_epp_kv_cache_events_active_subscribers should equal the number of Ready pods, and llm_d_epp_kv_cache_events_messages_received_total should grow with traffic. llm_d_epp_kv_cache_index_lookup_hits_total against llm_d_epp_kv_cache_index_lookup_requests_total is the hit rate, and events arriving with zero hits mean a name or block size mismatch. llm_d_epp_token_producer_render_failures_total above zero means requests are being routed without cache information.
I ran the picker image against stand-in pods that speak vLLM’s event format. A 1,700-token shared prefix went to the holder 24 of 24 times, and a 1,000-token one did not. With the guide’s default block size of 64, the 1,000-token prefix went to the holder 24 of 24 times too, which is the mismatch the first bullet warns about. The approximate index with the right block size behaved the same way on the same stand-ins.
I leave it off by default for this model, for three reasons. First, on a hybrid model the picker sees only the attention blocks. It skips the recurrent-state blocks, and the router’s own docs call hybrid-aware scoring a work in progress, while vLLM needs the state behind a prefix too. So even the exact index is an upper bound on what vLLM will reuse, the same limit the approximate index has. Second, it costs something: a render call on a serving pod for every request, which competes with serving for CPU and adds to the time to first token (I haven’t measured how much), an index that lives in one picker replica and restarts knowing only what vLLM replays, and ZMQ connections from the picker to every pod. Third, the approximate index with the right block size already gets the boundary that matters, the 1,600-token one, right. What precise adds is awareness of evictions and exact token boundaries, and for this model that doesn’t pay for the plumbing.
If you want it anyway, flipping it on is a values change, the two commands above. Keep the weights at queue 2, KV cache 3 and prefix 1 with either index. The pinning I described is a property of the weight ratio and not of how the match is computed, and a truer match makes the pin look more justified to the picker, not safer.
The Gateway
The Gateway gives the model an address. Here’s the raw YAML:
# k8s/gateway.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: ai-gateway
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
---
apiVersion: v1
kind: Namespace
metadata:
name: ai-gateway
---
# per-Gateway Envoy settings. On EKS the proxy's Service becomes a Network Load Balancer: the AWS Load Balancer Controller
# provisions it because of the loadBalancerClass, registers the pod IPs directly as targets, and the scheme decides whether
# it is reachable from the internet (internal is the default, and the safe one for an endpoint with no authentication).
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
name: llm-gateway-proxy
namespace: ai-gateway
spec:
provider:
type: Kubernetes
kubernetes:
envoyService:
type: LoadBalancer
loadBalancerClass: service.k8s.aws/nlb
annotations:
service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: ip
service.beta.kubernetes.io/aws-load-balancer-scheme: internal
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: llm-gateway
namespace: ai-gateway
spec:
gatewayClassName: ai-gateway
infrastructure:
parametersRef:
group: gateway.envoyproxy.io
kind: EnvoyProxy
name: llm-gateway-proxy
listeners:
- name: http
protocol: HTTP
port: 80
allowedRoutes:
namespaces:
from: All # let AIGatewayRoutes in the model namespace (llm) attach
The fields that matter:
- The
GatewayClassties the nameai-gatewayto Envoy Gateway’s controller, which is how Envoy Gateway knows these gateways are its to manage. - The
EnvoyProxyholds per-Gateway proxy settings, reached throughinfrastructure.parametersRef. Ours turns the proxy’s Service into an AWS load balancer, which the next subsection explains. - The listener is HTTP on port 80, and
allowedRoutes.namespaces.from: Alllets routes in other namespaces attach. We need that, because the Gateway lives inai-gatewayand our route lives next to the model, inllm.
Exposing the gateway
A gateway needs an address that clients can reach, and on EKS that means a load balancer. Envoy Gateway creates a Kubernetes Service for the proxy pods, and the EnvoyProxy above asks for it to be type: LoadBalancer with loadBalancerClass: service.k8s.aws/nlb. That class hands the Service to the AWS Load Balancer Controller instead of the cloud provider’s built-in implementation, and the controller provisions a Network Load Balancer for it. Terraform installs the controller, next to the cluster and Karpenter:
# terraform/lb_controller.tf
# AWS Load Balancer Controller. This is what turns the Envoy gateway's
# Service (loadBalancerClass: service.k8s.aws/nlb) into an NLB, and it
# reads the kubernetes.io/role/elb and kubernetes.io/role/internal-elb
# subnet tags (set in vpc.tf) to choose the subnets the load balancer uses.
module "lb_controller" {
source = "terraform-aws-modules/eks-pod-identity/aws"
version = "2.10.0"
name = "aws-load-balancer-controller"
# Attaches the controller's IAM policy (the one from the upstream
# documentation) instead of copying the long policy document here.
attach_aws_lb_controller_policy = true
# Trust policy is the module default: Service principal
# pods.eks.amazonaws.com with sts:AssumeRole and sts:TagSession, the same
# pattern as pod_identity.tf.
associations = {
this = {
cluster_name = var.cluster_name
namespace = "kube-system"
service_account = "aws-load-balancer-controller"
}
}
tags = var.tags
# The association needs a running cluster.
depends_on = [module.eks]
}
resource "helm_release" "aws_load_balancer_controller" {
name = "aws-load-balancer-controller"
repository = "https://aws.github.io/eks-charts"
chart = "aws-load-balancer-controller"
# 3.6.2, the latest chart in https://aws.github.io/eks-charts
# (appVersion v3.6.2).
version = "3.6.2"
namespace = "kube-system"
values = [yamlencode({
clusterName = var.cluster_name
region = var.region
vpcId = module.vpc.vpc_id
serviceAccount = {
create = true
name = "aws-load-balancer-controller"
}
})]
depends_on = [module.lb_controller]
}
The first module creates the IAM role with the controller’s policy, the one from the upstream documentation, and a Pod Identity association that ties the role to the aws-load-balancer-controller service account in kube-system. The second block installs the controller’s Helm chart (version 3.6.2) with the cluster name, region and VPC ID. The depends_on makes the association exist before the controller pod starts.
Three settings decide how the load balancer behaves:
aws-load-balancer-nlb-target-type: ipregisters the pod IPs of the Envoy pods directly as targets, so traffic goes straight to the pod and not through a node port.aws-load-balancer-schemeisinternalby default, which gives the load balancer a private address that only the VPC can reach. That’s the safe default for an endpoint with no authentication. To expose it to the internet, setrouting.gateway.loadBalancerScheme=internet-facing, and put authentication in front of it first.- The controller picks the subnets by tag.
kubernetes.io/role/elbmarks the public subnets for internet-facing load balancers, andkubernetes.io/role/internal-elbmarks the private ones for internal load balancers. Both tags are already on our subnets from the VPC in section 2 of part 4.
Why an NLB and not an ALB? The controller’s documentation maps a Service of type LoadBalancer to an NLB and an Ingress to an ALB, and Envoy Gateway’s data plane is a Service, so an NLB is the natural fit. It also keeps Envoy as the only layer-7 proxy in the path. An NLB forwards TCP, where an ALB would put a second HTTP proxy, with its own idle timeout, in front of long streamed answers.
The route
The AIGatewayRoute ties a model name to the pool. Here’s the raw YAML:
# k8s/aigatewayroute.yaml
apiVersion: aigateway.envoyproxy.io/v1beta1
kind: AIGatewayRoute
metadata:
name: qwen38-27b-nvfp4
namespace: llm
spec:
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: llm-gateway
namespace: ai-gateway
llmRequestCosts: # also makes the gateway force stream_options.include_usage on streamed requests
- metadataKey: llm_input_token
type: InputToken
- metadataKey: llm_output_token
type: OutputToken
- metadataKey: llm_total_token
type: TotalToken
rules:
- name: qwen38-27b-nvfp4
matches:
- headers:
- type: Exact
name: x-ai-eg-model
value: qwen38-27b-nvfp4 # must equal vLLM --served-model-name
timeouts:
request: 300s # default is 60s; a long streamed answer needs more
backendRefs:
- group: inference.networking.k8s.io
kind: InferencePool
name: qwen38-27b-nvfp4
The fields that matter:
parentRefsattaches the route to the Gateway above.llmRequestCostsrecords the input, output and total token counts of each request. It also makes the gateway forcestream_options.include_usageon streamed requests, so streamed answers report their usage too.- The match is the header
x-ai-eg-model, and its value must equal the name vLLM serves. That’s why section 3 of part 4 insisted on--served-model-name: on the pool path the model name in the request body is passed to vLLM unchanged. timeouts.requestis 300 seconds. The default is 60, which is shorter than a long thinking answer.backendRefspoints at theInferencePoolby name, the one the router chart created.
If the route lived in a different namespace from the pool, you’d also need a ReferenceGrant, and in this release it needs two from entries, one for AIGatewayRoute and one for the HTTPRoute it generates. With only the first, requests get a 500. Ours share the llm namespace, so we don’t need one.
Turning them into templates
Now let’s turn the Gateway and the route into templates. They read one block of values:
# helm/llm-serving/values.yaml (routing)
# AI gateway routing (GatewayClass, EnvoyProxy, Gateway, AIGatewayRoute) in its own namespace.
routing:
enabled: true
gateway:
namespace: ai-gateway
# Create the ai-gateway namespace; set false when it already exists.
createNamespace: true
# The NLB scheme of the gateway Service; internal is the safe default for an endpoint without authentication.
loadBalancerScheme: internal
routing.enabled switches the whole set off, for a cluster that already has a gateway, and routing.gateway.namespace says where the Gateway lives. createNamespace creates that namespace, and you set it to false when it already exists. loadBalancerScheme is the NLB scheme from the last subsection. Look at what changed from the raw files: the model name is no longer typed into the route. The route’s name, its rule, the header it matches and the InferencePool it points at all come from the single model.name value. The router release is named after the model too, so the route finds the pool by the same string. A rename is one edit, and the match and the pool can’t drift apart. The scheme in the EnvoyProxy comes from loadBalancerScheme in the same way.
# helm/llm-serving/templates/gateway.yaml
{{- if .Values.routing.enabled }}
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: ai-gateway
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
---
# per-Gateway Envoy settings. On EKS the proxy's Service becomes a Network Load Balancer: the AWS Load Balancer Controller
# provisions it because of the loadBalancerClass, registers the pod IPs directly as targets, and the scheme decides whether
# it is reachable from the internet (internal is the default, and the safe one for an endpoint with no authentication).
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
name: llm-gateway-proxy
namespace: {{ .Values.routing.gateway.namespace }}
spec:
provider:
type: Kubernetes
kubernetes:
envoyService:
type: LoadBalancer
loadBalancerClass: service.k8s.aws/nlb
annotations:
service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: ip
service.beta.kubernetes.io/aws-load-balancer-scheme: {{ .Values.routing.gateway.loadBalancerScheme }}
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: llm-gateway
namespace: {{ .Values.routing.gateway.namespace }}
spec:
gatewayClassName: ai-gateway
infrastructure:
parametersRef:
group: gateway.envoyproxy.io
kind: EnvoyProxy
name: llm-gateway-proxy
listeners:
- name: http
protocol: HTTP
port: 80
allowedRoutes:
namespaces:
from: All # let AIGatewayRoutes in the model namespace (llm) attach
{{- end }}
{{- if .Values.routing.gateway.createNamespace }}
---
apiVersion: v1
kind: Namespace
metadata:
name: {{ .Values.routing.gateway.namespace }}
{{- end }}
# helm/llm-serving/templates/aigatewayroute.yaml
{{- if .Values.routing.enabled }}
apiVersion: aigateway.envoyproxy.io/v1beta1
kind: AIGatewayRoute
metadata:
name: {{ include "llm-serving.modelName" . }}
namespace: {{ .Release.Namespace }}
spec:
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: llm-gateway
namespace: {{ .Values.routing.gateway.namespace }}
llmRequestCosts: # also makes the gateway force stream_options.include_usage on streamed requests
- metadataKey: llm_input_token
type: InputToken
- metadataKey: llm_output_token
type: OutputToken
- metadataKey: llm_total_token
type: TotalToken
rules:
- name: {{ include "llm-serving.modelName" . }}
matches:
- headers:
- type: Exact
name: x-ai-eg-model
value: {{ include "llm-serving.modelName" . }} # must equal vLLM --served-model-name
timeouts:
request: 300s # default is 60s; a long streamed answer needs more
backendRefs:
- group: inference.networking.k8s.io
kind: InferencePool
name: {{ include "llm-serving.modelName" . }}
{{- end }}
That’s the routing: the model name in the body decides the route, the route points at a pool, and the picker decides the pod. In the next section we deploy the gateway, send traffic through it and look at what it leaves behind in metrics.
2. Through the gateway: testing, a simulation and the metrics
The gateway stack and the router are installed, and the chart from section 4 of part 4 is still running with routing, autoscaling and observability switched off. In this section we turn routing on and send the same two requests through the gateway. Then we add Prometheus and the monitoring objects of the chart, try the whole request path without a GPU in a simulation, and finally read the numbers all of it produces.
Turn routing on
Everything routing needs is in place: the gateway stack and the router release from section 1, and the AWS Load Balancer Controller from the Terraform apply. The routing switch defaults to on, so we only stop passing the flag that turned it off:
helm upgrade llm-serving ./helm/llm-serving --namespace llm -f terraform-values.yaml \
--set autoscaling.enabled=false --set observability.enabled=false
That adds the GatewayClass, the EnvoyProxy, the Gateway and the AIGatewayRoute from section 1, and creates the ai-gateway namespace for them. Three things have to happen before a request can get through, and each has its own check. Envoy Gateway has to program a proxy for the Gateway, the AI Gateway controller has to accept the route, and the AWS Load Balancer Controller has to create the load balancer for the proxy’s Service and write its hostname on it:
kubectl wait --timeout=3m -n ai-gateway gateway/llm-gateway --for=condition=Programmed
kubectl wait --timeout=2m -n llm aigatewayroute/qwen38-27b-nvfp4 --for=condition=Accepted
kubectl get svc -n ai-gateway -l gateway.envoyproxy.io/owning-gateway-name=llm-gateway -w
Watch the Service until its EXTERNAL-IP column holds a hostname ending in elb.us-east-1.amazonaws.com (with your region), then stop the watch. If one of the waits times out, kubectl describe on the Gateway or the route shows in its conditions what it’s waiting for. Once the first route exists, the AI Gateway controller replaces the Envoy pod with one that carries its sidecar. So kubectl get pods -n ai-gateway shows a pod with two containers first and then, a moment later, a single pod with three. The InferencePool from the router release should report Accepted and ResolvedRefs.
The load balancer’s scheme is internal by default, which means its hostname resolves to private addresses and only answers inside the VPC. You have three ways to reach it for a test:
- Port-forward to the Envoy Service. It works from wherever
kubectlworks, and it tests everything except the load balancer itself. The examples below use it. - The load balancer’s hostname, from a host inside the VPC. A bastion or a pod will do. Use
http://$LBwhere the examples sayhttp://localhost:8080. - An internet-facing load balancer. Set
--set routing.gateway.loadBalancerScheme=internet-facingon the upgrade for a public test endpoint. The gateway has no authentication, so anyone who finds the hostname can use your GPUs. Treat it as a test endpoint and switch back tointernalwhen you’re done.
For the port-forward, find the Envoy Service by its label and forward the gateway’s port 80:
GW=$(kubectl get svc -n ai-gateway -l gateway.envoyproxy.io/owning-gateway-name=llm-gateway \
-o jsonpath='{.items[0].metadata.name}')
kubectl port-forward -n ai-gateway svc/$GW 8080:80 &
For the load balancer, read its hostname off the same Service:
LB=$(kubectl get svc -n ai-gateway -l gateway.envoyproxy.io/owning-gateway-name=llm-gateway \
-o jsonpath='{.items[0].status.loadBalancer.ingress[0].hostname}')
Test through the gateway
We ask the same two questions as in section 4 of part 4, this time of the gateway. The first is which models it serves:
curl -s http://localhost:8080/v1/models
This call never reaches a pod. In Envoy AI Gateway v1.2.0 the sidecar answers GET /v1/models itself, from the models declared in the AIGatewayRoute: every rule that matches the header x-ai-eg-model exactly adds one entry. We have one rule, so we get one entry:
{"data":[{"id":"qwen38-27b-nvfp4","created":1793349490,"object":"model","owned_by":"Envoy AI Gateway"}],"object":"list"}
The id must be qwen38-27b-nvfp4, the name the route matches on. created is the creation time of the route, unless a rule sets modelsCreatedAt, and owned_by is the gateway’s default unless a rule sets modelsOwnedBy. There’s no max_model_len here, because vLLM didn’t answer. The sidecar answers before the request goes anywhere, so a 200 proves that the proxy is up and that the route knows the model name. It proves nothing about the pods, and it still answers when none of them is Ready.
The second question is the chat completion, and this one goes through the picker to a pod:
curl -s http://localhost:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{
"model": "qwen38-27b-nvfp4",
"messages": [{"role": "user", "content": "In one sentence, what is a KV cache?"}],
"max_tokens": 400
}'
A good answer is a 200 with three things in it: model echoes qwen38-27b-nvfp4, choices[0].message.content holds the answer, and choices[0].message.reasoning holds the thinking. The usage block counts the tokens, and the gateway reads the same block to record them. The model name in the body is what the route matches on, so a name it doesn’t know gets a 404 from the gateway before anything reaches a pod. The route’s request timeout is 300 seconds, so a long thinking answer isn’t cut off at the default of 60.
When it doesn’t work
Through the gateway a request has more places to stop than it had in section 4 of part 4: the load balancer, the proxy, the route, the picker and the pod. The table goes by symptom, with what to check, the usual cause and the fix.
The first thing to find out is how far a request got. Port-forward to the Envoy Service tells you if the proxy works, and a request that returns the gateway’s own error text tells you the proxy answered before any pod was involved. The table goes by symptom, with what to check, the usual cause and the fix.
| What you see | Usual cause | What to check, and the fix |
|---|---|---|
The Service’s EXTERNAL-IP stays <pending> | The controller couldn’t build the load balancer. The log line unable to resolve at least one subnet means it found no usable subnets. The longer form counts the subnets it rejected: tagged for other clusters, or short of free IP addresses. An AccessDenied from the AWS API means its role lacks a permission. | Check: kubectl describe svc -n ai-gateway <service> for events with the reason FailedBuildModel or FailedDeployModel, then kubectl logs -n kube-system deploy/aws-load-balancer-controller. Fix: Put kubernetes.io/role/internal-elb on the private subnets (and kubernetes.io/role/elb on the public ones for an internet-facing load balancer), and keep a few free addresses in them. The Terraform in section 2 of part 4 sets both tags. |
| The hostname resolves but the connection hangs or is reset | With the default internal scheme the hostname only answers inside the VPC, so a request from your laptop goes nowhere. Inside the VPC, the targets may be unhealthy because the Envoy pod isn’t Ready. | Check: aws elbv2 describe-target-health for the target group of the load balancer, and the scheme of the load balancer. Fix: Test from a host inside the VPC, or through the port-forward. Check kubectl get pods -n ai-gateway. |
404 with the body No matching route found. It is likely because the model specified in your request is not configured in the Gateway. | The gateway routes on the model name in the body. A name that no rule matches gets this answer, and so does a body without a model field. A client-supplied x-ai-eg-model header doesn’t help: the gateway overwrites it with the body’s value. | Check: The model field of the request body, and the AIGatewayRoute. Fix: Use the name from /v1/models, which is qwen38-27b-nvfp4. |
404 with the body unsupported path: /v1/foo | The gateway only handles the OpenAI-style paths. | Check: The URL path of the request. Fix: Use /v1/chat/completions or /v1/models. |
400 with malformed request: failed to parse JSON for /v1/chat/completions | The body isn’t valid JSON. Shell quoting is the usual reason. | Check: The body of the request. Fix: Put the JSON in a file and use -d @file. |
503, with the response header x-llm-d-request-dropped-reason: rejected-no-endpoints | The picker sees no ready pod to send the request to. The pods may still be starting, or none passed the readiness probe. | Check: kubectl get pods -n llm, and the picker’s llm_d_epp_ready_endpoints. Fix: Wait for a pod to be Ready. A pod that keeps restarting is a section 4 of part 4 problem. |
The route doesn’t become Accepted, and kubectl get aigatewayroute shows NotAccepted | The controller couldn’t reconcile the route, and the condition message says why. One cause is a pool in another namespace than the route without a grant. | Check: kubectl describe aigatewayroute -n llm qwen38-27b-nvfp4, the message in its conditions. Fix: Read the message. If the pool and the route are in different namespaces, the pool’s namespace needs a ReferenceGrant with two from entries, as in section 1. A missing grant gives requests a 500 from Envoy even when the route reads Accepted. |
The InferencePool has no Accepted or ResolvedRefs conditions, or kubectl logs -n envoy-ai-gateway-system deploy/ai-gateway-controller says InferencePool CRD not found, skipping InferencePool controller | The AI Gateway controller decides at startup whether to watch InferencePools. It started before the CRDs existed. | Check: kubectl get inferencepool -n llm -o yaml, and that log. Fix: kubectl rollout restart -n envoy-ai-gateway-system deploy/ai-gateway-controller. This is why the CRDs come first in section 1. |
Accepted=False with the reason EndpointPickerRefMissing on the pool | The pool has no usable picker reference: the field is missing, or the Service it names doesn’t exist, which is what you see before the router release is installed. | Check: kubectl get svc -n llm. Fix: Install the router release from section 1, then compare the Service name with the pool’s endpointPickerRef. |
The envoy-gateway pod restarts, and its log says cannot list resource | The cluster role that lets Envoy Gateway read InferencePools ships in the AI Gateway chart, and that chart isn’t installed yet. | Check: kubectl logs -n envoy-gateway-system deploy/envoy-gateway --previous. Fix: Follow the install order in section 1: the AI Gateway chart before Envoy Gateway. |
| A long answer is cut off, or the client gives up | The route allows 300 seconds per request. A thinking model with a large max_tokens can use more, and many clients stop earlier. | Check: The timeouts on the route, and the client’s own timeout. Fix: Lower max_tokens, or raise the timeout on the route and in the client. |
When a request does reach a pod, the pod’s own log and vllm: metrics take over from here. The picker names its choice in the header x-gateway-destination-endpoint of the request it forwards, and its counter llm_d_epp_scheduler_attempts_total shows which pods the requests went to.
Observability
Now we need something watching all of this. Prometheus goes first, for two reasons. It creates the monitoring namespace that the chart’s metrics reader lives in, and it installs the custom resource definitions for PodMonitor, ServiceMonitor and PrometheusRule, which the cluster doesn’t know until then. The install is the community chart, with a values file from the examples:
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm upgrade -i kube-prometheus-stack prometheus-community/kube-prometheus-stack --version 92.16.1 \
--namespace monitoring --create-namespace -f platform/kube-prometheus-stack-values.yaml
The values file is short:
# platform/kube-prometheus-stack-values.yaml
# Values for the kube-prometheus-stack chart (version 92.16.1), installed as the release "kube-prometheus-stack" in the
# namespace "monitoring". That release name makes the Prometheus Service kube-prometheus-stack-prometheus, which the
# KEDA triggers in the llm-serving chart query on port 9090.
prometheus:
prometheusSpec:
# By default the stack only loads PodMonitors, ServiceMonitors and PrometheusRules that carry the labels of its own
# Helm release. With these three set to false it loads all of them, including the ones our chart creates in the
# llm namespace.
podMonitorSelectorNilUsesHelmValues: false
serviceMonitorSelectorNilUsesHelmValues: false
ruleSelectorNilUsesHelmValues: false
The release name makes the Prometheus Service kube-prometheus-stack-prometheus, which the KEDA triggers in the next section query on port 9090. The three NilUsesHelmValues settings matter more. By default the stack only loads the PodMonitors, ServiceMonitors and rules that carry the labels of its own Helm release. With all three set to false it loads every one it finds, including the ones our chart creates in the llm namespace.
The chart’s observability layer has three parts to explain, and we’ll take them in the order Prometheus needs them: first an identity to read the picker, then the two objects that tell Prometheus what to scrape, and last the rules.
The metrics reader
The picker’s /metrics is behind a bearer token, which is the default we kept in section 1. So before Prometheus can read it, it needs an identity the picker accepts. That takes four small objects: a ServiceAccount, a ClusterRole that allows reading /metrics, a ClusterRoleBinding that connects the two, and a Secret that holds the account’s token. Here’s the raw YAML:
# k8s/epp-metrics-reader.yaml
# A ServiceAccount allowed to read the EPP /metrics endpoint. The EPP (llm-d Router v1.0.0, default
# --metrics-endpoint-auth=true) validates the bearer token with a TokenReview and then a SubjectAccessReview for
# "get" on the non-resource URL /metrics, so the ServiceAccount needs that one rule.
# The Secret below carries NO token in this file: Kubernetes fills the token in when it sees the annotation + type.
# The monitoring namespace is created by the Prometheus install, which comes first.
apiVersion: v1
kind: ServiceAccount
metadata:
name: metrics-reader
namespace: monitoring
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: metrics-reader
rules:
- nonResourceURLs: ["/metrics"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: metrics-reader
subjects:
- kind: ServiceAccount
name: metrics-reader
namespace: monitoring
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: metrics-reader
---
apiVersion: v1
kind: Secret
metadata:
name: metrics-reader-token
namespace: monitoring
annotations:
kubernetes.io/service-account.name: metrics-reader
type: kubernetes.io/service-account-token
The ClusterRole holds the one rule that matters: get on the non-resource URL /metrics. The picker validates the caller’s token and then asks the API server whether that account may get /metrics, and this is the permission it looks for. The binding gives the role to the metrics-reader ServiceAccount in monitoring. The Secret’s type and its kubernetes.io/service-account.name annotation make Kubernetes fill in a token for that account, so the file carries no secret. If you already have a Prometheus service account, you can bind the role to it and give it a token instead.
Now let’s turn it into a template. It reads one value, observability.namespace, and the whole file sits behind observability.enabled. With the defaults it renders exactly the file above. The template doesn’t create the monitoring namespace, because the Prometheus install already did.
# helm/llm-serving/templates/epp-metrics-reader.yaml
{{- if .Values.observability.enabled }}
# A ServiceAccount allowed to read the EPP /metrics endpoint. The EPP (llm-d Router v1.0.0, default
# --metrics-endpoint-auth=true) validates the bearer token with a TokenReview and then a SubjectAccessReview for
# "get" on the non-resource URL /metrics, so the ServiceAccount needs that one rule.
# The Secret below carries NO token in this file: Kubernetes fills the token in when it sees the annotation + type.
# The monitoring namespace is created by the Prometheus install, which comes first.
apiVersion: v1
kind: ServiceAccount
metadata:
name: metrics-reader
namespace: {{ .Values.observability.namespace }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: metrics-reader
rules:
- nonResourceURLs: ["/metrics"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: metrics-reader
subjects:
- kind: ServiceAccount
name: metrics-reader
namespace: {{ .Values.observability.namespace }}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: metrics-reader
---
apiVersion: v1
kind: Secret
metadata:
name: metrics-reader-token
namespace: {{ .Values.observability.namespace }}
annotations:
kubernetes.io/service-account.name: metrics-reader
type: kubernetes.io/service-account-token
{{- end }}
Scrape targets
Prometheus scrapes only what it’s told to scrape, and the Prometheus Operator takes that instruction as objects. A PodMonitor selects pods and a ServiceMonitor selects Services. The vLLM pods have no Service in front of them, because the pool selects the pods directly, so they get a PodMonitor. The picker has a Service, so it gets a ServiceMonitor:
# k8s/podmonitors.yaml
# Two scrape targets for the Prometheus Operator (kube-prometheus-stack), so the metrics that the recording rules and the
# autoscaler read actually exist. Both objects are picked up without special labels because the stack is installed with
# podMonitorSelectorNilUsesHelmValues and serviceMonitorSelectorNilUsesHelmValues set to false.
# The vLLM pods expose /metrics on the container port named "http" (8000).
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
name: qwen38-27b-nvfp4
namespace: llm
spec:
selector:
matchLabels:
app: qwen38-27b-nvfp4
podMetricsEndpoints:
- port: http
path: /metrics
interval: 10s
---
# The endpoint picker's metrics Service (port http-metrics, 9090) needs the bearer token from epp-metrics-reader.yaml.
# A ServiceMonitor can only read a Secret from its own namespace, so it lives in monitoring and looks into llm.
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: qwen38-27b-nvfp4-epp
namespace: monitoring
spec:
namespaceSelector:
matchNames:
- llm
selector:
matchLabels:
app.kubernetes.io/name: qwen38-27b-nvfp4-epp
endpoints:
- port: http-metrics
interval: 10s
authorization:
type: Bearer
credentials:
name: metrics-reader-token
key: token
The PodMonitor lives next to the model, in llm. It selects the pods by the app label that the pool uses too, and scrapes the container port named http (8000) at /metrics every 10 seconds. The ServiceMonitor selects the picker’s Service by its app.kubernetes.io/name label, looks for it in the llm namespace through namespaceSelector, and scrapes the port named http-metrics (9090). Its authorization block sends the token from the metrics-reader-token Secret as a bearer token.
That ServiceMonitor lives in monitoring and not in llm, and the reason is the Secret. A ServiceMonitor can only read a Secret from its own namespace, and the token is in monitoring. So the monitor goes where the token is and looks across into llm for the Service.
Now the template. The names come from model.name, the PodMonitor goes into the release namespace, the ServiceMonitor goes into observability.namespace, and both sit behind observability.enabled:
# helm/llm-serving/templates/podmonitors.yaml
{{- if .Values.observability.enabled }}
# Two scrape targets for the Prometheus Operator (kube-prometheus-stack), so the metrics that the recording rules and the
# autoscaler read actually exist. Both objects are picked up without special labels because the stack is installed with
# podMonitorSelectorNilUsesHelmValues and serviceMonitorSelectorNilUsesHelmValues set to false.
# The vLLM pods expose /metrics on the container port named "http" (8000).
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
name: {{ .Values.model.name }}
namespace: {{ .Release.Namespace }}
spec:
selector:
matchLabels:
app: {{ .Values.model.name }}
podMetricsEndpoints:
- port: http
path: /metrics
interval: 10s
---
# The endpoint picker's metrics Service (port http-metrics, 9090) needs the bearer token from epp-metrics-reader.yaml.
# A ServiceMonitor can only read a Secret from its own namespace, so it lives in monitoring and looks into llm.
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: {{ .Values.model.name }}-epp
namespace: {{ .Values.observability.namespace }}
spec:
namespaceSelector:
matchNames:
- {{ .Release.Namespace }}
selector:
matchLabels:
app.kubernetes.io/name: {{ .Values.model.name }}-epp
endpoints:
- port: http-metrics
interval: 10s
authorization:
type: Bearer
credentials:
name: metrics-reader-token
key: token
{{- end }}
Recording rules
The last object loads the recording rules. A recording rule stores the result of a query as a new series, so a dashboard or the autoscaler reads a cheap, named series and not a heavy expression that runs on every refresh. The chart has 34 of them, and the sections below show the queries behind them. Here are the values that switch the layer on and say where its namespace is:
# helm/llm-serving/values.yaml (observability)
# Prometheus recording rules + the EPP metrics-reader ServiceAccount in its own namespace.
observability:
enabled: true
namespace: monitoring
A rules file isn’t a Kubernetes object, so the chart wraps it in a PrometheusRule, the object that the Prometheus Operator loads rules from. The template reads the rules file from the chart’s files folder, parses it and puts its groups under spec.groups. The expressions are never typed inside the template, so the braces of PromQL label matchers never collide with the braces of Go templates.
# helm/llm-serving/templates/prometheusrule.yaml
{{- /*
Prometheus recording rules: the groups are copied verbatim from files/queries.rules.yml
(validated with promtool check rules + promtool test rules), so the expressions never pass
through Go-template brace escaping. The rule file is not a Kubernetes object, so the chart
wraps the same groups in a real PrometheusRule.
*/}}
{{- if .Values.observability.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: {{ include "llm-serving.modelName" . }}-rules
namespace: {{ .Release.Namespace }}
spec:
groups:
{{ toYaml ((.Files.Get "files/queries.rules.yml" | fromYaml).groups) | indent 2 }}
{{- end }}
Switch on the layer and check it
With Prometheus running and the three parts explained, we switch the observability layer on:
helm upgrade llm-serving ./helm/llm-serving --namespace llm -f terraform-values.yaml \
--set autoscaling.enabled=false --set observability.enabled=true
To check that both scrapes work, forward Prometheus’s port and ask it for one series from each target. The Targets page at http://localhost:9090/targets shows the same thing:
kubectl port-forward -n monitoring svc/kube-prometheus-stack-prometheus 9090:9090 &
curl -s http://localhost:9090/api/v1/query --data-urlencode 'query=vllm:num_requests_running'
curl -s http://localhost:9090/api/v1/query --data-urlencode 'query=llm_d_epp_ready_endpoints'
The first returns one series per vLLM pod, so the PodMonitor works. The second is a picker metric, so a value there means the token, the ClusterRole and the ServiceMonitor all work. Give Prometheus a scrape interval or two first. If the second still comes back empty, look at the picker’s target on the Targets page, where a 401 or 403 is the authentication explained under “Where the numbers come from” below.
The simulation
The simulation is the real gateway and the real picker with fake model servers behind them: no GPU, no vLLM and no model. Before a GPU is involved, we want to see that the request path does what section 1 says, and see it happen. So let’s run it on a laptop. The simulation/ folder in the examples has the steps, the fake model server and a traffic script. Following the steps gives you a local kind cluster running the real Envoy Gateway v1.9.3, Envoy AI Gateway v1.2.0 and llm-d router v1.0.0, with three fake model servers behind the route. The kind node needs Kubernetes 1.33 or newer, which the folder’s kind-config.yaml pins.
Each fake is a small Python server that imitates vLLM’s API. It holds every request for a fake prefill and decode, has four request slots and a small prefix cache, and exposes metrics under vLLM’s names. It takes the place of the Deployment from section 3 of part 4, with the same label and port, so the picker finds it the same way. The simulation is evidence about the gateway and the picker, not about vLLM, a GPU or Qwen3.8. The fake’s latencies and KV usage mean nothing, so don’t read a tokens per second or a time to first token out of it.
The fake also adds an x-served-by header that says which pod answered, which real vLLM doesn’t, and the traffic script counts with it. On a real cluster you read the pod from the picker’s per-pod counters, which we use below.
Before you run anything, here’s what the picker will do, on toy numbers. The picture is the picker’s scoring arithmetic and not a measurement. It has three pods and eight requests, some sharing a long system prompt, and for each request it shows the scores the picker would compute with the router’s default weights, using the formulas from section 1.
It shows the shape to expect. The shared prompt pulls requests onto the pod that holds it, load pushes them off again, and when the warm pod’s queue reaches 5 the filter removes it and the next request goes elsewhere. The queue, KV and cache numbers in the figure are toy values, as its caption says. The figure uses the router’s built-in weights, queue 2, KV cache 2 and prefix 3, so its pull toward the warm pod is stronger than what your run will show with our weights of 2, 3 and 1.
Now run the four experiments in simulation/ with traffic.py. It prints a table of how many requests each pod answered. A pod that answered nothing has no column, and every start of the script uses a prompt the pods have never seen. Each experiment has a pattern to look for:
- The same long prompt, one request at a time (
shared). Thirty requests in a row, all with the same 3,000 character system prompt and only the last line different. The picker remembers which pod it sent a prompt prefix to, and the prefix scorer rewards that pod. Look for one pod answering all 30. Which pod it is doesn’t matter, because the first pick is arbitrary. - A different prompt every time, one at a time (
unique). Thirty requests, each with its own long prompt. There’s no prefix to follow, so the prefix scorer has no vote, and the queue and KV scorers see three equally idle pods. Look for all three pods answering and none of them taking much more than half. The split isn’t exactly even. The script waits 100 milliseconds between requests, and--pause 0removes the wait. - Twenty different prompts released at the same instant (
burstandburst-busy). The first sends them to an idle pool, and the second sends the same twenty while two background senders keep two pods busy. Requests released together all see the same load numbers, so they land where those numbers point. On an idle pool every pod looks alike and the picks take turns. In the busy run, look for the burst to land on the pod that looked free and to skip the two busy ones. Run each more than once, because the split changes from run to run, and the busy burst changes most. - Twelve senders on the shared prompt for 30 seconds (
shared sustained). Thesharedrun goes first in the same start, so one pod already holds the prompt. Look for the first twelve requests to go to the warm pod, then its queue to grow, the other pods to take requests and learn the prefix, and within a second or two all three to share the load. The script prints the first six seconds in a second table.
The picker also counts what it did, so compare three numbers that should agree: what the script sent, what each fake pod served, and the picker’s own llm_d_epp_scheduler_attempts_total per pod. The picker’s metrics need the token from the metrics reader above, and the folder shows how to read them. It can also log the score it gave every pod for every request, and picks.py prints them, which turns the burst from a story into evidence.
Here’s what I saw on my laptop. The folder installs the router with the values from section 1 (queue 2, KV cache 3, prefix 1), and this is one run of python3 traffic.py straight after resetting the counters. The pods are named after the column they got in the script’s table, so which pod is A differs from run to run.
| What I sent | Requests | Pod A | Pod B | Pod C |
|---|---|---|---|---|
| The same long system prompt, one request at a time | 30 | 0 | 30 | 0 |
| A different prompt every time, one at a time | 30 | 6 | 10 | 14 |
| 20 different prompts released at the same instant, idle pool | 20 | 6 | 6 | 8 |
| The same burst while two background senders keep two pods busy | 20 | 11 | 9 | 0 |
| 12 senders on the shared prompt for 30 seconds | 597 | 198 | 203 | 196 |
The exact split changes from run to run, so I repeated each experiment. This is what the repeats gave:
| What I sent | Runs | What I saw |
|---|---|---|
| The same long system prompt | 4 | All 30 on one pod every time, not always the same pod |
| A different prompt every time, 100 ms apart | 14 | The busiest pod answered 11 to 15 of the 30 and the quietest 5 to 9 |
The same, with --pause 0 | 5 | The least used pod answered 3 to 7 of the 30 |
| A burst of 20 on an idle pool | 11 | Always spread over all three pods: the busiest took 7 to 10, the quietest 3 to 6 |
| A burst of 20 with two pods busy | 9 | All 20 on one pod in 4 runs, on two pods in 4 runs, on all three in 1 |
| 12 senders on the shared prompt | 3 | Between 196 and 227 per pod |
The first row is the textbook case: with nothing else going on, a repeated prompt sticks to the pod that already has it, 30 out of 30. The last row is the correction. Under concurrent load it doesn’t stay pinned. In each of my three runs the warm pod took the first 12 requests, and after that the other pods took requests, learned the prefix, and the three ended within a few percent of each other. “A shared prefix concentrates traffic on one pod” is true for one request at a time and a poor description of a loaded system, where the prefix replicates and the pool balances.
The burst rows are the unexpected part. On an idle pool the twenty requests spread over all three pods, because every pod looks the same to the picker, and pods with equal scores take turns. With two pods busy they don’t spread. The picker scores each request from the load numbers it last scraped, every 50 milliseconds by default, and it doesn’t count the requests it has just sent. Requests inside one scrape window see the same snapshot and make the same choice. Here are three of the twenty lines that picks.py printed for a burst that went entirely to one pod. They fall within 32 milliseconds, and the numbers behind them were 13 to 46 milliseconds old and never changed during the burst. The pod with a request running scores 4.70 and the idle one 4.94, so the idle one wins every time:
12:27:48.722 8j692 score 4.94 queue 0 running 0 age 13 ms vjjdm score 4.70 queue 0 running 1 age 14 ms w4ktp score 4.70 queue 0 running 1 age 14 ms
12:27:48.728 8j692 score 4.94 queue 0 running 0 age 19 ms vjjdm score 4.70 queue 0 running 1 age 20 ms w4ktp score 4.70 queue 0 running 1 age 20 ms
12:27:48.754 8j692 score 4.94 queue 0 running 0 age 45 ms vjjdm score 4.70 queue 0 running 1 age 46 ms w4ktp score 4.70 queue 0 running 1 age 46 ms
The same old numbers show up one request at a time: with --pause 0 the next request arrives while the picker still thinks the last pod is busy, so it avoids that pod, and the requests go back and forth between two. If you serve agents that fan out in parallel, a burst is your normal traffic, so test your scheduling profile against one.
The bookkeeping adds up. In the run of the first table the script sent 725 requests, including the background ones. The fake pods served 230, 265 and 230 of them, and the picker’s llm_d_epp_scheduler_attempts_total counted the same 230, 265 and 230.
Where the numbers come from
Three places in this stack expose metrics, and they answer different questions.
The model servers expose vLLM’s own metrics on their serving port, /metrics on 8000, describing what happens inside an engine: queues, the KV cache, token counts and latencies. The endpoint picker exposes its own on port 9090, describing what happens between the gateway and the pods: how many pods it sees, the average queue and KV usage across them, and how long it took to choose. The PodMonitor and the ServiceMonitor from the observability layer scrape these two. The AI Gateway’s sidecar exposes a third set on port 1064, named aigw-admin, with the OpenAI-style token and latency histograms the gateway sees. The chart has no monitor for it, and the port isn’t in the Envoy pod’s Prometheus annotations either, which point only at Envoy. If you want those histograms, add a PodMonitor for the Envoy pods in ai-gateway that names the port aigw-admin. Nothing we do in this post depends on it.
The picker’s endpoint is authenticated by default, and its three answers tell you where you are. Without a token it answers 401: it doesn’t know who you are. With the token of an account that has no permission, like the default service account’s, it answers 403: it knows you and says no. It answers 200 only for a service account allowed get on the non-resource URL /metrics. The router chart doesn’t create that permission for your scraper, and the metrics reader above is the fix.
The rest of what comes out of those ports is long, so here’s the short version for a dashboard, with the metric names of vLLM v0.32.0.
| Metric | What it tells you |
|---|---|
vllm:num_requests_waiting | The queue. Zero when the engine keeps up, and the first thing to climb when it doesn’t |
vllm:num_requests_running | Requests in the current batch |
vllm:kv_cache_usage_perc | KV cache usage as a fraction from 0 to 1, despite the name |
vllm:prefix_cache_hits_total and vllm:prefix_cache_queries_total | Prefix cache hits and lookups, in tokens, not requests |
vllm:time_to_first_token_seconds | Arrival to first token, so queue plus prefill |
vllm:inter_token_latency_seconds | Time between streamed tokens |
vllm:e2e_request_latency_seconds | Arrival to finish |
vllm:request_success_total{finished_reason} | Finished requests, split into stop, length, abort and error |
vllm:num_preemptions_total | Requests evicted from the batch and recomputed: KV pressure made visible |
vllm:prompt_tokens_total, vllm:generation_tokens_total | Prefill and decode throughput. Prompt tokens include the cached ones |
vllm:spec_decode_num_accepted_tokens_total over vllm:spec_decode_num_draft_tokens_total | MTP acceptance rate, present only when speculative decoding is on |
llm_d_epp_average_queue_size, llm_d_epp_average_kv_cache_utilization | The picker’s pool averages, per pod, published every 5 seconds |
llm_d_epp_ready_endpoints | Pods the picker has fresh metrics for, which is not the same as Kubernetes Ready |
llm_d_epp_scheduler_attempts_total | Picks, split by the pod chosen: the traffic split |
llm_d_epp_scheduler_e2e_duration_seconds | How long the picker took to choose. In my simulation the p95 was 0.17 milliseconds |
A few of those need a warning. llm_d_epp_ready_endpoints counts pods whose metrics are fresh, and when it falls to zero the two average gauges don’t drop: they freeze at their last value. A dashboard that only plots the averages looks calm while nothing is serving. The picker’s time to first token is the whole response time unless the request was streamed.
The gateway’s token histograms count only what the gateway itself saw, and a 503 that the picker generates when no pod is ready never reaches them. In my simulation I scaled the pool to zero and the picker counted three errors while the gateway’s error series stayed unchanged. So for the error rate at the edge, use llm_d_epp_request_error_total or Envoy’s own response-class counters.
And a Prometheus that scrapes every ten seconds can’t see a spike that lasts a second. In my simulation I sent twelve simultaneous requests to one pod with four slots, and the most Prometheus ever recorded waiting on any pod was two. The picker polls at 50 milliseconds. Your dashboard doesn’t.
Queries for a dashboard
Here are the queries to start with. They live in the chart’s Prometheus recording rules, so each expression can be pasted into a Grafana panel or into a KEDA trigger, and swapping [5m] for [$__rate_interval] makes them follow the panel’s zoom.
# prefix cache hit ratio: sum first, then divide (an average of per-pod ratios would be wrong)
sum by (model_name) (rate(vllm:prefix_cache_hits_total[5m]))
/ sum by (model_name) (rate(vllm:prefix_cache_queries_total[5m]))
# time to first token, p95 across all pods
histogram_quantile(0.95, sum by (le, model_name) (rate(vllm:time_to_first_token_seconds_bucket[5m])))
# queue: requests waiting, summed over pods
sum by (model_name) (vllm:num_requests_waiting)
# the hottest pod's KV cache usage, and the average for comparison
max by (model_name) (vllm:kv_cache_usage_perc)
avg by (model_name) (vllm:kv_cache_usage_perc)
# requests evicted from the batch per second
sum by (model_name) (rate(vllm:num_preemptions_total[5m]))
# generated tokens per second: the throughput that is actually yours
sum by (model_name) (rate(vllm:generation_tokens_total[5m]))
# share of finished requests that ended in an error
sum by (model_name) (rate(vllm:request_success_total{finished_reason="error"}[5m]))
/ sum by (model_name) (rate(vllm:request_success_total[5m]))
# the picker's view of the pool, one series: exactly what a KEDA trigger needs
max(llm_d_epp_average_queue_size{name="qwen38-27b-nvfp4"})
The hit ratio is the one people get wrong, so the arithmetic is in a figure. Take one pod with a 70 percent hit rate on 1,500 tokens and another with 50 percent on 3,000. The pool’s ratio is 2,550 over 4,500, which is 56.7 percent, and the mean of the two ratios, 60 percent, is wrong because it ignores that one pod saw twice the traffic. Quantiles have a similar problem: histogram_quantile interpolates inside a bucket, so the answer is only as precise as the bucket edges, and vLLM’s default request-phase buckets start at 0.3 seconds. A latency objective below 300 milliseconds needs custom buckets.
The rules file has 34 rules: the 30 for dashboards and alerts, and four early-warning rules that the autoscaler uses in section 3. Each rule has a unit test with promtool, using synthetic series with the real metric names and labels, and each test asserts an expected value, including the 56.7 percent. The rules are in k8s/queries.rules.yml and the tests in k8s/queries.test.yml, and the chart ships the same rules as the PrometheusRule from the observability layer, so the queries behind the dashboards and the autoscaler are versioned with the thing they measure. When you point a dashboard at a new deployment, check that the selector matches a series: an empty panel and a healthy system look the same until you do.
Now we can see what the request path does and what it leaves behind in metrics. The next section uses what these queries return to decide when to start more pods.
3. Autoscaling with KEDA
Everything so far has been about getting one pod to serve well. Now the setup has to grow when traffic does, and the chain from sections 2 to 4 of part 4 runs again for every new pod. How long that takes decides the whole design, so we’ll start there. Then we’ll pick signals that move before users feel anything, see how KEDA sits on top of the HPA, write the ScaledObject and its template, and switch it on.
How long a new pod takes
A new vLLM replica takes minutes to become useful. I read the numbers below off a production pod’s startup log (vLLM v0.28.0, weights on local disk). From the first log line to the API server listening, my pod took 407 seconds, a little under 7 minutes.
| Phase | Seconds |
|---|---|
| Before loading starts | 45 |
| Loading the weights | 198 |
| Engine initialization | 147 |
| API server and multi-modal warmup | 17 |
| Total | 407 |
Engine initialization is where vLLM profiles memory, runs torch.compile (cold, about 57 seconds for the model and its speculative drafter together), sizes the KV cache and captures CUDA graphs (10 seconds).
That number is the pod alone. The log can’t show what happens before its first line: Karpenter launching a node, the image pull and the container start. It doesn’t cover streaming the weights from S3 either, which is what our Deployment does, and it leaves out the readiness probe (it checks every 10 seconds) and the router noticing the new endpoint. A fresh pod is also slow for its first requests: about two minutes after my server started, it compiled Triton kernels and logged latency spike warnings.
The autoscaler adds its own delays. Prometheus scrapes every 10 seconds, the HPA syncs every 15 seconds, and our scale-up window is 120 seconds. So 407 + 120 + 15 + 10 = 552 seconds is the least that passes between a metric crossing its threshold and a pod that serves, before any node or image work. A trigger that waits for users to feel the problem is always late. We want signals that move first.
KEDA and the HPA
The Horizontal Pod Autoscaler is the built-in controller that changes a Deployment’s replica count from a metric. KEDA doesn’t replace it, it drives one. It creates and manages an HPA for our Deployment, serves our Prometheus queries to it as external metrics, and takes over the one step the HPA can’t do: the move between zero and one replica. So there are two controllers and one ladder of replica counts, and each owns a rung.
KEDA owns 0 to 1, polling every 30 seconds (pollingInterval). The HPA owns 1 to N: it syncs every 15 seconds, takes the maximum of whatever its triggers ask for, and applies the behavior we configure.
Signals that move early
CPU and memory are poor signals. The vLLM process spends its life waiting on the GPU, so its CPU is flat at saturation, and a GPU that reads 100 percent busy doesn’t say whether it’s busy and healthy or busy and drowning. The good signals come from vLLM itself, and section 2 gave us the metrics for them: how full the KV cache is, how many requests are running and how many are waiting. The obvious autoscaler scales on a KV level of 0.7 and a pool-average queue of 2. Both are late, as we’ll see, so we use five triggers:
| Trigger | What it watches | Why it leads or lags | Metric type |
|---|---|---|---|
kv-forecast | Where the hottest pod’s KV cache will be in 10 minutes | Leads: it reads the trend, so a replica starts before the cache is full | Value |
worst-pod-kv-cache | The hottest pod’s KV cache right now | Backstop: a level and not a rate, so it acts late | Value |
batch-saturation | Running requests across all pods | Leads: a half-full batch still has room, and queueing starts when it’s full | AverageValue |
queue-sustained | A capacity queue on the busiest pod that didn’t empty for 3 minutes | Early warning: a waiting request is the first thing a user feels, filtered so one slow prompt doesn’t count | Value |
ttft-p95 | p95 time to first token over 5 minutes | Lags: users are already slowed, so it’s the safety net | Value |
kv-forecast. The first signal asks where the hottest pod’s KV cache will be in 10 minutes. Prometheus fits a straight line to the last 15 minutes of the worst pod’s usage and reads it 600 seconds ahead. The target stays 0.7, so a replica starts early enough to be Ready when the cache would have crossed it.
The fit runs on the maximum across pods, so a new pod with an empty cache, which climbs fast, can’t fake a trend. And 15 minutes is the first window I tried whose forecast stayed under 0.7 on my pod over 47 hours: the 2, 5 and 10 minute windows peaked at 2.08, 1.09 and 0.70, while the real KV usage never passed 0.457. Until the series has 10 minutes of history the query returns nothing, because a young series gives wild slopes (my second sample gave 3.24).
worst-pod-kv-cache. The level trigger stays as a backstop: the hottest pod’s KV usage right now, against 0.7. It covers what a straight line misses: a cache that is high but falling, and the first 10 minutes of a series, where the forecast stays silent on purpose. On its own it would be late. The HPA ignores ratios within 10 percent, so 0.7 acts above 0.77, and the largest 10-minute rise on my pod was 32.5 points of KV usage. Lowering the line isn’t the fix, because the threshold is also the steady-state target and a lower one holds more GPUs all day. We add the rate instead.
batch-saturation. The second signal counts the requests in the running batch across all pods. A pod runs at most 64 (--max-num-seqs, section 3 of part 4), and a full batch is where new requests start to queue, so we aim for half full: 32 per pod, which leaves room for traffic to double while a replica starts. We need it next to the KV signal because the two limits bind at different request sizes. On my pod a median running request held about 2 percent of the cache, so the cache fills at about 51 running requests, and at 33 for the heaviest tenth. Only the shortest requests reach the cap of 64 first, so on that traffic the cache is the likelier limit.
queue-sustained. A waiting request is the first thing a user feels, but one request waiting behind a long prompt is normal. On my pod a request was waiting in about 2 percent of the samples, never for more than 30 seconds at a stretch, and no 3-minute window in 47 hours had one at every point. So we count only a queue that didn’t empty for 3 minutes on the busiest pod, and only requests waiting for capacity (vLLM labels the rest deferred, such as a KV fetch in flight from the tiers of section 4).
The target is an empty queue, so the threshold is 0.8, just under 1. At 1 a sustained queue of 1 gives a ratio of exactly 1.0, inside the tolerance, and nothing happens. At 0.8 it gives 1.25, and 2 replicas become ceil(2.5) = 3. We read it from vLLM and not from the router’s pool average, which hides a hot pod (queues of 6, 0 and 0 average 2, and a trigger at 2 does nothing), has no per-pod series to take a max of, and adds a hop.
ttft-p95. The last trigger is the safety net: p95 time to first token over 5 minutes, against 10 seconds. It reacts after users are slowed, and a burst of long prompts can raise it with no capacity problem, so keep the threshold high. About twice the p95 of a healthy hour on your traffic is a good start, and 10 seconds is a placeholder. Below 0.2 first tokens per second (60 in 5 minutes) the p95 is decided by the slowest three requests, so the query returns nothing there.
Treat 32, 0.8 and 10 as starting values. My pod peaked at 30 running requests of 64 and 45.7 percent KV, so it’s a good record of the noise the triggers have to ignore. I replayed its 47 hours through the four new rules with promtool, and the forecast peaked at 0.652, the sustained queue stayed at 0 and the running total peaked at 30: nothing would have fired. Where saturation sits is for your own load test. Find the batch size where p95 inter-token latency doubles and put the batch threshold at 60 to 70 percent of it.
The four new queries are recording rules in the rules file from section 2, in their own group, llm-keda-leading. The level trigger is already in that file as llm:keda:worst_pod_kv_cache_utilization.
- record: llm:keda:worst_pod_kv_cache_forecast
expr: |
clamp(predict_linear(max(vllm:kv_cache_usage_perc{model_name="qwen38-27b-nvfp4"})[15m:30s], 600), 0, 1)
and
count_over_time(max(vllm:kv_cache_usage_perc{model_name="qwen38-27b-nvfp4"})[15m:30s]) >= 20
- record: llm:keda:vllm_running_total
expr: sum(vllm:num_requests_running{model_name="qwen38-27b-nvfp4"})
- record: llm:keda:worst_pod_queue_sustained
expr: min_over_time(max(vllm:num_requests_waiting_by_reason{model_name="qwen38-27b-nvfp4",reason="capacity"})[3m:15s])
- record: llm:keda:ttft_p95_seconds
expr: |
histogram_quantile(0.95, sum by (le) (rate(vllm:time_to_first_token_seconds_bucket{model_name="qwen38-27b-nvfp4"}[5m])))
and
sum(rate(vllm:time_to_first_token_seconds_count{model_name="qwen38-27b-nvfp4"}[5m])) > 0.2
The ScaledObject
The ScaledObject is KEDA’s own object. It names the Deployment to scale, the replica bounds and the triggers that decide the count. Each trigger’s query below is the same text as the expr of its rule, so a dashboard panel on the recorded series shows exactly what KEDA reads. Here’s the raw YAML, validated against the KEDA v2.21.0 schema:
# k8s/scaledobject.yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: qwen38-27b-nvfp4
namespace: llm
spec:
scaleTargetRef:
name: qwen38-27b-nvfp4 # the vLLM Deployment
minReplicaCount: 1 # a floor: scale-out is slow (node, image, weights), so never start from zero
maxReplicaCount: 8
fallback:
# if a Prometheus trigger fails 3 polls in a row, hold 2 replicas instead of trusting a broken metric
failureThreshold: 3
replicas: 2
advanced:
horizontalPodAutoscalerConfig:
behavior:
scaleUp:
stabilizationWindowSeconds: 120 # a trigger has to keep asking for more for 2 minutes, so one noisy sample cannot start a GPU node
policies:
- type: Pods
value: 2 # at most 2 new replicas a minute: each one is slow to become useful
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 1800 # act on the highest count the triggers asked for in the last 30 minutes
policies:
- type: Pods
value: 1 # give back one replica every 10 minutes at most: a GPU node we release may not come back
periodSeconds: 600
triggers:
# where the hottest pod's KV cache will be in 10 minutes (0 to 1), from a straight line fitted to the last 15 minutes.
# A new replica needs several minutes to become Ready, so this asks for it before the cache is full. The last line
# holds the answer back until there are 10 minutes of history. A max is not additive, so the metric type is Value:
# desired = ceil(ready replicas x value / threshold)
- type: prometheus
name: kv-forecast
metricType: Value
metadata:
serverAddress: http://kube-prometheus-stack-prometheus.monitoring.svc:9090
query: >-
clamp(predict_linear(max(vllm:kv_cache_usage_perc{model_name="qwen38-27b-nvfp4"})[15m:30s], 600), 0, 1)
and
count_over_time(max(vllm:kv_cache_usage_perc{model_name="qwen38-27b-nvfp4"})[15m:30s]) >= 20
threshold: "0.7"
# the hottest pod's KV cache utilization right now (0 to 1); an average would hide one saturated pod.
# This is the level trigger that backs up the forecast
- type: prometheus
name: worst-pod-kv-cache
metricType: Value
metadata:
serverAddress: http://kube-prometheus-stack-prometheus.monitoring.svc:9090
query: max(vllm:kv_cache_usage_perc{model_name="qwen38-27b-nvfp4"})
threshold: "0.7"
# requests in the running batch, summed over pods. --max-num-seqs is 64, so 32 per pod is a half-full batch,
# which leaves room for traffic to double while a new replica starts. A sum is additive, so the metric type
# is AverageValue: desired = ceil(total / threshold)
- type: prometheus
name: batch-saturation
metricType: AverageValue
metadata:
serverAddress: http://kube-prometheus-stack-prometheus.monitoring.svc:9090
query: sum(vllm:num_requests_running{model_name="qwen38-27b-nvfp4"})
threshold: "32"
# the lowest queue the busiest pod had in the last 3 minutes, counting only requests that wait for capacity.
# It is above 0 only when the queue never emptied, so a single request waiting behind a long prompt is ignored.
# The goal is an empty queue, so the threshold sits just under 1 and one request that never leaves is already over it
- type: prometheus
name: queue-sustained
metricType: Value
metadata:
serverAddress: http://kube-prometheus-stack-prometheus.monitoring.svc:9090
query: min_over_time(max(vllm:num_requests_waiting_by_reason{model_name="qwen38-27b-nvfp4",reason="capacity"})[3m:15s])
threshold: "0.8"
# the safety net: p95 time to first token over 5 minutes, in seconds. It reacts last, after users are already slowed.
# The last line ignores it below 0.2 first tokens per second, where one long prompt would decide the p95.
# 10 is a starting point: set it to about twice the p95 of a healthy hour on your traffic
- type: prometheus
name: ttft-p95
metricType: Value
metadata:
serverAddress: http://kube-prometheus-stack-prometheus.monitoring.svc:9090
query: >-
histogram_quantile(0.95, sum by (le) (rate(vllm:time_to_first_token_seconds_bucket{model_name="qwen38-27b-nvfp4"}[5m])))
and
sum(rate(vllm:time_to_first_token_seconds_count{model_name="qwen38-27b-nvfp4"}[5m])) > 0.2
threshold: "10"
The triggers are the five we just went through. Three more settings matter.
minReplicaCount: 1. Scaling to zero is tempting for expensive GPUs, but a cold start is a pending pod, a new node from Karpenter, an image pull, twenty gigabytes of weights, a torch compile, a CUDA graph capture, and only then a readiness probe. That’s the 407 seconds from earlier plus the node and the image. There’s a second problem: our signals are emitted by the pods themselves, so at zero replicas there’s no series, KEDA reads the empty result as 0, and nothing tells it to scale up. Waking from zero would need a signal from outside the pods, such as a gateway-side queue. So we keep a floor of one.
The 15 and 30 seconds. We don’t set pollingInterval, so KEDA’s 30 seconds applies, with one change in KEDA 2.21. When minReplicaCount is above zero and you aren’t using idleReplicaCount, useCachedMetrics or scalingModifiers, KEDA stops polling on its own schedule and reuses the values from the HPA’s queries. That’s our case, so our metrics effectively refresh every 15 seconds, not 30. Before the HPA’s first query, KEDA still queries the sources itself.
fallback. If Prometheus becomes unreachable, a broken query would freeze the scaler at whatever it last computed. After three failed polls in a row, fallback holds two replicas instead, a known-safe count.
Value or AverageValue, and one series
Two rules decide whether a trigger works at all, and the first is metricType. KEDA’s default is AverageValue, and the two types do different arithmetic. With AverageValue the HPA asks for the metric divided by the threshold, rounded up, and the replica count only enters through the 10 percent tolerance. That’s right for a total, like the requests running across all pods. With Value it asks for the number of Ready replicas times the metric over the threshold. That’s right for a number that isn’t a total: a utilization, a max, a latency.
The slide uses toy numbers: four replicas whose average queue is 3, against a threshold of 2. AverageValue gives ceil(3 / 2) = 2, so the autoscaler scales down while every pod has a queue. Value gives ceil(4 x 3 / 2) = 6, which is what we want.
Now our own numbers: two Ready replicas and the kv-forecast threshold of 0.7. The hottest pod is at 0.55 and has climbed 0.36 in 15 minutes, so the forecast is 0.55 + 0.24 = 0.79. The ratio is 0.79 / 0.7 = 1.129, above the HPA’s tolerance (it acts above 1.1, a forecast over 0.77), so it computes ceil(2 x 1.129) = ceil(2.26) = 3 and starts a third replica. The level trigger still reads 0.55, a ratio of 0.79, and asks for 2. On the same line it would cross 0.77 in 550 seconds, about 9 minutes later, which is roughly what the new pod needs. That’s the lead time we bought.
The HPA counts Ready pods, so while the third replica starts it still sees two, and the answer stays at 3 on every 15-second round instead of growing.
A gauge that never passes 1 also caps the ratio at 1 / 0.7 = 1.43. So the two KV triggers add about 43 percent a round (2 to 3, 3 to 5, 5 to 8), and the batch and queue triggers carry the big jumps. batch-saturation is our AverageValue case: 110 running requests over 3 replicas against 32 is a ratio of 1.146, outside the tolerance, so the HPA asks for ceil(110 / 32) = 4. At 100 the ratio is 1.04, inside it, and the count holds at 3 although ceil(100 / 32) is 4. And the forecast under AverageValue would be wrong: ceil(0.8 / 0.7) = 2 replicas in total, whatever the pool size.
The second rule is that every query must return exactly one series. KEDA’s Prometheus scaler fails the poll with returned multiple elements the moment it gets two, and two are easy to get by accident: two Prometheus replicas, or a bare selector that matches every pod. That’s why each query is wrapped in max(...), sum(...) or sum by (le) (...). The same scaler reads an empty result, or NaN, as 0, because ignoreNullValues defaults to true. We use that on purpose: the and in the forecast and TTFT queries returns nothing when its guard fails, KEDA reads 0, and the trigger asks for nothing.
Scaling in slowly
Scaling in is the risky direction. By default the HPA waits 300 seconds and may remove 100 percent of the replicas in one step, the wrong default for GPU pods. A replica we release takes its node with it, once the NodePool’s consolidateAfter: 30m from section 2 of part 4 has passed. AWS GPU capacity is scarce, so nothing promises we get a node back, and every cold start costs at least those 407 seconds plus the node.
So the behavior block changes three things. Scale-in gets a 30-minute stabilization window: the HPA acts on the highest count any trigger asked for in the last 30 minutes, so one calm half hour releases nothing, and a metrics hole that reads 0 needs 30 minutes to cost a replica. Scale-in also gets a policy of one pod every 10 minutes. Scale-up gets a 120-second window, which takes the lowest count asked for in the last 2 minutes, so one noisy sample can’t start a GPU node, and it adds at most two pods a minute because each is slow to become useful.
We don’t chase the minimum. A held replica costs GPU hours, while a released one we can’t replace costs the service. Flapping inside a day costs more than the idle hour.
Turning it into a template
Now let’s turn it into a template. The name qwen38-27b-nvfp4 appears in the object and in every query, and it comes from model.name like everywhere else in the chart. What we change per cluster are the bounds (minReplicas, maxReplicas), fallbackReplicas, the Prometheus address and the five thresholds: kvForecastThreshold, kvCacheThreshold, runningPerPod, queueThreshold and ttftSeconds. autoscaling.enabled switches the object off for a cluster that has its own autoscaler. The behavior block, the three failed polls and the query windows stay as they are in the template.
# helm/llm-serving/values.yaml (autoscaling)
# KEDA ScaledObject autoscaling of the vLLM Deployment: the per-cluster bounds and thresholds.
autoscaling:
enabled: true
# replica floor: scale-out is slow (node, image, weights), so never start from zero
minReplicas: 1
# replica ceiling
maxReplicas: 8
# replicas held when a Prometheus trigger fails 3 polls in a row
fallbackReplicas: 2
# Prometheus the triggers poll (the service the Prometheus stack creates in the observability namespace)
prometheusAddress: http://kube-prometheus-stack-prometheus.monitoring.svc:9090
# KV cache utilization (0 to 1) forecast 10 minutes ahead that pushes scale-out
kvForecastThreshold: "0.7"
# hottest pod's KV cache utilization (0 to 1) that pushes scale-out
kvCacheThreshold: "0.7"
# running requests per pod at which the batch is considered saturated; --max-num-seqs is 64, so 32 is half-full
runningPerPod: "32"
# lowest queue the busiest pod held over 3 minutes (just under 1) that pushes scale-out
queueThreshold: "0.8"
# p95 time to first token in seconds that pushes scale-out
ttftSeconds: "10"
# helm/llm-serving/templates/scaledobject.yaml
{{- if .Values.autoscaling.enabled }}
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: {{ include "llm-serving.modelName" . }}
namespace: {{ .Release.Namespace }}
spec:
scaleTargetRef:
name: {{ include "llm-serving.modelName" . }} # the vLLM Deployment
minReplicaCount: {{ .Values.autoscaling.minReplicas }} # a floor: scale-out is slow (node, image, weights), so never start from zero
maxReplicaCount: {{ .Values.autoscaling.maxReplicas }}
fallback:
# if a Prometheus trigger fails 3 polls in a row, hold 2 replicas instead of trusting a broken metric
failureThreshold: 3
replicas: {{ .Values.autoscaling.fallbackReplicas }}
advanced:
horizontalPodAutoscalerConfig:
behavior:
scaleUp:
stabilizationWindowSeconds: 120 # a trigger has to keep asking for more for 2 minutes, so one noisy sample cannot start a GPU node
policies:
- type: Pods
value: 2 # at most 2 new replicas a minute: each one is slow to become useful
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 1800 # act on the highest count the triggers asked for in the last 30 minutes
policies:
- type: Pods
value: 1 # give back one replica every 10 minutes at most: a GPU node we release may not come back
periodSeconds: 600
triggers:
# where the hottest pod's KV cache will be in 10 minutes (0 to 1), from a straight line fitted to the last 15 minutes.
# A new replica needs several minutes to become Ready, so this asks for it before the cache is full. The last line
# holds the answer back until there are 10 minutes of history. A max is not additive, so the metric type is Value:
# desired = ceil(ready replicas x value / threshold)
- type: prometheus
name: kv-forecast
metricType: Value
metadata:
serverAddress: {{ .Values.autoscaling.prometheusAddress }}
query: >-
clamp(predict_linear(max(vllm:kv_cache_usage_perc{model_name="{{ include "llm-serving.modelName" . }}"})[15m:30s], 600), 0, 1)
and
count_over_time(max(vllm:kv_cache_usage_perc{model_name="{{ include "llm-serving.modelName" . }}"})[15m:30s]) >= 20
threshold: "{{ .Values.autoscaling.kvForecastThreshold }}"
# the hottest pod's KV cache utilization right now (0 to 1); an average would hide one saturated pod.
# This is the level trigger that backs up the forecast
- type: prometheus
name: worst-pod-kv-cache
metricType: Value
metadata:
serverAddress: {{ .Values.autoscaling.prometheusAddress }}
query: max(vllm:kv_cache_usage_perc{model_name="{{ include "llm-serving.modelName" . }}"})
threshold: "{{ .Values.autoscaling.kvCacheThreshold }}"
# requests in the running batch, summed over pods. --max-num-seqs is 64, so 32 per pod is a half-full batch,
# which leaves room for traffic to double while a new replica starts. A sum is additive, so the metric type
# is AverageValue: desired = ceil(total / threshold)
- type: prometheus
name: batch-saturation
metricType: AverageValue
metadata:
serverAddress: {{ .Values.autoscaling.prometheusAddress }}
query: sum(vllm:num_requests_running{model_name="{{ include "llm-serving.modelName" . }}"})
threshold: "{{ .Values.autoscaling.runningPerPod }}"
# the lowest queue the busiest pod had in the last 3 minutes, counting only requests that wait for capacity.
# It is above 0 only when the queue never emptied, so a single request waiting behind a long prompt is ignored.
# The goal is an empty queue, so the threshold sits just under 1 and one request that never leaves is already over it
- type: prometheus
name: queue-sustained
metricType: Value
metadata:
serverAddress: {{ .Values.autoscaling.prometheusAddress }}
query: min_over_time(max(vllm:num_requests_waiting_by_reason{model_name="{{ include "llm-serving.modelName" . }}",reason="capacity"})[3m:15s])
threshold: "{{ .Values.autoscaling.queueThreshold }}"
# the safety net: p95 time to first token over 5 minutes, in seconds. It reacts last, after users are already slowed.
# The last line ignores it below 0.2 first tokens per second, where one long prompt would decide the p95.
# 10 is a starting point: set it to about twice the p95 of a healthy hour on your traffic
- type: prometheus
name: ttft-p95
metricType: Value
metadata:
serverAddress: {{ .Values.autoscaling.prometheusAddress }}
query: >-
histogram_quantile(0.95, sum by (le) (rate(vllm:time_to_first_token_seconds_bucket{model_name="{{ include "llm-serving.modelName" . }}"}[5m])))
and
sum(rate(vllm:time_to_first_token_seconds_count{model_name="{{ include "llm-serving.modelName" . }}"}[5m])) > 0.2
threshold: "{{ .Values.autoscaling.ttftSeconds }}"
{{- end }}
Installing KEDA and turning it on
KEDA is an ordinary CPU deployment, so it lands on the system node group from section 2 of part 4. Install it from its Helm chart:
helm repo add kedacore https://kedacore.github.io/charts
helm upgrade -i keda kedacore/keda --version 2.21.0 --namespace keda --create-namespace
The cluster doesn’t know what a ScaledObject is until KEDA’s custom resource definitions exist, which is why we installed our chart with autoscaling.enabled=false in section 4 of part 4. Now we turn it on. Routing and observability were switched on in section 2.
helm upgrade llm-serving ./helm/llm-serving --namespace llm -f terraform-values.yaml --set autoscaling.enabled=true
kubectl wait --timeout=2m -n llm scaledobject/qwen38-27b-nvfp4 --for=condition=Ready
The scale-out chain
When a trigger fires, the HPA adds a replica on its 15-second loop, the pod goes Pending, Karpenter launches a node, the image is pulled, the weights are streamed, the pod passes its readiness probe, and the router starts sending it traffic. The log gives us the pod’s own 407 seconds of that, and the forecast looks 600 seconds ahead to cover it. The node launch, the image pull, S3 instead of local disk, the probe and the router depend on your cluster, so measure them. If kube-state-metrics is running (the Prometheus stack installs it), the whole wait from created to Ready is one query:
kube_pod_status_ready_time{namespace="llm"} - on (namespace, pod, uid) kube_pod_created{namespace="llm"}
Take the p90 of it and add about 2.5 minutes for the autoscaler’s own delays. That’s the horizon for kv-forecast, the 600 in its query. It’s also the number to set maxReplicaCount and the scale-up policy from, and it explains why the floor beats chasing the queue. The autoscaler is what connects the two halves of this part: the signals come from the pods, the decision is the HPA’s, and the delay is everything sections 2 to 4 described.
Optional: a floor for a predictable day
If your traffic has a predictable daily shape, you can add a cron trigger to the triggers list as a floor. The HPA takes the maximum over all triggers, so inside the window the cron’s 2 sits under the demand-driven triggers, which can still push above it. Our manifest doesn’t have it.
# optional: hold at least 2 replicas on weekdays, 08:00 to 18:00 UTC
- type: cron
name: business-hours
metadata:
timezone: UTC
start: 0 8 * * 1-5
end: 0 18 * * 1-5
desiredReplicas: "2"
Think about what happens when the window ends. The count falls back to what the demand-driven triggers ask for, and every replica we give back takes its GPU node with it. GPU capacity on AWS is scarce, so a node we hand back at night may not be available again in the morning, and only a capacity reservation (section 1 of part 4) promises it. That’s also why scale-in here is slow: a 30-minute window and one pod every 10 minutes.
4. Tiered KV caching
The last lever makes every request cheaper by making fewer of them start from scratch. First we’ll see how vLLM spills KV blocks from the GPU to the CPU and to the local drive. Then we’ll size the tiers and turn them on in our Deployment and chart. Finally we’ll work out whether the disk tier pays for itself.
Recall the KV cache from part 2: the keys and values of every token already processed, kept so the next token doesn’t recompute them. Our KV pool is 59.26 GiB of GPU memory, as the startup log in section 3 of part 4 shows. When it’s full the engine evicts, and an evicted prefix that comes back has to be prefilled again. A g7e.2xlarge has two other places to keep it: 64 GiB of host RAM, and the 1.9 TB local NVMe drive that came with the instance (section 1 of part 4) and that so far we’ve only formatted. Tiered caching lets vLLM spill KV blocks from the GPU to the CPU and from the CPU to that drive, and bring them back when a prefix returns.
How the tiers work
The mental model most of us start with is that blocks move down a tier when the tier above is full, like a CPU cache. That’s wrong for this feature. In vLLM v0.32.0 blocks are written through. As each chunk of a prompt finishes, it’s copied from the GPU to the CPU tier and then cascaded to every secondary tier, immediately. Eviction afterwards only drops one copy: the GPU drops its block, the CPU tier drops its least recently used one, and the NVMe copy stays. When a later request has the same prefix, the lookup goes GPU first, then CPU, then disk. A hit is loaded back from the nearest tier that has it, and a disk hit is staged through CPU RAM, so it costs two hops.
Two things follow. The CPU tier is bounded and evicts. The disk tier isn’t: vLLM never deletes a file, so the directory grows until something else removes files, and at the write rate we’ll work out below that’s a matter of hours. And a chunk is not a token. The unit is a whole attention block, which for this model is 1,600 tokens (section 3 of part 4), so a prefix shorter than one chunk can never be served from an external tier.
Sizing the tiers
Each token costs 34 KiB of attention KV at fp8: the 16 full-attention layers plus the 17th one that the MTP head adds (section 3 of part 4). So a 16 GiB CPU tier holds about 493,000 tokens, and an 800 GiB budget on the NVMe holds about 24.7 million. That counts attention bytes only, so measure the real bytes per token on your own pods from the offload counters. Each cached prompt also stores a recurrent-state snapshot of about 159 MiB, which is three blocks of 53.125 MiB because the state is padded to the size of an attention block. That’s small against a 64,000-token prompt and large against a short one, which is one more reason tiering pays for long shared prefixes and not for short ones.
Why 16 GiB and not more? The CPU tier lives in /dev/shm, which counts against the pod’s memory limit. On a 64 GiB node the pod also needs the streamer’s buffer, which can hold the whole 20 GiB checkpoint while it loads, and about 10 GiB for the vLLM process itself. A 24 GiB tier would put us at the edge of what the node can allocate. Check your node’s allocatable memory before you choose.
The node side
The node needs the one setting we made in section 2 of part 4: instanceStorePolicy: RAID0 on the EC2NodeClass. It formats the NVMe and makes it the node’s ephemeral storage, so an emptyDir lands on it. Without it the emptyDir sits on the EBS volume and the exercise is pointless, so the pod fails closed: it requests ephemeral storage that only a node with instance store can offer, and stays Pending anywhere else.
The tiered Deployment
The tiered Deployment is the one from section 3 of part 4 with a few changes. Here’s the whole file, and the highlighted lines are the ones that changed from the Deployment of section 3 of part 4. The list after it explains each change.
# k8s/vllm-deployment-tiered.yaml (the highlighted lines are new or changed)
# Qwen3.8-27B NVFP4 on one RTX PRO 6000 (g7e.2xlarge), vLLM v0.32.0, weights streamed from S3.
apiVersion: v1
kind: ServiceAccount
metadata:
name: qwen38-27b-nvfp4
namespace: llm
# Nothing to annotate: the IAM role comes from an EKS Pod Identity association (terraform/pod_identity.tf).
# With IRSA instead, add the annotation eks.amazonaws.com/role-arn: <role arn> here.
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: qwen38-27b-nvfp4
namespace: llm
labels:
app: qwen38-27b-nvfp4
spec:
replicas: 1
strategy:
type: RollingUpdate
rollingUpdate:
# One pod owns one whole GPU node, so never surge: a surge pod would need a second GPU node.
maxSurge: 0
maxUnavailable: 1
selector:
matchLabels:
app: qwen38-27b-nvfp4
template:
metadata:
labels:
app: qwen38-27b-nvfp4
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8000"
prometheus.io/path: /metrics
spec:
serviceAccountName: qwen38-27b-nvfp4
nodeSelector:
karpenter.sh/nodepool: g7e # label Karpenter puts on every node of the pool
tolerations:
- key: nvidia.com/gpu # the taint set on the g7e NodePool
operator: Exists
effect: NoSchedule
terminationGracePeriodSeconds: 60
containers:
- name: vllm
image: vllm/vllm-openai:v0.32.0 # ENTRYPOINT is ["vllm","serve"], so args start with the model
imagePullPolicy: IfNotPresent
# the tiering spec can leave /dev/shm/vllm_offload_*.mmap behind after a non-graceful exit (vllm#57303)
command: ["/bin/sh", "-c", 'rm -f /dev/shm/vllm_offload_*.mmap; exec vllm serve "$@"', "vllm-serve"]
args:
# model = S3 prefix (trailing slash). Needs config.json, tokenizer files and *.safetensors in that prefix.
- s3://example-cluster-models-us-east-1/models/nvidia/Qwen3.8-27B-NVFP4/
- --served-model-name=qwen38-27b-nvfp4
- --host=0.0.0.0
- --port=8000
# weights: Run:ai Model Streamer (preinstalled in the official image)
- --load-format=runai_streamer
- '--model-loader-extra-config={"concurrency":16}'
# parallelism, context, memory
- --tensor-parallel-size=1
- --max-model-len=262144
- --kv-cache-dtype=fp8
- --gpu-memory-utilization=0.90
# scheduler
- --max-num-seqs=64
- --max-num-batched-tokens=8192
- --enable-prefix-caching
- --enable-chunked-prefill
- --async-scheduling
# speculative decoding with the checkpoint's own MTP head
- '--speculative-config={"method":"mtp","num_speculative_tokens":3}'
# KV tiers: 16 GiB of CPU RAM, then the local NVMe
- '--kv-transfer-config={"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"spec_name":"TieringOffloadingSpec","cpu_bytes_to_use":17179869184,"secondary_tiers":[{"type":"fs","root_dir":"/kv-nvme/kv-offload","n_read_threads":16,"n_write_threads":16}]}}'
# OpenAI API behaviour for a thinking + tool-calling model
- --reasoning-parser=qwen3
- --tool-call-parser=qwen3_coder
- --enable-auto-tool-choice
- --disable-access-log-for-endpoints=/health,/metrics,/v1/models
env:
- name: AWS_REGION # region of the models bucket
value: us-east-1
- name: HF_HUB_OFFLINE # weights and tokenizer come from S3, never the Hub
value: "1"
- name: VLLM_NO_USAGE_STATS
value: "1"
- name: DO_NOT_TRACK
value: "1"
ports:
- name: http
containerPort: 8000
resources:
requests:
cpu: "6"
memory: 52Gi
ephemeral-storage: 1050Gi # fails closed: a node without instance store cannot satisfy it
nvidia.com/gpu: "1"
limits:
# The streamer buffers up to RUNAI_STREAMER_MEMORY_LIMIT (default 40 GB) of the checkpoint in host RAM
# while loading: size the memory limit for checkpoint (about 21 GiB) + steady state (about 10 GiB) + headroom.
memory: 52Gi
ephemeral-storage: 1100Gi
nvidia.com/gpu: "1"
volumeMounts:
- name: dshm
mountPath: /dev/shm
- name: kv-nvme
mountPath: /kv-nvme
- name: cache
mountPath: /root/.cache # torch.compile, Triton, FlashInfer caches and the streamer's config-only dir
startupProbe: # 120 x 10 s = 20 min budget for stream + compile + CUDA graph capture
httpGet:
path: /health
port: http
periodSeconds: 10
failureThreshold: 120
readinessProbe:
httpGet:
path: /health
port: http
periodSeconds: 10
failureThreshold: 3
livenessProbe: # /health returns 503 once the engine process is dead
httpGet:
path: /health
port: http
periodSeconds: 30
failureThreshold: 3
- name: kv-guard # keeps the NVMe tier under a byte budget, oldest files first
image: busybox:1.37
command: ["/bin/sh", "/guard/guard.sh"]
env:
- name: ROOT
value: /kv-nvme/kv-offload
- name: BUDGET_GIB
value: "800"
resources:
requests: { cpu: 50m, memory: 32Mi, ephemeral-storage: 64Mi }
limits: { cpu: 200m, memory: 64Mi, ephemeral-storage: 64Mi }
volumeMounts:
- name: kv-nvme
mountPath: /kv-nvme
- name: guard
mountPath: /guard
readOnly: true
volumes:
- name: dshm
emptyDir:
medium: Memory
sizeLimit: 20Gi # the 16 GiB CPU tier plus slack
- name: cache
emptyDir:
sizeLimit: 20Gi
- name: kv-nvme
emptyDir:
sizeLimit: 1000Gi # lands on the NVMe because the EC2NodeClass sets instanceStorePolicy: RAID0
- name: guard
configMap:
name: kv-guard
- A wrapper around the start command. The container runs
rm -f /dev/shm/vllm_offload_*.mmap; exec vllm serve "$@". The tiering spec can leave its memory-mapped file behind after a hard crash (vllm#57303), and a container restart keeps a memory-backedemptyDir, so without thermthe next start would find it already full. - The connector argument. The CPU tier on its own is two flags,
--kv-offloading-size 16and--kv-offloading-backend native. The disk tier needs the full connector configuration, passed as one JSON argument,--kv-transfer-config. In it,cpu_bytes_to_useis the 16 GiB in bytes (17179869184), andsecondary_tiersholds onefstier at/kv-nvme/kv-offloadwith 16 read and 16 write threads. - Resources and volumes. Memory is 52Gi for request and limit, up from 40Gi and 48Gi. The ephemeral-storage request of 1050Gi and limit of 1100Gi are what make the pod fail closed. The
/dev/shmvolume grows from 8Gi to 20Gi (the 16 GiB tier plus slack), and a newemptyDir,kv-nvme, with a size limit of 1000Gi is mounted at/kv-nvmefor the disk tier. - A sidecar,
kv-guard. It does the thing vLLM won’t: it deletes the oldest block files once the NVMe directory passes a byte budget, here 800 GiB.
The guard sidecar
The sidecar’s script lives in a ConfigMap:
# k8s/kv-guard-configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: kv-guard
namespace: llm
data:
guard.sh: |
#!/bin/sh
# Keep $ROOT under $BUDGET_GIB GiB by deleting the oldest block files (FIFO by mtime).
# First in first out by modification time; a hot but old prefix is simply written again on its next miss.
# GUARD_ONCE=1 runs a single pass (used by the test).
BUDGET_KIB=${BUDGET_KIB:-$((BUDGET_GIB * 1024 * 1024))}
while :; do
used=$(du -sk "$ROOT" 2>/dev/null | cut -f1)
if [ "${used:-0}" -gt "$BUDGET_KIB" ]; then
find "$ROOT" -type f -name '*.bin' -exec stat -c '%Y %n' {} + \
| sort -n | head -n "${BATCH:-200}" | cut -d' ' -f2- | xargs -r rm -f
sleep 1
continue
fi
[ -n "$GUARD_ONCE" ] && exit 0
sleep "${INTERVAL:-30}"
done
It’s a loop that measures the directory and, while it’s over budget, deletes the oldest files by modification time. That’s first in first out. vLLM never rewrites a file that already exists, so the modification time is when a block was first written, and a hot prefix that gets deleted is simply written again on its next miss. In a container test with ten one-megabyte files and a budget of about five megabytes, I ran the script once and it removed the six oldest and left the newest four. The vLLM authors’ own NVMe benchmark, which we meet below, runs an external evictor against its volume the same way.
The budget is 800 GiB on a drive that shows about 1.9 TB because the node’s images and logs share it, and the kubelet starts evicting before the disk is full. If a write fails, whether the disk is full or the I/O errors out, vLLM logs block I/O failed and keeps serving, and a missing file on a load is a miss that gets recomputed. The failure that hurts is the kubelet evicting the whole pod when the emptyDir passes its 1100Gi limit. The guard prevents it, and its headroom is the 300 GiB between the budget and that limit, which at the write rate below fills in about two hours if the guard stops.
Turning it into a template
Now let’s turn it into a template. Tiering is a values change, not a second chart. tiering.enabled turns it on. tiering.cpuGiB sets the size of the CPU tier, tiering.nvmeGiB the size limit of the NVMe volume, and tiering.guardBudgetGiB the byte budget the guard enforces.
# helm/llm-serving/values.yaml (tiering)
# Optional KV tiering (CPU RAM, then local NVMe): kv-transfer-config, guard sidecar and its ConfigMap.
tiering:
enabled: false
cpuGiB: 16
# sizeLimit of the kv-nvme emptyDir, i.e. the NVMe tier's capacity in GiB
nvmeGiB: 1000
# byte budget the guard sidecar enforces on the NVMe tier (the BUDGET_GIB env var)
guardBudgetGiB: 800
In the Deployment template, everything the list above names sits behind a condition on tiering.enabled. With the value off we get the plain Deployment from section 3 of part 4, and with it on we get the tiered one. The 16 GiB in the connector argument is no longer written in bytes: the template multiplies tiering.cpuGiB by 1,073,741,824. Here are those parts of the template, one block per change: the start command, the connector argument, the memory and disk requests, and the sidecar with its volumes.
# helm/llm-serving/templates/deployment.yaml (lines 46 to 49)
{{- if .Values.tiering.enabled }}
# the tiering spec can leave /dev/shm/vllm_offload_*.mmap behind after a non-graceful exit (vllm#57303)
command: ["/bin/sh", "-c", 'rm -f /dev/shm/vllm_offload_*.mmap; exec vllm serve "$@"', "vllm-serve"]
{{- end }}
# helm/llm-serving/templates/deployment.yaml (lines 72 to 75)
{{- if .Values.tiering.enabled }}
# KV tiers: {{ .Values.tiering.cpuGiB }} GiB of CPU RAM, then the local NVMe
- '--kv-transfer-config={"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"spec_name":"TieringOffloadingSpec","cpu_bytes_to_use":{{ mul .Values.tiering.cpuGiB 1073741824 }},"secondary_tiers":[{"type":"fs","root_dir":"/kv-nvme/kv-offload","n_read_threads":16,"n_write_threads":16}]}}'
{{- end }}
# helm/llm-serving/templates/deployment.yaml (lines 96 to 112)
- name: POD_IP # expanded into the --kv-events-config topic by Kubernetes
valueFrom:
fieldRef:
fieldPath: status.podIP
{{- end }}
ports:
- name: http
containerPort: 8000
{{- if .Values.vllm.kvEvents.enabled }}
- name: kv-events
containerPort: {{ .Values.vllm.kvEvents.zmqPort }}
- name: kv-replay
containerPort: {{ .Values.vllm.kvEvents.replayPort }}
{{- end }}
resources:
requests:
cpu: "6"
# helm/llm-serving/templates/deployment.yaml (lines 140 to 178)
httpGet:
path: /health
port: http
periodSeconds: 10
failureThreshold: 120
readinessProbe:
httpGet:
path: /health
port: http
periodSeconds: 10
failureThreshold: 3
livenessProbe: # /health returns 503 once the engine process is dead
httpGet:
path: /health
port: http
periodSeconds: 30
failureThreshold: 3
{{- if .Values.tiering.enabled }}
- name: kv-guard # keeps the NVMe tier under a byte budget, oldest files first
image: busybox:1.37
command: ["/bin/sh", "/guard/guard.sh"]
env:
- name: ROOT
value: /kv-nvme/kv-offload
- name: BUDGET_GIB
value: "{{ .Values.tiering.guardBudgetGiB }}"
resources:
requests: { cpu: 50m, memory: 32Mi, ephemeral-storage: 64Mi }
limits: { cpu: 200m, memory: 64Mi, ephemeral-storage: 64Mi }
volumeMounts:
- name: kv-nvme
mountPath: /kv-nvme
- name: guard
mountPath: /guard
readOnly: true
{{- end }}
volumes:
- name: dshm
emptyDir:
The guard script is its own template, rendered only when tiering is on:
# helm/llm-serving/templates/kv-guard-configmap.yaml
{{- if .Values.tiering.enabled }}
apiVersion: v1
kind: ConfigMap
metadata:
name: kv-guard
namespace: {{ .Release.Namespace }}
data:
guard.sh: |
#!/bin/sh
# Keep $ROOT under $BUDGET_GIB GiB by deleting the oldest block files (FIFO by mtime).
# First in first out by modification time; a hot but old prefix is simply written again on its next miss.
# GUARD_ONCE=1 runs a single pass (used by the test).
BUDGET_KIB=${BUDGET_KIB:-$((BUDGET_GIB * 1024 * 1024))}
while :; do
used=$(du -sk "$ROOT" 2>/dev/null | cut -f1)
if [ "${used:-0}" -gt "$BUDGET_KIB" ]; then
find "$ROOT" -type f -name '*.bin' -exec stat -c '%Y %n' {} + \
| sort -n | head -n "${BATCH:-200}" | cut -d' ' -f2- | xargs -r rm -f
sleep 1
continue
fi
[ -n "$GUARD_ONCE" ] && exit 0
sleep "${INTERVAL:-30}"
done
{{- end }}
If your GPU nodes were created without instanceStorePolicy: RAID0, roll them first. Then switching tiering on is one upgrade of the release we already have, with the same values file and one extra flag:
helm upgrade llm-serving ./helm/llm-serving \
--namespace llm \
-f terraform-values.yaml \
--set tiering.enabled=true
Watching the tiers
A tier you can’t see is a tier you can’t trust, and vLLM v0.32.0 exposes what you need:
vllm:prompt_tokens_cached_by_source_totalsplits the cached tokens by the tier that supplied them, with asourcelabel such asdevice,hostordisk. It exists only from v0.32.0.vllm:external_prefix_cache_hits_totalovervllm:external_prefix_cache_queries_totalis the hit ratio of the CPU and disk tiers together.- The
vllm:kv_offload_tiering_*series break it down per tier, labelled0:primaryfor the CPU and1:fsfor the disk.
Run it as a canary before you trust it. If the external hit counter never rises, either your prefixes are shorter than a chunk, or you’re on a version where hybrid models with speculative decoding store blocks and never serve them. That bug is in v0.28.0 and v0.29.0 and was fixed in v0.30.0, so the v0.32.0 image we deploy has the fix.
Is it worth it?
The tiers cost a sidecar, a ConfigMap and a large ephemeral-storage request, so let’s see what they buy. I looked for someone who had measured this tier on a model like ours. The vLLM authors have, and their results and the arithmetic for our node both say to keep the disk tier. Their hardware isn’t a g7e, so we take the shape of the effect from them and the size from my pod’s numbers.
The CPU tier alone can’t pay on this node. vLLM’s usage guide says that in a CPU-only setup a tier smaller than the GPU pool just mirrors what the GPU already holds and adds no hit rate. Ours is 16 GiB against a 59.26 GiB pool, and a 64 GiB node can’t hold a bigger one. It also remembers for less time: at my pod’s average of about 1,350 computed prompt tokens a second and 34 KiB each, the GPU pool turns over in about 20 minutes and the CPU tier in about 6 (derived). So dropping only the disk would leave tiering that can’t raise the hit rate. The choice is CPU plus disk, or no tiering. On a g7e.4xlarge, with 128 GiB of RAM, a CPU tier can outgrow the pool and pay on its own.
The disk is what adds reach. At the same rate the 800 GiB budget turns over in about 5 hours (derived). My pod’s GPU prefix-cache hit rate has a median of 48.7 percent over the 46.7 hours in its log, so this traffic reuses prefixes heavily inside those 20 minutes. The disk pays for the ones that come back later, and only a running tier can show how many that is, which is what the check at the end is for.
Loading a block has to beat recomputing it. One block is 1,600 tokens and 53.125 MiB, so the disk has to read faster than 34 KiB per token times the GPU’s prefill speed. My pod’s log prints the average prompt throughput every 10 seconds, with decode and speculation running alongside. For the windows that had prompt work it gives:
| Prefill speed in my pod’s log | Prompt tokens per second | The disk must read faster than |
|---|---|---|
| Median busy window | 2,781 | 97 MB/s |
| 90th percentile | 6,214 | 216 MB/s |
| 99th percentile | 9,212 | 321 MB/s |
| Fastest single window | 15,581 | 543 MB/s |
Under load my pod prefills at roughly 6,000 to 7,000 tokens a second for long stretches, so the figure to beat is about 220 to 250 MB/s, and 540 MB/s at its fastest. AWS publishes the g7e.2xlarge drive as 275,000 random reads and 137,500 random writes a second at 4 KiB, and no throughput. Multiplied out, 275,000 reads of 4 KiB is at least 1.1 GB/s (derived, assuming large reads aren’t slower than small ones). That’s about twice the fastest figure and five times the load figure.
Short hits don’t pay. Every reload also carries the recurrent-state snapshot of about 159 MiB, a fixed cost per hit. A single 1,600-token block needs 865 MB/s at 6,214 tokens a second and 2,170 MB/s at the fastest rate, which is past the 1.1 GB/s the drive is known to read. A 16,000-token hit needs 281 and 705 MB/s, and a 64,000-token hit 233 and 583 (derived, one snapshot of three blocks per hit). So treat about 16,000 tokens as the floor: a system prompt plus tool schemas plus a long transcript pays, a short question doesn’t. An independent paper that measured this native tier on two models that aren’t hybrid agrees: below roughly 8,000 tokens no drive it measured beat recomputing.
On a hybrid model, the published sweep favours the disk. The vLLM authors swept Qwen3.6-35B-A3B, which mixes 30 linear-attention layers with 10 full-attention ones like ours, on two H100s with a 147 GB CPU tier and a local NVMe tier. While the conversations in flight fit in the CPU tier, the NVMe tier cost 3 to 5 percent of the requests per second. Once they outgrew it, it gave 2.4 times the throughput: 6.9 requests a second against 2.8 at 384 conversations (my arithmetic on their report). The tier isn’t new, either: their post says the framework has been available since v0.22, and the usage guide doesn’t mark the fs tier experimental.
The price is write traffic. Every prompt token the GPU computes is written to the disk once, so at my pod’s average of 1,346 computed prompt tokens a second that’s about 50 MB/s, or 4 to 5 TB a day, more than two full writes of the drive (derived: 47 MB/s at 34 KiB per token, 57 MB/s at the 42.5 KB per token that vllm#52735 implies once the recurrent state is counted). The drive can take it, since AWS’s 137,500 write IOPS imply at least 560 MB/s, but the guard deletes all day and 800 GiB holds only about five hours of prompts. AWS doesn’t publish this drive’s endurance, so that rate is the number to watch. The drive comes with the instance, so the tier costs no extra money, only those writes and one more thing to run.
Check it on your own pods. After a day of real traffic, read increase(vllm:prompt_tokens_cached_by_source_total{source="disk"}[1d]). If it stays flat, turn the tier off with --set tiering.enabled=false and the chart goes back to the plain Deployment from section 3 of part 4.
What the tier does not do
Two limits to plan around. The tier is local to the pod: it’s gone when the node is replaced, and it isn’t shared between replicas. And the endpoint picker doesn’t know it exists. It has no producer for local disk, and its index is sized from the GPU’s block count, so routing doesn’t change for a prefix that lives on the disk.
LMCache
A cache that’s shared between replicas is what LMCache is for. It’s a common cache store for offloading the KV cache. It plugs into vLLM as a connector and runs either inside the engine process or as a separate per-node service, so the cache survives engine crashes. It keeps blocks in CPU memory first and then on local disk, with network stores such as Redis, S3 or Mooncake behind them. Its authors report up to 15 times the throughput on workloads such as multi-round question answering and document analysis, measured on an eight-H100 server.
In vLLM v0.32.0, LMCache’s connectors need the hybrid KV cache manager turned off (the per-node service connector refuses to start with it on), and our model needs it on. So this post uses vLLM’s own connector. I’ll play around with LMCache on this setup and share what I find in a separate post.
Putting it together
That’s the whole stack, so let’s step back and look at what we built across the two parts. Terraform created everything that lives in AWS: the network, the EKS cluster, the AWS side of Karpenter, the AWS Load Balancer Controller, the bucket for the weights and the permissions that let a pod read it. Everything that lives inside Kubernetes went in with Helm. The community charts for Envoy Gateway, Envoy AI Gateway, the llm-d router, Prometheus and KEDA went in as they are, with a small values file from the examples wherever we needed one, and our own llm-serving chart holds everything specific to this model: the GPU nodes, vLLM, the route, the autoscaler and the rules.
Along the way we followed the three steps from the start. We provisioned the infrastructure in part 4: a region and a machine that exist, Karpenter and Bottlerocket to turn a pending pod into a ready GPU node, and vLLM streaming 20 GiB of weights straight from S3. In this part we set up the routing: a gateway that reads the model name from the request body, and an endpoint picker that sends each request to the best pod based on its queue, its KV cache and the prefixes it remembers sending. And we made the whole thing observable and autoscalable: metrics from vLLM and the picker, PromQL queries on top of them, KEDA scaling on five triggers that fire before users feel the load, and a CPU and NVMe tier to keep more prefixes around.
If you take three habits from these two parts, make them these:
- Write the name the model is served under in one place and let everything else derive from it. The route, the metrics label and the probe all depend on it.
- Scale on the worst pod and on signals that move early, never on an average or on a utilization number that can’t tell busy from drowning. A GPU pod takes minutes to start, so the scaler has to act before the queue is long.
- Read the numbers that depend on your hardware off your own logs. The pool size, the block size and the startup time are all printed when the pod starts.
All the code from both parts, the raw manifests, the Helm chart, the Terraform module, the values files for the community charts and the simulation, is in the examples folder. If something in there doesn’t work for you, it’s a bug in the post, so please let me know in the comments below.
Comments & reactions
React or leave a comment below — sign in with GitHub. It all lives in this site's GitHub Discussions.