llm-d 1.0 on GKE: routing, disaggregation, KV management¶
Prerequisites: Inference math: prefill, decode, KV cache, SGLang-TorchTPU
Chapters 18 and 19 served a model from one engine. A production fleet runs many engines, and the moment there is more than one, a question the engines cannot answer appears: which replica should take this request? A plain Kubernetes Service answers it by rotation, which throws away the KV cache that chapter 19 showed is worth most of an agent's TTFT. llm-d 1.0 is an open-source, Kubernetes-native stack that answers it with knowledge of the prompt, the replicas' caches and their load. This chapter explains its three ideas: routing each request to the replica that already holds its prefix, splitting prefill and decode into separate pools that hand the KV cache across, and managing the KV cache as a fleet-wide resource in tiers below HBM. It then lays out the exact Kubernetes objects of a GKE TPU deployment, with companion manifests and a validator for them, and ends with the metrics that tell you the router is doing its job.
What this chapter covers¶
- Why a fleet of engines needs a router that reads the prompt and the replicas' state, and the path of a request from the Gateway through the HTTPRoute, the InferencePool and the Endpoint Picker (EPP) to one model server pod.
- The EPP's filter, score and pick pipeline, and the approximate and precise prefix indexes behind prefix-cache-aware routing.
- Prefill/decode disaggregation: when it pays, how the EPP picks a decode and a prefill pod for one request, and how the KV cache moves between them on TPU over TPU Sync.
- KV offloading tiers, wide expert parallelism, LeaderWorkerSet and DisaggregatedSet, at the level needed to choose an llm-d well-lit path.
- The GKE TPU objects (Gateway, HTTPRoute, InferencePool, EndpointPickerConfig, Deployment, LeaderWorkerSet, DisaggregatedSet, InferenceObjective), with node selectors, chip counts and engine parallelism that match the slice.
- The metrics that show which pod served each request, the prefix-cache hit rate, the disaggregation decisions, and the TTFT gain of prefix-aware routing on a repeated-prefix workload.
Why one engine is not enough¶
The llm-d 1.0 announcement describes the shift that motivates it: a year earlier most traffic was chat, one prompt in and one response out; now "workloads are shifting to multi-step agents and reinforcement learning (RL) rollouts that fan out across tools, share long prefixes, and arrive in bursts." Served from one machine or behind a generic round-robin load balancer, such traffic "breaks down fast. Replicas recompute the same prompts, accelerator memory fills up with duplicate state, and one bursty agent loop can stall interactive users." The optimized-baseline guide gives the same argument from the load balancer's side: ordinary HTTP requests are fast, uniform and cheap, and round-robin balances them well, while LLM requests are multi-turn (they resend a growing prefix), slow (one can run for over a minute) and non-uniform (from a few hundred tokens to 100k).
Each of those properties breaks a different assumption of a generic load balancer:
| What an LLM request does | What a round-robin balancer assumes | What it costs |
|---|---|---|
| Resends a long prefix that one replica has cached | Any replica is as good as any other | A miss repeats the prefill: chapter 17's TTFT floor, paid again |
| Takes from milliseconds to minutes | Requests are short and similar | Counting requests says little about load; queued prompt tokens do |
| Has two phases with opposite bottlenecks | One kind of work | A long prefill stalls every decode on its replica |
| Holds HBM for its KV cache while it runs | Memory is not the scarce resource | Duplicate prefixes on every replica crowd out sequences |
llm-d keeps the engines (vLLM, SGLang and others) and adds what sits between them: "one router, one KV cache index, and one flow-control policy in front of the whole fleet." The project is a CNCF Sandbox project co-founded by Google with Red Hat, IBM and others. Its architecture has seven areas: the router, the model servers, disaggregation, KV cache management, model server orchestration, autoscaling, and batch and async serving. This chapter covers the first five; chapter 21 operates the fleet (autoscaling, rollouts, observability, flow control) and only the outline of autoscaling and batch appears here.
On TPU, nothing about llm-d's router changes. The GKE TPU provider page says so directly: "the router (EPP), InferencePool, Gateway API integration and OpenAI-compatible API are the same as on any other accelerator, and the model server is vLLM running on a TPU backend", which is vLLM-TorchTPU from chapter 18, using the image vllm/vllm-torchtpu. What is TPU-specific is the model server's manifest (slice shape, chip count, parallelism) and the KV transfer connectors.
The request path¶
The EPP decides and the Gateway carries the bytes. The request never passes through the EPP's data path: the Gateway holds it, asks, and forwards it straight to the chosen pod. The metrics arrow is what keeps the EPP's view of load current.
The llm-d router has two parts. The proxy is "any conformant industry-grade L7 proxy" (Envoy, Istio, agentgateway, or a cloud load balancer); it handles connections, TLS and forwarding. The Endpoint Picker (EPP) is "the routing engine that scores and selects model server pods based on real-time metrics, KV-cache affinity, and configured policies." The router page describes the handshake: "When an inference request arrives at the Proxy, the Proxy 'parks' the request and initiates a callback to the EPP via the ext-proc (External Processing) protocol." The EPP "returns the address of the optimal model server pod back to the Proxy. The Proxy then forwards the original request to that specific destination." Envoy's ext-proc is a standard filter, so llm-d reuses production proxies instead of writing one; the EPP page notes that the only supported request and response body mode is FULL_DUPLEX_STREAMED, which lets responses stream back through the EPP for accounting.
The InferencePool is the custom resource (inference.networking.k8s.io/v1) that ties the pieces together. It has two jobs. For the EPP it defines the candidates: a selector of pod labels, matched only in the pool's own namespace, and targetPorts, the ports serving inference ("Every port will be treated as a distinctive endpoint by EPP, addressable as a podIP:portNumber combination", up to 8). For the gateway controller it names the EPP: endpointPickerRef points at the EPP's Service, and the controller configures the proxy's ext-proc filter so that every request for the pool is first sent to the EPP. Its failureMode decides what the proxy does when the EPP does not answer: FailClose, the default, rejects; FailOpen forwards without a routing decision. Typically one InferencePool corresponds to one model deployment, served by one EPP. Model servers join by carrying the labels; scaling them changes the pool's membership without touching the pool.
Gateway mode or standalone mode. In Gateway mode the proxy is a Kubernetes Gateway, and an HTTPRoute whose backend is the InferencePool connects them; "If the selected backend in that rule is an InferencePool, the request is parked while the EPP configured for that InferencePool is consulted." One Gateway can host several routes, and a route can split traffic across several pools (a canary) or send other paths to an ordinary Service. In standalone mode a proxy runs as a sidecar in the EPP's pod and there is no Gateway, HTTPRoute or gateway controller; the guides recommend it for simple setups, tests, batch and RL pipelines, and the llm-d quickstart uses it. On GKE, Gateway mode is GKE Inference Gateway: "the llm-d router operating in Gateway Mode, a managed GKE Gateway that handles the L7 proxy and load balancing and calls the llm-d Endpoint Picker on every request." It is also how llm-d scales across clusters and regions.
Inside the EPP. A request passes through four stages. The request handler parses it (OpenAI HTTP by default, with parsers for the Anthropic Messages API and vLLM's HTTP and gRPC APIs) into an internal form; scheduling that reads the payload, such as prefix-cache scoring, needs a parser that understands it, and the passthrough-parser disables it. Flow control, when its feature gate is on, queues requests in priority bands and holds them when the pool is saturated (chapter 21). The scheduler picks the endpoint. The data layer works asynchronously: it watches the Kubernetes API for the pool's pods, scrapes every model server's Prometheus metrics, and holds in-memory state such as the prefix index that the scheduler reads. The EPP is configured by an EndpointPickerConfig file passed with --config-file; "While the configuration syntax looks like a Kubernetes Custom Resource, it is not a Kubernetes CRD": it is read once at startup, and changing it means restarting the EPP.
The request crosses the first three of the EPP's four stages in order and leaves with one address; the proxy, not the EPP, carries it to the pod. The fourth, the data layer, works off the request path, so the scheduler reads pod state and the prefix index without waiting for them.
Scheduling: filter, score, pick¶
The scheduler runs a pipeline for every request: filters remove candidates, scorers give each remaining endpoint a score between 0 and 1, and a picker chooses. A scheduling profile lists the plugins; scores are combined as a weighted sum:
The scheduling page's example: a scorer with weight 2.0 that returns 0.8 and one with weight 1.0 that returns 0.5 give \(0.8 \times 2.0 + 0.5 \times 1.0 = 2.1\). The default picker, max-score-picker, takes the highest total; it is injected into any profile that names no picker.
The plugins that matter for this chapter:
| Stage | Plugin | What it does |
|---|---|---|
| Filter | prefix-cache-affinity-filter |
Narrows to "sticky" endpoints with a high prefix-cache score, with a TTFT load gate that breaks stickiness when they are much slower |
| Filter | prefill-filter, decode-filter |
Keep endpoints by their llm-d.ai/role label (disaggregation) |
| Scorer | prefix-cache-scorer |
"Scores based on the length of the prefix cache match" |
| Scorer | kv-cache-utilization-scorer |
Prefers endpoints with lower KV cache utilization |
| Scorer | queue-scorer |
Prefers shorter request queues |
| Scorer | token-load-scorer |
Scores on the token load (input and output) the endpoint is handling |
| Scorer | no-hit-lru-scorer |
For cold requests (no cache hits), prefers endpoints that have never handled one, then the least recently used, spreading prefill work |
| Scorer | session-affinity-scorer |
Maximum score for the endpoint that served the session before |
| Picker | max-score-picker, weighted-random-picker |
Highest total, or a lottery weighted by score |
| Handler | single-profile-handler, disagg-profile-handler |
Run one profile, or a prefill and a decode profile |
The load signals come from the model servers. The EPP scrapes GET /metrics on the serving port and maps engine metrics to internal signals; for vLLM, the queue is vllm:num_requests_waiting, the running count vllm:num_requests_running, and the KV cache utilization vllm:kv_cache_usage_perc. Pods without an llm-d.ai/engine-type label are read with vLLM's names, which is why chapter 19's SGLang pods must carry llm-d.ai/engine-type: sglang.
A profile, and what its weights imply. The configuration guide gives "concrete values that are recommended for a typical production setup": prefix-cache-scorer at weight 3.0, kv-cache-utilization-scorer at 2.0 and queue-scorer at 2.0. Read the weights as a statement about trade-offs. With only the prefix scorer at 3 and a queue scorer at 2, a pod holding more than two thirds of a prompt always beats an idle pod holding none, however long its queue: the queue scorer can make up at most 2 points, and \(3 \times \tfrac{2}{3} = 2\). That is what you want for a multi-turn session, and exactly what you do not want when thousands of requests share one hot system prompt, because affinity then piles all of them onto the first pod that cached it. The llm-d optimized baseline, the recommended starting point for every accelerator, therefore uses a different shape: prefix-cache-affinity-filter, which keeps only cache-warm endpoints "with a saturation-aware override that spreads load when endpoints get hot", followed by token-load-scorer. The override "keys off the peakPrefillThroughput of the filter, which is hardware- and model-specific", and the guide warns that on non-default hardware an uncalibrated value can keep the override from ever spreading load. On TPU, measure it with llm-d's calibration recipe before you trust the defaults.
Prefix-cache-aware routing¶
Watch pod 1's chips: everything sessions A and C share is stored once and reused. Then watch request 7: when no pod holds the prefix, the load scorer decides, which is how a new prompt finds an idle pod.
The animation is computed by the chapter's scorer_sim.py. llm-d's KV cache page calls the routing layer "the 'intelligence' layer": it "aims to maximize 'cache hits' by routing requests to replicas that already contain the relevant KV cache for the request's prompt prefix." It needs the engines to cache across requests, which vLLM does with --enable-prefix-caching (chapter 18) and SGLang with RadixAttention (chapter 19). The router offers two ways to know what each pod holds.
Approximate: learn from your own decisions. The approx-prefix-cache-producer needs nothing from the model servers. Because the EPP has no tokenizer, it approximates tokens from characters, splits the prompt into fixed blocks (64 tokens by default) and builds a rolling hash chain over them. It keeps an in-memory LRU index of "which prefix hashes were recently sent to which Pods", and after each decision it records that the chosen pod now holds the prefix. The prefix-cache-scorer scores the ratio of matched blocks to total blocks. The trade is stated plainly: lightweight and dependency-free, but it "can diverge from actual model server state (e.g., if a Pod evicts a prefix due to memory pressure)". Its parameters in the configuration guide are blockSizeTokens: 64, maxPrefixTokensToMatch and lruCapacityPerServer: 31250.
Precise: listen to the engines. The precise implementation builds the index from the engines' own records. Model servers "publish every cache change as an event" over ZeroMQ: BlockStored when blocks are cached (with the parent hash, the tokens, and any LoRA or multimodal keys), BlockRemoved when they are evicted, and AllBlocksCleared when a pod drops its whole cache, as happens on a weight reload in RL. vLLM publishes with --kv-events-config; SGLang with --enable-kv-cache-events and --kv-events-config. Inside the EPP, four components cooperate:
- the index, a
block key → podsmap (in memory by default, two-level LRU; a cost-aware variant and Redis or Valkey are alternatives); - the token producer (
token-producer), which gets exact token IDs by calling vLLM's render endpoints (/v1/completions/render,/v1/chat/completions/render), served by the pool's own vLLM pods or by a GPU-lessvllm launch renderprocess; - the precise data producer (
precise-prefix-cache-producer), which turns the tokens into block keys, looks them up and publishes the match per endpoint; - the stateless
prefix-cache-scorer, pointed at that producer withprefixMatchInfoProducerName: precise-prefix-cache-producer. Without that setting it silently falls back to the approximate producer.
The scorer counts only the longest consecutive prefix: "Due to the causal nature of attention, a server can reuse a cached block only if it holds the unbroken prefix leading up to it." A pod holding blocks 3 and 4 of a prompt but not block 0 scores zero. When a block is cached in several tiers, the scorer weights it by the best tier, by default gpu = 1.0 and cpu = 0.8 (TPU HBM counts as the first). Two delivery shapes exist: centralized, where every pod connects to one socket on the EPP, and pod discovery, where every pod binds its own socket and each EPP replica subscribes to every pod; the precise well-lit path uses pod discovery on port 5556, with vLLM pods also keeping a replay buffer of their last 10,000 event batches on port 5559 so a restarted router can rebuild the index.
One gap remains between deciding and learning: "Back-to-back requests with the same prefix can be scheduled before KVEvents have propagated, breaking affinity." With speculativeIndexing: true the producer inserts short-lived entries for the chosen pod right after routing, expiring after a 2-second TTL unless a BlockStored confirms them.
| Approximate | Precise | |
|---|---|---|
| State source | The EPP's own routing decisions | KV events from the model servers |
| Tokens | Estimated from characters | Exact, from vLLM's render endpoint |
| Sees evictions and resets | No | Yes (BlockRemoved, AllBlocksCleared) |
| Extra infrastructure | None | ZMQ connectivity to every pod, a render endpoint |
| Use case in the docs | "Simple, homogeneous workloads" | "Complex, high-scale production serving" |
On TPU, the router's blocks must match the engine's. The precise path requires vLLM --block-size (or SGLang --page-size) to equal the producer's blockSizeTokens, 64 by default. TPU v6e is the documented exception: "--block-size=64 runs out of SMEM on TorchTPU, so the tpu/v6 overlay sets --block-size=256" and the router values match it. The TPU7x Qwen3.5-397B configurations go further: the hybrid model runs with --block-size=4352, and their router values "set 4352-token router blocks (the engines' --block-size) and a 262k match window." Block hashes must also agree between engines wherever blocks are shared, which is why the TPU guides set PYTHONHASHSEED=0 on every engine.
What the simulation shows. scorer_sim.py runs the EPP's scoring over pods with LRU caches of 64-token blocks, with prefill time charged only for uncached tokens at about 25.7k tokens per second (one v7x chip on Muse Glimmer 30B, chapter 17). On 16 sessions of 6 turns over 4 pods:
$ python code/ch20_llm_d/scorer_sim.py --cpu-smoke
== 1. Multi-turn sessions: 16 sessions x 6 turns, 4 system prompts, 4 pods of 256 blocks ==
router hit rate TTFT p50 TTFT p90 mean requests per pod
round-robin 67.2% 37.4ms 87.2ms 40.5ms [24, 24, 24, 24]
least-loaded 67.7% 37.4ms 87.2ms 39.6ms [24, 24, 24, 24]
prefix-approx 94.6% 7.5ms 52.2ms 14.5ms [24, 24, 24, 24]
prefix-precise 94.6% 7.5ms 52.2ms 14.5ms [24, 24, 24, 24]
affinity-gated 91.5% 7.5ms 44.7ms 15.0ms [24, 30, 18, 24]
== 2. One hot prefix: 96 single-turn requests, 5 ms apart, share a 4,096-token prompt ==
round-robin 92.9% 59.1ms 149.3ms 66.1ms [24, 24, 24, 24]
prefix-precise 96.0% 408.4ms 597.7ms 405.9ms [96, 0, 0, 0]
affinity-gated 92.9% 54.1ms 149.3ms 66.1ms [24, 24, 24, 24]
== 3. Pod 1 restarts after 40 requests: the approximate index cannot see it ==
prefix-approx hit rate 92.8%; 4 requests routed on 3,840 tokens the index believed cached ...
prefix-precise hit rate 92.8%; 0 requests routed on 0 tokens the index believed cached ...
Three lessons sit in those rows. Round-robin still reuses 67% because every pod soon holds the four system prompts; what it loses is each session's history, and that loss is a fivefold median TTFT. Weighted affinity with no gate sends all 96 requests that share one hot prompt to one pod and quadruples the tail; an affinity filter with a saturation override keeps the hit rate and spreads the load. And the approximate index routes on cache that a restarted pod no longer has, which the precise index learns from AllBlocksCleared. The numbers are a model's, not a cluster's: use them to see the mechanism, then measure yours.
Prefill/decode disaggregation¶
Chapter 17 showed why prefill and decode want different hardware: prefill is FLOPs-bound and decode is bandwidth-bound, and when they share a device, "prefills can slow down processing of existing requests in the decode phase." llm-d's disaggregation page lists three gains: specialization (for example "a larger TP for the memory-bound decoding phase while a smaller TP for the computation-bound prefill phase"), avoiding interference so long prefills never stall decodes, and compatibility with wide expert parallelism (below). It also says when to try it: "Medium-large models", "Longer input sequence lengths (e.g 10k ISL | 1k OSL, not 200 ISL | 200 OSL)", and "Sparse MoE architectures with opportunities for wide-ep". The benefits are "largest for long-context workloads (e.g. 10:1 ISL:OSL)". Tune two things: heterogeneous parallelism (prefill with less parallelism and more replicas, decode with more parallelism and fewer replicas) and the ratio of prefill to decode workers (xPyD), scaling each role on its own.
Two hops carry request metadata (prefiller header, then max_tokens=1 and KV params) and one carries the KV cache itself, the purple arrow. The decode pod's sidecar orchestrates both; the Gateway only ever talks to the decode pod.
How the EPP picks two pods. Both roles live in one InferencePool and are told apart by the pod label llm-d.ai/role: prefill, decode, or prefill-decode for pods that can do both. The EPP's disagg-profile-handler runs two scheduling profiles, named prefill and decode, whose filters keep only the matching role. It runs the decode profile first and picks a decode endpoint. Then it consults a decider: "given how much of the prompt is cached on D, should this request run disagg?" If not, it returns only the decode endpoint, and the decode engine prefills locally. If so ("large uncached suffix"), it runs the prefill profile, picks a prefill endpoint, and returns both. Two deciders exist. always-disagg-pd-decider always disaggregates. prefix-based-pd-decider disaggregates only when the uncached suffix on the chosen decode pod reaches its nonCachedTokens threshold, whose default of 0 selects decode-only for every request, so set it. The conditional decider is the one that suits agents: a turn whose history is already in the decode pod's cache prefills only its new suffix there, with no transfer. It is allowed only with vLLM, because a vLLM decode worker can prefill locally when a request does not ask for remote prefill; an SGLang decode worker "requires every request to include bootstrap rendezvous fields and cannot fall back to local prefill", so SGLang deployments must use always-disagg-pd-decider (chapter 19).
The decode pod is chosen first, so the decider can ask how much of this prompt it already holds. Only the prefix-based decider ever says no, and only vLLM decode pods can take that answer; leave its threshold at 0 and nothing disaggregates.
The routing sidecar. The decode endpoint is where the proxy sends the request; the prefill endpoint travels in the x-llm-d-prefiller-host-port header. Each decode pod runs a routing sidecar in front of its engine that reads the header and runs one of two protocols. For vLLM (nixlv2, the default) it is sequential: the sidecar sends the request to the prefill worker with max_tokens=1 and remote-decode metadata in kv_transfer_params, takes the KV transfer parameters from the response, and forwards the request to its local decode engine with those parameters and do_remote_prefill=True; the decode worker pulls the KV cache, the prefill worker releases it, and decode runs. If the prefill worker returns a server error, the sidecar falls back to decode-only. For SGLang it is concurrent: the sidecar injects bootstrap_host, bootstrap_port and bootstrap_room into both requests, fires the prefill asynchronously and sends the decode request at once, and the two engines meet in the bootstrap room. Without the header, the sidecar passes the request straight to its engine.
The pages are computed once, on the prefill pod, and moved once. The last frame is the reason the design works: moving a prompt's KV costs a few percent of computing it.
How the KV cache moves. Moving the cache is the other half of disaggregation, and it is where TPU differs. On GPUs llm-d focuses on NIXL, which registers the engines' preallocated KV memory and transfers directly between the two caches, and the docs are firm that it needs RDMA: "Without RDMA, NIXL falls back to TCP for transfer which is not efficient and should only be used for testing and development." On TPU the P/D well-lit path replaces NIXL with TPU KV connectors:
| Overlay | Model | Connector | Notes |
|---|---|---|---|
tpu/v5p |
Qwen/Qwen3-32B |
TPUConnector from tpu_inference (JAX backend) |
validated nightly |
tpu/v6 |
Qwen/Qwen3-32B, 1P + 1D, TP=8 each |
TorchTPU TPUConnector (vllm_torchtpu.distributed.kv_transfer.tpu_connector, ZMQ and host shared-memory staging) |
community |
tpu/v7 |
Qwen/Qwen3.5-397B-A17B-FP8, prefill PCP=8 to decode DP=8 |
TPURaidenConnector (TPU Sync), prefill also TPURaidenOffloadingConnector with a 64 GiB host tier |
community |
tpu/v7-dynamic-slice |
Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8 in a DisaggregatedSet |
TPUConnectorHMA |
community, validated by dry run in CI |
TPU Sync (Raiden in the code) is the C++ library chapter 18 introduced: it reads the device buffers behind PyTorch tensors directly and runs transfers on its own threads. vLLM-TorchTPU's disaggregation guide describes a production deployment as four parts: a Raiden controller that "Coordinates KV transfer metadata and pool registration", a prefill pool (kv_role="kv_producer"), a decode pool (kv_role="kv_consumer") that receives KV "resharding on the fly if P and D meshes differ", and a proxy, which llm-d's routing sidecar replaces. In the TPU7x overlay, prefill runs PCP=8 and decode runs DP=8, and "TPU Sync (tpu-sync) Stage-3 reshards the KV from the 8 prefill shards onto the 8 decode engines over TPU interconnect." The prefill pod wraps two connectors in a TPUMultiConnector: TPURaidenOffloadingConnector keeps blocks that leave prefill HBM in 64 GiB of pinned host DRAM, and TPURaidenConnector produces KV for decode. Each pod takes its TPU Sync engine ID from its own name, so raising the role replica counts gives xPyD without other changes. Between slices, KV moves over the data-center network: the GKE TPU page lists "Over DCN, 100 Gb/s per chip" for P/D transfer, and TPU Sync over ICI inside a slice.
Use the connector name from the code
vLLM-TorchTPU's disaggregation guide spells the connector TpuRaidenConnector in module vllm_torchtpu.distributed.kv_transfer.raiden.raiden_connector. Neither exists. The vLLM-TorchTPU source defines class TPURaidenConnector(TPUConnector) in vllm_torchtpu/distributed/kv_transfer/tpu_connector.py, the raiden/ package has no raiden_connector module, and every script in examples/disagg/ passes "kv_connector":"TPURaidenConnector","kv_connector_module_path":"vllm_torchtpu.distributed.kv_transfer.tpu_connector". The llm-d guide and this book's manifests use the code's name. The validator in this chapter's code rejects the guide's spelling.
What the transfer costs. Chapter 17's formula sizes it. Muse Glimmer 30B keeps 13 full-attention layers and 39 sliding-window layers with 2 KV heads of 128 dimensions in bf16, so a 10,000-token prompt has 215 MB of KV (model_kv_bytes(muse, 10000)). At one chip's 100 Gb/s of DCN, 12.5 GB/s, that is 17 ms; spread over four chips' links it is about 4 ms. Its prefill floor on one v7x device is 479 ms. The transfer is a few percent of the work it follows, and in exchange no decode step waits behind that prefill. Two consequences follow. A slow transfer shows up as TTFT, never as inter-token latency, which is how the P/D guide tells KV-transfer stalls from decode saturation. And for a short prompt the fixed costs (a second scheduling decision, a round trip through the sidecar, a transfer) can exceed the prefill they replace, which is why nonCachedTokens exists.
What decode does when it runs out of room. A decode pod holds the KV of every sequence it generates. vLLM-TorchTPU's decode pools, with kv_load_failure_policy="fail" (the upstream default), abort a request evicted under KV pressure instead of recomputing its prompt locally: it ends with finish_reason "error" and stop_reason "kv_cache_preempted". Set --additional-config '{"abort_on_preemption": false}' to recompute instead, and watch decode KV utilization, which the P/D guide calls "usually the scaling bottleneck."
KV offloading: tiers below HBM¶
KV caches outgrow HBM long before an agent session ends. llm-d's offloading page frames it as extending "the receptive field: how long a KV cache stays reusable after its request completes." Without offloading, a follow-up request that arrives after its prefix was evicted recomputes it; with offloading, it loads it back, which the page says "is typically faster than recomputing them", by up to 16x for long prompts. The tiers, nearest first; the shared filesystem and peer DRAM are both secondary tiers, reached through host DRAM:
Every tier below HBM is reached through host DRAM: a block found only on the shared filesystem or in a peer's memory comes back through the host into HBM. Each step down holds more and is shared more widely, at a higher cost to load back.
| Tier | Holds | Scope | On TPU |
|---|---|---|---|
| HBM | the engine's working KV cache | one engine | the paged cache of chapters 18 and 19 |
| Host DRAM | evicted blocks, pinned memory | one node | TPURaidenOffloadingConnector sized by cpu_bytes_to_use; SGLang HiCache with --hicache-io-backend raiden |
| Shared filesystem | evicted blocks, persistent | every replica | TPU7x: a TPU Sync storage tier at raiden_storage_path on a ReadWriteMany volume, validated with Google Cloud Managed Lustre, single host |
| Peer DRAM (P2P) | another pod's host tier | the fleet | experimental, vLLM OffloadingConnector over NIXL; no TPU configuration in the llm-d docs |
The guidance is to always enable the HBM and CPU RAM tiers, to add a filesystem tier only when the working set outgrows both, and to prefer each engine's native path: vLLM's OffloadingConnector on GPUs, HiCache on SGLang. On TPU the tiered-prefix-cache guide uses TorchTPU's own connector instead of vLLM's generic one, with the TPU Sync KV cache manager and a unified HBM and host block pool (TPU_USE_RAIDEN_KV_CACHE_MANAGER=1, TPU_VLLM_ENABLE_UNIFIED_BLOCK_POOL=1). The tiers fill lowest latency first. The sizes are concrete: on TPU7x each of the 8 DP engines of a 2x2x1 pod gets a 32 GiB host tier, 256 GiB pinned per pod, plus a 16 GiB staging buffer per engine, and the pod requests 850Gi of the roughly 919 GiB a tpu7x-standard-4t node offers; v6e runs one TP=8 engine with a 100 GiB tier and requests 900Gi. For the filesystem tier, every block is written to host and, write-through, to storage; a block found only in storage is recalled through host staging into HBM, "so a replica that has never seen a prefix restores it from the filesystem." Storage keys are prefix-block hashes, so every pod sets PYTHONHASHSEED=0, and "the engine refuses to start the tier without it."
The router has to know about the tiers too: the tiered guide "adds a second prefix-cache scorer that tracks what each model server holds in its CPU tier, so a request also prefers the pod that can load its prefix from CPU RAM." That is the cpu = 0.8 weight of the precise scorer at work: a prefix in another pod's DRAM is worth less than one in HBM, but more than nothing.
Wide expert parallelism¶
Very large MoE models fill HBM with weights. Wide expert parallelism (wide-EP) serves them across many nodes: "the attention layers run data-parallel (DP) and the expert (MLP) layers run expert-parallel (EP), so every accelerator holds a slice of the experts and its own share of the KV cache." Two properties make it scale. The dispatch and combine collectives are sparse, since each token goes only to the ranks holding its top-k experts, so they need much less bandwidth than tensor parallelism's all-reduces. And attention is data-parallel with TP=1 in each group, so there is exactly one copy of each token's KV: no replication, more room for sequences. Wide-EP pairs naturally with disaggregation, which avoids pipeline "bubbles" where one rank is computing a prefill while another is decoding, and lets prefill and decode use different kernels.
Wide-EP changes routing. With data-parallel attention, every DP rank has its own KV cache and queue, so prefix affinity and load balancing work best per rank, not per pod. vLLM can run one API server per rank on its own port; the InferencePool then lists every rank port in targetPorts (up to 8), and the EPP treats each podIP:port as an endpoint. When the engine exposes one port per pod instead, the router picks a pod and the engine balances across its ranks.
On TPU the same layout appears without the name. The TPU7x configurations of the llm-d guides run Qwen3.5-397B as DP=8 × TP=1 with expert parallelism on one 2x2x1 host, the GKE TPU page lists --data-parallel-size=8 --tensor-parallel-size=1 "for MoE models with expert parallelism", and the GLM-5.2 guide runs a tpu7x-2x2x2-dp16 LeaderWorkerSet. The wide-EP well-lit path itself has GPU and XPU configurations only; for TPU MoE recipes, follow the model guides.
Model server orchestration: LeaderWorkerSet and DisaggregatedSet¶
A Deployment manages independent pods. A model too large for one host needs a group of pods that start together, know each other's ranks, and fail together, and a disaggregated model needs two such groups that are upgraded together. llm-d uses two Kubernetes SIG Apps APIs for that.
LeaderWorkerSet (LWS), leaderworkerset.x-k8s.io/v1, deploys "a group of pods as a single unit of replication." Each replica is one leader pod and size - 1 workers, built from two tiers of StatefulSets so that every pod has a stable ordinal and DNS name. The leaderTemplate and workerTemplate can differ, and the controller injects LWS_LEADER_ADDRESS, LWS_GROUP_SIZE and LWS_WORKER_INDEX into every pod, plus TPU_WORKER_HOSTNAMES, TPU_WORKER_ID and TPU_NAME when TPUs are requested. Its default restart policy, RecreateGroupOnPodRestart, restarts the whole group when one pod fails, "preventing distributed collective hangs." On TPU this is how a multi-host slice is served: the GKE TPU page's tpu7x-standard-4t × 2 row is a 2x2x2 slice with 16 devices, "one pod per host, started together via LeaderWorkerSet". vLLM-TorchTPU's multi-host guide gives the launch: every host runs vllm serve with --nnodes 2 and its --node-rank, host 0 serves HTTP, and the others pass --headless. Only the leaders serve the API, so the InferencePool must select leaders only.
DisaggregatedSet, disaggregatedset.x-k8s.io/v1, does not replace LeaderWorkerSet: it "orchestrates multiple LeaderWorkerSets". Each role (prefill, decode, optionally encode) becomes a child LWS named <set>-<slice>-<revision>-<role>, with its own group size, template and replicas. What the set adds is coordination: one revision covers all roles, so prefill and decode always run matching versions; rollouts move the roles together while preserving their ratio (each role defaults to maxSurge: 0, maxUnavailable: 1); slices replicates the whole prefill-plus-decode topology into independent copies; and a role can hand its replica count to an external autoscaler. During a rollout, the EPP's disaggregatedset-rollout-screener pins each request to one revision "so prefill and decode never pair across revisions." On TPU, one practical consequence: "TPU node pools are fixed-size: a rollout that needs a spare node to surge onto leaves the new pod Pending until the old group is deleted."
| LeaderWorkerSet | DisaggregatedSet | |
|---|---|---|
| Unit | one leader and size - 1 workers |
several roles, each a child LWS |
| Use it for | a model that spans hosts (multi-host TP, DP, EP) | prefill and decode (and encode) as one versioned workload |
| Rollouts | per group (maxUnavailable, maxSurge) |
coordinated across roles, ratio-preserving |
| On TPU | multi-host slices such as 2x2x2 |
the P/D overlays, including TPU7x dynamic sub-slices with Kueue |
Autoscaling and batch, in outline. llm-d scales model servers on signals from the EPP (queued requests, saturation, token backlog, or estimated latency against an SLO) through KEDA, "because accelerator utilization is an unreliable proxy for LLM load"; the older Workload Variant Autoscaler is deprecated. For latency-tolerant work, the Batch Gateway offers an OpenAI-compatible /v1/batches API and the Async Processor pulls requests from queues such as Pub/Sub or Redis and dispatches them into spare capacity. Both are chapter 21's subject.
The GKE TPU deployment path¶
Adopt llm-d's well-lit paths in order, adding each only when its test holds:
Take the paths in this order, adding each only when its test holds; they are independent, so skip one that does not apply and go on to the next. The names match the rows of the table below.
The announcement's advice matches the ladder, with flow control as an extra step: "Start with prefix-aware routing in front of your existing vLLM deployment, then add flow control, KV cache offload and disaggregation." Each step is one of llm-d's well-lit paths, tested recipes with Helm charts, Kustomize overlays and benchmarks, and each lists its TPU configurations:
| Well-lit path | TPU v6e | TPU7x |
|---|---|---|
| Optimized baseline | Qwen/Qwen3-32B, 2 replicas of 2x4, TP=8 |
Qwen/Qwen3.5-397B-A17B-FP8, 2 replicas of 2x2x1, DP=8 × TP=1, EP |
| Precise prefix-cache routing | Qwen/Qwen3-32B, --block-size=256 |
Qwen/Qwen3.5-397B-A17B-FP8, DP=2 × TP=4 |
| Tiered prefix cache | 100 GiB TPU Sync host tier | host DRAM tier (single and multi-host), Lustre tier (single host) |
| P/D disaggregation | 1P + 1D, TorchTPU TPUConnector |
PCP=8 to DP=8, TPURaidenConnector, 64 GiB prefill host tier |
The v6e and TPU7x TorchTPU rows are marked community: maintained, but not in the nightly end-to-end matrix. The guides' nightly TPU runs use v5p.
The steps. The llm-d GKE pages give the order:
- Capacity. TPU node pools whose machine type matches the slice. The GKE TPU page suggests a custom ComputeClass that tries a reservation, then Spot, then DWS flex-start, with node auto-provisioning creating the pool; "Flex-start nodes run for at most 7 days and are then preempted, so don't rely on them alone for a long-running service." Size the boot disk for the checkpoint: weights are cached per node under
/var/cache/huggingface, at least 200 GB for Qwen3-32B on v6e and 1 TB for the 406 GB Qwen3.5-397B checkpoint, because the 100 GB auto-provisioning default is evicted mid-download. - APIs. Gateway API enabled on the cluster and a proxy-only subnet. On GKE
1.34.0-gke.1626000or later, GKE manages the Gateway API and v1InferencePoolCRDs; earlier, apply the Gateway API Inference Extension CRDs from the guide. For LWS-based paths, install the LeaderWorkerSet controller. - Gateway. A
Gatewayof classgke-l7-regional-external-managed(internet-facing) orgke-l7-rilb(VPC-internal), namedllm-d-inference-gatewayin the guides; wait forPROGRAMMEDto showTrue. - Router. The router Helm chart in Gateway mode with
--set provider.name=gke --set httpRoute.create=true, which deploys the EPP, its Service, the InferencePool and the HTTPRoute. - Model servers. The guide's Kustomize overlay for your accelerator,
guides/<path>/modelserver/tpu/v6/vllm/gke/or.../tpu/v7/.... - Verify, as in the last section of this chapter.
export PROVIDER_NAME=gke
helm install ${GUIDE_NAME} ${ROUTER_GATEWAY_CHART} \
-f ${ROUTER_BASE_VALUES} ${MONITORING_VALUES} -f ${ROUTER_VALUES} \
--set provider.name=${PROVIDER_NAME} \
--set httpRoute.create=true \
--set httpRoute.inferenceGatewayName=llm-d-inference-gateway \
-n ${NAMESPACE} --version ${ROUTER_CHART_VERSION}
export ACCELERATOR_TYPE=tpu/v6 # options: gpu, tpu/v6, tpu/v7, cpu
export MODEL_SERVER=vllm
kubectl apply -n ${NAMESPACE} -k ${REPO_ROOT}/guides/${GUIDE_NAME}/modelserver/${ACCELERATOR_TYPE}/${MODEL_SERVER}/gke/
The objects, by kind. These are the resource kinds a GKE TPU deployment of llm-d consists of, with the API groups the llm-d docs use:
| Kind | apiVersion | Role |
|---|---|---|
Gateway |
gateway.networking.k8s.io/v1 |
the L7 proxy (GKE-managed in Gateway mode) |
HTTPRoute |
gateway.networking.k8s.io/v1 |
matches paths and names the InferencePool as backend |
InferencePool |
inference.networking.k8s.io/v1 |
pod selector, target ports, EPP reference, failure mode |
EndpointPickerConfig |
llm-d.ai/v1, a file in a ConfigMap |
plugins and scheduling profiles; not a CRD |
InferenceObjective |
llm-d.ai/v1 |
priority per workload, via spec.poolRefs; negative is sheddable |
Deployment |
apps/v1 |
single-host model servers, and the EPP itself |
LeaderWorkerSet |
leaderworkerset.x-k8s.io/v1 |
multi-host model servers |
DisaggregatedSet |
disaggregatedset.x-k8s.io/v1 |
prefill and decode roles as one workload |
What is TPU-specific in a pod. The GKE TPU page: "A TPU pod describes the slice it needs with two node selectors (accelerator and topology) plus a chip count. All three must agree with the node's machine type, or the pod stays Pending without a clear error." Then the engine's parallelism must cover the slice: "The engine's TP × DP must equal the number of devices in the slice, otherwise part of the slice stays idle." On v6e a chip is one device; on TPU7x a chip is two, one per TensorCore.
| Machine type | gke-tpu-accelerator / gke-tpu-topology |
google.com/tpu per pod |
Devices | Engine parallelism |
|---|---|---|---|---|
ct6e-standard-4t |
tpu-v6e-slice / 2x2 |
4 | 4 | --tensor-parallel-size=4 |
ct6e-standard-8t |
tpu-v6e-slice / 2x4 |
8 | 8 | --tensor-parallel-size=8 |
tpu7x-standard-4t |
tpu7x / 2x2x1 |
4 | 8 | --data-parallel-size=8 --tensor-parallel-size=1 with EP, or --tensor-parallel-size=8 |
tpu7x-standard-4t × 2 |
tpu7x / 2x2x2 |
4 per pod, LWS of 2 | 16 | --tensor-parallel-size=16, or DP=16 × TP=1 |
The guides add three settings that are easy to miss: annotate model server pods cluster-autoscaler.kubernetes.io/safe-to-evict: "false" so the OPTIMIZE_UTILIZATION autoscaler profile does not remove a node that looks idle by CPU, use strategy: Recreate because TPU node pools are fixed-size (a surge pod has nowhere to schedule), and persist the compile cache and size the startupProbe for a cold compile, which "takes minutes for a large model". The cost of Recreate is that it deletes every old pod before creating a new one, so any change to the pod template is a full outage until the new pods have loaded and compiled; chapter 21 covers the alternatives (maxSurge: 0 with maxUnavailable: 1, spare capacity, blue-green). The manifests also carry the probe and drain settings of llm-d's lifecycle guides: startupProbe and readinessProbe on /v1/models (which answers only once the model is loaded, where /health reports only that the process is up), livenessProbe on /health, a 15 s preStop sleep, --shutdown-timeout=45 and a 75 s grace period. The prefill/decode manifest keeps the longer 20 s, 90 s and 150 s of the disaggregation rollout guide, because a prefill pod must outlive the KV pulls that depend on it. The image is vllm/vllm-torchtpu:v0.29.0; checkpoints load as FP8 on TPU7x and INT8 or AWQ INT4 on v6e.
The companion manifests. code/ch20_llm_d/manifests/ (source) spells out three deployments, one namespace each: baseline-v6e (two Deployment replicas of Qwen/Qwen3-32B, prefix-aware routing with the configuration guide's weights), pd-tpu7x (a DisaggregatedSet with the TPU7x prefill and decode roles, the Raiden controller, and an EPP config with disagg-profile-handler and prefix-based-pd-decider), and multihost-tpu7x (a TP=16 LeaderWorkerSet on 2x2x2 whose pool selects only the leader). They are for reading and adapting: the supported install remains the Helm chart and the guide overlays. The validator checks what the llm-d and vLLM-TorchTPU docs state and catches the mistakes that fail silently:
$ python code/ch20_llm_d/validate_manifests.py --cpu-smoke
directory file apiVersion kind
baseline-v6e inferencepool.yaml inference.networking.k8s.io/v1 InferencePool
pd-tpu7x disaggregatedset.yaml disaggregatedset.x-k8s.io/v1 DisaggregatedSet
multihost-tpu7x leaderworkerset.yaml leaderworkerset.x-k8s.io/v1 LeaderWorkerSet
...
baseline-v6e: OK
multihost-tpu7x: OK
pd-tpu7x: OK
four broken variants, each must be rejected:
connector spelled as the user guide spells it: rejected
... connector 'TpuRaidenConnector' does not exist in vllm-torchtpu; the class is 'TPURaidenConnector' ...
8 chips requested on a 4-chip tpu7x host: rejected
InferencePool selector with the HF model id: rejected
... matches no pod template here; the EPP would have no endpoints
disaggregating EPP, pods without role labels: rejected
cpu-smoke: OK
The routing sidecar's own arguments and the Raiden controller's working directory depend on the release overlay; copy them from guides/pd-disaggregation/modelserver/tpu/v7 in the llm-d repository.
What llm-d 1.0 reports¶
Each panel has its own units and its own workload. Read them as evidence that cache-aware routing matters at fleet scale, not as numbers to expect from your deployment. Data: Google Cloud, llm-d 1.0 announcement.
The announcement reports that the Gemini platform doubled its prefix cache hit rate through GKE Inference Gateway and cut TTFT by more than 35% for coding agents; that on an agentic coding workload on Ironwood, "prefix-aware routing plus host memory offload cut median time-to-first-token (TTFT) by more than 85% and raised total throughput 2.4x versus a plain Kubernetes Service"; and, in customer quotes, prefix cache hit rates of 75 to 80% at Snap and over 4x throughput for ZenteiQ on v6e. Check provenance before you quote the Ironwood figure as a PyTorch result: the announcement links it to llm-d's Qwen3-Coder-480B guide, and the current Qwen3.5-397B model guide says that "The previous revision of this guide served Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8 on the JAX tpu_inference backend; its results (June–July 2026) are in the git history and do not apply to this configuration", while results on TorchTPU "are being collected." The routing mechanism is independent of the engine; the multiplier is not yet a vLLM-TorchTPU measurement.
Failure modes¶
| Symptom | Mechanism | What to check or change |
|---|---|---|
| Requests spread evenly, hit rates low, TTFT grows every turn | Cache-unaware routing: a Service in front of the pods, an HTTPRoute pointing at a Service instead of the InferencePool, a profile without prefix-cache-scorer, or passthrough-parser |
Route to the InferencePool; add the prefix scorer; check per-pod vllm:prefix_cache_hits_total |
| Precise routing behaves like round-robin | The router gets no KV events or cannot tokenize: wrong port or topic, render endpoint failing, block size mismatch | llm_d_epp_kv_cache_events_messages_received_total per pod, llm_d_epp_token_producer_render_failures_total; --block-size equal to blockSizeTokens (256 on v6e, 4352 for the TPU7x Qwen3.5 engines) |
| Index and pods disagree after a restart | Approximate index blind to evictions; precise router restarted and rebuilding from the replay window | Compare predicted cached tokens with the pods' hit rate; prefer pod-discovery mode with replay |
| One pod saturated, others idle | Affinity without a load gate on a hot shared prefix, or an uncalibrated peakPrefillThroughput |
Gate affinity on load (the optimized baseline's filter); calibrate peakPrefillThroughput for your model and TPU |
| EPP has no endpoints; requests fail or bypass routing | Misconfigured InferencePool: selector labels that no pod carries (the guides' pods carry llm-d.ai/model: Qwen-Qwen3-32B, not the Hugging Face id), wrong targetPorts, pool in another namespace, endpointPickerRef naming the wrong Service |
llm_d_epp_ready_endpoints; compare the selector with kubectl get pods --show-labels; the validator |
| Fail-open hides an EPP outage | failureMode: FailOpen forwards without routing while the EPP is down |
Alert on EPP health; choose FailClose unless availability outweighs affinity |
Pod stays Pending with no clear error |
Node selectors, chip count and machine type disagree | The GKE TPU table; google.com/tpu: 4 on tpu7x 2x2x1, 8 on tpu-v6e-slice 2x4 |
| Part of the slice idle | Engine TP × DP smaller than the slice's devices | Remember TPU7x has two devices per chip |
| TTFT regresses, decode healthy | KV transfer bottleneck or saturated prefill pool | Prefill utilization and TTFT together; if prefill is idle and TTFT high, suspect the connector; decode's vllm:external_prefix_cache_hits_total should grow by each prompt's length |
| Prefill pods count no requests | The EPP is not disaggregating: missing llm-d.ai/role labels, decider threshold never reached, or default nonCachedTokens: 0 with prefix-based-pd-decider |
llm_d_epp_disagg_decision_total by decision_type; the labels; the decider's parameters |
Decode requests end with kv_cache_preempted |
Decode pool out of KV under kv_load_failure_policy="fail" |
More decode replicas or TP; fp8 KV; abort_on_preemption: false to recompute instead |
| Connector fails to load at startup | Connector name or module from the user guide | TPURaidenConnector in vllm_torchtpu.distributed.kv_transfer.tpu_connector |
| SGLang decode pods reject requests | Conditional decider with SGLang | always-disagg-pd-decider |
| Multi-host engine errors on some requests | The pool selects headless LWS workers | Put the serving labels on the leader template only |
New pod Pending during a rollout |
Fixed-size TPU pools and a surge that needs a spare node | maxSurge: 0, or capacity for the surge |
Verifying the result¶
A deployment is working when the router resolves its pods, each request lands on a pod that already holds its prefix, the cache hits show up on both sides, and TTFT on a repeated-prefix workload falls against a cache-unaware baseline.
-
The path resolves.
kubectl get gateway llm-d-inference-gateway -n ${NAMESPACE}showsPROGRAMMED True;kubectl describe httprouteshows theReconciledcondition with reasonReconciliationSucceeded; the InferencePool's status reportsAcceptedandResolvedRefs. The EPP'sllm_d_epp_ready_endpointsgauge (port 9090,/metrics) equals the number of serving pods. Then send the guide's test request through the Gateway's address. -
Which pod served each request. The EPP communicates its choice to the proxy through the endpoint picker protocol, not to the client, so read it from metrics. On the router,
llm_d_epp_scheduler_attempts_totalcarriesendpoint_nameandstatuslabels, one series per pod. On the model servers, read each pod's counters through the API server proxy, as the precise-routing guide does:for pod in $(kubectl get pods -n ${NAMESPACE} -l llm-d.ai/inferenceServing=true -o jsonpath='{.items[*].metadata.name}'); do echo "== ${pod}" kubectl get --raw "/api/v1/namespaces/${NAMESPACE}/pods/${pod}:8000/proxy/metrics" \ | grep -E '^vllm:(prefix_cache_(hits|queries)_total|request_success_total)' doneSend ten requests that share a long prefix (the guide uses about 2,000 tokens and spaces them 3 s apart, past the 2-second speculative-index TTL). "One pod reports most of the 10 requests in
vllm:request_success_total, and itsvllm:prefix_cache_hits_totalis a large fraction ofvllm:prefix_cache_queries_total." If they spread evenly with low hit rates, the router is not using cache state. -
Cache hits agree on both sides. For the precise router, compare the share of prompt tokens it predicted cached,
llm_d_epp_prefix_predicted_cached_tokens_sum / llm_d_epp_prefix_prompt_tokens_sum, with the pods'vllm:prefix_cache_hits_total / vllm:prefix_cache_queries_total. "With a complete index the two track each other closely." If the pods' share is clearly higher, the index is missing blocks; if both are low, the workload shares little. For the approximate router,llm_d_epp_prefix_indexer_hit_ratiois its own view. The EPP'sllm_d_epp_request_cached_tokenshistogram records prompt tokens read from cache per request, and a client sees them inusage.prompt_tokens_details.cached_tokenswhen vLLM runs with--enable-prompt-tokens-details(chapter 19). -
TTFT falls on a repeated-prefix workload. Run chapter 19's agent client through the Gateway twice: once with this chapter's prefix-aware EPP config, once against a cache-unaware baseline (an EPP profile with only
queue-scorer, or a Service over the same pods):python code/ch19_sglang/agentic_client.py run --base-url http://${IP} --model Qwen/Qwen3-32B --json aware.json python code/ch19_sglang/agentic_client.py run --base-url http://${IP} --model Qwen/Qwen3-32B --vary-system-prompt --json control.jsonRun several copies at once so that the sessions spread over the replicas. Turns 2 and later should keep chapter 19's single-server gain: a high
cached_tokensfraction and a TTFT well below turn 1's. Against the baseline they lose it on most turns, as the simulation's 37.4 ms against 7.5 ms median shows in miniature. The--vary-system-promptrun is the control: with no shared prefix, prefix-aware and cache-unaware routing should measure the same, which proves the gain came from the cache. The EPP'sllm_d_epp_request_ttft_secondshistogram gives the same comparison from the router's side. -
Disaggregation is real. Send a few requests with a prompt of several thousand tokens (the v6e guide warns that "Prompts shorter than one KV block are recomputed on decode rather than transferred"). Then the prefill pods'
vllm:request_success_totalcounts them, the decode pods'vllm:external_prefix_cache_hits_total"grows by roughly the prompt length of each request", and the router'sllm_d_epp_disagg_decision_total{decision_type="prefill-decode"}increases. If prefill counts the requests but decode reports no external hits, the transfer failed and decode recomputed the prompt. -
The manifests match the slice. Before applying anything you changed, run
python code/ch20_llm_d/validate_manifests.py your-dir/, and after applying, confirm every model server pod isRunningon a node of the intended machine type.
Worked problems¶
Problem 1. A profile uses prefix-cache-scorer at weight 3 and queue-scorer at weight 2. A request's prompt is 40 blocks. Pod A holds 30 of them and has the longest queue (queue score 0). Pod B holds 10 and has a queue score of 0.5. Pod C holds none and is idle (queue score 1). Which pod wins? How many blocks must A hold before no queue length can move the request off it?
Answer
A: \(3 \times 30/40 + 2 \times 0 = 2.25\). B: \(3 \times 10/40 + 2 \times 0.5 = 1.75\). C: \(0 + 2 \times 1 = 2.0\). Pod A wins despite having the longest queue. The queue scorer can contribute at most 2, so A wins against any empty pod once \(3 \times m/40 > 2\), that is \(m > 26.7\): 27 blocks or more. test_prefix_two_thirds_beats_any_queue checks the same rule. This is why a hot shared prefix needs a load-gated affinity filter, not only weights.
Problem 2. A model server pod is restarted to load new weights. Describe what the approximate and the precise prefix indexes believe about that pod in the next minute, and what each does with a session whose history was on it.
Answer
The approximate index learns only from its own routing decisions, so it still believes the pod holds every prefix it sent there. It keeps routing the session to the pod, which now misses and prefills the whole history; the index is wrong until its entries age out or are overwritten. The precise index receives AllBlocksCleared and drops every entry for the pod, so the session scores zero there and the router picks on load (or on another pod that shares the system prompt). In scorer_sim.py's third scenario, the approximate router routes four requests on 3,840 tokens it believed cached; the precise router on none.
Problem 3. An EPP uses prefix-based-pd-decider with nonCachedTokens: 2048 over vLLM-TorchTPU prefill and decode pools. An agent's turn 1 sends a 9,000-token prompt; turn 2 sends 9,600 tokens, of which the first 9,200 are cached on the decode pod that served turn 1. What happens to each turn, and what changes if the pools run SGLang?
Answer
Turn 1: the decode profile picks a decode pod, which holds none of the prompt; 9,000 uncached tokens is at least 2,048, so the handler also runs the prefill profile, and the request is disaggregated (decision_type="prefill-decode"). Turn 2: if the decode profile picks the same pod (its prefix score favors it), only 400 tokens are uncached, below 2,048, so the decider returns decode-only and the decode engine prefills 400 tokens locally, with no transfer. With SGLang, decode workers cannot prefill locally and reject requests without bootstrap fields, so the deployment must use always-disagg-pd-decider, and turn 2 is disaggregated too. Leaving nonCachedTokens at its default of 0 would make every request decode-only.
Problem 4. Size the KV transfer for a 32,768-token prompt to Muse Glimmer 30B in bf16 (13 full-attention layers and 39 sliding-window layers of 2,048 tokens, 2 KV heads of 128 dimensions), and compare it with the prefill floor on one v7x device and with one chip's 100 Gb/s DCN. Repeat for 2,048 tokens. What does the comparison say about the decider's threshold?
Answer
Per token, each layer stores \(2 \times 2 \times 128 \times 2 = 1{,}024\) bytes. Full-attention layers keep every token: \(13 \times 1{,}024 \times 32{,}768 = 436.2\) MB. Window layers keep 2,048: \(39 \times 1{,}024 \times 2{,}048 = 81.8\) MB. Total 518 MB, which at 12.5 GB/s is 41 ms, against a prefill floor of about 1,641 ms (prefill_time in chapter 17's code): 2.5%. At 2,048 tokens, every layer holds all tokens: \(52 \times 1{,}024 \times 2{,}048 = 109\) MB, 8.7 ms against a 96 ms prefill: 9%, before adding a second scheduling decision and a round trip through the sidecar. The transfer's share grows as prompts shrink, which is why short or mostly cached prompts should stay on the decode pod.
Problem 5. A teammate's TPU7x model server stays Pending. Its pod has cloud.google.com/gke-tpu-accelerator: tpu7x, cloud.google.com/gke-tpu-topology: 2x2x1, google.com/tpu: "8" and runs vllm serve ... --tensor-parallel-size=4. Find both mistakes and write the fix.
Answer
A tpu7x-standard-4t host, the 2x2x1 topology, has 4 chips, so google.com/tpu: "8" can never be scheduled: set requests and limits to "4". Once it runs, the 4 chips are 8 devices on TPU7x, two per chip, so TP=4 leaves half the slice idle: use --tensor-parallel-size=8, or --data-parallel-size=8 --tensor-parallel-size=1 with --enable-expert-parallel for an MoE model. validate_manifests.py reports both: the chip count against the shape, and TP × DP × PCP against 8 devices.
Problem 6. You move the TPU7x model to a two-host 2x2x2 slice with a LeaderWorkerSet of size 2 running TP=16, and copy the pod labels llm-d.ai/inferenceServing: "true" and llm-d.ai/model into both the leader and the worker templates. Some requests fail. Explain why, and fix the InferencePool or the templates.
Answer
The worker runs vllm serve ... --headless: it is part of the engine but serves no HTTP. With the labels on both templates, the InferencePool selects both pods, and the EPP sends some requests to the worker's port 8000, where nothing listens. Put llm-d.ai/inferenceServing: "true" on the leader template only (as multihost-tpu7x/leaderworkerset.yaml does), so the pool has one endpoint per engine; the tiered-prefix-cache guide's note is the rule: on TPU multi-host only the leaders serve :8000. The validator rejects a pool that selects a --headless worker.
Quick questions¶
- Name the two parts of the llm-d router and say which one carries the request's bytes.
- Which three fields of an
InferencePoolmatter to the EPP, and which one does the gateway controller use? - What is the difference between Gateway mode and standalone mode, and which does GKE Inference Gateway use?
- Why is the
EndpointPickerConfignot a Kubernetes resource, and what does that mean for changing it? - Why does the prefix-cache scorer count only the longest consecutive prefix of blocks?
- What can the precise prefix index see that the approximate one cannot, and what does it need from the model servers and from vLLM to see it?
- Why do the TPU v6e and TPU7x configurations change the block size, and what else must change with it?
- In which order does
disagg-profile-handlerrun its profiles, and what decides whether the second one runs? - What does the decode pod's routing sidecar do differently for vLLM and SGLang?
- Name the TPU KV connector the TPU7x P/D overlay uses for transfer, the one it uses for host offload, and the correct module of the first.
- What does a DisaggregatedSet add on top of two LeaderWorkerSets?
- Which three values in a TPU pod must agree with the node's machine type, and what must the engine's parallelism equal?
Key takeaways¶
- llm-d puts one router, one KV cache index and one flow-control policy in front of a fleet of unmodified engines. The proxy (a GKE Gateway in Gateway mode) carries requests; the EPP, called over ext-proc, picks the pod. An HTTPRoute names the InferencePool, whose label selector, target ports and
endpointPickerRefdefine the candidates and the EPP. - The EPP filters, scores each endpoint in [0, 1], and picks the highest weighted sum. Weights encode trade-offs: with prefix 3 and queue 2, affinity always wins past two thirds of a prompt, so a hot shared prefix needs a load-gated affinity filter, as in the optimized baseline.
- Prefix-aware routing keeps a session where its KV cache is. The approximate index learns from its own decisions; the precise index is built from the engines' KV events and exact tokens from vLLM's render endpoint, and sees evictions and resets. On TPU, router blocks must equal the engine's (
--block-size256 on v6e, 4352 for the TPU7x Qwen3.5 engines) andPYTHONHASHSEED=0must be set wherever hashes are shared. - P/D disaggregation pays for long prompts, larger models and MoE. The EPP picks the decode pod first, a decider chooses whether to prefill remotely, and the decode pod's sidecar runs the engine's protocol. On TPU7x, KV moves over TPU Sync with
TPURaidenConnector(invllm_torchtpu.distributed.kv_transfer.tpu_connector, not the guide'sTpuRaidenConnector), resharding PCP=8 into DP=8; moving a prompt's KV costs a few percent of computing it. - KV offloading extends how long a prefix stays reusable: HBM, then host DRAM (
TPURaidenOffloadingConnector, 32 GiB per TPU7x engine), then a shared filesystem such as Managed Lustre, with the router scoring CPU-tier hits at 0.8. Wide-EP runs attention data-parallel and experts expert-parallel, and routes per DP rank. - LeaderWorkerSet runs a multi-host slice as one unit with leader-only serving; DisaggregatedSet rolls prefill and decode LeaderWorkerSets out together. A TPU pod's accelerator, topology and chip count must match the machine type, and TP × DP must equal the slice's devices (two per TPU7x chip).
- Trust a deployment when the pool resolves,
vllm:request_success_totalandllm_d_epp_scheduler_attempts_totalshow requests landing on the pod with their prefix, the router's predicted cache share tracks the pods' hit rate, P/D decisions and external prefix-cache hits appear on the right pods, and TTFT on a repeated-prefix workload falls against a cache-unaware baseline and not in a varied-prompt control.
References¶
- Announcing llm-d 1.0: Open distributed inference for agents on Google Cloud TPUs and GPUs: the shift to agents, GKE Inference Gateway and the published results
- llm-d: Architecture: the seven areas and the well-lit paths
- llm-d Router: proxy and EPP
- llm-d: Proxy: ext-proc, Gateway and standalone modes, the HTTPRoute example
- llm-d: Endpoint Picker (EPP): the EPP and its body mode
- llm-d: InferencePool: selector-based discovery and the failure mode
- llm-d: Request Handler: request parsers and flow control
- llm-d: Request Scheduler: filters, scorers, pickers and profile handlers
- llm-d: Configuration: the recommended profile and producer parameters
- llm-d: Data Layer: endpoint discovery and metric scraping
- llm-d: Disaggregated Serving: the decider, role labels and the routing sidecar
- llm-d: Wide Expert Parallelism: DP attention with EP and DP-aware routing
- llm-d: Prefix-Cache Aware Routing: approximate and precise implementations
- llm-d: KV-Cache Indexer: KV events, index backends and speculative indexing
- llm-d: KV-Cache Offloading: offloading tiers and guidance
- llm-d: P2P KV-Cache Sharing: experimental peer sharing
- vLLM in llm-d: pod labels, metrics and KV events for vLLM
- SGLang in llm-d: SGLang labels and decode workers without local prefill
- llm-d: LeaderWorkerSet (LWS): templates, restart policy and injected variables
- llm-d: DisaggregatedSet: roles as child LeaderWorkerSets and coordinated rollouts
- llm-d: Autoscaling: autoscaling overview
- llm-d: Batch Inference: Batch Gateway and Async Processor overview
- llm-d: Quickstart: the standalone quickstart and the token Secret
- llm-d: Google Cloud TPU: chips, devices and slices; machine types; deployment settings
- llm-d: GKE Gateway: CRD versions, gateway classes and the Helm install
- llm-d: Deploy an Optimized Baseline: the affinity filter, token-load scorer and calibration
- llm-d: Enable Precise Prefix-Cache Aware Routing: TPU block sizes and verification commands
- llm-d: Configure a Tiered Prefix Cache: TPU host and filesystem tiers
- llm-d: Deploy Prefill/Decode Disaggregation: TPU connectors, overlays and verification
- llm-d: Scale MoE Models with Wide Expert Parallelism
- llm-d: Qwen3.5-397B: the TPU7x configurations and the note on earlier results
- llm-d: InferencePool
- llm-d: InferenceObjective
- llm-d: EPP HTTP Headers Reference
- llm-d: Artifacts: chart and image names
- llm-d: Disaggregated Serving: Operations (SGLang): deciders and
nonCachedTokens - llm-d: Safe Rollouts of Disaggregated Deployments with DisaggregatedSet: native sidecar and drain settings
- Disaggregated Serving (Prefill / Decode): Raiden controller, producer and consumer, resharding and the decode error contract
- Multi-Host Serving: the multi-host launch
- vllm-torchtpu repository:
tpu_connector.py,tpu_multi_connector.py,raiden_connector.pyand the scripts inexamples/disagg/ - vLLM and SGLang on TPU: Production Serving with llm-d 1.0: TPU Sync,
TPUMultiConnectorand llm-d on GKE in practice sample_02_vllm_sglang_agentic_serving_and_raiden.py: a GKE manifest generator and validator for llm-d on TPU- Companion code for this chapter

![An architecture read from the top. An amber Proxy box at the top left and a blue Model server pods box at the top right, joined by an arrow labelled forward the request. Below them an amber dashed container labelled EPP. From the Proxy an arrow labelled ext-proc runs down into the first stage, Request handler, Parse. An arrow runs right to Flow control, If enabled, and another into Filters, the first box of a dashed container labelled Scheduler, which holds Filters, Scorers and Picker joined left to right, with the note Each score in [0, 1]; total = weighted sum. From Picker an arrow labelled selected endpoint runs up and back to the Proxy. Below the stages a wide amber Data layer box reads Pods, metrics, prefix index; dashed arrows run up from it into Flow control and into the Scheduler. A dashed arrow labelled scrape metrics runs from Model server pods down the right margin into the Data layer, and a dashed arrow labelled watch pods runs up from a grey Kubernetes API box at the bottom left. A legend reads: solid arrow, Request path; dashed arrow, Asynchronous state.](../../../assets/ch20/epp-stages.png)






