Pidoku

Cost Per Token

Module 23 Lesson 23.c 1h 15m Difficulty 4/5

Prerequisites 1.d, 7.l, 23.b


Before you start: words you need#

WordPlain meaning
$/M tokensDollars per million tokens: the unit API providers price in, and the unit to compare everything with.
Input / output tokensTokens you send (the prompt, processed in prefill) and tokens the model generates (decode) (12.c).
Cached inputPrompt tokens whose KV cache was already computed and reused (12.m). Providers charge a fraction of the normal input price.
GPU-hourOne GPU for one hour. Its full cost (purchase, power, building, idle time) is built in 7.l.
UtilizationThe fraction of paid GPU time doing useful work. Idle time still costs money.
AttributionSplitting a shared bill fairly between tenants, teams or features.
KV block-secondsHow much KV-cache memory a request held, multiplied by how long it held it.
Build vs buyRunning your own inference fleet versus paying an API provider per token.

1. What is it?#

Cost per token is the total cost of running the inference fleet divided by the useful tokens it produced. Usually quoted per million output tokens, sometimes split into input and output.

                    everything you pay per hour
cost per token = ─────────────────────────────────
                  useful tokens produced per hour

7.l builds the numerator for one GPU: purchase price, interest, power, building, and the effect of idle time, ending in a cost per useful GPU-hour. This lesson starts from that number (or from a rental price) and builds the rest: throughput, waste, prefill, redundancy, the non-GPU platform, the split between input and output, per-tenant attribution, and the comparison with buying tokens from an API.

Facts checked on 12 November 2026.


2. Why does it matter?#

It is the one number that connects every engineering decision to the business, and the only fair way to compare configurations, models and providers.

"We improved throughput 30%"             → at what latency? on what hardware? so what?
"Cost per million output tokens fell
 from $2.69 to $1.35 at the same SLO"    → unambiguous, comparable, actionable

It is also the number your own costs are measured against. In November 2026 an API provider will sell you output tokens from a 70B-class open model for well under a dollar per million. If your fleet costs more than that, you need a reason other than price to run it.


3. Simple analogy#

A taxi company does not know its cost per kilometre from the price of the car. It adds fuel, insurance and the driver, then divides by the kilometres with a paying passenger. Driving empty back to the rank, waiting at the airport, and the spare car kept for breakdowns all count. The number on the meter has to cover all of it.


4. Tiny example#

One 8-GPU node rented at $20 per hour ($2.50 per GPU-hour), serving a 70B model at FP8, producing 8,136 output tokens per second while busy:

$20 ÷ (8,136 × 3,600) × 1,000,000 = $0.68 per million output tokens

That is the number people quote. It assumes the node is busy every second, that every token reaches a user, and that the node, alone, is the whole platform. None of that is true; section 5 adds each correction, and the real figure is about four times higher.


5. Technical explanation#

The full model#

NUMERATOR (per hour)                       typical share
  GPU nodes (owned → 7.l, or rented)          70–85%
  CPU hosts (gateway, router, tokenization)    3–8%
  storage (weights, caches, logs)              2–5%
  network (egress, cross-zone, load balancers) 2–8%
  observability (metrics, logs, traces)        1–4%
  control plane (registry, scheduler, K8s)     1–3%

DENOMINATOR (useful tokens per hour)
  tokens/s while busy × 3,600
  × average utilization over the day
  × (1 − waste: tokens for clients who left, padding)

Internal estimates that use only the GPU price and peak throughput are commonly far below the real figure. Every factor below is legitimate.

The waterfall#

CONFIGURATION
  70B dense model, FP8, one 8×H100 node, TP=8, batch ~96, ~4k context
  node price $20/hour; 8,136 output tokens/s while busy

STEP                         MULTIPLIER   $/M OUTPUT TOKENS
raw (busy, decode only)                        0.683
÷ utilization (58% over 24 h)    1.72          1.177
÷ (1 − prefill share 31%)        1.45          1.706   prefill time charged to output
÷ (1 − waste 20%)                1.25          2.133   14% aborted + 6% padding
× redundancy (N+1)               1.07          2.282
× non-GPU platform (+18%)        1.18          2.693

Notes on the steps:

  • Utilization is not “GPU utilization” from nvidia-smi (22.d). It is useful busy time over paid time, including the 3 a.m. trough.
  • Prefill. The raw figure counted only decode. Dividing by (1 − prefill share) puts prefill’s cost onto output tokens. The fairer alternative, used for pricing, splits the bill (below).
  • Waste. Tokens generated after the client disconnected are pure loss unless cancellation reaches the engine (20.e). Padding comes from CUDA-graph batch sizes (13.k).
  • Redundancy. The spare node earns nothing. Do not count headroom twice: if utilization is already the fleet-wide average, it already includes headroom idle time; add only what it leaves out.

Which parts you can fix#

FACTOR            TODAY   FIXED   HOW
utilization        58%     78%    consolidate models, fill troughs with batch work (23.d)
prefill share      31%     12%    prefix caching with prefix-aware routing (12.m, 21.h)
waste              20%      7%    cancellation propagation, tuned graph sizes

The program in section 6 reruns the waterfall: $2.69 → $1.35, a 50% cut with the same GPUs and the same model. Then come hardware and model levers: FP4 on Blackwell (13.g), speculative decoding (13.n), a smaller or MoE model, a newer GPU generation.

Input and output tokens#

Providers charge more for output than input. The reason is physics:

prefill: all prompt tokens in one compute-bound pass   ~50,000 tokens/s per node
decode:  one token per sequence per memory-bound step  ~8,100 tokens/s per node

per node-hour: input ≈ $0.11/M, output ≈ $0.68/M → an output token costs ~6× an input token

Price lists in November 2026 show the same shape: output costs roughly 3–8 times input, and cached input costs a small fraction of normal input (5–10% at the large providers, about half at some open-model hosts).

To attribute cost properly, measure the prefill/decode split of GPU time and divide each part by its own token count:

input $/token  = node $/h × prefill time share ÷ input tokens per hour
output $/token = node $/h × decode time share  ÷ output tokens per hour

This is how you price your own service and how you charge tenants.

Per-tenant attribution#

NAIVE   cost per request                       wrong: requests differ 1,000×
BETTER  input × in_price + output × out_price
BEST    + cached_input × cached_price
        + kv_block_seconds × kv_price          ← long contexts hold memory others need

A request with a 100k-token context holds about 25 times the KV of a 4k request for its whole life, denying that memory to everyone else. Charging only for tokens under-charges long-context users. Some providers now price this directly: a higher per-token rate for prompts above a length threshold is a KV-occupancy charge in disguise.

kv_price per block-second = node $/second × share of node cost you assign to memory
                            ÷ KV blocks on the node

Emit kv_block_seconds per request (23.h). Few systems do; it is the missing term in most attribution models. 21.f covers how quotas and fair sharing use the same accounting.

Build vs buy#

SELF-HOSTED
  your $/M from the waterfall
  + platform engineers (say 3 people, ~$750k a year fully loaded)
  + capacity risk, procurement lead time, on-call

API
  published $/M, no capacity risk, instant scale
  but: data handling and residency, their region's latency, their model list,
       rate limits, limited control over versions and fine-tunes

BREAK-EVEN tokens/year = engineering cost ÷ (API $/token − your $/token)

Reference prices, checked 12 November 2026 (list prices; they move monthly):

OfferingInput $/MOutput $/MNotes
Llama 3.3 70B Instruct Turbo on DeepInfra0.100.32open-weight 70B dense
gpt-oss-120b on Fireworks0.150.60open-weight MoE; batch 50% off
Claude Haiku 5.50.100.50prompts over 100k tokens: 0.50 / 2.50
Claude Sonnet 5.52.0010.00cache hits 0.10; batch 50% off
Claude Opus 5.54.0020.00fast mode (up to 2.5× speed): 8 / 40
GPT-5.5 (as reported by several trackers)5.0030.00cached input reported at 0.50

What this says:

  • For a popular open model, you will not beat an API on price at moderate scale. Hosts pool thousands of customers, run at high batch on the newest GPUs with FP8/FP4, and may price near or below cost. At $0.32 per million output tokens, the program shows self-hosting never wins on cost alone.
  • The reasons to self-host are elsewhere: data that may not leave your network, your own fine-tunes, latency and version control, very high steady volume, or capacity you already own.
  • Per-user speed is now priced separately. “Fast” tiers at about 2× the price for about 2.5× the speed show that low-batch serving costs more per token, as 2.d predicts.

Compare like with like: a blended cost per request (your input/output mix, your cache hit rate) against the API’s blended price for the same mix.


6. Under the hood#

The waterfall, the fixed version, the input/output split and a break-even calculation in one program.

Go
// costpertoken.go — from a node's hourly price to the real cost per million output tokens.
package main

import "fmt"

type fleet struct {
	nodePerHour    float64 // $ per node-hour (8 GPUs), rented or from a TCO model (7.l)
	decodeTokSec   float64 // measured output tokens/s per node at the operating point
	avgUtil        float64 // average busy fraction over 24 h
	prefillShare   float64 // fraction of busy GPU time spent on prefill
	wasteShare     float64 // tokens nobody received (aborts) + padding
	redundancy     float64 // spare capacity held for failures (N+1 → 1.07 for 15 nodes)
	nonGPUOverhead float64 // gateways, storage, network, observability, as a fraction of GPU cost
}

func (f fleet) waterfall(print bool) float64 {
	raw := f.nodePerHour / (f.decodeTokSec * 3600) * 1e6
	steps := []struct {
		name string
		mult float64
	}{
		{"÷ utilization", 1 / f.avgUtil},
		{"÷ (1 − prefill share)", 1 / (1 - f.prefillShare)},
		{"÷ (1 − waste)", 1 / (1 - f.wasteShare)},
		{"× redundancy", f.redundancy},
		{"× (1 + non-GPU overhead)", 1 + f.nonGPUOverhead},
	}
	cost := raw
	if print {
		fmt.Printf("  %-26s        $%.3f\n", "raw (busy, decode only)", raw)
	}
	for _, s := range steps {
		cost *= s.mult
		if print {
			fmt.Printf("  %-26s ×%.2f  $%.3f\n", s.name, s.mult, cost)
		}
	}
	return cost
}

func main() {
	today := fleet{nodePerHour: 20, decodeTokSec: 8136, avgUtil: 0.58, prefillShare: 0.31,
		wasteShare: 0.20, redundancy: 1.07, nonGPUOverhead: 0.18}
	fmt.Println("today, $ per million output tokens:")
	c1 := today.waterfall(true)

	better := today
	better.avgUtil, better.prefillShare, better.wasteShare = 0.78, 0.12, 0.07
	fmt.Println("\nafter consolidation, prefix caching and cancellation:")
	c2 := better.waterfall(true)
	fmt.Printf("\nsaving: %.0f%% with the same GPUs and the same model\n", (1-c2/c1)*100)

	// Split one node-hour between input and output tokens by measured GPU time.
	const inTokSec, outTokSec = 50000.0, 8136.0 // prefill and decode rates when each runs alone
	in := 20 / (inTokSec * 3600) * 1e6
	out := 20 / (outTokSec * 3600) * 1e6
	fmt.Printf("\nGPU-time price: input $%.3f/M, output $%.3f/M → output costs %.1f× input\n",
		in, out, out/in)

	// Build vs buy: when does a self-hosted platform beat an API price?
	const engineersPerYear = 750000.0 // ~3 engineers, fully loaded
	for _, api := range []float64{0.32, 2.00, 10.00} {
		if api <= c2 {
			fmt.Printf("API at $%5.2f/M output: self-hosting never wins on cost\n", api)
			continue
		}
		breakeven := engineersPerYear / ((api - c2) / 1e6) // tokens per year
		fmt.Printf("API at $%5.2f/M output: break-even at %.1f billion output tokens/year\n",
			api, breakeven/1e9)
	}
}

Output:

today, $ per million output tokens:
  raw (busy, decode only)           $0.683
  ÷ utilization              ×1.72  $1.177
  ÷ (1 − prefill share)      ×1.45  $1.706
  ÷ (1 − waste)              ×1.25  $2.133
  × redundancy               ×1.07  $2.282
  × (1 + non-GPU overhead)   ×1.18  $2.693

after consolidation, prefix caching and cancellation:
  raw (busy, decode only)           $0.683
  ÷ utilization              ×1.28  $0.875
  ÷ (1 − prefill share)      ×1.14  $0.995
  ÷ (1 − waste)              ×1.08  $1.070
  × redundancy               ×1.07  $1.145
  × (1 + non-GPU overhead)   ×1.18  $1.351

saving: 50% with the same GPUs and the same model

GPU-time price: input $0.111/M, output $0.683/M → output costs 6.1× input
API at $ 0.32/M output: self-hosting never wins on cost
API at $ 2.00/M output: break-even at 1154.9 billion output tokens/year
API at $10.00/M output: break-even at 86.7 billion output tokens/year

Against a $2 per million price, break-even needs over a trillion output tokens a year, about 37,000 tokens per second around the clock. Against a premium model’s price it comes much sooner, but then the comparison is only fair if your model is as good.


7. Performance implications#

  • Throughput at the SLO is the lever. Doubling tokens per second at the same latency halves cost per token on hardware you already pay for (7.l).
  • Utilization usually beats raw speed. In the waterfall, utilization (×1.72) costs more than any single kernel optimization would save.
  • Batch size trades latency for cost. Larger batches cut cost per token and raise ITL; the SLO (23.a) decides where to stop.

8. Production implications#

  • Track $/M tokens as a first-class metric, per model and per tenant, trended daily (22.j).
  • Decompose it into the waterfall factors so you know which to attack.
  • Report input and output costs separately, and cached input as its own line.
  • Attribute to tenants, including KV occupancy, and publish it internally: visibility changes behaviour.
  • Set a cost target next to the SLO. “p95 TTFT < 800 ms at < $1.50 per million output tokens” is a complete engineering objective.
  • Recompute after every optimization and every price change, yours and the market’s.

9. Common mistakes#

  1. Using only the GPU price and peak throughput. Several times too low.
  2. Ignoring utilization. Often the largest single factor.
  3. Not attributing prefill. Under-prices input-heavy workloads such as RAG and agents.
  4. Ignoring aborted generations. Tokens nobody read still cost GPU time.
  5. Charging per request in a multi-tenant system.
  6. Not charging for KV occupancy. Long-context users are subsidised.
  7. Comparing your cost to an API without engineering cost, or comparing output-only prices when the workload is mostly input.
  8. Computing it once. It moves with every configuration change and every price cut.

10. Hands-on exercise#

  1. Run costpertoken.go with your own node price and measured throughput. How far is the real figure from the raw one?
  2. Which factor in your waterfall is largest? Which is cheapest to fix? Estimate the annual saving.
  3. Measure your prefill/decode time split and compute separate input and output prices. How does the ratio compare with the providers’ ratios in the table?
  4. Add kv_block_seconds to your request logs and rank tenants by cost per token. Is the most expensive tenant the one you expected?
  5. Compute the break-even volume against the cheapest API that serves a model of the same quality. Then list the non-price reasons that would still justify self-hosting.

11. Interview questions#

  1. Derive cost per token from a node’s hourly price and its throughput. What is missing from that first number?
  2. Name the factors between raw and real cost. Which can you fix without new hardware?
  3. Why do output tokens cost more than input tokens? Derive the ratio.
  4. Why are cached input tokens so much cheaper?
  5. How would you attribute cost to tenants in a shared cluster, and why charge for KV occupancy?
  6. An API sells your model at $0.32 per million output tokens. Should you self-host?
  7. Your cost is four times your estimate. Where did the estimate go wrong?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

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