Pidoku

Prefix-Aware Routing

Module 21 Lesson 21.h 1h Difficulty 4/5

Prerequisites 12.m, 17.f, 20.f, 21.g


Before you start: words you need#

WordPlain meaning
Prefix cacheA replica’s store of KV cache for prompt beginnings it has already computed, so a later prompt that starts the same way skips that prefill (12.m, 17.f). It lives on one replica only.
Hit rateThe share of prompt tokens that were already in the chosen replica’s cache.
Block hashThe cache is kept in fixed-size blocks of tokens (12.l); each block is named by a hash of its tokens and of every block before it. Two prompts share a cached block only if everything up to it is identical.
KV eventsMessages a replica publishes when it stores or evicts cache blocks, so a router can keep an exact picture of what each replica holds.
AffinityPreferring the replica that already holds a request’s prefix, even if another is less busy.
Release valveThe rule that breaks affinity when the preferred replica is too busy.
TTFTTime to first token: queueing plus prefill. Prefix hits shorten the prefill part.

1. What is it?#

Prefix caching (12.m) only helps if the request lands on the replica that holds its prefix. With N replicas and routing that ignores the cache, a conversation’s next turn finds its history on the right replica about 1 time in N. Prefix-aware routing is the router logic that sends a request to where its cache already is, without piling everything onto one replica.

20.f introduced the idea and the simplest form, hashing a conversation id to a home replica with a release valve. This lesson owns the rest: how a router knows what each replica holds (guessing, or listening to KV events), how it weighs a cache hit against load, what goes wrong when it trusts the cache too much, and when the whole thing is not worth building.

Facts checked on 13 November 2026: llm-d Router v1.0.0, NVIDIA Dynamo 1.6.2, SGLang Model Gateway (SGLang v0.5.23), vLLM v0.32.0.

flowchart LR
  R["Request"] --> T["Tokenise, hash blocks"]
  T --> L["Look up: which replicas<br/>hold these blocks?"]
  IDX[("Cache index<br/>guessed or from KV events")] -.-> L
  L --> S["Score each replica:<br/>cache hit vs queue and KV load"]
  S --> P{"Best replica<br/>too busy?"}
  P -->|"no"| A["Route to it<br/>cache hit, short prefill"]
  P -->|"yes"| B["Release valve:<br/>a less-loaded replica"]
  A -.->|"KV events or<br/>routing record"| IDX
  B -.-> IDX

  class R,T neutral
  class L,S,P queue
  class IDX memory
  class A,B compute

2. Why does it matter?#

Prefill is paid per uncached token. Take a chat turn with a 1,500-token system prompt, 2,000 tokens of history and a 200-token new message:

nothing cached                 prefill 3,700 tokens
system prompt cached only      prefill 2,200 tokens
whole history cached           prefill   200 tokens      18x less prefill than nothing cached

Without the history in cache, turn k of a conversation re-prefills all earlier turns, so total prefill work grows with the square of the conversation length. Agents, which run tens of turns with large tool lists, are the extreme case.

The saving shows up twice: in TTFT (a short prefill starts streaming sooner) and in capacity (prefill work you do not do is GPU time other requests can use).


3. Simple analogy#

A hospital with eight doctors. Each doctor keeps notes on the patients they have seen. Send a returning patient to their own doctor and the visit takes five minutes; send them to a stranger and the history must be taken again. But if one doctor is famous and everyone insists on seeing them, the waiting room overflows while seven doctors sit idle. A good receptionist sends you to your own doctor unless the queue there is longer than the time a new doctor would take to catch up.


4. Tiny example: the simulation’s answer#

Section 6 simulates 8 replicas serving 200 live conversations (8 turns each, sharing 20 system prompts of very unequal popularity) at 80 requests per second:

random                   hit  50%   TTFT p50  161 ms   p99   849 ms
least loaded (w=0)       hit  50%   TTFT p50   80 ms   p99   211 ms
session affinity         hit  92%   TTFT p50   10 ms   p99    85 ms
score w=0.5              hit  88%   TTFT p50   10 ms   p99   132 ms
score w=1 (est. TTFT)    hit  88%   TTFT p50   10 ms   p99   132 ms
score w=4                hit  85%   TTFT p50   11 ms   p99   198 ms
pure affinity (w=1000)   hit  83%   TTFT p50   56 ms   p99 71472 ms
  • Even random routing hits 50%: the 20 system prompts are small enough to sit in every replica’s cache. Shared prefixes that fit everywhere need no routing. Per-conversation history is what needs routing.
  • Any cache awareness cuts the median TTFT by 8–16x and the p99 by 2–10x against plain load balancing.
  • Over-trusting the cache destroys the tail. With w = 1000 the router will queue a request for 70 seconds to save 75 ms of prefill.

5. Technical explanation#

Three ways to know what a replica holds#

VIEW            HOW THE ROUTER KNOWS                       EXAMPLES (Nov 2026)
none            hash a session or conversation id          20.f; Envoy ring hash on a header
                to a home replica

approximate     remember where it sent each prompt,        SGLang Model Gateway cache_aware
                assume it is still cached for a while      (a radix tree of prompt text per
                (TTL or LRU)                               worker); llm-d approx-prefix-cache-
                                                           producer; Dynamo --no-router-kv-events
                                                           (block TTL 120 s by default)

precise         replicas publish KV events (block          llm-d precise-prefix-cache-producer
                stored / removed); the router keeps an     (ZMQ events from vLLM or SGLang);
                index of block hash → replicas             Dynamo KV router with KV events
  • No view costs nothing and captures most of the value for chat, where every turn of one conversation shares its history. It cannot help different conversations that share a long document or tool list.
  • Approximate needs no cooperation from the engine and works with any engine. It is wrong when the replica evicts early, restarts, or when another router instance sent the request. SGLang’s docs say plainly that its tree is not synchronised across gateway replicas.
  • Precise is right about eviction, but the router must reproduce the engine’s block hashes from token IDs. That means tokenising in the router, using the same block size, and using a hash other languages can compute: vLLM’s --prefix-caching-hash-algo sha256_cbor, not the default sha256 over Python pickle (19.b). Per-tenant cache_salt (21.f) changes the hashes too, so the router must know the salt.

Scoring: a hit is worth time, a queue costs time#

Every serious router combines the two in one score. The open ones, as configured today:

llm-d Router (EPP)  filters, then weighted scorers summed, highest wins:
                    prefix-cache-scorer, kv-cache-utilization, queue-depth,
                    session-affinity, lora-affinity, ... each with a weight
                    (default 1.0); the utilization-detector filter drops
                    saturated pods unless that would drop them all (21.g)

Dynamo KV router    lowest cost wins:
                    prefill_load_scale × max(0, prefill blocks already queued on the worker
                                               + this prompt's blocks − cached-block credit)
                    + potential decode blocks
                    (+ decode_active_request_weight × active requests, experimental)
                    cached-block credit: overlap_score_credit (1.0) per GPU block,
                    0.75 per CPU-tier block, 0.25 per disk-tier block (defaults)
                    router_temperature 0 = always the lowest; > 0 = softmax sampling

SGLang gateway      if load is imbalanced (max − min > 64 requests AND max > 1.5 × min):
cache_aware         shortest queue; else the best prefix match if it covers > 30% of the
                    prompt; else the worker with the smallest tree (most free cache)

The cleanest way to think about the weight is in seconds. Estimated TTFT on a replica is roughly its queue wait plus the time to prefill the tokens it does not hold:

score(r) = wait(r) + w × uncached_tokens(r) / prefill_speed

With w = 1 the router picks the replica with the lowest estimated TTFT. w > 1 overvalues cache hits; w < 1 undervalues them. Tune w (or the equivalent weights) on measured p50 and p99 TTFT, never on hit rate: in section 4, pure affinity has a hit rate close to the best policy and a p99 nearly 1,000 times worse.

Why greedy scoring can lose to a plain session hash#

In the simulation, session affinity beats the w = 1 score. The score is greedy: it moves a conversation whenever another replica looks faster for this turn, which costs every later turn its history. A conversation hash keeps conversations put and, with many similar conversations, spreads load evenly by itself. That breaks down when sessions are very unequal (one agent with a 200k-token context), which is when the scored router and its release valve earn their keep. Dynamo’s overlap_score_credit_decay and the llm-d session-affinity scorer exist for exactly this middle ground.

Races: siblings that arrive together#

A precise index learns about a prefix only after the engine has stored it. If 16 requests with the same new prefix arrive in the same 50 ms (best-of-N sampling, a fan-out agent), every one sees zero overlap and they spread across the fleet, each prefilling the same prefix. Both open routers fix this by also recording their own decisions for a few seconds:

  • Dynamo: --router-predicted-ttl-secs keeps a short-TTL side index of routing decisions alongside the event-driven one and takes the larger overlap.
  • llm-d: speculativeIndexing on the precise producer seeds predicted entries for 2 s by default.

Churn: adding and removing replicas#

If the home replica is hash(id) mod N, changing N moves almost every conversation and throws away its cache. Consistent hashing moves only about 1/N (20.f). The program below measures it. Also drain before removing a replica, so in-flight conversations finish where their cache is (21.c, 23.d).

Go
// ring.go — consistent hashing: adding a replica moves only ~1/N of the keys.
package main

import (
	"fmt"
	"hash/fnv"
	"sort"
)

func hash(s string) uint64 {
	h := fnv.New64a()
	h.Write([]byte(s))
	x := h.Sum64() // FNV alone clusters on similar strings; mix the bits
	x ^= x >> 33
	x *= 0xff51afd7ed558ccd
	x ^= x >> 33
	return x
}

type Ring struct {
	points []uint64
	owner  map[uint64]string
}

func NewRing(replicas []string, vnodes int) *Ring {
	r := &Ring{owner: map[uint64]string{}}
	for _, rep := range replicas {
		for i := 0; i < vnodes; i++ { // many points per replica smooth out the load
			p := hash(fmt.Sprintf("%s:%d", rep, i))
			r.points, r.owner[p] = append(r.points, p), rep
		}
	}
	sort.Slice(r.points, func(a, b int) bool { return r.points[a] < r.points[b] })
	return r
}

// Get returns the first replica clockwise from the key's position on the ring.
func (r *Ring) Get(key string) string {
	h := hash(key)
	i := sort.Search(len(r.points), func(i int) bool { return r.points[i] >= h }) % len(r.points)
	return r.owner[r.points[i]]
}

func main() {
	before := NewRing([]string{"r1", "r2", "r3", "r4"}, 150)
	after := NewRing([]string{"r1", "r2", "r3", "r4", "r5"}, 150)
	ringMoved, modMoved := 0, 0
	for i := 0; i < 10000; i++ {
		key := fmt.Sprint("conversation-", i)
		if before.Get(key) != after.Get(key) {
			ringMoved++
		}
		if hash(key)%4 != hash(key)%5 { // the naive way: hash(key) mod N
			modMoved++
		}
	}
	fmt.Printf("adding a 5th replica, consistent hashing: %.1f%% of conversations moved (ideal 20%%)\n",
		float64(ringMoved)/100)
	fmt.Printf("adding a 5th replica, hash mod N:         %.1f%% of conversations moved\n",
		float64(modMoved)/100)
}

Output:

adding a 5th replica, consistent hashing: 22.9% of conversations moved (ideal 20%)
adding a 5th replica, hash mod N:         80.2% of conversations moved

Precise and approximate views do not need a ring: a new replica simply has no cached blocks, scores low on cache and high on free capacity, and fills up.

Warming new replicas#

A new replica’s cache is empty, so its first requests prefill in full. Three options: ramp its traffic over a few minutes; replay the known-popular prefixes (system prompts, tool lists) before marking it ready; or accept a few seconds of misses. Ramping is usually enough and matches the gradual traffic return after a failure (23.f).


6. Under the hood: simulating the trade-off#

Each replica prefills one prompt at a time (the same simplification as 21.g) and keeps an LRU cache of prefixes up to 150,000 tokens. A request’s uncached tokens decide its prefill time; queueing decides the rest. The router sees the cache exactly, so this is the precise view at its best.

Go
// prefixroute.go — what does prefix-aware routing buy, and what does pure affinity cost?
// 8 replicas, each prefills one prompt at a time and keeps an LRU prefix cache.
// Chat traffic: 20 shared system prompts (some far more popular than others) and
// multi-turn conversations whose history grows every turn.
package main

import (
	"container/list"
	"fmt"
	"math"
	"math/rand/v2"
	"slices"
)

const (
	replicas     = 8
	tokensPerSec = 20000.0 // prefill speed of one replica
	cacheTokens  = 150000  // prefix-cache room per replica, in tokens
	sysTokens    = 1500    // each system prompt
	turnTokens   = 350     // user message + answer added to the history per turn
	newMsg       = 200     // the new user message
	ratePerSec   = 80.0    // arrivals across the fleet
	liveConvs    = 200     // conversations under way at any moment
	requests     = 100000
)

// ---------- a replica: a prefill queue and an LRU of cached prefixes ----------

type entry struct {
	key    string
	tokens int
}

type replica struct {
	freeAt float64
	used   int
	lru    *list.List // front = most recent
	index  map[string]*list.Element
}

func newReplica() *replica { return &replica{lru: list.New(), index: map[string]*list.Element{}} }

func (r *replica) cached(key string) int {
	if e, ok := r.index[key]; ok {
		return e.Value.(*entry).tokens
	}
	return 0
}

func (r *replica) put(key string, tokens int) {
	if e, ok := r.index[key]; ok {
		r.used -= e.Value.(*entry).tokens
		r.lru.Remove(e)
	}
	r.index[key] = r.lru.PushFront(&entry{key, tokens})
	r.used += tokens
	for r.used > cacheTokens { // evict least recently used prefixes
		e := r.lru.Back()
		r.used -= e.Value.(*entry).tokens
		delete(r.index, e.Value.(*entry).key)
		r.lru.Remove(e)
	}
}

// ---------- requests ----------

type request struct {
	conv, sys int
	history   int // tokens of earlier turns, after the system prompt
}

func (q request) promptTokens() int { return sysTokens + q.history + newMsg }
func (q request) convKey() string   { return fmt.Sprint("conv:", q.conv) }
func (q request) sysKey() string    { return fmt.Sprint("sys:", q.sys) }

// hit returns how many leading tokens of q replica r already holds.
func hit(r *replica, q request) int {
	if q.history > 0 {
		if c := r.cached(q.convKey()); c >= sysTokens+q.history {
			return sysTokens + q.history // the whole conversation so far
		}
	}
	return r.cached(q.sysKey()) // at least the shared system prompt?
}

// ---------- routing policies ----------

type policy func(rs []*replica, q request, now float64, rng *rand.Rand) *replica

func wait(r *replica, now float64) float64 { return math.Max(0, r.freeAt-now) }

func random(rs []*replica, _ request, _ float64, rng *rand.Rand) *replica {
	return rs[rng.IntN(len(rs))]
}

func leastLoaded(rs []*replica, _ request, now float64, _ *rand.Rand) *replica {
	best := rs[0]
	for _, r := range rs[1:] {
		if wait(r, now) < wait(best, now) {
			best = r
		}
	}
	return best
}

// sessionAffinity: same conversation → same replica, unless that replica is more than
// valve seconds behind (the release valve); then the least-loaded replica.
func sessionAffinity(valve float64) policy {
	return func(rs []*replica, q request, now float64, rng *rand.Rand) *replica {
		r := rs[(uint64(q.conv)*0x9e3779b97f4a7c15)>>61] // hash of the id → 0..7 (fixed fleet)
		if wait(r, now) > valve {
			return leastLoaded(rs, q, now, rng)
		}
		return r
	}
}

// scored(w): minimise  queue wait + w × (time to prefill the uncached tokens).
// w = 0 ignores the cache; w = 1 is the replica's estimated TTFT; large w is near-pure affinity.
func scored(w float64) policy {
	return func(rs []*replica, q request, now float64, _ *rand.Rand) *replica {
		var best *replica
		bestScore := math.Inf(1)
		for _, r := range rs {
			s := wait(r, now) + w*float64(q.promptTokens()-hit(r, q))/tokensPerSec
			if s < bestScore {
				best, bestScore = r, s
			}
		}
		return best
	}
}

// ---------- the simulation ----------

func pct(xs []float64, p float64) float64 {
	slices.Sort(xs)
	return xs[int(p*float64(len(xs)-1))]
}

func run(name string, route policy) {
	rng := rand.New(rand.NewPCG(7, 11))
	rs := make([]*replica, replicas)
	for i := range rs {
		rs[i] = newReplica()
	}
	zipf := rand.NewZipf(rand.New(rand.NewPCG(1, 2)), 1.2, 1, 19) // system prompt popularity
	// conversations under way; each request is the next turn of one of them
	active := make([]request, liveConvs)
	for i := range active {
		active[i] = request{conv: i, sys: int(zipf.Uint64())}
	}
	nextConv, clock := liveConvs, 0.0
	var ttft []float64
	var hitTok, promptTok float64
	for i := 0; i < requests; i++ {
		clock += -math.Log(1-rng.Float64()) / ratePerSec
		j := rng.IntN(len(active))
		q := active[j]
		r := route(rs, q, clock, rng)
		h := hit(r, q)
		start := math.Max(clock, r.freeAt)
		r.freeAt = start + float64(q.promptTokens()-h)/tokensPerSec
		ttft = append(ttft, (r.freeAt-clock)*1000)
		hitTok += float64(h)
		promptTok += float64(q.promptTokens())
		r.put(q.sysKey(), sysTokens)
		r.put(q.convKey(), q.promptTokens()+turnTokens-newMsg) // prompt + the answer
		if q.history/turnTokens < 7 {                          // 8 turns, then a new conversation takes its place
			active[j].history += turnTokens
		} else {
			active[j] = request{conv: nextConv, sys: int(zipf.Uint64())}
			nextConv++
		}
	}
	fmt.Printf("%-24s hit %3.0f%%   TTFT p50 %4.0f ms   p99 %5.0f ms\n",
		name, 100*hitTok/promptTok, pct(ttft, 0.5), pct(ttft, 0.99))
}

func main() {
	run("random", random)
	run("least loaded (w=0)", scored(0))
	run("session affinity", sessionAffinity(0.5))
	run("score w=0.5", scored(0.5))
	run("score w=1 (est. TTFT)", scored(1))
	run("score w=4", scored(4))
	run("pure affinity (w=1000)", scored(1000))
}

Output:

random                   hit  50%   TTFT p50  161 ms   p99   849 ms
least loaded (w=0)       hit  50%   TTFT p50   80 ms   p99   211 ms
session affinity         hit  92%   TTFT p50   10 ms   p99    85 ms
score w=0.5              hit  88%   TTFT p50   10 ms   p99   132 ms
score w=1 (est. TTFT)    hit  88%   TTFT p50   10 ms   p99   132 ms
score w=4                hit  85%   TTFT p50   11 ms   p99   198 ms
pure affinity (w=1000)   hit  83%   TTFT p50   56 ms   p99 71472 ms

Why pure affinity collapses: rare system prompts are evicted from most replicas, so the one replica that still holds a rare prompt wins every new conversation that uses it, whatever its queue. Saving 1,500 tokens (75 ms) outweighs any wait. That replica’s queue grows, its LRU churns, and its hit rate falls too. Affinity overloads both the GPU and the cache of the favoured replica.

The model leaves out decode, chunked prefill (12.k) and stale metrics. Those change the numbers, not the shape: a little cache awareness is a large win, and too much is a disaster.


7. Performance implications#

Estimate the value before building anything beyond session affinity:

capacity gain ≈ prefill share of GPU time
              × (hit rate you could reach − hit rate you have now)

Example A: chat, prefill 30% of GPU time, hit rate 50% → 90%:
           0.30 × 0.40 = 12% capacity, plus a large TTFT win.   Worth it.

Example B: batch summarisation of unique documents, prefill 60%, hit rate 2% → 4%:
           0.60 × 0.02 = 1.2%.                                   Not worth it.

Measure both inputs: the prefill share from a profile (22.h) or the engine’s metrics, and the reachable hit rate by replaying a trace against one large simulated cache.

Other costs to keep in view:

  • Tokenising in the router. Precise routing needs token IDs. Tokenise once, at the gateway or router, and forward the IDs (21.i); llm-d’s token-producer and SGLang’s gRPC mode do this.
  • Index size. A precise index holds an entry per block per replica. KV events arrive far more often than requests; llm-d leaves tracing of them off by default for that reason.
  • When it does not help: unique prompts; short prompts (a few hundred tokens: the hit saves less than the imbalance costs); two or three replicas (chance already gives a third to a half); decode-dominated work.

8. Production implications#

  • Start with session affinity and a release valve (20.f); it is a configuration change.
  • Adopt a precise router when prompts share long prefixes across conversations (agents with shared tool lists, RAG over the same documents). Use the llm-d Router, Dynamo’s KV router or the SGLang gateway rather than writing one (21.j).
  • Pin the hash algorithm and block size across engines and router (sha256_cbor in vLLM), and treat changing them as a breaking change.
  • Run several router replicas? Approximate views diverge between them; precise views fed by the same events agree.
  • Make hit rate a first-class metric per model and tenant (vllm:prefix_cache_hits and vllm:prefix_cache_queries, 19.c), and alert on drops. A drop usually means a prompt change, not a router bug.
  • Protect prompt structure. A timestamp or user name at the start of a system prompt makes every prompt unique and the hit rate collapses (12.m). Put dynamic content last.

9. Common mistakes#

  1. Prefix caching on, routing unaware of it. Hit rate near 1/N for history.
  2. Affinity with no release valve. One favoured replica, a p99 measured in minutes.
  3. Tuning on hit rate instead of TTFT p50 and p99.
  4. hash(id) mod N. Every scale event throws away most caches.
  5. A router that cannot reproduce the engine’s block hashes: wrong block size, Python-pickle hashing, or a missing cache_salt. The index never matches, silently.
  6. Ignoring the sibling race. Fan-out requests prefill the same prefix on every replica.
  7. Building a precise index when session affinity would do.
  8. Not noticing when a product change breaks cache-friendliness.

10. Hands-on exercise#

  1. Run prefixroute.go. Change ratePerSec to 60 and 100. At which load does the gap between least loaded and session affinity grow fastest, and why?
  2. Find the best weight. Sweep w from 0.25 to 8. Plot p50 and p99. Is the best p99 at w = 1?
  3. Break session affinity. Make one conversation an agent that sends 10% of all requests with a 50,000-token history. Compare session affinity with and without the 0.5 s release valve, and with scored(1).
  4. Add staleness. Let the router see each replica’s cache as it was 2 seconds ago. How much of the gain survives?
  5. Measure the real inputs. From a request log, compute the share of prompt tokens that repeat a prefix seen in the last 10 minutes, and the prefill share of GPU time. Apply section 7’s formula.
  6. Break it on purpose. Put a timestamp at the front of the system prompt and watch vllm:prefix_cache_hits fall. This is the demo to show your product team.

11. Interview questions#

  1. Why does prefix caching need prefix-aware routing, and what hit rate do you get without it?
  2. Compare session hashing, approximate and precise cache views. What can each get wrong?
  3. What does a router need to reproduce an engine’s block hashes?
  4. How do you weigh a cache hit against queue length? Express it in seconds.
  5. Why must you tune on TTFT and not on hit rate?
  6. What is the sibling race, and how do Dynamo and llm-d deal with it?
  7. When is prefix-aware routing not worth building?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in