Skip to Content
Recodocs

LLM inference infrastructure

Six levers that decide what serving an LLM costs — explained from first principles with plain mental models, exact math, production systems, and failure guards.

23 min read

Imagine a queue of customers asking an assistant questions. Each request spends time reading its input and time producing the answer; meanwhile, earlier conversations occupy memory. If the queue grows, the bottleneck may be memory capacity, memory bandwidth, compute, or repeated work. Buying a faster model without identifying which constraint is binding can make little difference.

This chapter follows one coding-agent session through those constraints. Read the numbers as a worked example, not as hardware-independent constants. The six serving techniques are answers to six different bottlenecks.

You ship a 10-turn coding agent on a 4×H100-80GB node (320 GB GPU memory, 140 GB for a 70B model, 180 GB left for conversations). Three things break immediately. First, live chat freezes for >500 ms whenever someone uploads a 30K-token file. Second, a single 128K-token conversation under full attention needs 335 GB of memory, so zero sessions fit (at 1M tokens it needs 2.62 TB, 19× the model's weights).

Third, your GPUs are 99.7% idle while generating words one at a time, locked to a 41.8 ms/word speed limit (~24 tokens/s). Meanwhile, your 10-turn agent bills $0.285/session instead of $0.106 because every tool call re-sends the whole conversation from scratch.

Every [R] figure below was re-derived in code. [V] marks vendor-reported claims, [S] marks secondary coverage, and [I] marks illustrative late-2026 models.

The unifying spine

Every LLM serving bill comes down to four questions. Two are about GPU hardware, and two are about how your app calls the model.

Plain questionEquationWhat it controls
Is the GPU waiting on math or memory?AI=FLOPsbytes_moved\mathrm{AI} = \frac{\text{FLOPs}}{\text{bytes\_moved}}Speed floor (H100 BF16 ridge ≈295 FLOPs/byte\approx 295\text{ FLOPs/byte}, FP8 ≈591\approx 591)
How big are the model's conversation notes?KV bytes/token=L×2×Hkv×dh×belem\text{KV bytes/token} = L \times 2 \times H_{\text{kv}} \times d_h \times b_{\text{elem}}Max concurrent users and step latency
How many tokens does a multi-turn agent send?total_input=T⋅P+g⋅T(T−1)2\text{total\_input} = T \cdot P + g \cdot \frac{T(T - 1)}{2}Quadratic bill growth over TT turns (PP base, gg new/turn)
What did one completed user task actually cost?effective_cost=total_session_costsuccessful_tasks_within_SLO\text{effective\_cost} = \frac{\text{total\_session\_cost}}{\text{successful\_tasks\_within\_SLO}}Real unit economics after retries, cache misses, and latency

Think of generating a word like carrying a 140 GB book off the shelf just to write one word. Reading a 2,048-word prompt (prefill) lets the GPU do lots of math per trip off the shelf, so it is compute-bound. Writing words one by one (decode) forces the GPU to carry all 140 GB from GPU memory (HBM) for every single word, so it is memory-bandwidth-bound.

Roofline: attainable throughput vs arithmetic intensityTwo regimes: memory-bound below 295 FLOPs/byte, compute-bound above. Decode at batch 1 sits at AI=1; prefill at 2048 tokens sits at AI2048.H100 BF16 roofline: memory-bound decode vs. compute-bound prefill989.5 TFLOP/s peak compute · 3.35 TB/s HBM bandwidth · ridge at ~295 FLOPs/byte1101001,0004,0001101001,000arithmetic intensity (FLOPs / byte) — log scaleattainable TFLOP/sridge ≈ 295 F/Bdecode (batch 1): AI = 1 → 3.4 TFLOP/s0.3% of compute roof (bandwidth-capped)prefill (2,048-token prompt)AI ≈ 2,048 (7× past the ridge)MEMORY-BOUNDCOMPUTE-BOUND
H100 BF16 roofline [R]. One user decoding uses 0.3% of the GPU's math roof. Batching shares that 140 GB trip across many users until hitting the roof near 295 concurrent tokens.

Batching is the only free lunch: when b users share one 140 GB weight read, GPU math utilization climbs linearly until ~295 concurrent tokens [R]. One catch remains—each user still reads their own conversation notes (KV cache), so attention stays memory-bound at any batch size.

Concurrent decoding users bEffective FLOPs% of H100 compute roof
13.4 TFLOP/s0.3%
32107.2 TFLOP/s10.8%
128428.8 TFLOP/s43.3%
256857.6 TFLOP/s86.7%
512989.5 TFLOP/s100% — roof reached

What this concept does not change

Buying faster GPUs or picking the cheapest $/Mtok price sheet will not fix slow streaming or runaway agent bills. Single-stream speed is capped by memory bandwidth, not math speed. Changing a single byte early in a prompt breaks caching at any price tier, and two providers serving the exact same model routinely differ 2–10× [S] because of hidden serving settings.

Toy walkthrough: one 10-turn coding session

Imagine an agent fixing a bug in 10 tool calls. It starts with a 5,000-token system prompt and tool list (P = 5,000), appends 1,500 tokens of file output each turn (g = 1,500), and writes 500 output tokens per turn. Prices are \$2/M input, \$10/M output, \$0.10/M cache reads (95% off), and 1.25× cache writes (\$2.50/M).

Naive setup (timestamp at token 400 + shared prefill/decode queue):
  Turn 1 (5.0K in):  cache misses -> $0.0150 cumulative
  Turn 5 (40.0K in): 30K upload stalls stream >500 ms -> $0.1050 total
  Turn 10 (117.5K in): 117.5K*$2/M ($0.235) + 5K out ($0.050) = $0.285

Fixed setup (timestamp at end + prefix caching + split P/D pools):
  Turn 1 (5.0K write): $0.0125 in + $0.0050 out = $0.0175 cumulative
  Turn 5 (34K read + 11K write): flat ITL on decode -> $0.0559 total
  Turn 10 (99K read + 18.5K write): $0.0562 in (-76%) + $0.050 = $0.106
  (Warm 5K prefix: 102.5K reads + 15K writes -> $0.098, 2.9x cheaper)

Moving one timestamp out of the prefix saved more money than a 50% list-price cut. Even with caching, a 10-turn session still costs 7.1× a single 5K-token call (\$0.015).

Lever 1 — Compress the KV cache

The key-value cache stores intermediate attention state for tokens already processed, so each new token does not have to rebuild that state from scratch. It trades memory for repeated work; compression changes that trade-off and may affect quality.

Spine target: KV bytes/token=L×2×Hkv×dh×belem\text{KV bytes/token} = L \times 2 \times H_{\text{kv}} \times d_h \times b_{\text{elem}}.

Plain idea: To write word 10,001, the model needs to check every earlier word. Re-reading the whole conversation from scratch on every word is too slow, so the GPU saves sticky notes (keys and values, called the KV cache) for every token. The catch is size: on a classic 70B model, those sticky notes grow to 2.62 TB at 1M tokens—19× heavier than the model itself [R].

Napkin check: On a 4×H100 node with 180 GB of spare GPU memory, full attention holds zero 128K-token chats, grouped heads (GQA) hold 4, and compressed latent notes (MLA) hold 20 [R]:

ArchitectureKB / tokenCache @ 128KCache @ 1MConcurrent 128K chats
MHA (80L, 64 KV heads, 128d, FP16)2,621335 GB2.62 TB0 — doesn't fit
GQA (80L, 8 KV heads, 128d, FP16)32841.9 GB328 GB~4
MLA (61L, 512+64 latent, FP16)709.0 GB70 GB~20

Because decode reads those notes on every word, smaller notes also speed up streaming. On GQA 70B at 100K context, reading ~33 GB of notes per step adds ~9.8 ms and slows a single stream from ~24 tok/s to ~19 tok/s [R].

Four model designs shrink the notes, while serving tricks stack on top of any model: FP8 quantization cuts notes in half (70 KB to 35 KB/token on MLA), PagedAttention removes memory waste for 2–4× throughput [V], and CPU/NVMe offload trades speed for extra room.

MovePlain-English trick & examplesReduction vs. baselineTrade-off
1. Share heads (MQA/GQA)Share 8 note pads across 64 heads (Llama 3, Mistral, Qwen)8× smaller (0.33 MB/tok)Negligible quality loss, hits a floor at 8×
2. Compress entries (MLA)Store one compact 512+64 summary vector (DeepSeek-V2/V3)~37× vs. MHA (70 KB/tok), 93.3% cut [V]Needs custom kernels, 5.76× throughput [V]
3. Keep fewer tokens (DSA / CSA+HCA)Index history and read only top matches (DeepSeek V3.2 / V4)27% FLOPs, 10% KV @ 1M (~7 GB) [V]Long-context recall risk [S], Blackwell FP4 fit
4. Replace growing layers (Hybrids)Use fixed-size memory in 3 of 4 layers (Qwen3-Next, Kimi Linear, Falcon-H1)Fixed-size recurrent stateSequential state complicates prefix replay

In an illustrative 1,000-chat fleet at 128K context on 4×H100 nodes [I], MHA fits zero chats, GQA needs ~250 nodes (4/node), and MLA needs ~50 nodes (20/node) while reading 9.0 GB instead of 41.9 GB per step.

Failure modes: KV compression

Failure modeTrigger -> Observable break -> Code-level guard
Needle-in-a-haystack recall dropAggressive stride or top-k compression drops rare facts -> silent retrieval misses on audit tasks -> validate on your own retrieval evals
Immature runtime kernelsDeploying MLA or FP4 indexers before engine kernels mature -> throughput lags dense baselines -> benchmark candidate vLLM/SGLang releases first
Hardware-coupled indexersFP4 indexers emulate in software on Hopper GPUs -> indexer latency eats memory savings -> verify hardware support matrix before selection

Lever 2 — Split prefill from decode

Prefill reads the input and builds its attention state. Decode then produces tokens one at a time. They stress hardware differently; separating them can protect interactive requests, but moving the cached state has a cost.

Spine target: AI=FLOPsbytes_moved\mathrm{AI} = \frac{\text{FLOPs}}{\text{bytes\_moved}} and KV_payload/link_bandwidth\text{KV\_payload} / \text{link\_bandwidth}.

Plain idea: Reading a 30,000-word PDF (prefill, which sets TTFT—the wait before the first word appears) and typing one word at a time (decode, which sets ITL—the pause between words) are opposite jobs. Putting both in one queue means every huge upload freezes 50 live chats mid-sentence. Chunked prefill slices the PDF between typed words, smoothing the stream at the cost of a slower first word.

Disaggregation puts each job on its own GPU pool—one desk reads PDFs, another desk types words—and ships the KV sticky notes across the network between them:

Client ─▶ KV-aware router ─▶ Prefill pool (math-tuned, scales on TTFT)
                                  │
                                  ▼  NIXL / Mooncake (~50 GB/s RDMA)
Client ◀──────────────────── Decode pool (memory-tuned, scales on ITL)

Napkin check: Shipping sticky notes is not free. At ~50 GB/s (PCIe or 400G RDMA networking), a 10K-token prompt takes 524 ms to ship under MHA, 66 ms under GQA, and just 14 ms under MLA [R] (over same-host NVLink at ~900 GB/s, GQA's 3.3 GB takes ~3.6 ms):

Prompt lengthMHA (2.6 MB/tok)GQA (0.33 MB/tok)MLA (0.07 MB/tok)
1K tokens52 ms7 ms1.4 ms
10K tokens524 ms66 ms14 ms
100K tokens5.2 s656 ms141 ms

Production stacks (NVIDIA Dynamo, vLLM Production Stack, SGLang, llm-d DisaggregatedSet, Mooncake) hide this shipping tax three ways: streaming notes layer-by-layer while prefill runs, moving bytes directly GPU-to-GPU (NIXL, LMCache), and matching tensor-parallel (TP) layouts across pools. Their routers also score nodes by prefix overlap so repeat sessions land where their notes already live.

When to split vs. stay monolithic

Split when prompts exceed ~10K tokens, agents re-prefill heavy history, or p99 TTFT/ITL interference freezes live chats. Stay monolithic when prompts sit at or below ~2K tokens with ~200-token outputs on well-batched servers, because the shipping hop costs more than the interference it removes.

Failure modes: disaggregation

Failure modeTrigger -> Observable break -> Code-level guard
Transfer exceeds interference gainKV handoff saturates links -> TTFT climbs past monolithic baselines -> instrument per-request transfer time and alert above 10% of TTFT
TP layout mismatchPrefill and decode use different tensor-parallel degrees -> receiver runs per-request transpose kernels -> standardize TP layouts per pool
Cache-affinity routing thrashRouter pins prefix-heavy tenants to one warm node -> queue depth spikes while cold nodes idle -> cap affinity weight against live queue depth
Mid-stream decode crashDecode worker drops after receiving transferred KV state -> request hangs or restarts cold -> drill KV re-materialization or prefill retry

Lever 3 — Spend idle FLOPs on guesses

Speculative decoding tries to make generation more efficient by proposing several possible next tokens and checking them against the target model. The useful comparison is how much verified output is produced per unit of work.

Spine target: AI=FLOPsbytes_moved\mathrm{AI} = \frac{\text{FLOPs}}{\text{bytes\_moved}} below the 295 FLOPs/byte295\text{ FLOPs/byte} ridge.

Plain idea: While writing one word at a time, 99.7% of the GPU's math cores sit idle waiting on memory. Speculative decoding puts a fast junior assistant (a tiny draft model or lookup table) in front of the big model. The assistant guesses kk words in a row, and the big model grades all k+1k + 1 positions in one 140 GB trip—accepting the matching prefix plus one bonus word with zero quality change.

Napkin check: If the big model agrees with 70% of guesses (p=0.7p = 0.7) across 4 drafted words (k=4k = 4), one trip outputs 2.77 words instead of 1 [R]:

How fast does speculative decoding actually feel?
A fast junior assistant guesses words ahead; the big model grades them all in one trip
At 70% match rate, 4 guesses, and 10% helper cost -> 2.77 words/trip (~2x faster).
Step 1 of 3 — How many words one big-model trip produces

Even if the assistant guesses badly, the big model still gives you 1 word for free. When the assistant matches 70% of the time across 4 guesses, those lucky streaks add up to 2.77 words per trip instead of 1.

1 / 3
Hover a symbol to spot it:

Here rr is how long one draft step takes compared to a big-model step (200k-trial Monte Carlo check: 2.77252.7725 vs. exact 2.77312.7731) [R]. Extra draft slots decay fast (pk+1p^{k+1} adds 0.49 at k=1, 0.17 at k=4, 0.04 at k=8), so teams stop at 4–6. If the assistant is too slow, speculation backfires: at p=0.7, k=4, speedup drops from 1.98× (r=0.10) to 1.54× (r=0.20), 1.26× (r=0.30), and 0.92× (slower) at r=0.50 [R]. Break-even sits at r=0.44r = 0.44.

DrafterHow it guessesAcceptance pCost rProduction profile
Small draft modelIndependent autoregressive passesModerate0.1–0.3Pays own weight reads
MedusaExtra parallel target headsModerate~0.05~2× reported [V]
EAGLE / EAGLE-3Reuses target features to draftHigh~0.1–0.23.0–6.5× reported [V]
n-gram / prompt-lookupCopies spans directly from promptSpiky~0.01Free; shines on RAG & code edits
MTP (DeepSeek-V3)Co-trained model-native heads85–90%~0.051.8× tokens/s reported [V]
SAM (ICLR 2026)Reasoning-oriented draftingHighLow2.66× vs. EAGLE-3's 1.93× on R1 [V]

Failure modes: speculative decoding

Failure modeTrigger -> Observable break -> Code-level guard
High-batch roofline flipConcurrency crosses ~295 tokens -> GPU turns compute-bound and verify math steals throughput -> gate speculation off above ~256 concurrent tokens
Structured-output grammar mismatchJSON schemas force legal-but-non-drafted tokens -> acceptance hits 60–75% [S] yet SGLang #9187 stalls slower than baseline -> disable if E1+k⋅r<1\frac{E}{1 + k \cdot r} < 1
Long-context triple taxDrafter reads growing cache, competes for decode HBM, and loses retrieval alignment -> r rises as p drops -> prefer n-gram lookup on RAG routes

Lever 4 — Sell capability by the token

More reasoning tokens may improve difficult answers, but they also spend time and money. Compare accuracy on the same task at different budgets, and check which budget actually meets the requirement.

Spine target: effective_cost\text{effective\_cost} and thinking_tokens×output_price\text{thinking\_tokens} \times \text{output\_price}.

Plain idea: Instead of waiting for a bigger model, test-time compute (TTC) lets the same model buy accuracy by using scratch paper before answering. Four knobs do this: voting across kk parallel tries, critique-and-revise loops, tree search with a scorer, and built-in long reasoning (reasoning_effort).

Napkin check: Extra thinking helps dramatically on hard problems and wastes money on easy ones. Snell et al. showed smart allocation lets a smaller model beat one ~14× larger on easy prompts. Similarly, s1 budget forcing ("Wait") pushed Qwen2.5-32B from 50% to 57% on AIME24, and o3 hit 87.5% on ARC-AGI using ~57M tokens/question [S].

Conversely, GSM8K and MATH-500 reach 95% of peak accuracy at just 256 thinking tokens. "Stop Overthinking" surveys document accuracy drops on overlong chains, and Apple's collapse study found accuracy collapses past complexity walls [S].

cost/problem = thinking_tokens × output_price (@ $60/M illustrative) [R]
  256 tokens -> $0.015    |    100K tokens -> $6.00
  1M tokens  -> $60.00    |    57M tokens  -> $3,420.00

Because those wins cluster on math and executable code, TTC pays reliably only where a cheap verifier can check the answer. Meanwhile, Epoch AI tracks the cost of a fixed score falling ~47% per quarter (~13×/year) [S], so effort policies need quarterly re-pricing.

Task classVerifierCompute-optimal policyGuardrail
Easy / chat / extractionImplicit1 pass, ~256 thinking tokensHard token cap; never escalate
Medium, verifiableUnit tests / scorerParallel best-of-k votek <= 4–8; per-request cap
Hard, verifiable, high-valueExplicit checkerSequential budget forcing / searchEscalation gate tied to task value
Open-ended prose / strategyNone reliableDefault effort; skip loopsBlock iterative loops without a scorer

Failure modes: test-time compute

Failure modeTrigger -> Observable break -> Code-level guard
Runaway reasonerAmbiguous prompt triggers unbounded deliberation -> single request bills tens or hundreds of dollars -> enforce hard per-request thinking caps in code
Overthinking easy trafficHigh reasoning effort applied globally -> 10–100× wasted output spend past the 256-token knee -> route effort by prompt difficulty
Unverified refinement loopSelf-critique runs without an executable checker -> model hallucinates fixes and degrades accuracy -> require a deterministic verifier or exit after one pass

Lever 5 — Bill the session, not the request

A multi-turn agent often sends the same instructions and earlier history repeatedly. Measure the whole session, not one model call; caching can remove repeated work without claiming the underlying evidence changed.

Spine target: T⋅P+g⋅T(T−1)2T \cdot P + g \cdot \frac{T(T - 1)}{2}.

Plain idea: Model APIs have no memory between calls. Every time an agent runs a tool, it re-mails the entire email thread—system prompt, tool schemas, and every earlier result—back to the model. That makes multi-step workflows consume 75–105× more tokens than single queries, and coding agents up to ~1,000× more (15K–1M+ tokens/task plus a 1.7–2.0× retry multiplier) [S].

Prefix caching is the escape hatch: the provider keeps the KV sticky notes from the old thread on their desk and charges just 5–10% of input price to reuse them, with a small write premium (1.25×–2×) and a time-to-live (TTL) [S]:

Model (direct API, late 2026 [S])Input $/MCache writeCache readOutput $/MTTL
Claude Opus 5.5$4.001.25× / 2×$0.20 (95% off)$20.005 min / 1 h
Claude Sonnet 5.5$2.001.25× / 2×$0.10 (95% off)$10.005 min / 1 h
Claude Haiku 5.5$0.101.25× / 2×$0.01 (90% off)$0.505 min / 1 h
GPT-6.1 Sol / class$2.001.25× / 2×$0.10 (95% off)$10.0030 min / 12 h
Gemini 4 Argon$2.00automatic$0.10 (95% off)$10.0024 h

The catch is prefix stability: changing one byte early in the prompt invalidates everything after it. Put static instructions, tool schemas, and docs first, and append dynamic turn outputs at the end. Agent loops also fatten the prefill pool, make cache-affinity routing (Dynamo, llm-d, Mooncake) essential, and make free n-gram speculation pay off on echoed code.

Failure modes: session economics

Failure modeTrigger -> Observable break -> Code-level guard
Mid-prompt cache busterPer-request timestamp or nonce inside the system prompt -> prefix invalidates and quadratic billing returns -> hash prefixes and alert below 80% hit rate
TTL mismatch5-minute cache expires during a 20-minute approval or tool call -> next turn pays a full write -> align TTL tier to loop cadence or compact at boundaries
Fat-tail loopFailing tool output triggers 200 retries at 500K context -> single session exhausts budget -> enforce loop-depth caps, token budgets, and isolated sub-agents

Lever 6 — Measure the serving function

A cheaper response is not a savings if it fails the task or arrives too late. The denominator is successful work within the service target, rather than the number of responses generated.

Spine target: effective_cost=total_session_costsuccessful_tasks_within_SLO\text{effective\_cost} = \frac{\text{total\_session\_cost}}{\text{successful\_tasks\_within\_SLO}}.

Plain idea: Comparing providers by $/Mtok is like buying a car from a brochure that lists sticker price and seat count, but hides gas mileage and top speed. Providers publish a feature catalog and hide the serving machinery—yet two providers serving the exact same open weights on identical GPUs routinely differ 2–10× in speed and latency [S].

Published feature catalogUnpublished serving function
Context limits and max outputBatch sizes and continuous-batching policy
$/Mtok tiers and rate limitsServed weight and KV quantization precision
Cache write premiums and TTLsCache eviction policy and KV pool topology
reasoning_effort parametersSpeculation gating and P/D split ratios

Napkin check: Take two providers both quoting \$2/M input and \$10/M output [I]. Provider A uses automatic 12-hour caching, KV-aware routing, FP8 weights, and isolated P/D pools—finishing our 10-turn session for $0.106 cold-start ($0.098 warm-prefix) with smooth streaming. Provider B uses 5-minute opt-in caching, round-robin routing, and colocated BF16 serving—billing ~$0.21 (~2× higher) with 3× p99 latency spikes.

Run this 5-step probe every quarter against candidate providers:

StepProbe actionWhat it exposes
1. Replay real trafficRun your prompt lengths, session depths, and schemas instead of public synthetic promptsTrue workload latency and cost baseline
2. Sweep concurrencyRecord p50 and p99 TTFT and ITL across concurrent streamsThe hidden continuous-batching knee
3. Probe prefix residencySend identical long prefixes across your actual loop cadenceEffective cache TTL, eviction, and discount
4. Score effective_costDivide total spend (with retries and write premiums) by tasks passing quality and latency SLOsReal procurement price per task
5. Re-probe quarterlyRe-run the suite every 90 days as silent backend changes land and costs fall ~47%/quarter [S]Stale priors before they hit production

Earned cheat sheet

LeverWhen it paysWhen to skipPrimary guardrail / alert
1. KV compression (MLA/GQA/hybrid + FP8 + PagedAttention)Long context, high concurrencyTiny prompts (<1K) on spare VRAMCompute KV bytes/token before evals; validate retrieval recall on your tasks
2. P/D disaggregationPrompts >10K, strict p99 ITLShort chat (<=2K in, 200 out)Alert if KV handoff exceeds 10% of TTFT; match TP layouts; monitor P:D ratio
3. Speculative decodingInteractive, low batch (<128)Saturated batches (>256)Toggle per route; log weekly EE; disable if E1+k⋅r<1.1×\frac{E}{1 + k \cdot r} < 1.1\times
4. Test-time computeHard verifiable code/mathEasy chat (<=256 tok) or proseRoute reasoning_effort by difficulty; enforce hard per-request token caps
5. Session prefix cachingMulti-turn agents, shared toolsOne-shot stateless promptsStatic prefix first, dynamic suffix last; alert <80% hit rate; cap loop depth
6. Quarterly traffic probeAny production procurementExperimental prototypesTrack effective_cost (with retries), not $/Mtok; rehearse tail-failure drills

How is this page?

Last updated on