Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 1: Foundations

Chapter 4Performance and cost math

30 min read, 1 lab, Intermediate

The same GPU can serve a million output tokens for about 10 cents or for over 5 dollars, a more than 50-fold difference decided almost entirely by how you batch requests. This chapter gives you the handful of formulas that predict latency, throughput, GPU count and cost before you rent anything, and the habits to check them against measurements.

After this chapter you can

  • Convert a model and a workload into bytes, FLOPs and tokens per second
  • Define TTFT, inter-token latency and end-to-end latency, and read them as percentiles
  • Explain how batch size trades per-user speed for total throughput
  • Compute cost per million tokens from a GPU's hourly price and measured throughput
  • Size a deployment from requests per second, tokens per request and a latency target

Tokens are the unit of work

Every number in this chapter is per token, so first convert traffic into tokens. A request has input tokens (the prompt, including system prompt, history and retrieved documents) and output tokens (what the model generates). The two cost very different amounts of hardware time, which is why API providers price output tokens several times higher than input tokens.

PhaseWhat happensBound bySpeed per GPU
PrefillAll input tokens processed in one parallel forward passCompute (FLOPS)Thousands to tens of thousands of tokens per second
DecodeOne output token per forward pass, sequentiallyMemory bandwidthTens to a few hundred tokens per second per sequence

The Inference fundamentals chapter explains the mechanics of each phase. Here you only need the consequence: prefill costs FLOPs, decode costs bytes.

Prefill compute = 2 x params x input_tokens
  8B model, 1,000-token prompt: 2 x 8.03e9 x 1,000 = 1.6e13 FLOPs
  H100 at 40% of 989 TFLOPS:    1.6e13 / 3.96e14  = about 41 ms
 
Decode, batch 1 = weight bytes / effective bandwidth, per token
  8B BF16 (16.1 GB), H100 at 60% of 3.35 TB/s:  16.1e9 / 2.0e12 = about 8 ms
  -> about 124 tokens per second for one user

The 40 and 60 percent factors are realistic efficiencies; real software rarely reaches vendor peaks. Calibrate them from your own measurements, as the lab does.

Latency metrics users feel

A streaming chat request has three latencies worth measuring separately, because they fail for different reasons.

MetricDefinitionDriven byTypical chat target
TTFT (time to first token)Request sent to first token receivedQueueing plus prefillUnder 1 second
ITL (inter-token latency)Gap between consecutive output tokens; TPOT (time per output token) is its averageDecode step time, so batch size and bandwidthUnder 50 ms (20+ tokens per second, faster than reading speed)
End-to-end latencyRequest sent to last token receivedBoth, plus output lengthDepends on output length
end_to_end = TTFT + (output_tokens - 1) x ITL
             0.4 s + 299 x 0.035 s = about 10.9 s for a 300-token answer

Batch jobs (summarizing a million documents overnight) care only about throughput and cost. Interactive products care about TTFT and ITL. Decide which you are serving before optimizing anything.

Percentiles, not averages

Latency distributions have long tails: most requests are fast, a few are very slow, and the slow ones are what users remember. Report the p50 (median), p95 and p99: the latency that 50, 95 and 99 percent of requests beat. An average hides the tail, because a handful of 30-second requests barely move it.

10 measured TTFTs (ms): 210 220 230 240 250 260 280 300 900 4,800
 
mean = 769 ms       looks bad but describes no real request
p50  = 255 ms       the typical user
p90  = 900 ms       one user in ten waits this long or longer
max  = 4,800 ms     probably queued behind a long prompt

Tails grow fastest as a system approaches full capacity. In simple queueing models the average wait grows like utilization / (1 - utilization), which is why capacity plans target 60 to 80 percent load, not 100.

Load (utilization)Relative queueing delay
50%1x
80%4x
90%9x
95%19x

Batch size trades latency for throughput

At batch size 1, each decode step reads all 16 GB of weights to produce one token. With 64 sequences in the batch, the same read produces 64 tokens, and each step is only a little slower because the extra work is the sequences' KV caches. This is the single largest lever on cost.

The table models Llama 3.1 8B in BF16 on one H100 at 60 percent effective bandwidth, each sequence holding 1,300 tokens of KV cache (about 0.17 GB). It is the output of the lab's calculator.

BatchStep timeTokens/s per userTokens/s per GPU
18.1 ms124124
88.7 ms115923
3210.7 ms932,990
6413.4 ms754,771
12818.8 ms536,794
25629.7 ms348,622

Two ceilings stop you: the inter-token latency target (here, a 50 ms limit allows a very large batch) and memory for the KV cache. Serving engines with continuous batching, covered in the Serving engines chapter, keep the batch full as requests come and go.

Utilization means three different things

"The GPU is at 100 percent" usually comes from nvidia-smi, and that number is the fraction of time at least one kernel was running. It says nothing about how much of the chip did useful work. Use the metric that matches the bottleneck.

MetricFormulaDecode, batch 1, 8B BF16 on H100 at 124 tok/s
GPU utilization (nvidia-smi)Time with any kernel active / wall timeClose to 100%
MBU (model bandwidth utilization)Bytes moved per second / peak bandwidth124 x 16.1 GB / 3.35 TB/s = about 60%
MFU (model FLOPs utilization)Useful FLOPs per second / peak FLOPS124 x 1.6e10 / 9.89e14 = about 0.2%

For decode-heavy serving, track MBU and tokens per second per GPU. For training and prefill, track MFU; well-tuned large training runs commonly reach 35 to 50 percent. A GPU showing 100 percent utilization at 0.2 percent MFU is busy, not efficient.

Cost per million tokens

Throughput turns an hourly GPU price into a unit cost. The formula is short:

cost per million tokens = GPU price per hour / (tokens per second x 3,600) x 1,000,000

Prices are approximate and change monthly. As of late 2026, on-demand H100 prices are roughly 2 to 4 US dollars per GPU-hour at specialist GPU clouds and roughly 7 to 12 dollars at the large hyperscalers; reserved contracts and spot capacity go lower. Using the batch table above, cost per million output tokens is:

Throughput per GPUAt 2.50 dollars per hourAt 4 dollars per hourAt 10 dollars per hour
124 tok/s (batch 1)5.608.9622.40
4,771 tok/s (batch 64)0.150.230.58
8,622 tok/s (batch 256)0.080.130.32

Three effects push real costs above these ideal numbers: GPUs idle between traffic peaks, you keep headroom for latency, and prefill consumes GPU time that produces no output tokens. Divide by your real average utilization; at 40 percent average load, multiply the table by 2.5. The Cost engineering and GPU economics chapter covers buy versus rent versus API.

Sizing a deployment

Capacity planning combines everything above with Little's law: the average number of requests in flight equals arrival rate times average time in the system. You compute how many sequences must be in flight at once, then how many GPUs can hold them within the latency target.

  1. Write down the workload

    20 requests per second at peak, 1,000 input and 300 output tokens each, p95 ITL under 50 ms, TTFT under 1 second. Model: Llama 3.1 8B in BF16 on H100s.

  2. Find the batch per GPU

    Memory after weights holds about 328 sequences of 1,300 tokens. At that batch, a step takes about 36 ms, under the 50 ms target, so each user gets about 28 tokens per second.

  3. Apply Little's law

    Each request lasts about 0.04 s of prefill plus 300 x 0.036 s of decode, about 10.8 s. In flight: 20 x 10.8 = about 216 sequences, which is 0.66 of one GPU's batch capacity.

  4. Add prefill compute

    20 x 1,000 input tokens per second x 1.6e10 FLOPs per token = 3.2e14 FLOP/s, which at 40 percent MFU is 0.81 of an H100. Prefill is a large share of the load for prompt-heavy work.

  5. Add headroom and price it

    0.66 + 0.81 = 1.47 GPUs of load. At a 70 percent utilization target, that is 3 GPUs. At about 3 dollars per GPU-hour: 9 dollars per hour, about 6,570 dollars per month, or about 0.10 dollars per million total tokens.

A back-of-envelope estimate like this is typically within a factor of two of reality, which is enough to choose between 3 GPUs and 30. Always confirm it with a load test before committing money.

Key terms

Prefill
Processing all prompt tokens in one parallel pass; compute-bound.
Decode
Generating output tokens one per forward pass; memory-bandwidth-bound at small batches.
TTFT
Time to first token: queueing plus prefill, what users feel as responsiveness.
Inter-token latency
The gap between consecutive streamed tokens, set by decode step time.
Throughput
Total tokens processed or generated per second across all users, per GPU or per deployment.
Percentile
The value a given fraction of measurements fall below; p99 latency is beaten by 99 percent of requests.
MFU
Model FLOPs utilization: useful FLOPs per second as a fraction of the chip's peak.
MBU
Model bandwidth utilization: bytes moved per second as a fraction of peak memory bandwidth.
Little's law
Average items in a system equal arrival rate times average time each spends in it.
Lab

Build a deployment sizing calculator and check it against reality

Intermediate, 60 min

Goal: write a Python calculator that sizes a deployment from requests per second, tokens per request and latency targets, then calibrate it by predicting and measuring decode speed on your own machine.

You need: Python 3 (no packages needed for the calculator), and Ollama for the measurement (free; macOS, Linux and Windows). About 2 GB of disk for a small model. A GPU is optional.

  1. Save the calculator. Every assumption is a named constant at the top, so you can change one and see its effect.
sizer.py
"""Back-of-envelope sizing for an LLM inference deployment (decode-dominated)."""
import math
 
# ---- Workload -------------------------------------------------------------
RPS = 20                 # requests per second at peak
IN_TOK = 1000            # prompt tokens per request
OUT_TOK = 300            # generated tokens per request
TARGET_ITL_MS = 50       # max inter-token latency (50 ms = 20 tokens/s per user)
TARGET_TTFT_MS = 1000    # time-to-first-token target
 
# ---- Model: Llama 3.1 8B in BF16 -------------------------------------------
PARAMS = 8.03e9
BYTES_PER_PARAM = 2
KV_BYTES_PER_TOKEN = 2 * 32 * 8 * 128 * 2     # 2 x layers x kv_heads x head_dim x bytes
 
# ---- Accelerator: H100 SXM, vendor peaks ------------------------------------
GPU_MEM_GB = 80
GPU_BW_TBS = 3.35
GPU_TFLOPS = 989         # dense BF16
GPU_PRICE_HR = 3.00      # USD per GPU-hour; approximate, check current prices
 
# ---- Realism factors: what fraction of peak you actually get ----------------
BW_EFF = 0.6             # achieved fraction of memory bandwidth in decode
MFU = 0.4                # achieved fraction of peak FLOPS in prefill
MEM_USABLE = 0.9         # leave 10% for runtime, activations, fragmentation
UTIL_TARGET = 0.7        # plan to run GPUs at 70% of capacity: queues explode near 100%
 
weights = PARAMS * BYTES_PER_PARAM
kv_per_seq = KV_BYTES_PER_TOKEN * (IN_TOK + OUT_TOK)
max_batch_mem = int((GPU_MEM_GB * 1e9 * MEM_USABLE - weights) // kv_per_seq)
 
def step_seconds(batch):
    """One decode step: read all weights once plus every sequence's KV cache."""
    mem_time = (weights + batch * kv_per_seq) / (GPU_BW_TBS * 1e12 * BW_EFF)
    compute_time = 2 * PARAMS * batch / (GPU_TFLOPS * 1e12 * MFU)
    return max(mem_time, compute_time)
 
print(f"weights {weights / 1e9:.1f} GB, KV per sequence {kv_per_seq / 1e9:.2f} GB, "
      f"memory allows batch {max_batch_mem}")
print(f"\n{'batch':>6} {'step ms':>8} {'tok/s/user':>11} {'tok/s/GPU':>10}")
best = 1
for b in (1, 8, 16, 32, 64, 128, 256):
    if b > max_batch_mem:
        break
    t = step_seconds(b)
    print(f"{b:>6} {t * 1e3:>8.1f} {1 / t:>11.0f} {b / t:>10.0f}")
for b in range(1, max_batch_mem + 1):          # largest batch meeting the ITL target
    if step_seconds(b) * 1e3 <= TARGET_ITL_MS:
        best = b
itl = step_seconds(best)
 
prefill_s = 2 * PARAMS * IN_TOK / (GPU_TFLOPS * 1e12 * MFU)   # one prompt, alone
duration = prefill_s + OUT_TOK * itl                          # one request, end to end
concurrency = RPS * duration                                  # Little's law: L = lambda x W
decode_gpus = concurrency / best
prefill_gpus = RPS * 2 * PARAMS * IN_TOK / (GPU_TFLOPS * 1e12 * MFU)
gpus = math.ceil((decode_gpus + prefill_gpus) / UTIL_TARGET)
 
tokens_per_hour = RPS * (IN_TOK + OUT_TOK) * 3600
cost_hr = gpus * GPU_PRICE_HR
print(f"\nbatch per GPU at {TARGET_ITL_MS} ms ITL: {best}  (ITL {itl * 1e3:.1f} ms, "
      f"{1 / itl:.0f} tok/s per user)")
print(f"TTFT estimate (unloaded): {prefill_s * 1e3:.0f} ms  target {TARGET_TTFT_MS} ms")
print(f"request duration {duration:.1f} s -> {concurrency:.0f} concurrent sequences")
print(f"GPU load: decode {decode_gpus:.2f} + prefill {prefill_gpus:.2f} "
      f"-> {gpus} GPUs at {UTIL_TARGET:.0%} target utilization")
print(f"cost ${cost_hr:.2f}/hour, ${cost_hr * 730:,.0f}/month at {gpus} GPUs")
print(f"${cost_hr / tokens_per_hour * 1e6:.3f} per million tokens (input + output), "
      f"${cost_hr / (RPS * OUT_TOK * 3600) * 1e6:.3f} per million output tokens")
  1. Run it and compare with the chapter.
python3 sizer.py

You should see the batch table from this chapter, batch per GPU at 50 ms ITL: 328, 216 concurrent sequences, 3 GPUs and about $0.096 per million tokens.

  1. Run three what-if experiments and record the GPU count for each: set TARGET_ITL_MS = 15 (a premium low-latency tier), set IN_TOK = 8000 (a retrieval-heavy app), and set BYTES_PER_PARAM = 1 (FP8 weights). Write one sentence per experiment on which term (decode, prefill or memory) changed the answer.

  2. Now calibrate against a real measurement. Install Ollama, pull a small model and check its size.

ollama pull llama3.2:1b
ollama list            # note the SIZE column, about 1.3 GB
  1. Predict before you measure. Use the memory bandwidth you measured in the GPUs and accelerators lab (or your device's spec-sheet figure), and compute the batch-1 decode ceiling.
predicted tokens/s = bandwidth (GB/s) / model size (GB)
example: 100 GB/s / 1.3 GB = about 77 tokens/s ceiling
  1. Measure. The --verbose flag prints timing statistics after each answer.
ollama run llama3.2:1b --verbose "Explain memory bandwidth in 200 words."

Read eval rate (decode tokens per second) and prompt eval rate (prefill tokens per second). Run it three times and take the median, ignoring the first run, which includes loading the model.

  1. Compute your effective bandwidth efficiency: measured eval rate divided by predicted ceiling. Put that value into BW_EFF in your notes as the calibration for this class of hardware. Values of 0.5 to 0.9 are typical; much lower suggests the model did not run where you think (check ollama ps to see whether it is on GPU or CPU).

Check your work: your calculator reproduces the chapter's numbers, you have a table of three what-if results, and you have a predicted versus measured decode rate whose ratio you can explain. Publish sizer.py and your results table in a repository; it is a reusable tool you will extend in later chapters.

Stretch: add a cost comparison to the calculator: given an API price per million input and output tokens, compute the monthly API bill for the same workload and the break-even request rate at which self-hosting becomes cheaper.

Check yourself

An 8B model on one GPU serves 124 tokens per second at batch 1 and 4,771 tokens per second at batch 64. The GPU costs 3 dollars per hour. Roughly what happens to the cost per million output tokens when you move from batch 1 to batch 64?

Your dashboard shows mean TTFT of 400 ms, but users complain about multi-second waits. What should you look at first?

nvidia-smi reports 100 percent GPU utilization during single-user decoding. Which statement is correct?

A service receives 10 requests per second and each request spends 6 seconds in the system on average. How many requests are in flight on average?

You change a workload from 1,000 to 8,000 input tokens per request, with the same output length and request rate. Which part of the sizing grows most?

Recap

  • Prefill costs about 2 x params FLOPs per input token and is compute-bound; decode reads all the weights per step and is bandwidth-bound.
  • Measure TTFT, inter-token latency and end-to-end latency separately, and report them as p50, p95 and p99.
  • Batching divides the weight reads across users, raising throughput per GPU by tens of times at a modest cost in per-user speed.
  • Cost per million tokens is hourly price divided by tokens per hour; utilization and headroom multiply it in practice.
  • Size deployments with Little's law plus prefill compute plus headroom, then calibrate the efficiency factors with a real measurement.

Go deeper