Pidoku

Case Studies

Module 22 Lesson 22.k 1h 30m Difficulty 4/5

Prerequisites 22.a–22.j


Before you start: words you need#

WordPlain meaning
SymptomWhat someone noticed: “TTFT is 4 seconds”. Not yet a cause.
HypothesisA guess at the cause that a measurement can prove wrong.
Phase decompositionSplitting a latency into its parts (queue, prefill, decode, network) to see which part grew (22.a).
CorrelationTwo things that move together in time, such as latency spikes and long prompts arriving. A lead, not yet proof.
Little’s lawAverage number in a system = arrival rate × average time in it (L = λW). True for any stable system.
Load (ρ)Arrival rate ÷ the most the system can serve. Above 1 the queue grows without limit.
PostmortemA written account of an incident: what happened, why, and what changes so it does not recur.

1. What is it?#

Eight worked investigations of inference performance problems, each in the same format: symptom, measurements, diagnosis, wrong fixes, right fix, result, lesson. They bring the whole module together: the method (22.a), roofline arithmetic (22.b, 22.c), GPU utilisation (22.d), memory (22.e, 22.f), benchmarking (22.g), profiling (22.h, 22.i) and metrics (22.j).

The cases are composites: each is built from a kind of incident that recurs across teams, with numbers chosen to be internally consistent, not taken from one named deployment. The mechanisms are real; the exact percentages are illustrative.

How to read them. After each symptom, stop and write down your hypotheses before reading on. Predicting, then checking, is the skill; reading the answers is not.

Flags and metric names are vLLM v0.32.0, consistent with Modules 17–19. Facts checked on 13 November 2026.


2. Why does it matter?#

Most performance incidents are not novel. The same few causes come back: the system is at capacity, one request shape blocks the rest, the CPU or a sync starves the GPU, a configuration flag left over from debugging, a topology nobody checked, a metric that measures the wrong thing, a buffer in the network path. Engineers who have seen the pattern once find it in minutes; those who have not spend days on kernels.

The cases also show the most expensive mistake in the field: buying hardware to fix a problem that is not capacity. Two of the eight end with no purchase and freed GPUs.


3. Simple analogy#

A doctor’s case book. Medical students learn from cases: “a patient presents with a fever and a rash; what do you test first?” They learn the common causes, which test rules each out, and which symptoms mislead. These are the same, for servers: the fever is a latency percentile, the tests are metrics and profilers, and the misleading symptom is usually GPU utilisation.


4. Tiny example: is it really capacity?#

Case 1 below hinges on one calculation. A request holds one of --max-num-seqs slots for its prefill plus all its decode steps. Little’s law gives the most the server can serve; queueing theory (the Erlang C formula for a queue with many servers, assuming random arrivals) gives how the wait grows as load approaches that limit.

Go
// capacity.go — Case 1's arithmetic: Little's law for capacity, and an
// M/M/c queue (Erlang C) for how long requests wait as load nears it.
package main

import (
	"fmt"
	"math"
)

// erlangC is the probability that an arrival must wait, for c servers
// at offered load a = λ/μ (in servers).
func erlangC(c int, a float64) float64 {
	term, sum := 1.0, 1.0 // a^k / k!, starting at k = 0
	for k := 1; k < c; k++ {
		term *= a / float64(k)
		sum += term
	}
	last := term * a / float64(c) // a^c / c!
	rho := a / float64(c)
	top := last / (1 - rho)
	return top / (sum + top)
}

func report(name string, slots int, prefill, itl float64, outTokens, arrival float64) {
	service := prefill + outTokens*itl // seconds one request holds a slot
	capacity := float64(slots) / service
	rho := arrival / capacity
	fmt.Printf("%s\n", name)
	fmt.Printf("  service time %.2f s, %d slots -> capacity %.2f req/s; arrival %.1f -> load %.0f%%\n",
		service, slots, capacity, arrival, 100*rho)
	if rho >= 1 {
		fmt.Println("  load >= 100%: the queue grows without limit")
		return
	}
	mu := 1 / service
	pw := erlangC(slots, arrival/mu)
	gap := float64(slots)*mu - arrival // spare service rate, req/s
	mean := pw / gap
	p95 := 0.0
	if pw > 0.05 {
		p95 = math.Log(pw/0.05) / gap
	}
	fmt.Printf("  P(wait) %.2f, mean wait %.2f s, p95 wait %.2f s\n", pw, mean, p95)
}

func main() {
	// Before: 64 slots (max_num_seqs), 380 ms prefill, 260 output tokens at 24 ms.
	report("before", 64, 0.38, 0.024, 260, 9.0)
	// Peak traffic 10% higher.
	report("before, peak +10%", 64, 0.38, 0.024, 260, 9.9)
	// After prefix-aware routing (prefill 380 -> 120 ms) and FP8 weights and KV
	// (cache room for 128 slots; ITL 26 ms at the larger batch).
	report("after", 128, 0.12, 0.026, 260, 9.9)
}

Output:

before
  service time 6.62 s, 64 slots -> capacity 9.67 req/s; arrival 9.0 -> load 93%
  P(wait) 0.47, mean wait 0.70 s, p95 wait 3.35 s
before, peak +10%
  service time 6.62 s, 64 slots -> capacity 9.67 req/s; arrival 9.9 -> load 102%
  load >= 100%: the queue grows without limit
after
  service time 6.88 s, 128 slots -> capacity 18.60 req/s; arrival 9.9 -> load 53%
  P(wait) 0.00, mean wait 0.00 s, p95 wait 0.00 s

At 93% load the median request barely waits but the p95 waits 3.35 s; 10% more traffic and the queue never drains. That cliff is why “TTFT went from fine to terrible overnight” is so often plain capacity. Real LLM traffic is not exactly random and service times vary widely, so treat the numbers as the shape, not a forecast.


5. Technical explanation: eight cases#

Case 1: “TTFT is 4 seconds”#

SYMPTOM   p95 TTFT 3,800 ms (objective 800 ms). p95 ITL 24 ms (fine). No errors.
          Chat assistant, one 8-GPU replica group, BF16.

STOP. What are your hypotheses?

MEASUREMENTS (22.j panels)
  vllm:request_queue_time_seconds p95     3,350 ms   ← most of TTFT
  vllm:request_prefill_time_seconds p95     380 ms
  vllm:num_requests_running avg              60      (max_num_seqs = 64)
  vllm:kv_cache_usage_perc                 0.94
  arrival 9.0 req/s; mean output 260 tokens at 24 ms
  Little's law: 64 slots ÷ 6.62 s per request = 9.7 req/s capacity → load 93%
  prefix-cache hit rate 4%; every request starts with the same 1,100-token system prompt

DIAGNOSIS
  Genuinely near capacity, and with no headroom for a peak (section 4).
  But capacity is being spent badly: the shared system prompt is recomputed on most
  requests because round-robin routing spreads each conversation over all replicas.

WRONG FIXES
  ✗ tune kernels (prefill and ITL are fine)
  ✗ raise --max-num-seqs (the KV cache is at 94%; this causes preemptions, 17.c)
  ✗ raise the tensor-parallel degree (lower ITL, not more throughput, 14.m way 1)

RIGHT FIXES, in order
  1. Prefix-aware routing (20.f, 12.m): hit rate 4% → 70%, prefill p95 380 → 120 ms.
  2. FP8 weights and FP8 KV cache (13.e, 13.h): room for 128 running requests.
  3. Only then size replicas for the remaining growth.

RESULT    Capacity 9.7 → 18.6 req/s on the same GPUs; p95 TTFT 640 ms at peak.

Lesson: “at capacity” is a real diagnosis, but check that you are at capacity efficiently before buying hardware.

Case 2: “ITL spikes to 300 ms at random”#

SYMPTOM   p50 ITL 22 ms, p99 ITL 310 ms, irregular. TTFT and throughput fine.

STOP. Hypotheses?

MEASUREMENTS
  ITL over time: spikes of ~400 ms, 3–8 times a minute.
  Each spike lines up with a request whose prompt is over 12,000 tokens.
  --max-num-batched-tokens 32768   ← raised last month during a throughput benchmark
  --long-prefill-token-threshold   not set

DIAGNOSIS
  Chunked prefill is on (the default, 12.k, 17.b), but the token budget is so large
  that a 12k-token prompt fits in one step. That step runs ~400 ms of prefill, and every
  decoding request in the batch waits for it.

FIX
  --max-num-batched-tokens 4096 and --long-prefill-token-threshold 2048
  → long prompts are split into ~2k-token chunks that share steps with decodes.

RESULT    p50 ITL 22 → 25 ms (a little worse). p99 ITL 310 → 52 ms (6× better).
          p95 TTFT for long prompts 480 → 610 ms (worse). Throughput −3%.

Lesson: a p99 many times the p50 is almost always a blocking event, not general slowness. Correlate the spikes with something. And a setting tuned for a throughput benchmark (22.g) can be wrong for a latency objective.

Case 3: “Throughput is a third of what we calculated”#

SYMPTOM   Roofline predicts ~3,000 tok/s (22.b); measured 980 tok/s.
          8B model, one H100, batch 32.

STOP. Hypotheses?

MEASUREMENTS
  nsys (22.h): GPU busy 38% of wall time; ~900 cudaLaunchKernel calls per step,
               no cudaGraphLaunch; one cudaStreamSynchronize per step
  py-spy --native (22.i), engine worker: 41% of samples in a custom logits
               processor that calls .cpu() on the logits every step
  config:      --enforce-eager, left over from a debugging session

DIAGNOSIS
  Two compounding host-side problems:
  1. --enforce-eager turns off CUDA graphs (13.k): every kernel is launched from Python.
  2. A per-step device-to-host copy and sync in the logits processor: the GPU idles
     while Python inspects the result.

FIX
  1. Remove --enforce-eager                                   980 → 1,510 tok/s
  2. Rewrite the processor to stay on the GPU (tensor ops, no .cpu())  → 2,740 tok/s

RESULT    2,740 tok/s, 91% of the prediction. About three hours of work.

Lesson: a 3× gap from the roofline is almost never kernel efficiency. It is CPU, launches or synchronisation. Look at GPU busy first (22.c: the host-bound regime).

Case 4: “OOM every day and a half”#

SYMPTOM   A replica dies with CUDA out of memory roughly every 30–40 hours, at any load.
          Restarts cleanly. Started after a plugin release (19.f).

STOP. Hypotheses?

MEASUREMENTS
  OOM at low load → not over-admission; preemptions flat (22.f type 3 ruled out).
  Memory sampled every 10 s from the worker (torch.cuda.memory_allocated / _reserved):
    allocated grows ~0.2 GiB per hour, steadily; reserved − allocated flat
  → a real leak, not fragmentation (22.f type 4, 22.e).
  The growth rate tracks the abort rate: vllm:request_success_total{finished_reason="abort"}.
  Code review: the plugin keeps per-request GPU tensors (token log-probs) in a dict keyed by
  request ID, and removes them on normal completion only.

DIAGNOSIS
  Aborted requests never reach the clean-up path, so their tensors stay referenced.
  Each one is small; a day's aborts are several GiB, then the next allocation fails.

FIX
  1. Clean up in the abort and error paths too (a finally block; a size-bounded cache).
  2. Keep log-probs on the CPU unless the client asked for them.
  3. Alert on the slope of allocated memory, not only on OOM.

RESULT    Allocated memory flat over a two-week soak test. Zero OOMs in 30 days.

Lesson: an OOM that is independent of load and periodic in time is a leak. Separate allocated from reserved first; then correlate the growth with a request event. 22.f has the full OOM taxonomy and a different worked incident (an outlier request shape).

Case 5: “Adding GPUs made it slower”#

SYMPTOM   Moved from TP=2 to TP=4 to raise throughput. Throughput per GPU fell 40%;
          total throughput rose only 20%.

STOP. Hypotheses?

MEASUREMENTS
  Server: 8× H100 NVL (PCIe cards, joined in pairs by NVLink bridges)
  nvidia-smi topo -m:
     GPU0–GPU1: NV12           ← NVLink bridge
     GPU0–GPU2: SYS            ← PCIe, across the CPU socket interconnect
  nsys with NCCL ranges (22.h): all-reduce 4.0 ms of a 9.5 ms step at TP=4
                                all-reduce 0.5 ms of a 12.5 ms step at TP=2

DIAGNOSIS
  The node is four NVLink pairs, not one NVLink switch fabric. TP=4 sends every
  layer's all-reduce over PCIe and across sockets (9.c, 14.m way 2).

FIX
  Keep TP=2 and run four replicas, one per NVLink pair (data parallelism, 14.b).
  Pin each replica's CPU threads and memory to the GPU's NUMA node (3.c).

RESULT    Total throughput +90% over the original single TP=2 replica, against +20% for TP=4.
          Same eight GPUs.

Lesson: run nvidia-smi topo -m before choosing a tensor-parallel degree. PCIe servers and cloud instances often have NVLink in pairs or not at all.

Case 6: “The GPUs are at 100%, we need more”#

SYMPTOM   A request for 64 more GPUs. Justification: "all 64 existing GPUs at 100% utilisation."

STOP. Hypotheses?

MEASUREMENTS (22.d, 22.j)
  nvidia-smi GPU-Util / DCGM_FI_DEV_GPU_UTIL_RATIO   ~1.0
  DCGM_FI_PROF_DRAM_UTIL_RATIO                       0.24
  vllm:num_requests_running avg                      7     (max_num_seqs = 96)
  vllm:kv_cache_usage_perc                           0.09
  vllm:request_queue_time_seconds p95                ~0
  16 replicas of TP=4, each receiving ~4 req/s

DIAGNOSIS
  Not capacity-limited. Traffic is spread too thinly: each replica reads all its weights
  every step to serve 7 sequences (14.m way 5). "GPU-Util" counts time a kernel was
  running, not how much of the GPU it used (22.d).

FIX
  1. Consolidate 16 → 5 replicas, plus 1 spare for headroom and failures.
  2. Prefix-aware routing across them.
  3. Autoscale on queue time, not utilisation (19.e, 23.d).

RESULT    Running batch 7 → 26; DRAM_UTIL_RATIO 0.24 → 0.71; throughput per GPU 3.4×.
          40 of 64 GPUs freed. No purchase.

Lesson: GPU utilisation is not a capacity signal. Require DRAM activity, running batch and queue time in every capacity request.

Case 7: “Quality dropped after a deploy, but every test passed”#

SYMPTOM   Complaints about "worse answers" from Tuesday. Errors, latency, throughput normal.
          CI green.

STOP. Hypotheses?

MEASUREMENTS
  Deploy log: Tuesday's release switched weights from BF16 to INT4 (W4A16, GPTQ,
              group size 128) to save cost.
  Offline evaluation at deploy: a multiple-choice benchmark −0.4 points, perplexity +0.08.
  vllm:request_generation_tokens mean     218 → 341 tokens (+56%)   ← the signal
  vllm:request_success_total{finished_reason="length"} share   3% → 9%
  regeneration rate (gateway)            4.1% → 11.3%
  structured-output validity (gateway)   99.2% → 91.7%

DIAGNOSIS
  Four-bit weights degraded instruction following and long-form coherence in ways that
  short multiple-choice scores and perplexity did not show (13.f, 11.k). Answers ramble
  and break JSON schemas more often.

FIX
  1. Roll back to BF16 at once (the old version was still deployable: 23.g).
  2. Re-evaluate on long generations, instruction following and schema validity.
  3. Ship FP8 instead (13.e): output length unchanged, schema validity 99.1%,
     most of the cost saving.

RESULT    Cost target met with FP8. Output length distribution and schema validity added to
          the canary checks (20.j).

Lesson: the output-length distribution is a cheap, sensitive early quality signal, and it is already a vLLM metric. Perplexity and a multiple-choice score are not enough to validate a precision change.

Case 8: “The client sees 8 seconds; the server says 200 ms”#

SYMPTOM   Users say the answer appears all at once after ~8 s.
          vllm:time_to_first_token_seconds p95 210 ms; e2e p95 7.9 s.

STOP. Hypotheses?

MEASUREMENTS
  curl -N -o /dev/null -w '%{time_starttransfer}\n' through the public ingress:  7.82 s
  the same request straight to the pod:                                          0.19 s   ← the answer
  ingress: nginx, proxy_buffering not set (its default is on)

DIAGNOSIS
  The proxy buffers the server-sent-events stream and forwards it only when the
  response ends. The server's metrics are right; the user's experience is not.

FIX
  In nginx, for the streaming location:
    proxy_buffering off;
    proxy_cache off;
    proxy_read_timeout 3600s;
  or have the server send the response header "X-Accel-Buffering: no", which nginx
  honours per response. Then check every other hop (CDN, WAF, service mesh) the same way.

RESULT    Client-side TTFT p95 7.82 s → 0.26 s. A synthetic client that measures TTFT
          through the public path added to monitoring.

Lesson: measure from a real client through the real path. Server-side metrics cannot see this class of problem (12.p). If the ingress is the community ingress-nginx controller, note that the Kubernetes project ended its maintenance in March 2026; migration to a Gateway API implementation is the time to re-check streaming settings.


6. Under the hood: the patterns across all eight#

1. DECOMPOSE FIRST.     Cases 1, 2, 4 and 8 were solved by splitting a number into phases or
                        correlating it with one event, before any deep profiling.

2. CHECK THE CONFIG.    Cases 2 and 3 were flags left from earlier work (a benchmark budget,
                        --enforce-eager). Case 5 was a parallelism choice made without topology.

3. MEASURE OUTSIDE.     Case 8 is invisible from inside the server; Case 7 is invisible to
                        latency metrics.

4. THE OBVIOUS METRIC   Case 6: GPU utilisation. Case 7: a benchmark score.
   LIES.

5. CORRELATE.           Spikes with prompt length (Case 2); memory growth with aborts (Case 4);
                        quality with a deploy (Case 7).

6. THE FIX IS OFTEN     Cases 2, 3, 5 and 8 were fixed by configuration. Hours of work each.
   SMALL.

7. AMDAHL.              Every right fix attacked the dominant term (22.a). In Case 3 a month
                        of kernel work would have bought a few per cent.

Why the method works: each measurement rules out a layer. Queue time versus prefill time splits capacity from compute; GPU busy splits host from device; allocated versus reserved splits leaks from fragmentation; client versus pod timing splits the network from the server. Four or five such splits reach the cause from any starting symptom, which is why a short, ordered checklist (section 8) beats intuition.


7. Performance implications#

  • Configuration dominates. Across the cases, the large wins (2× to 4×) came from routing, precision, parallelism layout and removing debug flags. Kernel work matters, but only once the host, the batch and the topology are right.
  • Capacity has a cliff. Section 4: near full load, small traffic changes cause large waits. Keep headroom (load well below 90% at peak) or shed load deliberately (20.c).
  • Every fix has a cost somewhere. Case 2 traded a little median ITL and long-prompt TTFT for the tail; Case 7 traded some of the saving for quality. Write the trade down.

8. Production implications#

The first fifteen minutes of any inference performance incident, in order:

1. Which objective broke, for whom?   TTFT or ITL; all traffic or one model, tenant, prompt size
2. What changed?                      deploys, config, traffic mix, in the last 24 hours (23.g)
3. Queue or compute?                  queue time vs prefill time (22.j, 19.c)
4. Capacity signals                   running vs max_num_seqs, KV usage, preemptions, rejections
5. One replica or all?                the fleet heatmap (22.j)
6. Host or device?                    GPU busy (22.h), engine CPU (22.i)
7. Inside or outside the server?      client-side timing through the real path

A capacity request should carry the evidence Cases 1 and 6 show is needed: queue time and running batch at peak, KV cache usage, DRAM activity, prefix-cache hit rate, and what was already tried. Without these, “the GPUs are at 100%” is not evidence.

A postmortem in this lesson’s format (symptom, measurements, diagnosis, wrong fixes, right fix, result, lesson) is easy to write and easy to learn from. Keep them in one place; the next on-call engineer’s case book is your team’s past incidents.


9. Common mistakes#

  1. Reading the diagnosis first. You learn the answer, not the method.
  2. Fixing before measuring. Every wrong fix in the cases was plausible.
  3. Buying hardware for a non-capacity problem (Cases 1 and 6).
  4. Trusting server-side latency as the user’s experience (Case 8).
  5. Validating a change only on throughput and a benchmark score (Case 7).
  6. Leaving debugging and benchmarking flags in production (Cases 2 and 3).
  7. Choosing parallelism without the topology (Case 5).
  8. Not writing the incident up, so the next team meets the same cause from scratch.

10. Hands-on exercise#

  1. Predict before reading. Cover each diagnosis, write your hypotheses, then check. Which cases fooled you, and which measurement would have saved you?
  2. Run capacity.go. Find the arrival rate at which p95 queue wait first exceeds 500 ms for 64 slots. How much traffic headroom does a 500 ms queue budget leave?
  3. Reproduce Case 2. On a test server, set --max-num-batched-tokens 32768, run steady short-prompt traffic plus an occasional 12k-token prompt, and plot ITL. Then apply the fix and compare p50, p99 and long-prompt TTFT.
  4. Reproduce Case 3. Benchmark with and without --enforce-eager (22.g) and record GPU busy in nsys for both.
  5. Write your own case. Take a real performance problem you have met, in any system, and write it in this format.
  6. Write the capacity-request template for your organisation from section 8.

11. Interview questions#

  1. p95 TTFT is 4 s and ITL is fine. Walk through your investigation.
  2. p99 ITL is fourteen times p50, irregularly. What is your first hypothesis, and how do you test it?
  3. Measured throughput is a third of the roofline prediction. What do you check first, and why not the kernels?
  4. A team asks for 64 more GPUs because utilisation is 100%. What evidence do you ask for?
  5. A replica runs out of memory every day and a half at any load. How do you tell a leak from fragmentation?
  6. Going from TP=2 to TP=4 lowered per-GPU throughput by 40%. What happened, and what would you do?
  7. Quality dropped after a deploy but all tests passed. How do you detect it, and how do you stop it happening next time?
  8. Client-side latency is forty times server-side latency. Diagnose.

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

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