Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Agent runtime | The program that runs the agent loop: calls the model, runs tools, stores history. |
| Task | One unit of user value (fix this bug, research this question), made of many turns. |
| Working set | The KV cache of all sessions that are alive right now, wherever it is stored. |
| KV tier | A place KV can live: GPU memory (HBM), host memory, local SSD, a shared store. |
| Session lifecycle | The states a session moves through: generating, waiting on a tool, waiting on a person, finished. |
| Task success rate | The share of tasks that end with the outcome the user wanted. The agent equivalent of “correct answer”. |
| Sandbox | An isolated container or VM where an agent’s tools run code, tests or a browser. |
1. What is it?#
The earlier lessons each tuned one part of agent serving: how much to think (27.a), how to keep a session’s KV warm (27.b), how to make tool calls reliable (27.c), and how to run work that outlives a connection (27.g). This lesson puts them into one system and asks the design questions in the order a design review would.
The shape of the system:
flowchart LR C["Clients and<br/>agent runtimes"] --> G["Gateway<br/><small>auth, quotas, session ID,<br/>effort policy</small>"] G --> R["Session-aware router<br/><small>sticky / prefix-aware</small>"] R --> P["Prefill pool"] R --> D["Decode pool"] P <--> K["KV tiers<br/><small>HBM, host, SSD,<br/>shared store</small>"] D <--> K C <--> T["Tool sandboxes<br/><small>code, tests, browser</small>"] C <--> S["Session and job store<br/><small>history, checkpoints</small>"] S --> E["Traces to evals,<br/>batch and RL"] class C,G io class R queue class P,D compute class K,S memory class T neutral class E warn
Facts used in this lesson were checked in the earlier lessons of this module on 13 November 2026.
2. Why does it matter?#
Because the pieces interact, and the interactions are where agent platforms fail:
- The cache TTL only works if it is longer than the tool latency, which belongs to a different team.
- Sticky routing raises hit rates and makes failover expensive.
- Higher reasoning effort improves task success and multiplies the KV working set.
- A tool definition change by one product team resets every session’s cache.
And the unit of value changed. Users pay for tasks, not tokens or requests. A system with great per-request latency and a 60% task success rate is worse than a slower one at 80%, and a cheap model that needs three times the turns may cost more per task.
3. Simple analogy#
A hotel for long-stay guests.
- Rooms are GPU memory. A guest (session) needs a room only while they are in it (generating).
- Luggage storage (host memory, SSD) holds a guest’s things while they are out (waiting on a tool or a person), so the room can be used by someone else.
- The concierge (router) sends returning guests to the floor where their luggage is.
- The ledger (session store) records everything, so a guest whose room floods (a failed replica) can be moved without losing their stay.
- The hotel’s size is set by how many guests have luggage at once, not by how many are in their rooms at any moment.
4. Tiny example: a first capacity plan#
A coding agent product: 200,000 tasks a day, peak hour three times the average, 40 turns per task, a 13,000-token start, 3,400 tokens appended and 1,000 generated per turn (reasoning plus answer), 15 seconds of tool time per turn, 60 tokens per second per stream. Replicas are 8 GPUs at $64 per hour with 600 GiB of HBM for KV and 8,000 GiB of host memory for parked KV.
task: 1267 s, 4.0M prompt tokens, 40k output tokens, avg context 99k
peak: 6.9 new tasks/s, 8796 live sessions, 4630 generating -> 15 replicas of decode slots
cache hit KV/token KV working set prefill rep KV-bound rep replicas $/task
80% 160 KiB 130 TiB 55 116 171 0.44
96% 160 KiB 130 TiB 11 116 127 0.33
96% 80 KiB 65 TiB 11 58 69 0.18
96% 40 KiB 32 TiB 11 29 40 0.10Three lessons in one table:
- Decode slots are not the constraint. 15 replicas could generate for every active session.
- KV memory is. With a 160 KiB-per-token model, 116 replicas are needed just to hold the working set of the sessions that are generating. Halving KV bytes per token (FP4 KV, 13.h; MLA or sparse and hybrid attention, 12.g) halves the fleet.
- Cache hit rate sets the prefill pool. Going from 80% to 96% removes 44 replicas of prefill.
The cost per task is at peak sizing; filling the daily troughs with batch work (27.f) lowers the effective cost further.
5. Technical explanation#
Start from the task, not the request#
Write down the service-level indicators for agents before choosing anything (23.a):
| Indicator | Why |
|---|---|
| Task success rate (by agent type and effort) | The value delivered |
| Task completion time, p50 and p90 | What the user waits for |
| Time to first visible token per turn | What the user sees waiting |
| Cost per task, and per successful task | The unit economics (27.a) |
| Turns per task, tokens per task | The drivers of cost |
| Cache hit rate per session | The driver of prefill cost and TTFT (27.b) |
| Tool-call failure rate by type | The driver of retries and stuck tasks (27.c) |
| Task interruption and resume rate | The health of the job layer (27.g) |
The design decisions, in review order#
| Decision | Options | Choose by |
|---|---|---|
| Model and KV footprint | Dense GQA; MLA; sparse or hybrid attention; FP8 or FP4 KV | KV bytes per token at your context lengths: section 4 shows it sets the fleet size |
| Effort policy | One level; per route; adaptive with escalation | Cost per successful task by route (27.a) |
| Context policy | Append only; compaction at a threshold; deferred tool loading | Cache stability vs context size (27.b, 27.c) |
| Routing | Session-sticky; prefix-aware; both with load limits | Hit rate measured on real traces; failover cost (21.h) |
| Serving topology | Aggregated replicas; prefill/decode disaggregation | Agent traffic is prefill- and cache-heavy with short outputs; disaggregation and KV transfer pay off at scale (14.j) |
| KV tiers and retention | HBM only; host and SSD tiers; shared store; per-turn retention; TTL during tools | Tool-time distribution vs reload cost (24.h); memory prices |
| Tool reliability | Free text; envelope constraint; strict arguments | Per-call failure × turns (27.c) |
| Job semantics | Streaming only; background jobs; durable workflows | Task length and interruption rate (27.g) |
| Isolation | Shared fleet with priorities; per-tenant pools | Tenant size, compliance, noisy-neighbour risk (21.f) |
The session lifecycle drives memory policy#
┌──────────── tool returns ─────────────┐
▼ │
NEW ──► GENERATING ──► WAITING ON TOOL ──► (seconds to minutes) ──┘
│ │
│ └──► WAITING ON PERSON (minutes to days) ──► RESUMED ──► GENERATING
▼
FINISHED ──► history to store; KV dropped| State | Where its KV should be | Why |
|---|---|---|
| Generating | HBM, on the replica decoding it | Every step reads it |
| Waiting on a short tool (seconds) | HBM, pinned with a TTL | Reloading would cost more than holding (24.h) |
| Waiting on a long tool (minutes) | Host memory or SSD tier | Free HBM for generating sessions; reload in well under a second |
| Waiting on a person (hours) | Shared store, or dropped | Recompute is acceptable once; holding is not |
| Finished | Nowhere | Keep the history in the session store, not the KV |
This table is what turns “130 TiB working set” into “HBM for the generating half, tiers for the rest” in section 4. Without parking, every live session would need HBM: 221 replicas instead of 116 at 160 KiB per token.
Failure and recovery#
- Replica failure: move sessions to replicas that can fetch their KV from a shared tier; fall back to re-prefill from the session store (27.g). Sticky routing must have a failover target.
- Deploys: drain by stopping new sessions on a replica and waiting for turns, not tasks, to end; the next turn goes elsewhere with a fetch or a re-prefill.
- Tool fleet failure: tools are on the critical path of every turn; size, isolate and monitor sandboxes like a serving tier.
- Bad model or template rollout: a template change resets every session’s cache and can change tool-call formats; roll out per session (new sessions only), not per request (23.g).
Closing the loop: traces, evals, batch and RL#
Agent traces (prompts, tool calls, outcomes) are the best evaluation and training data the platform has. A mature design treats them as an output: replay them as benchmarks for serving changes (24.h’s point that synthetic single-turn benchmarks mislead), as batch evaluation sets (27.f), and as environments for RL (27.d). The same GPU fleet can run all three in its troughs.
6. Under the hood: the capacity model#
// agentplan.go — a first capacity plan for an agent product.
package main
import (
"fmt"
"math"
)
const (
tasksPerDay = 200_000.0
peakFactor = 3.0 // peak hour vs daily average
turns = 40.0
header = 13_000.0 // system + tools + task
perTurnIn = 3_400.0 // tool result + previous output appended each turn
perTurnOut = 1_000.0 // reasoning + visible output per turn
toolSecs = 15.0 // mean tool time per turn
perUserTokS = 60.0
hbmKVGiB = 600.0 // per replica
cpuTierGiB = 8_000.0
prefillTokS = 100_000.0
replicaSlots = 300.0 // decode streams per replica at 60 tok/s
replicaUSDh = 64.0
)
func main() {
inputAll, ctxSum := 0.0, 0.0
for t := 0.0; t < turns; t++ {
ctx := header + t*(perTurnIn+perTurnOut)
inputAll += ctx
ctxSum += ctx
}
avgCtx := ctxSum / turns
modelSecs := perTurnOut / perUserTokS
taskSecs := turns * (modelSecs + toolSecs)
busy := modelSecs / (modelSecs + toolSecs) // share of a session's life spent generating
peakTasksS := tasksPerDay / 86400 * peakFactor
sessions := peakTasksS * taskSecs // Little's law
decodeRep := sessions * busy / replicaSlots
fmt.Printf("task: %.0f s, %.1fM prompt tokens, %.0fk output tokens, avg context %.0fk\n",
taskSecs, inputAll/1e6, turns*perTurnOut/1e3, avgCtx/1e3)
fmt.Printf("peak: %.1f new tasks/s, %.0f live sessions, %.0f generating -> %.0f replicas of decode slots\n\n",
peakTasksS, sessions, sessions*busy, decodeRep)
plan := func(hit, kvKiB float64) {
kvGiB := sessions * avgCtx * kvKiB / (1 << 20)
prefillRep := peakTasksS * inputAll * (1 - hit) / prefillTokS
// Generating sessions need HBM; idle ones may sit in the CPU tier.
kvRep := math.Max(kvGiB*busy/hbmKVGiB, kvGiB/(hbmKVGiB+cpuTierGiB))
replicas := prefillRep + math.Max(decodeRep, kvRep)
fmt.Printf("%7.0f%% %8.0f KiB %9.0f TiB %11.0f %14.0f %8.0f %7.2f\n",
100*hit, kvKiB, kvGiB/1024, prefillRep, kvRep, replicas,
replicas*replicaUSDh/3600/peakTasksS)
}
fmt.Println("cache hit KV/token KV working set prefill rep KV-bound rep replicas $/task")
for _, hit := range []float64{0.80, 0.96} {
plan(hit, 160)
}
for _, kv := range []float64{80, 40} {
plan(0.96, kv)
}
}Output:
task: 1267 s, 4.0M prompt tokens, 40k output tokens, avg context 99k
peak: 6.9 new tasks/s, 8796 live sessions, 4630 generating -> 15 replicas of decode slots
cache hit KV/token KV working set prefill rep KV-bound rep replicas $/task
80% 160 KiB 130 TiB 55 116 171 0.44
96% 160 KiB 130 TiB 11 116 127 0.33
96% 80 KiB 65 TiB 11 58 69 0.18
96% 40 KiB 32 TiB 11 29 40 0.10How to use it: replace every constant with measurements from your own traces (turn count, tokens per turn, tool time distribution, KV bytes per token of your model, prefill speed at your context lengths). The model treats prefill and decode as separate pools and ignores the interference between them, slower attention at long context, and the HBM the generating sessions’ growing contexts need beyond the average. Each of those raises the replica count; none changes the conclusion that KV capacity and cache hit rate dominate.
7. Performance implications#
- KV bytes per token is the first-order cost driver for agents with long contexts. Model choice, KV quantization and attention design matter more than FLOP efficiency.
- Cache hit rate is the second. It sets the prefill pool size and turn TTFT.
- Decode capacity is rarely the limit for agent traffic with short outputs; it becomes one when reasoning effort rises (27.a).
- Tool time is capacity. Every second a session waits on a tool, its KV sits somewhere; faster tools shrink the working set by Little’s law.
- Turn count multiplies everything. Parallel tool calls, better tool design and fewer retries (27.c) reduce turns, and so reduce every other number.
8. Production implications#
- Instrument per task and per session, not just per request: a dashboard with the indicators in section 5, sliced by agent type, tenant and effort level.
- Own the contracts between teams: prompt layout and tool-definition stability (application teams), tool latency SLOs (tool owners), retention and routing (serving), job semantics (platform).
- Load-test with replayed agent traces, including tool pauses and human waits, never with single-turn prompts.
- Roll out per session: model, template and tool-list changes apply to new sessions; old ones finish on the old configuration.
- Plan capacity by working set: KV TiB per tier at peak, with the lifecycle mix, then replicas.
- Revisit the plan when the model changes: a new model with a different KV footprint or thinking behaviour changes every number in section 4.
9. Common mistakes#
- Sizing an agent fleet by tokens per second or requests per second instead of KV working set.
- Measuring request latency and ignoring task success and task completion time.
- Choosing a model by benchmark score without checking KV bytes per token at long context.
- Sticky routing without a warm failover path.
- Letting product teams change tool definitions or system prompts without considering the cache.
- Holding the KV of sessions waiting for a person in HBM.
- Building the platform for agents and still benchmarking it with chat prompts.
10. Hands-on exercise#
A. Your numbers. Collect a day of agent traces (or use a public agent trace). Measure turns per
task, tokens per turn, tool-time distribution and cache hit rate. Re-run agentplan.go with them.
B. Lifecycle mix. Add “waiting on person” sessions to the model (for example 20% of sessions idle for a median of 30 minutes). How much does the host or SSD tier have to grow?
C. Model choice. Compare two open models you could serve: compute KV bytes per token for each (12.f) and plug them in. How many replicas does each need for the same traffic?
D. Design review. Write a one-page design for an agent platform for your organisation using the decision table in section 5. For each decision, write the measurement that would change it.
11. Interview questions#
- What limits the size of an agent-serving fleet, and why is it usually not decode throughput?
- Walk through a session’s lifecycle and where its KV should live in each state.
- Which indicators would you put on an agent platform’s top-level dashboard?
- How do routing and failover interact for long agent sessions?
- A product team wants to double reasoning effort. What changes in your capacity plan?
- How would you use agent traces beyond monitoring?
12. Further reading#
Checked on 13 November 2026.
- vLLM x AgentX: optimising for real-world agentic serving (September 2026)
- Continuum: agent KV with time-to-live (arXiv 2511.02230)
- Anthropic Engineering — Advanced tool use
- Temporal — Workflows and durable execution
- This module: 27.a (effort economics), 27.b (sessions and KV reuse), 27.c (tool calls), 27.d–27.e (RL), 27.f (batch), 27.g (long jobs). Platform pieces: 21.f, 21.h, 21.j. Production: 23.a–23.c.