Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Agent | A program that calls a model in a loop: the model asks for a tool, the program runs it, appends the result, and calls the model again until the task is done. |
| Turn | One model call inside that loop. A coding task can take dozens. |
| Session | All the turns of one task, which share a growing context. |
| Prefix cache hit | The start of a prompt matches KV already in memory, so those tokens are not recomputed (17.f). |
| TTL | Time to live: how long a cached entry is kept after its last use before it may be dropped. |
| Sticky routing | Sending every request of a session to the same replica, where its KV already is. |
| Compaction | Replacing a long history with a shorter summary to keep the context small. |
| Subagent | A second agent started by the first one for a sub-task, with its own context. |
1. What is it?#
An agent does not send one request. It sends a chain of them, and each one contains everything that came before:
turn 1 [system + tools][user task] → tool call A
turn 2 [system + tools][user task][call A][result A] → tool call B
turn 3 [system + tools][user task][call A][result A][call B][result B] → ...
└──────────────── identical to the previous prompt ───────────┘ + new tokensThe context only grows at the end. So almost every token of turn N’s prompt was already in turn N−1’s prompt, and its KV cache already exists somewhere, if the server kept it and the request is sent back to where it lives.
Real traces show how extreme this is. SemiAnalysis’s AgentX traces of agentic coding, as reported by the vLLM team, have a median of 43 turns per session, median input of 142k tokens, median output of only 444 tokens, and a prefix-cache hit rate above 96%; 44% of sessions start at least one subagent. Facts checked on 13 November 2026.
This lesson is about serving that shape: what it costs, what breaks the reuse, and how routing and retention keep it. How a prefix cache works inside vLLM is 17.f; the keep-park-or-recompute choice during a single tool pause is worked through in 24.h.
2. Why does it matter?#
Because without reuse, an agent’s cost grows with the square of its length. Turn N prefills N turns’ worth of history; summed over the session, that is about N²/2 turns of prefill. With reuse, each turn prefills only what is new.
For the session in section 4, that is the difference between 3.2 million and 0.13 million prefilled tokens: 24 times less GPU work, and the difference between a 7-second and a sub-second time to first token on the last turn. Agents are the fastest-growing workload in 2026, so for many platforms the cache hit rate is now the single number that most affects both cost and latency.
3. Simple analogy#
A lawyer on a long case takes forty phone calls from a client. Before each call they must know the whole case file.
- No cache: they reread the entire file before every call. By call forty, that takes hours.
- Cache: they keep the file open on their desk and read only the new pages.
- TTL expiry: if the client takes too long to call back, the clerk tidies the desk and the file goes back to the archive. Next call starts with a full reread.
- Wrong office (no sticky routing): the call is put through to a colleague who has never seen the file.
4. Tiny example: one 40-turn session, four outcomes#
The session starts with 13,000 tokens (system prompt, tool definitions, task). Each turn the model writes 400 tokens and a tool appends 3,000. Prices are illustrative list prices ($3 per million input, $15 per million output, cache writes at 1.25 times and reads at 0.1 times the input price). Prefill runs at 20,000 tokens per second.
scenario prefilled reused hit rate $/session prefill GPU-s
no prefix cache 3172000 0 0.0% 9.76 158.6
cache, never expires 130000 3042000 95.9% 1.64 6.5
cache, miss every 8th turn 571000 2601000 82.0% 3.16 28.6
cache + compact at 100k 160000 2054400 92.8% 1.46 8.0
context at the last turn: 145600 tokens; a cold last turn needs 7.3 s of prefill- The perfectly cached session lands at a 96% hit rate and a 146k-token final context: close to the AgentX medians, which is why those traces look the way they do.
- Losing the cache on only one turn in eight (a slow tool outliving the TTL, a re-route, an eviction) doubles the bill and quadruples prefill work.
- Compaction resets the prefix once, so that turn is a full miss, but every later turn is cheaper. Here it wins slightly; with a larger summary or earlier compaction it can lose.
5. Technical explanation#
What breaks the prefix#
A cache hit needs the new prompt to be byte-identical (after tokenization) to an earlier one up to some point. Anything that changes an early token throws away everything after it:
| Change | Where it bites | Fix |
|---|---|---|
| A timestamp, request ID or random example in the system prompt | Turn 1 onward: no hit ever | Move volatile values to the end, or into the newest message |
| Tool definitions reordered or regenerated (for example an MCP server returning tools in a different order) | Every turn | Sort tools deterministically; pin the tool list per session |
| Editing or truncating an earlier message (“context editing”, dropping old tool results) | From the edit onward | Edit rarely, in bulk, and accept one miss |
| A chat template that renders past turns differently from how they were generated (some open-model templates drop earlier turns’ reasoning when rendering history) | From the last assistant message onward, every turn | Know your template; keep or strip reasoning consistently (18.i) |
| Changing effort or thinking settings mid-session (27.a) | Usually the whole conversation | Hold settings per session |
| Compaction | One full miss | Compact rarely and early enough that the summary is reused many times |
This is why agent frameworks put the stable parts first (system prompt, tools), the history next, and anything volatile last. The ordering is a performance contract between the application and the serving layer.
Three places the KV can live#
| Layer | Who keeps it | Lifetime | You control |
|---|---|---|---|
| Provider prompt cache | The API provider | Anthropic: 5 minutes by default or 1 hour, refreshed on each hit. OpenAI: older models in_memory (about 5–10 minutes idle, up to an hour) or 24h; GPT-5.6 and later prompt_cache_options.ttl of 30m (default) or 12h | Breakpoints or retention settings, and the order of your content |
| Engine prefix cache | Your vLLM or SGLang replica, in GPU memory | No TTL: freed blocks stay reusable until the pool needs them, least-recently-used first (17.f) | Pool size, routing, eviction pressure |
| Offload tiers | CPU memory, local SSD, or a shared KV store such as Mooncake or LMCache (14.k, 14.l) | Minutes to hours | Tier sizes, connector, retention policy |
Provider prices make the rent explicit. Anthropic charges 1.25 times the input price to write a 5-minute cache entry, 2 times for a 1-hour entry, and 0.1 times to read one (less on some newer models). OpenAI discounts cached input by up to 95% depending on the model. A slow tool that outlives a 5-minute TTL turns a 0.1x read into a 1.25x write for the whole context. Providers say so themselves: Anthropic’s batch documentation recommends the 1-hour cache because batches can take longer than 5 minutes.
Routing: the cache lives on one replica#
An engine’s prefix cache is local to a replica. A session whose turns are spread round-robin over eight replicas hits at roughly one-eighth of the rate. Two families of fix:
- Session-sticky routing: hash a session ID to a replica. In the AgentX experiments, “simple session-aware sticky routing” beat queue-depth, running-token and KV-utilisation policies.
- Prefix-aware routing: the router tracks which replica holds which block hashes and picks the best overlap, balancing against load (21.h). More general; also catches sharing across sessions (the same system prompt for every user).
vLLM v0.32.0 gives routers something to key on: a request may carry a session_id (a body field,
the X-Session-ID header, or vllm_xargs), described as a “stable session identity shared by
related requests”. The engine attaches it to the request and to its KV-cache events, so an external
router or KV indexer can attribute cached blocks to sessions. There is also a generic kv_hints
envelope through which an orchestrator can attach versioned hint actions to a request; the actions
are defined by whichever component implements them.
Retention: which KV to keep when memory is short#
An LRU pool treats a 140k-token agent prefix that will be reused in 3 seconds the same as a one-off chat prompt. Agent-aware retention changes that:
- Interval-based retention (from the vLLM AgentX work) preserves the cache at the end of each turn’s prompt, the point the next turn will extend.
- Selective retention for hybrid models (Marconi-style, also from that work) saves a state checkpoint only when a prefix is seen a second time, because hybrid attention/state-space models cannot reuse an arbitrary prefix cheaply (17.i).
- TTL pinning during tool calls (Continuum and related research, 24.h) keeps a paused session’s KV for a time chosen from the predicted tool duration.
Subagents and fan-out#
A parent agent that starts four subagents creates a burst of four new sessions, each beginning with a shared header (system prompt and tools) and a task-specific suffix. Two consequences: the shared header is a cross-session prefix worth caching everywhere, and the burst arrives at once, so admission control (20.c) and per-tenant concurrency limits matter more than for chat.
6. Under the hood: the session model#
// sessioncost.go — one 40-turn agent session, four cache outcomes.
package main
import "fmt"
const (
turns = 40
header = 13_000 // system prompt + tool definitions + first user message
toolResult = 3_000 // tokens appended by each tool result
output = 400 // tokens the model writes per turn
inUSD = 3.0 // $ per million input tokens (illustrative list price)
outUSD = 15.0 // $ per million output tokens
writeX = 1.25 // cache write multiplier (5-minute cache)
readX = 0.10 // cache read multiplier
prefillTPS = 20_000.0
)
type result struct{ computed, cached, final int }
// run walks the session. miss(t) says whether turn t lost its cache;
// compactAt > 0 replaces the history with a summary once the context passes it.
func run(cacheOn bool, miss func(int) bool, compactAt, summary int) (r result, usd float64) {
ctx, prevCtx := header, 0
wx := writeX
if !cacheOn {
wx = 1 // no cache: plain input price, no write premium
}
for t := 1; t <= turns; t++ {
reuse := prevCtx
if miss(t) {
reuse = 0
}
fresh := ctx - reuse
r.computed += fresh
r.cached += reuse
usd += (float64(fresh)*wx + float64(reuse)*readX) * inUSD / 1e6
usd += output * outUSD / 1e6
prevCtx = ctx + output // the model's own output is cached for the next turn
ctx = prevCtx + toolResult
if compactAt > 0 && ctx > compactAt {
ctx, prevCtx = header+summary, 0 // new prefix: nothing cached
}
}
r.final = ctx
return
}
func main() {
never := func(int) bool { return false }
always := func(int) bool { return true }
every8th := func(t int) bool { return t%8 == 0 } // a slow tool outlives the cache TTL
cases := []struct {
name string
cacheOn bool
miss func(int) bool
compactAt, summary int
}{
{"no prefix cache", false, always, 0, 0},
{"cache, never expires", true, never, 0, 0},
{"cache, miss every 8th turn", true, every8th, 0, 0},
{"cache + compact at 100k", true, never, 100_000, 20_000},
}
fmt.Println("scenario prefilled reused hit rate $/session prefill GPU-s")
for _, c := range cases {
r, usd := run(c.cacheOn, c.miss, c.compactAt, c.summary)
hit := float64(r.cached) / float64(r.cached+r.computed)
fmt.Printf("%-27s %10d %9d %7.1f%% %9.2f %13.1f\n",
c.name, r.computed, r.cached, 100*hit, usd, float64(r.computed)/prefillTPS)
}
r, _ := run(true, never, 0, 0)
fmt.Printf("\ncontext at the last turn: %d tokens; a cold last turn needs %.1f s of prefill\n",
r.final-toolResult-output, float64(r.final-toolResult-output)/prefillTPS)
}Output:
scenario prefilled reused hit rate $/session prefill GPU-s
no prefix cache 3172000 0 0.0% 9.76 158.6
cache, never expires 130000 3042000 95.9% 1.64 6.5
cache, miss every 8th turn 571000 2601000 82.0% 3.16 28.6
cache + compact at 100k 160000 2054400 92.8% 1.46 8.0
context at the last turn: 145600 tokens; a cold last turn needs 7.3 s of prefillSimplifications to keep in mind: the prefill speed is constant (real prefill slows down at long context because attention is quadratic, 12.h), and a “miss” here loses the whole prefix; a real miss may keep the system prompt and tools if another session holds them.
7. Performance implications#
- Time to first token is set by cache state, not by prompt length. A warm 145k-token turn prefills 3,400 new tokens; a cold one prefills all of them. Track TTFT split by hit and miss.
- Agent prefill chunks still disturb decodes. Even with high hit rates, a few cold long
prefills stall the decode streams sharing their steps. The AgentX work capped long prefills per
step (
--long-prefill-token-threshold); at 512 tokens it reported up to 93% more throughput per GPU and about 2.3 times better p90 interactivity on DeepSeek V4 Pro on B300, at the cost of higher TTFT for the long request (vLLM-team numbers). - KV per session is large. At 160 KiB per token, a 145k-token session is about 22 GiB of KV. A replica holds tens of such sessions in HBM, not thousands. Offload tiers (14.k) are what make high hit rates affordable.
- Output is small. With a median of 444 output tokens, these workloads are prefill- and cache-bound, which is why disaggregated prefill and KV transfer (14.j) matter so much for agents.
8. Production implications#
- Make session identity first-class. Require a session ID from agent clients, pass it to the
router and to the engine (
session_idorX-Session-IDin vLLM v0.32.0), and log it. - Route sticky, fail over warm. Use session-sticky or prefix-aware routing; when a replica dies, move sessions to a replica that can fetch their KV from a shared tier instead of recomputing.
- Watch the hit rate per session, not just per server: a fleet average of 90% can hide one tenant at 20% because of a timestamp in their system prompt.
- Match the TTL to the tool latency distribution. Measure p90 tool-call duration per agent type; if it exceeds the cache lifetime, use a longer cache (provider 1-hour or 12-hour options) or offload to CPU.
- Publish cache-friendly prompt rules for application teams: stable first, volatile last, sorted tools, no history edits without a reason.
- Plan compaction with the serving team. Every compaction is a deliberate full miss.
9. Common mistakes#
- Benchmarking an agent platform with independent single-turn prompts: hit rates, TTFT and KV pressure will all be wrong.
- Putting the current time or a request ID at the top of the system prompt.
- Round-robin load balancing for multi-turn traffic.
- Regenerating tool definitions per request in a different order.
- Assuming the provider cache lasts as long as the session; the default is minutes.
- Measuring cache hit rate as a fleet average only.
- Compacting every few turns, so the cache never pays back.
10. Hands-on exercise#
A. Break and fix a prefix. Run a small model with vLLM and prefix caching. Replay a 20-turn
conversation twice: once with a timestamp at the top of the system prompt, once at the end of the
last user message. Compare usage.prompt_tokens_details.cached_tokens and TTFT per turn.
B. Routing. Run two replicas behind a round-robin proxy and behind a proxy that hashes
X-Session-ID. Replay ten concurrent sessions. Compare hit rate and p90 TTFT.
C. TTL. Extend sessioncost.go so that each turn’s tool call has a random duration (for example
lognormal with a median of 20 s) and the cache expires after a TTL. Plot cost per session against
TTL from 1 to 30 minutes.
D. Compaction. In sessioncost.go, sweep the compaction threshold and summary size. When does
compaction pay?
11. Interview questions#
- Why does an agent’s prefill cost grow quadratically without a cache, and linearly with one?
- List four things an application can do that silently destroy prefix-cache hits.
- Session-sticky routing or prefix-aware routing for agents? What does each miss?
- A slow tool makes the provider cache expire. What does that cost, and what are your options?
- How would you size KV memory and offload tiers for a fleet serving coding agents?
- When is compaction worth a full cache miss?
12. Further reading#
Checked on 13 November 2026.
- vLLM x AgentX: optimising for real-world agentic serving (September 2026)
- Anthropic — Prompt caching (TTL, prices, breakpoints)
- OpenAI — Prompt caching (retention,
prompt_cache_key) - Continuum: agent KV with time-to-live (arXiv 2511.02230)
- SGLang: RadixAttention for prefix sharing (arXiv 2312.07104)
- Prefix caching in vLLM: 17.f. Prefix-aware routing: 21.h. Agent-aware scheduling research: 24.h.