Pidoku

The Performance Debugging Methodology

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

Prerequisites 13.a, 6.d, 3.k

★ If you take one thing from Module 22, take this procedure. The other ten lessons are the tools each step calls for.


Before you start: words you need#

WordPlain meaning
TTFTTime to first token: from sending a request to receiving the first generated token (2.c).
ITLInter-token latency: the gap between two streamed tokens of one response (2.c).
Percentile (p95, p99)The value that 95% (or 99%) of requests are faster than. p99 describes the slowest 1 in 100.
PhaseOne stage a request passes through: queue, tokenize, prefill, decode, detokenize, network.
Wall clockReal elapsed time, as a stopwatch on the wall would measure it.
Amdahl’s lawIf a part taking fraction p of the time gets s times faster, the whole gets 1 / ((1 − p) + p/s) times faster.
RegimeWhich resource limits a piece of work: compute, memory bandwidth, latency, or the host CPU (22.c).
SLOService-level objective: the target a metric must meet, such as “p95 TTFT under 800 ms” (23.a).

1. What is it?#

A fixed order of questions for answering “why is this inference service slow?”. Each question is cheap, and each one rules out a large set of possible causes before you spend time on an expensive one.

STEP 0  REPRODUCE        Can you make it slow on demand?
STEP 1  DEFINE           Which number, at which percentile, against which target?
STEP 2  DECOMPOSE        Which phase of the request holds the time?
STEP 3  WHO IS BUSY?     The GPU, the CPU, or nobody (waiting)?
STEP 4  WHICH REGIME?    Compute-, memory-, latency- or host-bound?
STEP 5  WHICH KERNEL?    Only now: per-kernel analysis
STEP 6  ESTIMATE         What is the most this fix could gain (Amdahl)?
STEP 7  CHANGE ONE THING, re-measure, write it down.

Lesson 13.a describes the same loop from the side of choosing an optimisation. This lesson is the debugging side: you start from a symptom and do not yet know the cause.

flowchart TB
  S["Service is slow"] --> W{"Where does the time go?<br/>queue wait vs engine time"}
  W -->|"queue wait"| CAP["Capacity or admission problem<br/>batch size, replicas, routing"]
  W -->|"engine time"| H{"Is the GPU busy<br/>for the whole step?"}
  H -->|"no: gaps between kernels"| HOST["Host-bound<br/>Python, tokenizer, launch overhead, syncs"]
  H -->|"yes"| R{"Roofline: is bandwidth<br/>or FLOPs saturated?"}
  R -->|"bandwidth"| MEM["Memory-bound<br/>batch more, quantize, shrink KV"]
  R -->|"FLOPs"| CMP["Compute-bound<br/>precision, kernels, more GPUs"]
  R -->|"neither"| KRN["Inefficient kernel<br/>occupancy, coalescing, fusion"]

  class W,H,R,CAP queue
  class HOST io
  class MEM memory
  class CMP compute
  class KRN warn
  class S neutral

2. Why does it exist?#

Because the most common failure in performance work is starting too deep.

Step 2 (phase decomposition) costs 5 minutes and rules out 5 of 6 phases.
Step 5 (kernel analysis) costs 2 hours and tells you about one kernel.

Doing step 5 first can mean 2 hours on a kernel in a phase that is 3% of the latency.

Kernel analysis feels like real engineering; reading a table of phase timings feels trivial. But the phase table is where the answer usually is. In the case studies of 22.k, six of eight problems were solved before anyone opened a GPU profiler.


3. Simple analogy#

A doctor’s order of tests. Pulse and temperature first, then history, then blood tests, then a scan, and a biopsy last. Nobody starts with the biopsy: it is slow, invasive, and without the earlier steps you would not know where to take the sample.

Performance debugging has the same shape, and fails the same way when done backwards.


4. Tiny example: ten minutes on “TTFT is 3 seconds”#

STEP 1  p95 TTFT = 3.2 s, target 0.8 s. p95 ITL = 24 ms, target 50 ms (fine).
STEP 2  One query on the per-request log (section 5):
          p95 queue_wait = 2.7 s   p95 prefill = 0.38 s   p95 tokenize = 3 ms
        → the time is in the QUEUE. Not a kernel problem.
STEP 3  (skipped: the engine is not the slow part)
        Why do requests wait? running batch = 58, max allowed = 256,
        KV cache 41% full → memory is not the limit.
        Long prompts (p99 = 22k tokens) arrive and each blocks the batch for 400 ms.
STEP 6  Fix: a smaller per-step token budget, so long prompts are split into chunks (12.k).
STEP 7  p95 TTFT 0.78 s, p99 ITL 145 → 52 ms. Written up in the journal (section 6).

No profiler was opened. The fix was one setting.


5. Technical explanation#

Step 0 and 1: reproduce, then define the metric#

If you cannot make it slow on demand, you are debugging a ghost. Capture the workload shape (prompt and output length distribution), the concurrency or arrival rate, and the full configuration. Then say exactly which number is wrong:

p95 TTFT is 3.2 s, target 800 ms.
p99 ITL is 180 ms, target 50 ms.
Throughput is 1,200 tok/s, expected 3,000.
Cost is $1.80 per million tokens, budget $0.60.

These four have different causes. “It feels slow” has none you can find.

Step 2: decompose by phase (the highest-value step)#

Emit one structured record per request (sampled if volume is high). The fields are the phases:

JSON
{
  "request_id": "req_abc123",
  "tokenize_ms": 1.2,
  "queue_wait_ms": 2340.0,
  "prefill_ms": 87.3,
  "first_token_ms": 2428.5,
  "decode_ms": 4210.0,
  "itl_p50_ms": 21.0,
  "itl_p99_ms": 145.0,
  "detokenize_ms": 12.4,
  "total_ms": 6650.9,
  "prompt_tokens": 1843,
  "output_tokens": 200,
  "prefix_cache_hit_tokens": 1536,
  "running_batch_at_admission": 47,
  "model_version": "v1.5.0-fp8"
}

With it, most investigations become a query:

SQL
SELECT
  percentile_cont(0.95) WITHIN GROUP (ORDER BY queue_wait_ms) AS p95_queue,
  percentile_cont(0.95) WITHIN GROUP (ORDER BY prefill_ms)    AS p95_prefill,
  percentile_cont(0.95) WITHIN GROUP (ORDER BY tokenize_ms)   AS p95_tokenize
FROM requests WHERE ts > now() - interval '1 hour';

vLLM exports the same split as histograms (vllm:request_queue_time_seconds, vllm:request_prefill_time_seconds, vllm:time_to_first_token_seconds; see 19.c), so you can do this from Prometheus even without per-request logs. Lesson 22.j covers the metrics side.

What each dominant phase tells you:

QUEUE_WAIT dominates
  → capacity or admission. Compare the running batch with its limit:
       far below the limit → traffic-limited or scheduler-limited (20.c)
       at the limit        → genuinely at capacity (23.b)
  → are long prefills blocking the batch? (chunked prefill, 12.k)

PREFILL dominates
  → did the prompt length distribution change?
  → prefix cache hit rate (12.m)
  → is prefill near the compute roof? (22.b) Then kernel analysis (22.h)

DECODE (ITL) dominates
  → compute the bandwidth floor: bytes read per step / memory bandwidth (22.b)
  → measured ÷ floor:
       about 1.0–1.25 → near the physical limit; read fewer bytes (quantize, 13.b)
       1.25–2.5       → kernel or launch overhead; profile (22.h)
       above 2.5      → something structural: syncs, CPU-bound loop, no CUDA graphs

TOKENIZE / DETOKENIZE dominates
  → slow tokenizer, or per-token detokenization done badly (12.b)

NETWORK dominates (client TTFT far above server TTFT)
  → a buffering proxy (9.a, case 8 in 22.k)

NOTHING dominates (all phases small, total large)
  → you are measuring wrong, or the time is in gaps between phases (step 3)

Step 3: GPU, CPU, or waiting?#

Take one timeline of a few engine steps (22.h) and compute three numbers:

gpu_busy  = time with at least one kernel running   (from the Nsight Systems trace)
cpu_busy  = on-CPU time of the engine thread         (from py-spy or the PyTorch profiler)
wall      = elapsed time of those steps

gpu_busy ≈ wall              → GPU-bound. Go to step 4.
cpu_busy ≈ wall, gpu < wall  → host-bound. Go to 22.i.
both well below wall         → WAITING. On what?
                                 a lock (py-spy dump shows it)
                                 an implicit sync (.item(), .cpu())
                                 the network or another process
                                 a collective on another GPU (NCCL)

The “both below wall clock” case is the one people miss. The process is blocked, and only off-CPU profiling (22.i) or the timeline’s gaps find it.

Step 4 and 5: regime, then kernels#

Only once the GPU is known to be the busy party: place the step and its top kernels on the roofline (22.b), classify the regime (22.c), and only then look at one kernel in Nsight Compute (6.d, 22.h). The regime decides which fixes can possibly help.

Step 6: estimate before you build#

Compute the Amdahl ceiling for every candidate fix. It takes thirty seconds and regularly reorders the plan (section 6 has a program).

Step 7: one change, re-measure, record#

Change one thing. Re-run the same benchmark (22.g). Record the result, including when it did not help.


6. Under the hood: the arithmetic and the journal#

Ranking fixes with Amdahl’s law#

Go
// amdahl.go: rank candidate fixes by the most they could possibly gain.
package main

import (
	"fmt"
	"sort"
)

type Finding struct {
	Name     string
	Share    float64 // fraction of the metric this part accounts for (0..1)
	Speedup  float64 // how much faster the fix makes that part
	EffortHr float64 // honest guess at engineering hours
}

// Amdahl: overall speedup when a fraction p gets s times faster.
func amdahl(p, s float64) float64 { return 1 / ((1 - p) + p/s) }

func main() {
	fs := []Finding{
		{"fuse RMSNorm kernels", 0.09, 3, 16},
		{"raise running batch 8 -> 40 (fix routing)", 0.80, 4, 6},
		{"remove per-step .item() sync", 0.25, 25, 2},
		{"FP8 weights", 0.70, 1.8, 24},
		{"faster JSON encoder in API", 0.02, 5, 4},
	}
	sort.Slice(fs, func(i, j int) bool {
		gi := amdahl(fs[i].Share, fs[i].Speedup) - 1
		gj := amdahl(fs[j].Share, fs[j].Speedup) - 1
		return gi/fs[i].EffortHr > gj/fs[j].EffortHr
	})
	fmt.Printf("%-44s %6s %8s %6s %10s\n", "finding", "share", "speedup", "gain", "gain/hour")
	for _, f := range fs {
		g := amdahl(f.Share, f.Speedup) - 1
		fmt.Printf("%-44s %5.0f%% %7.1fx %5.1f%% %9.2f%%\n",
			f.Name, f.Share*100, f.Speedup, g*100, g*100/f.EffortHr)
	}
}

Output:

finding                                       share  speedup   gain  gain/hour
raise running batch 8 -> 40 (fix routing)       80%     4.0x 150.0%     25.00%
remove per-step .item() sync                    25%    25.0x  31.6%     15.79%
FP8 weights                                     70%     1.8x  45.2%      1.88%
faster JSON encoder in API                       2%     5.0x   1.6%      0.41%
fuse RMSNorm kernels                             9%     3.0x   6.4%      0.40%

The kernel fusion, which is the most satisfying piece of engineering on the list, comes last. The share and speedup numbers are guesses; the point is that writing them down forces the comparison.

The performance journal#

Keep one entry per investigation:

DATE       2026-03-14
SYMPTOM    p95 TTFT 3.2 s, target 800 ms
WORKLOAD   1,800 avg prompt tokens, 250 output, 45 req/s
BASELINE   TTFT p50 340 ms, p95 3,200 ms; queue_wait p95 2,700 ms
DIAGNOSIS  Queue-bound. Running batch 58 of 256, KV 41%: not memory-limited.
           Token budget per step was 32,768; long prompts (p99 22k tokens)
           ran as one chunk and blocked decode for 400+ ms each.
CHANGE     --max-num-batched-tokens 4096
RESULT     TTFT p95 780 ms; ITL p99 145 → 52 ms; throughput +8%
QUALITY    unchanged (200 paired generations, identical outputs)
EFFORT     30 minutes

The journal becomes the team’s memory. It is also what makes you credible in capacity discussions: you can show the baseline and every change since.


7. Performance implications#

  • The order is the optimisation. The procedure itself does not make anything faster; it makes sure the hours go to the term that dominates.
  • Percentiles have different causes. p50 is usually set by steady-state step time; p99 by blocking events (a long prefill, a preemption, a garbage-collection pause). Fixing one rarely fixes the other.
  • Throughput and latency trade. Most levers (batch size, token budget) move one up and the other down. Define which one the SLO is on before tuning.
  • Ceilings change with the workload. A fix worth 30% at batch 8 may be worth 3% at batch 128. Re-estimate at the operating point you actually run.

8. Production implications#

  • Instrument phases permanently. Per-request phase timings, or at least the engine’s queue, prefill and decode histograms, should exist before the incident, not be added during it.
  • Keep a baseline. Record the key numbers for each release. Without a baseline you cannot tell a regression from normal behaviour.
  • Measure quality with performance. Many inference optimisations trade accuracy (13.b). Every journal entry needs a quality line.
  • Use the same benchmark every time (22.g), so before and after are comparable.
  • Escalate by evidence. “The GPU is at 100%” is not evidence (22.d). Phase timings, running batch and the roofline gap are.

9. Common mistakes#

  1. Starting with kernel analysis. The most common and most expensive mistake.
  2. Not defining the metric. “Faster” is not a target.
  3. Changing several things at once. You learn nothing about which one helped.
  4. Skipping the Amdahl ceiling. Weeks spent on a 4% gain.
  5. Optimising p50 when the SLO is on p99. Different causes, different fixes.
  6. Not measuring quality alongside performance.
  7. Benchmarking an unrealistic workload (22.g).
  8. Not writing it down. You will investigate the same thing again in six months.

10. Hands-on exercise#

  1. Build the instrumentation. Add per-request phase timings (section 5) to a server you run, or scrape vLLM’s queue, prefill and TTFT histograms. Write the query that decomposes p95 TTFT.
  2. Run the full procedure. Take a system that is slower than you would like and go through all seven steps. Write it up in the journal format.
  3. Rank five fixes. Edit the fs list in amdahl.go with five real candidate fixes from your system, with honest shares and effort guesses. Does the order surprise you?
  4. The three-way split. For a few decode steps, measure GPU-busy time, engine-thread CPU time, and wall clock. What are you waiting on, if anything?
  5. Start the journal. Record today’s baseline for a system you work on.

11. Interview questions#

  1. Walk me through how you would investigate a slow inference service.
  2. Why start with phase decomposition rather than kernel profiling?
  3. What per-request telemetry would you emit, and what does each field diagnose?
  4. GPU time and CPU time are both far below wall clock. What is happening, and how do you find out what?
  5. How do you decide whether an optimisation is worth doing before doing it?
  6. p95 TTFT is 3 s and ITL is fine. What do you look at in the first ten minutes?
  7. Why change one thing at a time?

12. Further reading#

↑↓ navigate↵ openesc close

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