Sub topic 2
Where latency comes from: queueing, prefill, and decoding
This chapter assumes you have called an LLM API, can read basic Python, and know what a token is from the previous chapter. It breaks the wait for a response into stages. Later chapters on prompt trimming, output limits, streaming, and caching each target one of these stages, so you need to know which stage is slow before you pick a fix.
The three stages of a request
When you send a request, the time before you see the full answer is spent in three places.
- Queueing and network. Your request travels to the provider, passes through load balancers, and waits for a free slot on a GPU server. This time depends on provider load and your rate limits, not on your prompt.
- Prefill. The model reads your whole input (system message, history, retrieved documents, user question) and builds its internal state for it. All input tokens are processed together in parallel, so the work is large but fast per token.
- Decoding. The model produces the answer one token at a time. Each new token depends on the one before it, so this step cannot be parallelized across the output. Time here grows in a straight line with the number of output tokens.
Two numbers that describe the stages
Two measurements split the three stages cleanly.
- Time to first token (TTFT) is the time from sending the request until the first output token arrives. It contains network time, queueing, and prefill, plus the decode of one token.
- Time per output token (TPOT) is the average gap between consecutive output tokens after the first. Its inverse, tokens per second, is the decode speed.
Total latency is approximately:
total = TTFT + (output_tokens - 1) * TPOTThis formula is the working model for the chapter. It says total latency has a fixed-looking part (TTFT) and a part that scales with output length. For short answers such as classification labels, TTFT dominates. For long answers such as drafts, summaries, or code, decoding dominates.
Here is a worked example. Suppose TTFT is 0.4 s and TPOT is 20 ms (50 tokens per second). A 50-token answer takes about 0.4 + 49 × 0.02 = 1.38 s. A 1,000-token answer takes about 0.4 + 999 × 0.02 = 20.4 s. The prompt did not change, but the second request is fifteen times slower because it is mostly decoding.
Why each stage behaves the way it does
Prefill scales with input length. More input tokens means more computation before the first output token. A 20,000-token prompt has a visibly larger TTFT than a 500-token prompt, even though the answer is the same length. The cost is not strictly linear on long inputs, because attention work grows faster than the token count. Very long contexts can therefore be slower than a simple proportional estimate suggests.
Decoding scales with output length. Generating each token requires reading the model's weights and the stored state for the whole context from GPU memory. The limit is memory bandwidth more than raw arithmetic. This is why a bigger model has a higher TPOT, and why a very long context can also slow each decoded token a little.
Queueing scales with load, not with your request. The same prompt can have different TTFT at 3 a.m. and at peak hours. If you hit your rate limit, a retry adds a wait that looks like queueing in your measurements even though it happens on your side of the API.
Edge cases that distort the picture
- Hidden output tokens. Reasoning models produce internal reasoning tokens before the visible answer. These are decoded, billed as output, and delay the first visible token. A short visible answer can still have a large TTFT and total time.
- Chunks are not tokens. A streaming API may send several tokens in one chunk, or a chunk with no text (for example a role marker). Counting chunks gives only an approximation of token counts. Use the token count from the response's usage field when you need accuracy.
- Multi-call workflows add up. An agent that makes a tool call and then a second model call pays TTFT twice, plus tool time. Latency of a pipeline is the sum of its sequential calls, so the slowest step is not always the one to attack first.
- Cold starts and first requests. The first request after idle time may include connection setup (DNS, TLS) or, on some self-hosted or serverless setups, model loading. Discard or separately report the first sample when you benchmark.
- Cached prefixes shorten prefill. If the provider reuses a stable prompt prefix, prefill for that part is skipped or cheaper. TTFT then depends on how much of the prompt is a cache hit. A later chapter covers this.
- Non-streaming hides the split. Without streaming you see only the total. You cannot tell whether a slow call was queueing, prefill, or decoding.
Measuring the split in code
You can separate TTFT from decode speed by timing a streamed response. The function below extends the timing wrapper idea: it records time to first chunk, total time, and an estimate of time per chunk after the first. A fake stream stands in for a real API so the example runs without credentials.
import time
def fake_stream(n_chunks=50, ttft=0.4, per_chunk=0.02):
"""Simulate a streamed response: a delay for queue and prefill, then steady decoding."""
time.sleep(ttft)
for i in range(n_chunks):
if i > 0:
time.sleep(per_chunk)
yield f"tok{i} "
def time_stream(chunks):
"""Measure TTFT, total time, and average gap between chunks after the first."""
start = time.perf_counter()
first = None
count = 0
for _ in chunks:
if first is None:
first = time.perf_counter() - start
count += 1
total = time.perf_counter() - start
if count > 1:
per_chunk = (total - first) / (count - 1)
else:
per_chunk = None
return {"ttft_s": first, "total_s": total, "chunks": count, "per_chunk_s": per_chunk}
def predict_total(ttft_s, tpot_s, output_tokens):
"""Apply the model: total = TTFT + (output_tokens - 1) * TPOT."""
return ttft_s + max(output_tokens - 1, 0) * tpot_s
if __name__ == "__main__":
result = time_stream(fake_stream())
print(result)
print("predicted for 50 tokens:", predict_total(0.4, 0.02, 50))
print("predicted for 1000 tokens:", predict_total(0.4, 0.02, 1000))The measured total for the fake stream should land close to 1.4 s. Real APIs will show more variation, so collect many samples and look at percentiles such as p50 and p95, not one run.
With a real API, use the same wrapper around the streaming iterator. Replace per_chunk_s with a true TPOT by dividing by the output token count from the usage field when it is available.
Which lever targets which stage
| Stage | Grows with | Typical levers |
|---|---|---|
| Network and queue | Provider load, your rate limits, region distance | Retries with backoff, concurrency limits, closer region, batch endpoints for non-urgent work |
| Prefill | Input tokens | Prompt trimming, retrieval budgets, prompt caching, smaller model |
| Decoding | Output tokens, model size | Output limits, concise formats, smaller model, streaming for perceived speed |
Streaming does not change total time. It changes when the user starts seeing text, so it lowers perceived latency without lowering the number in the formula.
Reading your own numbers
Use these rules of thumb when you look at a baseline.
- If TTFT is high and output is short, look at prompt length, cache hits, and queueing.
- If TTFT is fine but total time is high, look at output length and model size.
- If latency varies a lot between identical requests, look at the tail (p95, p99). The cause is usually queueing, retries, or hidden reasoning tokens.
- If TPOT rises as the conversation grows, the context is getting long. Trim history.
Exercise
A request has a TTFT of 0.8 s and a TPOT of 25 ms. The model returns 400 output tokens. Using the chapter's model, what is the predicted total latency, and which stage dominates? Then say what would change most if you cut the answer to 100 tokens.
Show answer
Total = 0.8 + 399 × 0.025 = 0.8 + 9.975 ≈ 10.8 s. Decoding dominates (about 10 s of the 10.8 s). Cutting the answer to 100 tokens gives 0.8 + 99 × 0.025 = 0.8 + 2.475 ≈ 3.3 s, a drop of about 7.5 s. TTFT stays the same, so it becomes a much larger share of the total.
Exercise
Your application sends a 15,000-token document and asks for a one-word label. Users complain it is slow, yet outputs are tiny. Which stage is most likely responsible, and name two levers that target it.
Show answer
Prefill, because the input is large and the output is only a few tokens, so decoding time is negligible. Levers: trim or truncate the document to the relevant parts, use provider prompt caching if a large prefix is shared across requests, or use a smaller model.