Skip to playbook content
Browse all chapters
Chapter 0518 min readReviewed 31 August 2026

AI inference from first token to fleet capacity

Prefill, decode, KV cache, latency metrics, batching, caching, quantization, and capacity planning.

On this page
  1. Two phases
  2. Metrics
  3. KV cache
  4. Serving levers
  5. Capacity method
One request, two regimes

Prefill and decode stress the GPU differently

An LLM request is not a single homogeneous job. Prompt processing and token generation have different parallelism, memory traffic, and user-facing consequences.

01 · Prefill / context

Process prompt tokens in parallel

Build the first logits and write keys and values for every attention layer and live prompt token.

Tendency
Compute-bound for long prompts or useful batches
User sees
Time to first token
Pressure
Prompt length, attention cost, queueing
02 · Decode / generation

Generate one token per sequence per step

Read weights and prior KV, append one entry, sample, then repeat. Each response is sequential even when many responses batch together.

Tendency
HBM-bandwidth-bound at low-to-medium batch
User sees
Inter-token latency / TPOT
Pressure
Live sequences, output length, KV occupancy
Measurement contract

A single tokens-per-second number hides the service

Define where the clock starts, publish tail percentiles, and keep input, output, request, and total-token throughput separate.

MetricDefinitionWhat it diagnoses
TTFTRequest submission to first output tokenGateway, queue, tokenization, prefill, first decode, cold state
ITLEach interval between adjacent streamed tokensVisible stalls and tail cadence
TPOTAverage post-first-token time per generated tokenAverage decode cadence per request
E2E latencySubmission to final tokenWhole response experience
Output throughputGenerated output tokens / wall timeFleet generation capacity
Request throughputCompleted requests / secondOnly comparable with the same length distributions
GoodputRequests or tokens completed inside latency, quality, and error SLOsCapacity that is safe to sell or plan
E2E ≈ TTFT + (O − 1) × TPOT
For one response with O output tokens; TPOT is an average approximation.
  • Report p50/p95/p99 TTFT and ITL or TPOT, not averages alone.
  • Record prompt/output distributions, arrival rate, burstiness, concurrency, prefix reuse, and sampling settings.
  • Keep engine-internal latency separate from user-observed gateway-to-token latency.
  • Compare goodput only at the same model revision, tokenizer, precision, lengths, engine version, and SLO.
The second memory budget

KV cache grows with live tokens, not parameter count

The model weights may fit while production concurrency does not. Plan keys and values for every live prompt and generated token.

KV bytes = 2 × layers × KV heads × head dimension × bytes × Σ live sequence tokens
Standard attention. Hkv is KV heads, not query heads; b is bytes per element.
Worked example

32 layers × 8 KV heads × 128 head dimension × 2 bytes × key/value = 128 KiB per live token.

One 8,192-token sequence is roughly 1 GiB of raw KV. Thirty-two such live sequences are roughly 32 GiB - before block rounding, runtime pools, and other overhead.

What reduces KV

GQA/MQA, fewer live tokens, sliding-window/hybrid attention, lower KV precision, prefix block sharing, and architecture-specific cache designs.

What multiplies KV

Concurrency, long outputs, beam search, n > 1, multimodal tokens, block rounding, and replicated KV heads at some tensor-parallel degrees.

Paged attention manages allocation, not physics. Block-based KV reduces fragmentation and enables sharing, but the actual K/V payload still consumes memory.

Prefix caching removes repeated prefill work. It helps TTFT when token-identical prefixes recur; it does not accelerate the uncached suffix or ordinary decode. Template changes, timestamps, whitespace, tokenizer versions, and round-robin routing can destroy reuse.

Engine controls

Batch continuously, then tune the tradeoff you actually own

LeverIt helps whenIt can hurt whenTrack
Continuous batchingSequences have varied lengths and traffic is concurrentAdmission is too aggressive for KV or tail SLOActive/waiting sequences, batch tokens, queue, goodput
Chunked prefillLong prompts interfere with streaming decodeChunk/token budget adds scheduling overhead or worsens TTFTTTFT, ITL, prefill chunks, queue
Prefix cachingStable token-identical prefixes recurTemplates vary, routing fragments locality, cache churnsQuery/hit tokens, eviction, warm vs cold TTFT
Weight quantizationWeights do not fit or decode is weight-bandwidth-boundKernel fallback/dequant or quality loss dominatesHBM, quality, prefill and decode separately
KV quantization/offloadContext/concurrency is the memory limitConversion or host transfer increases latencyKV capacity, occupancy, transfer, p99 ITL
Speculative decodingLow/medium batch decode is bandwidth-bound and proposals are acceptedLarge batches saturate target or proposer overhead is highAccepted length, draft/verify time, TPOT and total throughput
From one replica to a fleet

Capacity planning is trace replay plus memory feasibility

  1. Capture demand.Prompt/output distributions, arrival pattern, burstiness, prefixes, model mix, sampling and SLOs.
  2. Calculate fit.Subtract measured weights, workspace, graphs, and reserve from HBM; estimate the remaining physical KV-token capacity.
  3. Benchmark one request.Establish the best attainable TTFT and TPOT before queueing and batching.
  4. Sweep concurrency and arrival rate.Replay realistic and bursty traffic through the queueing knee, including long-prompt probes.
  5. Select the SLO operating point.Use the highest rate where all latency, quality, and error gates pass - not saturation throughput.
  6. Add headroom and failure capacity.Test a missing replica, rollout overlap, cold node, cache loss, and model reload.
replicas ≈ ceil(target demand ÷ goodput per replica × (1 + reserve fraction))
Reserve fraction is a decimal: 20% reserve = 0.20. Validate the result with failure and burst tests.
output token demand/s = request rate × E[output tokens]
Demand must be split by phase; average lengths alone hide bursts and tails.