Latency engineering, TTFT, tokens per second and streaming
"The model is slow" is the most common complaint about LLM features, and it is usually several different problems wearing one coat. The user waits for the first word (time to first token), then watches the rest arrive at some speed (inter-token latency), and the whole thing ends at some point (end-to-end latency). Each has different causes and different fixes. This doc is my playbook for measuring them separately and pulling the right lever.
Why it matters
Users judge responsiveness mostly by how quickly something starts happening. A chat that begins streaming quickly feels fast even if the full answer takes a while; a blank screen for several seconds feels broken. For agents and pipelines with no human watching, the picture flips: only end-to-end time matters, multiplied by the number of sequential steps. Knowing which metric your product depends on decides which optimisations are worth the effort.
How it works
Define the metrics precisely:
TTFT = time from request sent to first content token received
ITL = time between consecutive tokens (also called TPOT)
E2E = TTFT + (output_tokens - 1) × mean_ITL
tokens_per_second (per stream) ≈ 1 / mean_ITL
From how inference works: TTFT is dominated by queueing plus prefill (proportional to uncached prompt length), and ITL is dominated by decode step time (weights and KV cache streamed per step, shared across the batch). E2E is dominated by output length, because decode is sequential.
Rendering diagram…
Where the time goes, and the lever for each
| Component | Main driver | Levers |
|---|---|---|
| Network and gateway | Distance, TLS, extra hops | Region close to users, connection reuse, fewer proxies |
| Queueing | Load versus capacity | Autoscaling, priority, load shedding |
| Prefill | Uncached prompt tokens | Shorter prompts, prompt or prefix caching, faster GPUs, chunked prefill tuning |
| Decode per token | Bandwidth, batch size, model size | Quantization, smaller model, speculative decoding, lower batch caps |
| Output length | Tokens generated | Tighter instructions, max_tokens, structured output, less verbose reasoning |
Two cheap wins show up almost every time. First, generate fewer tokens: asking for a short JSON object instead of a paragraph can cut E2E more than any infrastructure change. Second, cache the prefix: putting static instructions first and enabling caching cuts TTFT on long prompts (see caching).
For reasoning models, remember that hidden thinking tokens are still decode steps. Many providers expose a reasoning effort or thinking budget setting; lowering it is a direct latency lever for simple tasks.
Streaming
Streaming does not make generation faster, but it makes TTFT the perceived latency instead of E2E. Use server-sent events end to end, and make sure nothing in the path buffers: some proxies, compression middleware and serverless platforms buffer responses until complete, which silently turns a streamed answer back into a blocking one.
Reference architecture
Rendering diagram…
Measure at two points: at the engine (vLLM exports vllm:time_to_first_token_seconds and an inter-token latency histogram, named vllm:inter_token_latency_seconds in recent versions) and at the client, because the gap between them is your network, gateway and buffering overhead. Track percentiles (p50, p95, p99), not averages, and break them down by prompt length bucket so a few huge prompts do not hide behind the median.
Code
A client-side probe that measures TTFT, ITL and E2E for any OpenAI-compatible endpoint, which I run in CI and against production on a schedule:
import time, statistics
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="local")
def probe(prompt: str, model: str, max_tokens: int = 256):
t0 = time.perf_counter()
first, stamps = None, []
stream = client.chat.completions.create(
model=model, max_tokens=max_tokens, stream=True,
messages=[{"role": "user", "content": prompt}],
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
now = time.perf_counter()
first = first or now
stamps.append(now)
end = time.perf_counter()
gaps = [b - a for a, b in zip(stamps, stamps[1:])]
return {
"ttft_s": round(first - t0, 3),
"itl_ms_p50": round(statistics.median(gaps) * 1000, 1) if gaps else None,
"e2e_s": round(end - t0, 3),
"chunks": len(stamps),
}
print(probe("List five ways to reduce LLM latency.", "Qwen/Qwen2.5-7B-Instruct"))
Note that a streamed chunk can carry more than one token, so count tokens from the usage field if you need exact tokens per second. For load testing at realistic concurrency, use a benchmarking tool such as vllm bench serve or your own replay of production traffic.
Trade-offs and pitfalls
- Throughput versus latency. Bigger batches raise tokens per second per GPU but slow each stream. Decide your ITL target and cap concurrency to meet it.
- Single-request benchmarks lie. Latency at one concurrent request says little about latency at peak. Always test at production concurrency and prompt lengths.
- Averages hide tails. A good mean with a bad p99 still means some users wait a long time. Alert on percentiles.
- Buffering anywhere breaks streaming. Test streaming through the full production path, including CDN, load balancer and framework middleware.
- Smaller is not always faster end to end. A smaller model that needs two retries or a longer answer can lose to a larger one that gets it right first time.
- Parallelise when you can. Independent sub-tasks in an agent or pipeline should run concurrently; sequential chains multiply latency.
Checklist
- I track TTFT, ITL and E2E separately as p50, p95 and p99.
- I measure at both the engine and the client.
- Streaming works through the full production path without buffering.
- Prompts put static content first and prompt caching is on.
- Every endpoint sets
max_tokensand asks for the shortest useful output format. - Concurrency caps are set from an ITL target and verified under load.
- I re-run latency probes after every model, engine or prompt change.