On this page
Your phone buzzes. Users say the assistant feels slow. You open the dashboards and find zero errors, a healthy request rate, and GPUs that look busy. A colleague insists the model is fine. Then a customer sends a screen recording: the chat window sits blank for several seconds, and the reply arrives in uneven bursts.
Both observations are right, and that is the core puzzle of LLM serving. "Slow" bundles at least two distinct complaints coming from two different phases of the same request. The initial wait before the first token and the streaming cadence after it hit different hardware walls, respond to different optimizations, and often trade off against one another.
Here we trace one request through a GPU serving engine. You already know what a single forward step computes from Decoding Strategies. Now that step has to share finite memory bandwidth, Tensor Core compute, and HBM capacity across live traffic. By the end you will read a latency trace cleanly, place prefill and decode on a GPU roofline, size a KV cache pool accurately, and choose between chunked prefill, disaggregation, and cache quantization.
Two clocks, not one
Start with a healthy trace from one request. It arrives at time 0 ms, and four output tokens arrive at 320, 355, 392, and 428 ms. Look at the rhythm: one long pause, then a steady beat.
- Time to First Token (TTFT): Elapsed time from request arrival to the first observed output token (). Users feel this blank screen directly.
- Inter-Token Latency (ITL): Each consecutive gap after token 1 ( for ). Here the gaps are
35,37, and36 ms. Tail ITL (p95/p99) exposes stuttering that averages hide. - Time Per Output Token (TPOT) and Decode TPS: Mean post-first-token gap and its per-request inverse for output tokens:
Those three decode gaps span 108 ms, giving TPOT = 36.0 ms and a decode rate of . Dividing all four tokens by the full 428 ms gives an end-to-end output rate of . Both rates are valid, and they answer different questions. Whenever someone quotes tokens per second, ask for the numerator, the interval, and whether they mean one stream or aggregate cluster throughput ().
| Clock metric | From trace [320, 355, 392, 428] ms | Value |
|---|---|---|
| TTFT | First token arrival | 320 ms |
| Inter-token gaps (ITL) | [355-320, 392-355, 428-392] | 35, 37, 36 ms |
| TPOT | 36.0 ms | |
| Decode rate (per-request TPS) | 27.8 tokens/s | |
| End-to-end rate | 9.35 tokens/s |

from math import isfinite
def token_metrics(arrival_ms: float, times_ms: list[float]) -> dict:
if not isfinite(arrival_ms) or any(not isfinite(t) for t in times_ms):
raise ValueError("timestamps must be finite")
if any(b < a for a, b in zip([arrival_ms] + times_ms, times_ms)):
raise ValueError("timestamps must be nondecreasing after arrival")
if not times_ms:
return {"ttft": None, "itls": [], "tpot": None, "tps": None}
gaps = [b - a for a, b in zip(times_ms, times_ms[1:])]
tpot = sum(gaps) / len(gaps) if gaps else None
tps = 1000 / tpot if tpot is not None and tpot > 0 else None
return {"ttft": times_ms[0] - arrival_ms, "itls": gaps,
"tpot": tpot, "tps": tps}
m = token_metrics(0, [320, 355, 392, 428])assert token_metrics(0, [])["ttft"] is None
assert token_metrics(0, [320])["tpot"] is None
assert token_metrics(0, [320, 320])["tps"] is None
print("TTFT:", m["ttft"], "ms")
print("decode ITLs:", m["itls"], "ms")
print(f"decode TPS: {m['tps']:.1f}")TTFT: 320 ms
decode ITLs: [35, 37, 36] ms
decode TPS: 27.8Three subtle measurement traps break dashboards if left unchecked:
- Client vs. server clocks: Client TTFT starts when the user hits Send (capturing transport, proxy buffering, and hidden reasoning tokens before visible text). Server TTFT starts at an internal hook: vLLM starts front-end
arrival_timewhen tokenization begins.[1] Never compare mismatched clocks directly. - Bundled streaming chunks and one-token replies: If a server or speculative decoder delivers four tokens in one
40 mschunk, dividing by four gives a10 msinterval average rather than four observed token timestamps. Single-token replies have no post-first-token gap at all: vLLM's Prometheus histogram records0whilevllm bench serveexcludes them, so a traffic shift toward one-token answers can drop the histogram mean without speeding up decode.[1] - Inverting mean TPOT is not mean TPS: Across two streams with
10 ms(100 tok/s) and100 ms(10 tok/s) TPOT, mean request TPS is , whereas inverting the mean TPOT of55 msgives . TPOT and TPS are reciprocals only for a single request.
If users complain that nothing appears for a long time, which metric do you inspect first? What if streaming looks choppy after it starts?
Answer
Inspect TTFT first for a long initial pause, which points to queueing, tokenization, or prefill. Inspect ITL percentiles, TPOT, and TPS when streaming stutters after token 1 arrives, which points to decode bandwidth, batching, or prefill interference.
Prefill and decode: two shapes on the same weights
Every autoregressive request passes through two distinct execution phases.[2] A modern serving iteration can mix requests from both phases in one batch, yet each phase has a completely different tensor shape:
- Prefill (parallel prompt processing via GEMM): All uncached prompt tokens are known upfront, so the model stacks them into an activation matrix , multiplies against weight matrices using matrix-matrix multiplication (GEMM), writes Key and Value pairs into HBM, and samples token . Every weight tile loaded from HBM is reused across token rows.
- Decode (autoregressive token extension via GEMV): Once exists, generation proceeds one token at a time. At batch size 1, the input is a single row vector multiplied against each layer's weight matrix (GEMV). The model computes , appends it to the cached history, attends over all retained positions, and samples .
Notice one counting rule that trips up capacity math: the KV cache holds tokens the model has consumed, not the newest prediction. Walk through a four-token prompt: prefill consumes 4 prompt tokens, caches 4 positions, and emits . Step 1 consumes , grows the cache to 5, and emits . Step 2 consumes , grows the cache to 6, and emits . After prompt tokens and outputs under ordinary full attention, the cache holds exactly positions.

Different products feel these two clocks differently: real-time voice and code completion live or die on tail TTFT, conversational chat balances TTFT against smooth ITL, and offline batch pipelines maximize aggregate cluster TPS.
The same GPU, two different walls
Now we can answer the opening mystery: how can a GPU look busy while streaming feels slow?
Every GPU kernel is bounded by either how fast Tensor Cores multiply or how fast HBM delivers bytes. Operational (arithmetic) intensity measures floating-point operations performed per byte fetched from HBM:
The roofline model[3] bounds attainable compute rate by the lower of two ceilings:
Check hardware specs carefully before plotting the ridge. NVIDIA lists the H100 SXM at 1,979 TFLOPS BF16 with structured sparsity and 3.35 TB/s HBM bandwidth.[4][5] Structured sparsity doubles the dense rate, so dense BF16 peak is , putting the dense ridge point at (missing that footnote puts your ridge off by !).
import numpy as np
sparse_bf16_tflops = 1979.0
dense_bf16_tflops = sparse_bf16_tflops / 2.0
bandwidth_tb_s = 3.35
intensities = np.array([1.0, 64.0, 2048.0], dtype=np.float64)
attainable_tflops = np.minimum(dense_bf16_tflops, bandwidth_tb_s * intensities)
assert dense_bf16_tflops == 989.5
print(f"dense ridge: {dense_bf16_tflops / bandwidth_tb_s:.1f} FLOPs/byte")
print(f"sparse ridge: {sparse_bf16_tflops / bandwidth_tb_s:.1f} FLOPs/byte")
print(f"I=1 arithmetic rate / dense peak: {100 * attainable_tflops[0] / dense_bf16_tflops:.2f}%")dense ridge: 295.4 FLOPs/byte
sparse ridge: 590.7 FLOPs/byte
I=1 arithmetic rate / dense peak: 0.34%For a BF16 linear projection serving token rows, each 2-byte weight executes multiply-add FLOPs, giving a weight-only operational intensity of FLOPs/byte:
- Long-prompt prefill (): Reuses each weight tile across thousands of rows, sitting well right of the ridge on the flat compute roof.
- Single-stream decode (): Reads every active weight for a single row ( FLOP/byte), pinning performance on the sloped memory-bandwidth roof at just
3.35 TFLOPS, or 0.34% of dense compute peak. - Batched decode (): Stacks 64 active requests into a activation matrix, reusing each weight tile across 64 rows () to lift aggregate throughput until KV reads and per-step latency grow too large.

This bandwidth roof gives an immediate back-of-the-envelope ceiling for single-stream decode:
Take Qwen3.6-27B's roughly 54 GB of BF16 language weights on one H100 SXM (3,350 GB/s):[6]
def ideal_weight_stream_tps(model_bytes: int, bandwidth_bytes_per_s: int) -> float:
if model_bytes <= 0 or bandwidth_bytes_per_s <= 0:
raise ValueError("weight bytes and bandwidth must be positive")
return bandwidth_bytes_per_s / model_bytes
model_gb = 54
h100_capacity_gb = 80
print("weights alone fit in 80 GB:", model_gb <= h100_capacity_gb)
bound = ideal_weight_stream_tps(54 * 10**9, 3350 * 10**9)
print(f"single-GPU ideal weight-read bound: {bound:.1f} tokens/s")weights alone fit in 80 GB: True
single-GPU ideal weight-read bound: 62.0 tokens/s62.0 tokens/s is an optimistic ceiling for one stream (real sustained bandwidth is lower than peak, and reading a growing KV prefix adds more HBM traffic on every decode step). In thirty seconds you know that unless speculative decoding amortizes several tokens per weight pass or quantization shrinks those 54 GB, no prompt tweak can push a single stream to 500 tokens/s. To locate a real kernel on your roofline, measure elapsed time, FLOPs, and hardware traffic counters such as dram__bytes.sum via NVIDIA Nsight Compute (ncu --query-metrics):[7] near the sloped roof means attack memory traffic (quantization, FlashAttention[8]), near the flat roof means attack math/precision/parallelism, and far below both means launch overhead or synchronization stalls.
A teammate says, "Decode only reaches 0.34% of peak FLOPs, so the GPU must be almost idle." What is wrong with that reasoning?
Answer
0.34% compares arithmetic throughput against dense Tensor Core peak at . The memory bus is saturated moving weights for one token row; the GPU is bandwidth-bound, not idle.
The KV cache: the dynamic capacity bottleneck
Memory bandwidth sets single-stream speed; HBM capacity decides how many users fit before requests queue, preempt, or fail.
Deleting cached Key and Value tensors after each token would force the model to recompute and for the entire prefix on every decode step ( projection work). Retaining the KV cache eliminates those redundant projections, though each new query still reads every cached position in full attention, so longer contexts slow decode and grow memory linearly.
For sequences of cached length across full-attention layers, KV heads, head dimension , and bytes per stored value (2 for FP16/BF16, 1 for FP8/INT8):
Plug in Qwen3.6-27B's architecture: 64 total layers, of which 16 use full attention (the other 48 are Gated DeltaNet linear-attention layers with fixed-size recurrent state), 4 KV heads shared across 24 query heads via Grouped-Query Attention (GQA),[9] and explicit head dimension 256 (notice 5120 / 24 would be wrong; always read head_dim and num_key_value_heads from the model config!).[6]
def kv_cache_bytes(
layers: int, kv_heads: int, head_dim: int, tokens: int, bytes_per_value: int
) -> int:
dimensions = (layers, kv_heads, head_dim, bytes_per_value)
if any(x <= 0 for x in dimensions) or tokens < 0:
raise ValueError("cache dimensions must be positive and tokens nonnegative")
return 2 * layers * kv_heads * head_dim * tokens * bytes_per_value
gqa_bytes = kv_cache_bytes(16, 4, 256, 4096, 2)
mha_bytes = kv_cache_bytes(16, 24, 256, 4096, 2)
print(f"GQA cache: {gqa_bytes / 1e9:.2f} GB")
print(f"MHA cache: {mha_bytes / 1e9:.2f} GB")
print("MHA / GQA:", mha_bytes // gqa_bytes)GQA cache: 0.27 GB
MHA cache: 1.61 GB
MHA / GQA: 6
Fragmentation and dynamic token budgeting
Reserving one contiguous max_model_len buffer per request wastes huge amounts of VRAM: a sequence stopping at 120 tokens inside a 4,096-token reservation leaves 97% unused (internal fragmentation), and freeing variable-sized buffers leaves scattered holes (external fragmentation). PagedAttention allocates fixed-size KV blocks (typically 16 tokens), eliminating contiguous-buffer fragmentation and confining unused slack to at most 15 trailing slots per sequence (17 cached tokens round up to two 16-token blocks = 32 reserved slots).[10]
A model's advertised context window (262,144 tokens for Qwen3.6-27B) is an architectural limit, not your production concurrency budget. Subtract static weights, runtime activations/CUDA graphs, prefix caches, and any hybrid recurrent state from HBM; what remains is your KV pool. Dividing an 18 GB KV pool across 50 concurrent users in 16-token blocks leaves 5,488 tokens per user (and 2,736 at 100 users). Similarly, an online admission check rejects a 64K request that would overflow a 12 GB pool already holding 40 active 4K sequences (10.74 GB), while admitting a 16K request (11.81 GB):
BYTES_PER_TOKEN = 2 * 16 * 4 * 256 * 2
def max_context_for_budget(
kv_pool_bytes: int, bytes_per_token: int, num_concurrent: int,
block_tokens: int = 16, context_limit: int = 262_144,
) -> int:
blocks_per_user = kv_pool_bytes // (bytes_per_token * block_tokens * num_concurrent)
return min(blocks_per_user * block_tokens, context_limit)
def reservation_bytes(tokens: int, block_tokens: int = 16) -> int:
blocks = (tokens + block_tokens - 1) // block_tokens
return blocks * block_tokens * BYTES_PER_TOKEN
def fits_kv_budget(existing_tokens: list[int], new_tokens: int, kv_budget_bytes: int) -> bool:
reservations = existing_tokens + [new_tokens]
needed = sum(reservation_bytes(tokens) for tokens in reservations)
return max(reservations) <= 262_144 and needed <= kv_budget_bytes
print(f"50 users in 18 GB pool: {max_context_for_budget(18 * 10**9, BYTES_PER_TOKEN, 50):,} tokens each")
active = [4096] * 40
print("fit 16K request in 12 GB pool:", fits_kv_budget(active, 16_384, kv_budget_bytes=12 * 10**9))
print("fit 64K request in 12 GB pool:", fits_kv_budget(active, 65_536, kv_budget_bytes=12 * 10**9))
assert reservation_bytes(17) == reservation_bytes(32)50 users in 18 GB pool: 5,488 tokens each
fit 16K request in 12 GB pool: True
fit 64K request in 12 GB pool: False
Always leave an explicit runtime reserve (activations, workspace, allocator slack) before promising concurrency: a 7B FP16 model (14 GB weights, 32 layers, 8 KV heads, 128 head dim) serving 200 users at 2,048 tokens uses 67.69 GB of raw weights plus KV, which clears an 80 GB card under an 8 GB reserve (75.69 GB) but overflows under a 16 GB reserve (83.69 GB).
Stop a new prefill from stalling live streams
A request can fit comfortably in HBM and still wreck interactive latency. Suppose one worker serves 32 live decode streams with 35 ms token gaps when a new 8,192-token prompt arrives. If that monolithic prefill holds the GPU exclusively for 200 ms, all 32 live streams experience a 235 ms generation stall before their next token appears.
Chunked prefill
Chunked prefill (Sarathi-Serve; default in vLLM V1) slices long prompts into bounded chunks (e.g., 2,048 tokens) and co-batches them with active decode steps under a shared per-step token budget.[11][12][13] Live decode streams keep advancing between chunks instead of waiting behind an entire document, trading a small amount of extra scheduling overhead and slightly longer TTFT for much tighter tail ITL.
def chunked_schedule(prompt_tokens: int, chunk_tokens: int) -> list[str]:
actions: list[str] = []
remaining = prompt_tokens
while remaining:
processed = min(chunk_tokens, remaining)
actions.append(f"prefill {processed}")
remaining -= processed
actions.append("decode active streams")
return actions
for action in chunked_schedule(prompt_tokens=6144, chunk_tokens=2048):
print(action)prefill 2048
decode active streams
prefill 2048
decode active streams
prefill 2048
decode active streams
Prefill-decode disaggregation
When heavy prompt bursts still violate tight streaming SLOs on a shared pool, prefill-decode disaggregation (Splitwise, DistServe, Mooncake) separates prompt processing and token decoding onto dedicated GPU pools with independent sharding and scaling.[14][15][16]
Separation eliminates direct compute contention at the cost of transferring KV state (and any hybrid recurrent state) across the interconnect:
Notice carefully which request pays which clock: on a shared worker, a 95 ms prefill for request B delays active chat A's next decode gap; on disaggregated pools, if B emits its first token on the prefill worker and then copies state for 20 ms before decoding token 2, that 20 ms copy lands on B's gap between tokens 1 and 2 (or on TTFT if token 1 is buffered). Over a 200 Gbps (25 GB/s) link, raw Qwen3.6-27B KV serialization takes at least 10.7 ms at 4K tokens and 171.8 ms at 64K tokens before protocol overhead and recurrent state:
bytes_per_token = 2 * 16 * 4 * 256 * 2
link_bytes_per_s = 200 * 10**9 / 8
for prompt_tokens in (4096, 65_536):
payload_bytes = prompt_tokens * bytes_per_token
lower_bound_ms = 1000 * payload_bytes / link_bytes_per_s
print(f"{prompt_tokens:,} tokens: {payload_bytes / 1e9:.3f} GB, "
f"at least {lower_bound_ms:.1f} ms transfer")4,096 tokens: 0.268 GB, at least 10.7 ms transfer
65,536 tokens: 4.295 GB, at least 171.8 ms transfer
Shrinking per-request state: KV quantization and hybrid models
When cache capacity rather than scheduling interference limits concurrency, quantizing the KV cache from 16-bit (FP16/BF16) to 8-bit (FP8/INT8) cuts raw per-token KV bytes in half.[17][18][19] Weight quantization shrinks static model memory (expanding the leftover pool), whereas KV quantization shrinks each active user's dynamic footprint.
On our 18 GB leftover pool (80 - 54 - 8 GB) with 5,120 tokens per user, switching from FP16 to FP8 KV cache nearly doubles KV-only capacity from 53 to 107 users. On hybrid models, however, fixed recurrent state changes the ratio dramatically. Qwen3.6-27B's 48 DeltaNet layers keep a fixed FP32 recurrent matrix of per active sequence regardless of context length.[6][20] At 128 cached positions inside an 8 GiB state pool, halving only the 8 MiB growing KV portion raises capacity from 53 to 55 sequences (1.04x), not :
mib = 2**20
recurrent_bytes = 48 * 48 * 128 * 128 * 4
kv_bytes = 2 * 16 * 4 * 256 * 128 * 2
state_pool = 8 * 2**30
full_state = recurrent_bytes + kv_bytes
half_kv_state = recurrent_bytes + kv_bytes // 2
before, after = state_pool // full_state, state_pool // half_kv_state
assert recurrent_bytes == 144 * mib and kv_bytes == 8 * mib
print(f"Per sequence (128 tok): recurrent={recurrent_bytes // mib} MiB, KV={kv_bytes // mib} MiB")
print(f"Only KV halved: total state {full_state // mib} -> {half_kv_state // mib} MiB")
print(f"8 GiB pool capacity: {before} -> {after} sequences ({after / before:.2f}x)")
kv_budget = 18 * 10**9
fp16_5k = 2 * 16 * 4 * 256 * 5120 * 2
print(f"18 GB KV-only pool (5,120 tok): FP16={kv_budget // fp16_5k}, FP8={kv_budget // (fp16_5k // 2)} users")Per sequence (128 tok): recurrent=144 MiB, KV=8 MiB
Only KV halved: total state 152 -> 148 MiB
8 GiB pool capacity: 53 -> 55 sequences (1.04x)
18 GB KV-only pool (5,120 tok): FP16=53, FP8=107 users
Read the symptom first
When the pager goes off, start from what users actually feel, name the clock and the hardware ceiling, and verify with a real load sweep (tracking goodput over all offered requests, including timeouts and rejections):
| Symptom | Check first | Likely culprits |
|---|---|---|
| Long blank wait, then smooth streaming | Queue time vs. prefill time | Queueing, long uncached prompts, cold workers |
| Fast first token, then widening gaps under load | Active streams and batch size | Decode HBM bandwidth, growing KV traffic |
| Smooth stream with occasional long freezes | Whether pauses align with new arrivals | Monolithic prefill generation stalls |
| Requests fail or stall mid-generation | KV pool occupancy and preemptions | Exhausted KV pool, unbudgeted output growth |
| Busy GPU dashboard, low tokens/s | Memory traffic per phase | Sloped HBM bandwidth roof, not compute roof |