Pidoku

Worked Design: A Coding Agent for a Million Developers

Module 31 Lesson 31.i 1h 30m Difficulty 5/5

Prerequisites 23.k, 14.j, 14.l, 21.h, 31.b, 31.c

This is a design exercise. Read the brief in section 1, sketch your own answer, then read on.


Before you start: words you need#

WordPlain meaning
Coding agentA model that works on a code base in a loop: reads files, runs tools (tests, search, shell), edits code, and repeats until the task is done.
SessionOne agent task from start to finish: often dozens of model calls (“turns”) with tool calls in between.
TurnOne model call in a session. Its input is the whole conversation so far, so inputs grow turn by turn.
Session-sticky routingSending every turn of a session to the replica that already holds its KV cache (21.h).
KV tieringKeeping KV caches in several layers of memory: GPU HBM, CPU DRAM, local SSD, a distributed store, moving them as sessions pause and resume (14.k, 14.l).
DisaggregationRunning prefill and decode on separate GPU pools and moving the KV cache between them (14.j).
Recompute stormMany sessions losing their KV at once and all needing a full prefill at the same moment.

1. What is it? The brief#

REQUIREMENTS
  Users:        1,000,000 developers; ~40% active on a weekday
  Product:      an agentic coding assistant in the IDE and terminal
  Workload:     ~8 agent sessions per active developer per day
                per session: ~43 turns; per turn ~142k input tokens (growing context),
                ~444 output tokens; >96% of input tokens are prefix-cache hits
                ~20 s of tool execution between turns
  Experience:   ≥ 60 output tokens/s per session; p95 time to first token < 2 s on a warm turn
                sessions must survive node failures
  Quality:      at least as good as today's premium API on our coding evals
  Budget:       well under what the premium API would cost at this volume

QUESTION: design the serving system. How many GPUs? What does it cost?
          Should we build it at all?

The turn shape comes from SemiAnalysis’s AgentX benchmark of real agentic coding traces: median 43 turns per session, median 142k input and 444 output tokens, and over 96% prefix-cache hits (24.h). The sessions per developer, active share and tool time are assumptions.

Facts checked on 13 November 2026.


2. Why does it matter?#

This is the workload that dominates new inference demand in 2026, and it breaks chat-era intuitions:

  • Input dwarfs output. 142,000 tokens in for 444 out. Even with 96% cache hits, the uncached 4% is 5,700 tokens per turn: thirteen times the output. Prefill, not decode, may set the GPU count.
  • The KV cache is the system. A 142k-token session holds gigabytes of KV. Tens of thousands of sessions pause for tool calls at any moment. Where those caches live decides latency and cost.
  • Losing state is expensive. A dropped KV cache costs a full 142k-token prefill to rebuild, and a mass failure can trigger a recompute storm.
  • The buy option is expensive at this scale and excellent in quality. The design must answer “should we build at all?”, not only “how” (31.c).

3. Simple analogy#

A library with a million researchers. Each researcher works at a desk piled with the books for their project (the KV cache). They keep stepping out for a coffee (tool calls) and coming back. The librarian cannot clear and re-stack every desk each time someone steps out (recompute), and there are not enough desks for everyone at once (HBM). So desks of people on a break are wheeled to a nearby storeroom (CPU memory) and wheeled back when they return, to the same reading room (session-sticky routing).


4. Tiny example: the napkin before the design#

active developers         1,000,000 × 40%                  = 400,000
turns per weekday         400,000 × 8 sessions × 43 turns  = 138 million
turns per second, peak    138 M ÷ 86,400 × 2 (peak/avg)    ≈ 3,200

KV per session            142,000 tokens × 35 KB (MLA-style, FP8) ≈ 5 GB
sessions decoding         3,200/s × 7.4 s per turn          ≈ 23,600 → 117 TB of KV
sessions paused in tools  3,200/s × 20 s                    ≈ 63,700 → 317 TB of KV

uncached prefill          3,200/s × 142,000 × 4%            ≈ 18 million tokens/s
output                    3,200/s × 444                     ≈ 1.4 million tokens/s

Three conclusions before drawing a single box: prefill is a large share of the compute, the paused sessions’ KV (317 TB) cannot live in GPU memory, and the cache hit rate is the most important number in the design.


5. Technical explanation: the design#

Architecture#

flowchart LR
  IDE["IDE / CLI clients"] --> GW["Gateway<br/><small>auth, org quotas, metering</small>"]
  GW --> CL["Task classifier<br/><small>tier by difficulty</small>"]
  CL --> SR["Session router<br/><small>sticky, KV-aware</small>"]
  CL -.->|"hardest tasks"| API["Premium API<br/><small>fallback and escalation</small>"]
  SR --> PF["Prefill pool<br/><small>only uncached tokens</small>"]
  PF -->|"KV transfer (NIXL)"| DC["Decode pool<br/><small>≥ 60 tok/s per session</small>"]
  DC <--> KV["KV tiers<br/><small>HBM → host DRAM → distributed store</small>"]
  PF <--> KV
  DC --> GW
  GW <--> TOOLS["Tool sandboxes<br/><small>tests, search, shell</small>"]
  class IDE,GW,CL,SR io
  class PF,DC compute
  class KV memory
  class API,TOOLS warn

The components and why#

Gateway (21.i). Authentication, per-organisation and per-user quotas (21.f, 23.j), metering of tokens by kind for billing and cost attribution (31.e), and the single API in front of every model and provider.

Task classifier and tiers (21.k, 31.e). Not every turn needs the largest model. A small model handles quick edits and summaries; the main open model handles agent turns; the hardest tasks, or tasks where the main model has failed twice, escalate to a premium API. Routing is decided per session where possible, because switching models mid-session throws away the KV cache.

Session router (21.h). Every turn of a session goes to the replica that holds its KV, or to the replica that can fetch it fastest. This is what turns 90% cache hits into 96–99%. The router needs session IDs from the client, replica load, and a view of where each session’s KV is.

Disaggregated prefill and decode (14.j). The two phases have different shapes here: prefill is 5,700 new tokens attending to a 142k prefix, compute-heavy; decode is long-context, memory-bound and latency-critical. Separate pools let each run at its own batch size and parallelism, and stop a large prefill from stalling the decode streams of thousands of users. In 2026 this is standard at this scale (24.h).

KV tiers (14.k, 14.l). Decoding sessions live in HBM. Paused sessions move to host DRAM on the same node during tool calls, and to a distributed KV store (Mooncake-style, or LMCache) if the pause is long or the node is busy. The keep-or-move decision per session is an open research area (24.h: Continuum, SAGA); start with a time-to-live per tier and tune it on traces.

Model choice and attention. A large open MoE coding model with a compressed KV cache (MLA-style, 12.g) at FP8 is assumed. A model with sparse attention (24.b) would cut decode KV reads at long context; a GQA model with a larger KV per token would roughly double the KV memory in every number above.

Tool sandboxes. Not GPU work, but on the critical path: 20 s of tool time per turn is longer than the model’s 7 s. Faster tools shorten sessions, which reduces paused KV and frees capacity.

SLOs#

SLOTargetWhy
Output speed per session≥ 60 tok/s p50, ≥ 40 p95developers watch the stream
TTFT, warm turn (KV found)p95 < 2 smost turns
TTFT, cold turn (KV recomputed)p95 < 15 s142k tokens at ~10k tok/s
Session continuity99.9% of sessions finish without a hard errorsessions last minutes
Qualityno worse than the reference on the coding eval suiteModule 28

Failure: the recompute storm#

If one decode node fails, its roughly 200 sessions (8 GPUs × ~27 each) recompute their KV: about 2,800 GPU-seconds of prefill, which the prefill pool’s headroom absorbs in a few seconds. If a whole KV store shard fails, thousands of paused sessions return cold at once. 10,000 sessions × 142,000 tokens = 1.4 billion tokens of prefill. The prefill pool (about 2,600 GPUs sized for 70% busy) has roughly 8 million tokens per second of headroom at peak, so the storm takes about three minutes to clear, and every user’s TTFT spikes while it does. Defences: replicate hot KV in the store, spread sessions across shards, and admit cold sessions at a capped rate with a visible “resuming…” state (20.c, 31.g).

Build or buy#

Section 6 prices both. The answer this design gives: self-host the main tier, keep the premium API for escalation, if and only if the open model passes the coding evals. If it does not, the design shrinks to a gateway, a router and a large API contract, which is a perfectly good answer.


6. Under the hood: the sizing model#

The program computes peak load, KV memory, prefill and decode GPUs for three cache hit rates, the yearly cost at a reserved B300 price, and the cost of buying the same tokens from a premium API. The AgentX turn shape and the API’s list prices are sourced; every hardware and model number is an assumption to replace with your own benchmark (22.g).

Go
// codingagent.go — sizing a coding agent for a million developers.
package main

import (
	"fmt"
	"math"
)

func main() {
	// Demand. Turn shape from SemiAnalysis AgentX coding traces (median 43 turns per session,
	// 142k input and 444 output tokens per turn, >96% prefix-cache hits); the rest ASSUMED.
	const (
		developers      = 1e6
		activeShare     = 0.40 // active on a given weekday
		sessionsPerDay  = 8.0
		turnsPerSession = 43.0
		inTok, outTok   = 142000.0, 444.0
		peakToAvg       = 2.0  // weekday working hours across time zones
		toolSeconds     = 20.0 // average pause for tool calls between turns
		userTokS        = 60.0 // per-session output speed target (tokens/s)
	)
	// Model and hardware: a large open MoE with compressed (MLA-style) KV at FP8, on B300.
	// All ASSUMED; replace with your benchmark at the SLO (22.g).
	const (
		kvPerTokKB    = 35.0    // KV bytes per token, in KB (MLA-style latent cache at FP8)
		prefillGPUTok = 10000.0 // uncached prefill tokens/s per GPU at 142k context
		decodeGPUTok  = 1600.0  // output tokens/s per GPU at 60 tok/s per session, long context
		gpuKVGB       = 200.0   // HBM per GPU left for KV after weights and activations
		targetUtil    = 0.70
		gpuHour       = 7.00 // B300 $/GPU-hour on a reservation: ASSUMED (list is $9.50, 31.d)
	)

	turnsPerSec := developers * activeShare * sessionsPerDay * turnsPerSession / 86400 * peakToAvg
	turnTime := outTok / userTokS
	sessionKVGB := inTok * kvPerTokKB / 1e6
	fmt.Printf("peak: %.0f turns/s, %.1f s per turn, %.1f GB of KV per session\n",
		turnsPerSec, turnTime, sessionKVGB)

	decoding := turnsPerSec * turnTime
	paused := turnsPerSec * toolSeconds
	fmt.Printf("sessions decoding: %.0f (%.0f TB KV)   paused in tool calls: %.0f (%.0f TB KV)\n\n",
		decoding, decoding*sessionKVGB/1000, paused, paused*sessionKVGB/1000)

	fmt.Printf("%-9s %14s %12s %12s %10s %12s\n", "cache hit", "prefill tok/s", "prefill GPUs", "decode GPUs", "total", "$M / year")
	for _, hit := range []float64{0.90, 0.96, 0.99} {
		prefillTok := turnsPerSec * inTok * (1 - hit)
		pGPU := prefillTok / prefillGPUTok
		dGPU := math.Max(turnsPerSec*outTok/decodeGPUTok, decoding*sessionKVGB/gpuKVGB)
		total := math.Ceil((pGPU + dGPU) / targetUtil)
		fmt.Printf("%-9.0f %13.1fM %12.0f %12.0f %10.0f %12.0f\n", hit*100, prefillTok/1e6, pGPU, dGPU,
			total, total*gpuHour*8760*1.18/1e6)
	}

	// Buying the same tokens from a premium API at list price (Claude Sonnet 5.5, 23.c).
	turnsPerDay := developers * activeShare * sessionsPerDay * turnsPerSession
	const hit = 0.96
	apiDay := turnsPerDay * (inTok*(1-hit)*2.00 + inTok*hit*0.10 + outTok*10.00) / 1e6
	fmt.Printf("\npremium API at list: $%.1fM per weekday → $%.0fM per year (250 weekdays)\n",
		apiDay/1e6, apiDay*250/1e6)
	fmt.Printf("per active developer: $%.2f per weekday\n", apiDay/(developers*activeShare))
}

Output:

peak: 3185 turns/s, 7.4 s per turn, 5.0 GB of KV per session
sessions decoding: 23570 (117 TB KV)   paused in tool calls: 63704 (317 TB KV)

cache hit  prefill tok/s prefill GPUs  decode GPUs      total    $M / year
90                 45.2M         4523          884       7725          559
96                 18.1M         1809          884       3848          278
99                  4.5M          452          884       1909          138

premium API at list: $4.0M per weekday → $1012M per year (250 weekdays)
per active developer: $10.12 per weekday

How to read it:

  • The cache hit rate is the design. From 96% to 90% doubles the fleet (3,848 → 7,725 GPUs); from 96% to 99% halves it. Session-sticky routing, KV tiering and keeping paused sessions warm are worth hundreds of millions of dollars a year here. This is the single most important finding.
  • Prefill outweighs decode at 96%. 1,809 prefill GPUs against 884 decode GPUs, with only 4% of input tokens uncached. On agent workloads, “decode is the bottleneck” is no longer the default.
  • Paused KV does not fit in HBM. 317 TB for paused sessions against roughly 770 TB of KV space in a 3,848-GPU fleet at 200 GB each, most of which is needed for active work. Host DRAM and a distributed store must hold it, which is why KV tiering is a core component, not an optimisation.
  • Self-hosting at 96% costs about $278M a year against about $1.0B for the premium API at list price, before the team, before committed-spend discounts on the API, and with the self-hosted fleet sized for peak every hour of the year. The weekend and night troughs should be filled with background agents, batch evaluations or RL rollouts (Module 27).
  • The comparison is only valid at equal quality. If the open model fails more tasks, cost per successful task (31.e) may favour the API. The eval decides first.

7. Performance implications#

  • Prefill efficiency matters as much as decode. Long-context prefill kernels (Module 25), chunked prefill caps that protect decode (12.k), and context parallelism for very long prefixes (14.f) all move the prefill GPU count.
  • Per-session speed and batch fight. 60 tok/s per session at 142k context limits the decode batch per GPU. Speculative decoding (13.n) helps at this low-batch, memory-bound point; an SRAM “fast mode” tier (7.k) is an option for premium users.
  • KV transfer bandwidth between prefill, decode and the store must keep up: 5 GB per session, thousands of times per second, across the network (9.e).

8. Production implications#

  • Launch on the API, collecting traces, session shapes and evals. Move the main tier to the self-hosted fleet per organisation, behind the gateway, once the open model passes (31.c).
  • Meter per organisation with cached and uncached input, output and KV-seconds (23.c); agent customers vary by 100x in usage.
  • Quotas per user and per org, plus a hard cap on session length; runaway agents loop.
  • Watch the hit rate as the top-line health metric, next to TTFT and tokens per second. A router change that drops it from 96% to 90% doubles the cost overnight.
  • Rollouts are per session: a new model or engine version must not change mid-session (20.j).
  • Fill the troughs. Weekend and night capacity runs background agents and evaluations.

9. Common mistakes#

  1. Sizing for decode only. At 142k-token inputs, prefill can need twice as many GPUs.
  2. Treating the cache hit rate as a constant. It is the most sensitive input in the model.
  3. Keeping paused sessions in HBM. It caps concurrency at a fraction of demand.
  4. Switching models mid-session for cost. It discards the cache and costs a full prefill.
  5. No plan for a recompute storm. A KV store failure becomes a fleet-wide latency incident.
  6. Comparing cost against the API without equal-quality evals.
  7. Benchmarking with chat prompts. Agent traces have different shapes (24.h).

10. Hands-on exercise#

  1. Run codingagent.go. Set toolSeconds to 60. How much paused KV is there now, and where would you put it?
  2. Replace the model with a GQA model at 160 KB of KV per token (Llama-3-70B-like at FP8, 12.f). What happens to KV memory and to the decode GPU count?
  3. Add a premium “fast mode” for 10% of sessions at 200 tok/s per session on SRAM machines (7.k). What changes in the design?
  4. Compute the recompute storm for a failure that drops 20% of paused sessions. How long is the prefill pool saturated? Design the admission policy.
  5. Write the one-page decision record: build, buy or hybrid, with the triggers to revisit.

11. Interview questions#

  1. Why can prefill need more GPUs than decode for a coding agent, even at a 96% cache hit rate?
  2. Where do you keep the KV cache of a session that is waiting 20 seconds for a test run?
  3. How does session-sticky routing change the cost of this system?
  4. What is a recompute storm, and how do you prevent it?
  5. When would you not build this at all?
  6. How do you roll out a new model version to agents with sessions in flight?

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