Sub topic 10
Latency versus throughput
This chapter assumes you can call an LLM API, read short Python programs, and know what a token and a context window are. It covers the two speed measures you will compare when choosing between hosted APIs and self-hosted models, and how model size affects each.
Two different questions
Latency and throughput answer different questions about speed.
- Latency is how long one request takes from the user's point of view.
- Throughput is how much work the system finishes per unit of time across all requests, usually measured in tokens per second or requests per second.
A system can have good latency and poor throughput, or the reverse. A single user on a laptop may see fast replies, but the same machine falls over when fifty users arrive. A batch pipeline may process millions of tokens an hour while each request waits minutes.
Which one matters depends on the task, which is why it belongs with your selection criteria.
| Workload | Cares most about | Why |
|---|---|---|
| Chat assistant | Latency | A person is waiting for the reply |
| Autocomplete in an editor | Latency | Suggestions must appear while the user types |
| Nightly document classification | Throughput | Nobody waits on a single item |
| Bulk summarization of an archive | Throughput | Total time and cost for the whole job matter |
| Agent making many sequential calls | Latency | Delays add up across steps |
The parts of latency
A single request to a language model has two phases, and they behave differently.
- Prefill. The model reads the whole prompt. This work can run in parallel across the input tokens, so it is fast per token, but it grows with prompt length.
- Decode. The model generates the answer one token at a time. Each new token depends on the previous one, so this phase is sequential and usually dominates the time for long answers.
From these phases come the numbers you will see in provider dashboards and benchmarks:
- Time to first token (TTFT): the delay before the first output token arrives. It is mostly network time, queueing, and prefill.
- Inter-token latency, or tokens per second: how fast the output streams after it starts.
- End-to-end latency: the total time until the last token.
A useful approximation is:
end-to-end latency ≈ TTFT + (output tokens × time per output token)
This shows that output length is often the biggest lever you control. A reply of 500 tokens takes far longer than one of 20, no matter which model you pick.
def end_to_end_seconds(ttft_s: float, output_tokens: int, tokens_per_second: float) -> float:
return ttft_s + output_tokens / tokens_per_second
for out in (20, 200, 800):
t = end_to_end_seconds(ttft_s=0.6, output_tokens=out, tokens_per_second=50)
print(f"{out:>4} output tokens: {t:.1f} s")
# 20 output tokens: 1.0 s
# 200 output tokens: 4.6 s
# 800 output tokens: 16.6 sThe numbers (0.6 s and 50 tokens per second) are illustrative. Measure your own.
Streaming changes how latency feels
If the API supports streaming, the user sees tokens as they are produced. End-to-end latency stays the same, but the perceived wait becomes the TTFT. For a chat interface, streaming often matters more than choosing a faster model. For a program that needs the complete answer, such as one that parses JSON, streaming does not help, and end-to-end latency is what counts.
How model size affects speed
The chapter on model sizes explained that more parameters usually mean better quality and more memory. They also mean slower generation. Each output token requires reading the model's weights from memory, so a larger model has more to read per token. On the same hardware, a 70B model generates tokens noticeably slower than a 7B model.
This links speed to the memory estimate from the earlier chapter. Smaller weights, whether from fewer parameters or from quantization, can speed up decoding because less data moves per token. Quantization is not guaranteed to speed things up, though. The gain depends on the hardware and the serving software, so measure it.
Hosted providers usually offer a family of sizes at different speeds and prices. A small tier often has lower TTFT and a faster token rate than the flagship tier. This is one reason the decision process favors the smallest model that meets your requirements.
How throughput works
Throughput depends on how well the hardware is kept busy. A GPU generating tokens for a single request leaves most of its compute idle, because the decode step is limited by memory reads. Serving software fixes this with batching: it processes many requests together, so one read of the weights serves many sequences at once.
The result is a trade-off:
- Larger batches raise total throughput (tokens per second across all users).
- Larger batches also raise the wait for each individual request, because requests queue up and share the GPU.
Modern serving tools such as vLLM use continuous batching, which adds new requests to a running batch as others finish. This keeps the GPU busy without making every request wait for a full batch to complete. You will still need to tune limits such as the maximum number of concurrent sequences.
Hosted versus self-hosted speed
On a hosted API, the provider handles batching and hardware. You see these effects:
- Variable latency. Speed changes with load. Measure at several times of day, and look at percentiles, not just averages.
- Rate limits. Your throughput is capped by requests-per-minute and tokens-per-minute quotas. Hitting the cap returns errors (often HTTP 429) that you must handle with retries and backoff.
- Network time. Every call crosses the internet, which adds to TTFT.
- Batch endpoints. Some providers offer asynchronous batch processing, often at a discount, in exchange for results arriving later. This suits throughput-oriented jobs.
When you self-host, you control the trade-off but own the tuning. A local model on one GPU can have low network overhead and predictable latency for a single user. Serving many users needs enough GPU memory for the weights plus the KV cache for every concurrent sequence, so the concurrency you can sustain is bounded by memory.
Measure the right thing
Averages hide the problems users notice. Record the distribution.
- p50 is the typical request.
- p95 and p99 are the slow tail. A chat product with a good p50 and a bad p99 still feels unreliable.
The script below times a streaming request and reports TTFT, total time, and an approximate token rate. It uses the same environment-variable setup as the portability chapter's client code.
import os
import time
from openai import OpenAI
client = OpenAI(
base_url=os.environ["LLM_BASE_URL"],
api_key=os.environ.get("LLM_API_KEY", "not-needed-for-local"),
)
MODEL = os.environ["LLM_MODEL"]
def measure(prompt: str) -> dict:
start = time.perf_counter()
first = None
chunks = 0
stream = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
temperature=0,
stream=True,
)
for event in stream:
if not event.choices:
continue
delta = event.choices[0].delta.content
if delta:
if first is None:
first = time.perf_counter() - start
chunks += 1
total = time.perf_counter() - start
decode_time = total - (first or 0)
return {
"ttft_s": first,
"total_s": total,
"chunks_per_s": chunks / decode_time if decode_time > 0 else None,
}
print(measure("Explain what a hash map is in two sentences."))Streamed chunks are usually close to one token each, but not always, so treat chunks_per_s as an estimate. For exact counts, read the token usage the provider reports. Run the function many times with realistic prompts and compute p50 and p95 from the results.
Common mistakes
- Comparing speeds on different prompts. Prefill time depends on input length, and decode time depends on output length. Use the same cases for every candidate, as in the evaluation chapter.
- Trusting a single run. One measurement tells you nothing about the tail. Collect dozens.
- Ignoring output length. Asking for concise answers or setting a maximum output token limit can cut latency more than switching models.
- Optimizing the wrong metric. Tuning for throughput with big batches can make an interactive product feel slow. Tuning for single-request latency leaves hardware idle in a batch job and costs more per token.
- Forgetting retries. Rate limit errors and timeouts add to the latency users see. Include them in your measurements.
Using speed in the decision
Turn the workload into numbers before comparing models. For example: "p95 end-to-end latency under 3 seconds for answers of up to 150 tokens," or "process 2 million documents overnight." Then:
- Filter out candidates that cannot meet the numbers under realistic load.
- Among the rest, choose the smallest model that passes your quality evaluation.
- Consider routing, where easy requests go to a small fast model and hard ones go to a larger one, if no single model fits both speed and quality.
Exercise
A support chatbot shows replies as they stream. The model has a TTFT of 0.8 s and generates 40 tokens per second. A typical reply is 240 tokens. (a) What is the approximate end-to-end latency, and what wait does the user perceive before text appears? (b) A nightly job summarizes 100,000 documents with the same model and no user is waiting. Which metric should you optimize for the job, and what serving technique helps?
Show answer
(a) End-to-end latency ≈ 0.8 + 240 / 40 = 0.8 + 6.0 = 6.8 s. Because the reply streams, the user perceives the wait as the TTFT, about 0.8 s, before text begins to appear. (b) Optimize throughput (total tokens or documents per second), not single-request latency. Batching many requests together, ideally with continuous batching, or a provider's asynchronous batch endpoint, raises throughput even though each individual request takes longer.
Exercise
Your p50 latency is 1.2 s but your p99 is 14 s. Name two possible causes on a hosted API and one change you could make.
Show answer
Possible causes include provider load at peak times, rate limiting that triggers retries (such as HTTP 429 responses), and unusually long outputs or prompts for some requests. Changes include setting a maximum output token limit, adding retries with backoff and a timeout, switching to a smaller model tier, or routing long requests separately. Any two causes and one valid change are correct.