Pidoku

Designing for Agents End to End

Module 27 Lesson 27.h 1h 15m Difficulty 4/5

Prerequisites 21.h, 23.a, 23.b, 27.a, 27.b, 27.c, 27.g


Before you start: words you need#

WordPlain meaning
Agent runtimeThe program that runs the agent loop: calls the model, runs tools, stores history.
TaskOne unit of user value (fix this bug, research this question), made of many turns.
Working setThe KV cache of all sessions that are alive right now, wherever it is stored.
KV tierA place KV can live: GPU memory (HBM), host memory, local SSD, a shared store.
Session lifecycleThe states a session moves through: generating, waiting on a tool, waiting on a person, finished.
Task success rateThe share of tasks that end with the outcome the user wanted. The agent equivalent of “correct answer”.
SandboxAn 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.10

Three lessons in one table:

  1. Decode slots are not the constraint. 15 replicas could generate for every active session.
  2. 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.
  3. 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):

IndicatorWhy
Task success rate (by agent type and effort)The value delivered
Task completion time, p50 and p90What the user waits for
Time to first visible token per turnWhat the user sees waiting
Cost per task, and per successful taskThe unit economics (27.a)
Turns per task, tokens per taskThe drivers of cost
Cache hit rate per sessionThe driver of prefill cost and TTFT (27.b)
Tool-call failure rate by typeThe driver of retries and stuck tasks (27.c)
Task interruption and resume rateThe health of the job layer (27.g)

The design decisions, in review order#

DecisionOptionsChoose by
Model and KV footprintDense GQA; MLA; sparse or hybrid attention; FP8 or FP4 KVKV bytes per token at your context lengths: section 4 shows it sets the fleet size
Effort policyOne level; per route; adaptive with escalationCost per successful task by route (27.a)
Context policyAppend only; compaction at a threshold; deferred tool loadingCache stability vs context size (27.b, 27.c)
RoutingSession-sticky; prefix-aware; both with load limitsHit rate measured on real traces; failover cost (21.h)
Serving topologyAggregated replicas; prefill/decode disaggregationAgent traffic is prefill- and cache-heavy with short outputs; disaggregation and KV transfer pay off at scale (14.j)
KV tiers and retentionHBM only; host and SSD tiers; shared store; per-turn retention; TTL during toolsTool-time distribution vs reload cost (24.h); memory prices
Tool reliabilityFree text; envelope constraint; strict argumentsPer-call failure × turns (27.c)
Job semanticsStreaming only; background jobs; durable workflowsTask length and interruption rate (27.g)
IsolationShared fleet with priorities; per-tenant poolsTenant 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
StateWhere its KV should beWhy
GeneratingHBM, on the replica decoding itEvery step reads it
Waiting on a short tool (seconds)HBM, pinned with a TTLReloading would cost more than holding (24.h)
Waiting on a long tool (minutes)Host memory or SSD tierFree HBM for generating sessions; reload in well under a second
Waiting on a person (hours)Shared store, or droppedRecompute is acceptable once; holding is not
FinishedNowhereKeep 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#

Go
// 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.10

How 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#

  1. Sizing an agent fleet by tokens per second or requests per second instead of KV working set.
  2. Measuring request latency and ignoring task success and task completion time.
  3. Choosing a model by benchmark score without checking KV bytes per token at long context.
  4. Sticky routing without a warm failover path.
  5. Letting product teams change tool definitions or system prompts without considering the cache.
  6. Holding the KV of sessions waiting for a person in HBM.
  7. 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#

  1. What limits the size of an agent-serving fleet, and why is it usually not decode throughput?
  2. Walk through a session’s lifecycle and where its KV should live in each state.
  3. Which indicators would you put on an agent platform’s top-level dashboard?
  4. How do routing and failover interact for long agent sessions?
  5. A product team wants to double reasoning effort. What changes in your capacity plan?
  6. How would you use agent traces beyond monitoring?

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