Pidoku

Why Inference Gets Expensive at Scale

Module 1 Lesson 1.d 1h Difficulty 2/5

Prerequisites 1.a–1.c


Before you start#

WordPlain meaning
GPU-hourRenting one GPU for one hour. Cloud prices are quoted this way.
Decode stepOne pass of the model that produces one new token for every request in the batch (1.a, 12.d).
Memory bandwidthHow many bytes per second the GPU can read from its own memory (HBM). For decoding this, not arithmetic speed, usually sets the pace — lesson 2.e explains why.
UtilisationThe fraction of paid GPU time spent doing useful work.
Prefill / decodeReading the prompt vs. generating the answer token by token (1.a, 12.c).

1. What is it?#

This lesson is about the money: where it goes, why costs grow the way they do, and which engineering levers actually move the number.

The headline: producing one LLM token costs roughly a million times more than fetching a database row. At scale, that ratio turns inference efficiency into a business problem, not an engineering nicety. You will build the cost model yourself, from GPU price to dollars per million tokens.


2. Why does it exist?#

Three factors multiply together.

1. The hardware is expensive and must be dedicated. In late 2026, renting an H100 costs roughly $2–4.50 per hour from GPU-specialist clouds and $5–12 per hour from the big hyperscalers before discounts; a B200 roughly $4–8 per hour (checked on 11 November 2026 — prices moved up in 2026 after falling in 2025). Unlike a CPU, a GPU cannot be finely shared between unrelated jobs, because the model’s weights fill its memory. You pay for it whether it works or not.

2. The work per interaction is enormous. A chat turn with a 70B dense model generating 500 tokens needs about 70 trillion arithmetic operations, and — because every decode step reads all 140 GB of weights — tens of terabytes of memory traffic if it ran alone. That is more work than a web server does in a day. Reasoning models and agents multiply it again (1.e).

3. Keeping GPUs busy is hard. Traffic is bursty, decoding uses the GPU poorly unless many requests share each step, and long requests block short ones. A GPU doing 20% useful work makes each token five times more expensive than one doing 100%.

Multiply the three and you have the industry’s defining cost problem.


3. Simple analogy#

Chartering a private jet versus taking a bus.

The jet (GPU) costs the same per hour whether it carries one passenger or twelve. Your job is to fill the seats. One passenger pays for the whole flight; twelve split it.

Now add what makes it hard:

  • Passengers arrive at random times, and you cannot make them wait forever (a latency target).
  • Some fly 100 miles, others 4,000 (output length varies wildly).
  • A new jet takes eight minutes to start (cold start), so you cannot summon one per passenger.
  • An empty seat cannot be sold later — capacity is perishable.

Almost every technique in this material is a way to sell more seats per flight without making anyone wait too long.


4. Tiny example#

Work out the cost per million output tokens from first principles. The setup: a 70B dense model with 16-bit weights, split across 8 H100 GPUs (each holds one-eighth of the model; Module 14 explains how), rented at $2.50 per GPU-hour.

The key fact you need (lesson 2.e proves it): during decoding, each step reads every weight once, plus the KV cache of every request in the batch. Reading is the slow part, so:

step time ≈ bytes read per GPU ÷ memory bandwidth + a little overhead

The program below does the arithmetic and then asks “what if?” for the main levers:

Go
// costmodel: cost per million output tokens, from first principles.
package main

import "fmt"

type setup struct {
	name        string
	gpus        int
	dollarsPerH float64 // per GPU-hour
	weightsGB   float64 // weight bytes per GPU, GB
	kvPerTokKB  float64 // KV cache bytes per token, per GPU, KB
	avgContext  float64 // average tokens of context per running request
	batch       float64 // requests decoding together
	bwTBs       float64 // achieved HBM bandwidth per GPU, TB/s
	overheadMs  float64 // communication + launch overhead per step
}

// decode step time: every step reads the weights once plus every running request's KV cache.
func (s setup) stepMs() float64 {
	kvGB := s.batch * s.avgContext * s.kvPerTokKB / 1e6
	return (s.weightsGB+kvGB)/s.bwTBs + s.overheadMs // GB / (TB/s) = ms
}

func (s setup) dollarsPerM(util, prefill, spare, waste float64) float64 {
	tokPerSec := s.batch / (s.stepMs() / 1000)
	perTok := float64(s.gpus) * s.dollarsPerH / 3600 / tokPerSec
	return perTok * 1e6 / util * prefill * spare * waste
}

func main() {
	// 70B dense model, 16-bit weights, tensor parallel over 8 H100s at $2.50/GPU-hour.
	// KV: 320 KB per token in total (9.e), split over 8 GPUs = 40 KB per GPU.
	base := setup{"70B FP16, 8xH100", 8, 2.50, 17.5, 40, 2048, 64, 3.0, 1.5}
	fmt.Printf("decode step: %.1f ms, %.0f output tokens/s per node\n",
		base.stepMs(), base.batch/(base.stepMs()/1000))
	ideal := base.dollarsPerM(1, 1, 1, 1)
	real := base.dollarsPerM(0.40, 1.15, 1.3, 1.1)
	fmt.Printf("ideal (100%% busy):            $%.2f per M output tokens\n", ideal)
	fmt.Printf("realistic (40%% util, +prefill, +spare, +waste): $%.2f\n\n", real)

	type change struct {
		name string
		s    setup
		util float64
	}
	b8, b256, fp8 := base, base, base
	b8.batch, b256.batch = 8, 256
	fp8.weightsGB, fp8.kvPerTokKB = 8.75, 20
	all := fp8
	all.batch = 256
	for _, c := range []change{
		{"baseline", base, 0.40},
		{"batch 64 -> 8 (poor batching)", b8, 0.40},
		{"batch 64 -> 256", b256, 0.40},
		{"FP16 -> FP8 weights and KV", fp8, 0.40},
		{"utilisation 40% -> 70%", base, 0.70},
		{"all three together", all, 0.70},
	} {
		v := c.s.dollarsPerM(c.util, 1.15, 1.3, 1.1)
		verdict := fmt.Sprintf("%.1fx cheaper", real/v)
		if v > real {
			verdict = fmt.Sprintf("%.1fx dearer", v/real)
		}
		if c.name == "baseline" {
			verdict = ""
		}
		fmt.Printf("%-32s $%5.2f  %s\n", c.name, v, verdict)
	}
}

Output:

decode step: 9.1 ms, 7048 output tokens/s per node
ideal (100% busy):            $0.79 per M output tokens
realistic (40% util, +prefill, +spare, +waste): $3.24

baseline                         $ 3.24  
batch 64 -> 8 (poor batching)    $21.56  6.7x dearer
batch 64 -> 256                  $ 1.28  2.5x cheaper
FP16 -> FP8 weights and KV       $ 1.89  1.7x cheaper
utilisation 40% -> 70%           $ 1.85  1.7x cheaper
all three together               $ 0.40  8.0x cheaper

Read it carefully:

  1. The hardware alone costs $0.79 per million tokens — if the GPUs were busy 100% of the time.
  2. Reality multiplied that by four. The “realistic” line divides by 40% average utilisation and adds 15% for prefill time, 30% for spare capacity and 10% for abandoned or failed generations. Most cost work is not making the GPU faster; it is making sure it does useful work.
  3. The same model on the same hardware ranges from $21.56 to $0.40 — a 50x spread — depending on batching, number format and utilisation. Add prefix caching (12.m), speculative decoding (13.n) or a smaller model where quality allows, and the spread grows further.

That spread is the entire justification for this field. It is also why providers charge very different prices for the same open model.


5. Technical explanation#

The cost model#

                 hardware $ per hour
cost / token = ───────────────────────────────────────────────
               3600 × (B / T_step) × U × (1 − waste)

 lever      what it changes                                typical spread
 ──────────────────────────────────────────────────────────────────────────
 hardware   $ per hour per unit of memory bandwidth          1–3x
 B          batch size (scheduler quality, memory left)      2–20x
 T_step     number format, kernels, model size and design    2–8x
 U          utilisation (traffic shaping, consolidation)     1.5–4x
 waste      cancellations, retries, padding                  1.1–1.5x

Multiplying the achievable ranges gives a 10–100x total spread, unusually large for a software discipline.

Where the money actually goes#

For a typical production LLM deployment:

GPU time                              70–85% of the bill
  ├─ decode                             50–70% of GPU time
  ├─ prefill                            15–35%
  └─ idle and gaps                       5–30%   ← the recoverable part
Networking (especially multi-node)     2–8%
Storage (weights, caches, logs)        2–5%
CPU hosts (tokenisation, gateway)      3–8%
Observability and logging              1–4%

The “idle and gaps” line is where effort pays. Gaps come from:

  • a batch that is not full (too little traffic, or an over-cautious scheduler),
  • long prompts blocking everyone else (fixed by chunked prefill, 12.k),
  • pausing and swapping requests when KV cache memory runs out (12.l),
  • per-step CPU overhead (fixed by CUDA graphs, 13.k),
  • uneven load across replicas (21.h),
  • draining replicas before deployments.

Why cost grows faster than context length#

Doubling the context does not just double the cost:

1. The KV cache doubles      → half as many requests fit → batch halves
                             → cost per token roughly doubles
2. Attention work per generated token doubles (it reads twice as much history)
3. Prefill work up to quadruples (attention over the prompt grows with its square)
4. Longer requests hold memory longer → more blocking of others

Going from 4k to 32k tokens of context often costs 4–8x more per token. That is why long-context pricing is steep, and why prefix caching (12.m), compact attention designs (12.g), KV cache quantization (13.h) and offloading to cheaper memory (14.k) matter commercially.

Prefill vs decode economics#

Prompt-heavy work (RAG, summarisation, code review, agent turns with long history):
  10,000 tokens in : 500 out
  Prefill dominates. Optimise: prefix caching, chunked prefill, compute-efficient kernels.

Output-heavy work (writing, reasoning traces):
  100 tokens in : 4,000+ out
  Decode dominates. Optimise: quantization, batching, speculative decoding, GQA/MLA, MoE.

These want different settings and sometimes different hardware — which is why large deployments now run prefill and decode on separate pools of GPUs (14.j). Providers charge more for output tokens than input tokens (commonly 3–5x) for the same reason: prefill uses the GPU efficiently, decode does not, and cached input is cheaper still.


6. Under the hood#

Where a “wasted” GPU-second physically goes:

One GPU-second under a mediocre scheduler:

|■■■■ decode batch 12 ■■■■|░░ idle ░░|■ prefill ■|░ preempt/swap ░|■■■ decode ■■■|
      420 ms                180 ms      150 ms        90 ms          160 ms

  Busy:    420 + 150 + 160 = 730 ms
  Wasted:  270 ms  (27%)
  And the decode ran with 12 requests when memory allowed 48
    → effective utilisation ≈ 0.73 × (12 / 48) ≈ 18%

The second line is the one people miss. Running is not the same as running efficiently. A GPU that is 100% busy with 4 requests when it could serve 64 wastes 94% of its economic value — and every standard dashboard shows it as healthy. That is why KV cache usage and the average number of running requests belong on your main dashboard (23.h).


7. Performance implications#

The cost levers ranked by typical impact per unit of effort:

RankLeverTypical gainEffortLesson
1Use an engine with continuous batching (vLLM, SGLang, TensorRT-LLM)3–10xlow12.j, Module 15
2Prefix caching, if prompts share beginnings (agents, chat, RAG)1.3–5xlow12.m
3FP8 weights and KV cache; FP4 on Blackwell-class GPUs1.5–3xlow–medium13.e, 13.g
4Right-size the model — do you need the biggest one?2–10xmedium (needs evaluation)21.k
5Cancel abandoned generations1.1–1.4xlow1.c
6Raise utilisation by pooling traffic onto shared fleets1.5–3xmedium21.f
7Chunked prefill and better scheduling1.2–1.5xlow (configuration)12.k
8Speculative decoding1.3–2.5xmedium13.n
9CUDA graphs and kernel fusion1.1–1.4xmedium13.j, 13.k
10Custom kernels1.05–1.3xvery high6.e

The top of the list is mostly configuration and product decisions, not deep systems work. Teams routinely jump to #10 while leaving #1–#5 undone. Work down the list in order.


8. Production implications#

  • Track cost per million tokens as a first-class metric, per model and per tenant. Without it you cannot tell whether an optimisation worked.
  • Attribute cost to tenants. In a shared platform, one customer with 100k-token prompts can consume most of the fleet (21.f).
  • Mix purchase models. Reserved capacity for the steady baseline, on-demand for spikes, spot or preemptible GPUs for batch work; prices differ by 2–4x.
  • Build vs buy is real arithmetic. At low volume an API is cheaper than your own GPUs, because the provider keeps its GPUs busier than you will. The crossover is usually around keeping a few GPUs busy around the clock. Include engineer time in the comparison.
  • Trade cost against quality deliberately. A router that sends easy requests to a small model and hard ones to a large model (21.k) can cut cost several times with little quality loss — measure it.

9. Common mistakes#

Optimising the kernel before the scheduler. A 20% faster attention kernel on a system running 4 requests at a time is worth far less than fixing why it runs only 4.

Measuring cost at peak. Cost is set by average utilisation over the whole day, including 3 a.m. Report cost per million tokens over 24 hours, not during a load test.

Ignoring prefill. For RAG and agent workloads, prefill can be most of the GPU time. A cost model that counts only output tokens is badly wrong.

Forgetting spare capacity. Running at 100% of capacity is not a plan; spare capacity for failures and spikes is typically 20–40% of a fleet.

Assuming the newest GPU is always the best value. Compare dollars per unit of memory bandwidth and per unit of compute for your workload. For decode-heavy serving, an older GPU with good bandwidth per dollar can beat a newer one (Module 8).

Not measuring your own platform overhead. Gateways, sidecars and logging can quietly add 10–15%.


10. Hands-on exercise#

A. Make the model yours. Run the program with a GPU price you can actually get today and a model you might serve. Add a separate cost per million input tokens, using a prefill speed of 10,000 tokens per second per GPU as a starting guess.

B. Sensitivity. Change each lever by ±50% and rank them by effect. Which three matter most for your configuration? Does the ranking match section 7?

C. Compare with the market. Look up current API prices for an open model of similar size. What utilisation would you need to match that price on your own GPUs?

D. Find the waste. On a running engine, measure the average number of running requests, KV cache usage and the share of GPU time in prefill, decode and idle. Compute effective utilisation as busy fraction × (average batch ÷ maximum batch). Most teams are shocked the first time.


11. Interview questions#

  1. Derive cost per token from hardware cost and throughput. What are the terms?
  2. Why do output tokens cost more than input tokens?
  3. Why does cost grow faster than linearly with context length? Give three mechanisms.
  4. Rank the top five cost optimisations for an LLM service and justify the order.
  5. Your GPU shows 100% utilisation but cost per token is four times your estimate. What do you investigate?
  6. When does self-hosting beat an API? Show the calculation.
  7. How would you attribute cost to tenants in a shared inference cluster?

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in