# LLM Inference Serving: Latency Metrics, Measuring, and Choosing an Engine

> A serving system has to balance time to first token, time per output token and total throughput. This page measures where one request's time goes with llama.cpp, shows why laptop benchmarks need a warm-up, and compares llama.cpp, Ollama, vLLM and SGLang.

- URL: https://dmxsf.com/en/wiki/inference/serving/
- [DMXSF](https://dmxsf.com/en/about/)
- Intermediate
- Updated: 2026-11-24
- Tags: Serving, Inference, KV cache

## After this page you will be able to

- State the definitions of TTFT, TPOT, end-to-end latency and throughput, and relate them with one formula.
- Explain why prefill is compute-bound and decode is memory-bandwidth-bound, and check it against measured numbers.
- Run a reproducible benchmark on a laptop: warm up, alternate configurations and report the sustained state.
- Tell llama.cpp, Ollama, vLLM and SGLang apart by what they are for, and read the metrics they expose.
- Use Little's law to estimate how many concurrent slots and machines are needed.

A serving system has to let one piece of hardware serve many requests at once. Every user cares about "how long until the text starts" (TTFT) and "does it stream smoothly" (TPOT); the operator cares about how many tokens the machine produces per second (throughput). These pull against each other: a bigger batch means higher throughput and a longer TPOT for each user. This page first measures where one request's time goes, then covers how to measure, how to choose an engine and which metrics to watch. How to pack many requests together efficiently is the subject of [Continuous Batching and PagedAttention](https://dmxsf.com/en/wiki/inference/continuous-batching/).

If you are new to this topic, start with [Your first inference service](https://dmxsf.com/en/wiki/inference/first-inference-service/).

> [!NOTE] Experimental setup
> The numbers on this page and on [the next one](https://dmxsf.com/en/wiki/inference/continuous-batching/) come from one machine: a MacBook Pro (Apple M2 Max, 12 CPU cores, 38 GPU cores, 64 GB of unified memory, on AC power) running `llama-server` from llama.cpp (build 11146, commit 7fe450e19) with Qwen2.5-7B-Instruct quantized to Q4_K_M (4.68 GB, from `Qwen/Qwen2.5-7B-Instruct-GGUF` on Hugging Face). Absolute numbers differ on other hardware; take away the trends and the method. vLLM needs a GPU that this machine does not have, so what the page says about vLLM comes from its documentation and paper and was not run locally.

## Where the Time of One Request Goes

A generation request goes through three phases in the server: **queueing** (waiting for a free slot), **prefill** (processing the whole prompt in parallel, which produces the first token) and **decode** (one token per step until the request ends).

*Figure: Durations are schematic. A longer prefill raises TTFT; more generated tokens raise the end-to-end latency.*

This gives four metrics:

| Metric | Meaning | What mainly determines it | What the user feels |
| --- | --- | --- | --- |
| TTFT (Time To First Token) | From sending the request to receiving the first token | Queueing time plus prefill time | How long until text appears |
| TPOT (Time Per Output Token), also ITL (Inter-Token Latency) | The gap between two consecutive output tokens | The time of one decode step: batch size, bytes of weights and KV cache read | Whether the text streams smoothly |
| End-to-end latency | From sending the request to the last token | TTFT plus N−1 TPOTs | How long the whole answer takes |
| Throughput | Tokens the server generates per second, in total | Batch size and scheduling | Cost per token |

For N output tokens, the first three are tied together by

$$
T_{\text{e2e}} = \underbrace{T_{\text{queue}} + T_{\text{prefill}}}_{\text{TTFT}} + (N-1)\,T_{\text{tpot}}
$$

Strictly, ITL is the gap at each step and TPOT is its average over a request; vLLM exports them as two separate metrics. The first token appears when prefill ends, so only N−1 gaps follow it.

## Experiment: Measuring One Request

Start a server first. Download the two Q4_K_M shards from Hugging Face and pass the path of the first one to `-m`; llama.cpp loads the remaining shards by itself:

```bash
llama-server -m qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf \
  -c 8192 -np 1 --metrics --port 8089
```

`-c` is the context length, `-np` is the number of slots (requests handled at the same time; the next page covers it) and `--metrics` enables a Prometheus-format `/metrics`. The server speaks an OpenAI-compatible API, so a request is one `curl` away:

```bash
curl -s http://127.0.0.1:8089/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"messages": [{"role": "user", "content":
       "Describe the Great Wall in three sentences."}],
       "max_tokens": 80, "temperature": 0}'
```

The `usage` and `timings` fields of the response (excerpt, rounded to two decimals) already hold all the times we need:

```json
"usage": {"prompt_tokens": 37, "completion_tokens": 80, "total_tokens": 117},
"timings": {
  "cache_n": 0,
  "prompt_n": 37,
  "prompt_ms": 127.97,
  "predicted_n": 80,
  "predicted_ms": 1229.75,
  "predicted_per_token_ms": 15.57,
  "predicted_per_second": 64.24
}
```

`prompt_n` is the number of prompt tokens actually computed and `cache_n` the number reused from the cache (the next page covers prefix caching). Prefilling 37 tokens took 128 ms, which is the bulk of the TTFT; the 80 output tokens took 1230 ms, 15.57 ms each, so the whole request takes about $0.128 + 79 \times 0.0156 \approx 1.36$ s.

Note that this decode speed is 64.2 tokens/s, whereas the sustained measurements below give about 42 tokens/s: right after startup, while the machine is still cool, it runs faster and then slows down under sustained load. That is a property of laptops, and this page measures it a little later.

A systematic measurement cannot be done with hand-typed `curl`. The client below streams `/completion` with `aiohttp` and records the TTFT and TPOT seen by the client together with the `timings` reported by the server. The text comes from WikiText-2, so that every request has a different prompt (no accidental cache hits). It is also the client used by all experiments on the next page:

```python
import asyncio
import json
import statistics as st
import time

import aiohttp
import pandas as pd
from huggingface_hub import hf_hub_download

URL = "http://127.0.0.1:8089"
path = hf_hub_download("Salesforce/wikitext",
                       "wikitext-2-raw-v1/train-00000-of-00001.parquet",
                       repo_type="dataset")
text = "".join(pd.read_parquet(path)["text"])[:600_000]

async def post(s, route, body):
    async with s.post(URL + route, json=body) as r:
        return r.status, await r.json()

async def request(s, tokens, n_predict, t0, cache=False):
    # stream one completion, record client- and server-side timings
    body = {"prompt": tokens, "n_predict": n_predict, "temperature": 0,
            "ignore_eos": True, "stream": True, "cache_prompt": cache}
    sent = time.perf_counter()
    first = last = None
    async with s.post(URL + "/completion", json=body) as r:
        async for raw in r.content:
            line = raw.decode().strip()
            if not line.startswith("data:"):
                continue
            d = json.loads(line[5:])
            if d.get("content"):
                last = time.perf_counter()
                first = first or last
            if d.get("stop"):
                srv = d["timings"]
    n = srv["predicted_n"]
    return {"sent": sent - t0, "ttft": first - sent, "done": last - t0,
            "n": n, "tpot": (last - first) / max(n - 1, 1), "srv": srv}

async def start():
    # a fresh connection per request: the server closes streamed connections
    s = aiohttp.ClientSession(
        connector=aiohttp.TCPConnector(force_close=True),
        timeout=aiohttp.ClientTimeout(total=3600))
    _, d = await post(s, "/tokenize", {"content": text})
    return s, d["tokens"]

def piece(toks, i, n):  # the i-th slice of n tokens, every start differs
    return toks[i * 2500: i * 2500 + n]

async def warm_up(s, toks, seconds):
    # a laptop GPU is faster in the first seconds than under sustained
    # load: hold the load until the speed settles, then measure
    t0, i = time.perf_counter(), 0
    while time.perf_counter() - t0 < seconds:
        await request(s, piece(toks, i, 1024), 32, t0)
        i += 1
```

Use it to measure prompts of different lengths: 3 requests per length, median reported, 64 generated tokens each.

```python
async def anatomy():
    s, toks = await start()
    seconds = {}  # prompt length -> seconds spent on prefill
    print("prompt  TTFT(s)  prefill(tok/s)  decode(tok/s)")
    for L in (32, 128, 512, 1024, 2048, 4096):
        rs = [await request(s, piece(toks, i, L), 64, time.perf_counter())
              for i in range(3)]
        med = lambda f: st.median(f(r) for r in rs)
        seconds[L] = med(lambda r: r["srv"]["prompt_ms"]) / 1000
        print(f"{L:>6} {med(lambda r: r['ttft']):8.2f} "
              f"{med(lambda r: r['srv']['prompt_per_second']):15.0f} "
              f"{med(lambda r: r['srv']['predicted_per_second']):14.1f}")
    await s.close()
    return seconds

PROMPT_SECONDS = asyncio.run(anatomy())
```

Output:

```text
prompt  TTFT(s)  prefill(tok/s)  decode(tok/s)
    32     0.13             256           40.9
   128     0.35             373           40.6
   512     1.10             469           42.3
  1024     2.18             470           42.3
  2048     4.16             495           40.8
  4096     8.50             484           38.7
```

The widget below makes this table draggable: drag the prompt length (log axis) to watch TTFT, prefill and decode speed each move; the dashed TTFT line recomputes L/v with each row's own prefill speed — matching the printed seconds to rounding.

Three observations:

1. **TTFT is roughly proportional to the prompt length.** 2048 tokens took 4.16 s and 4096 tokens took 8.50 s; TTFT is approximately $L / v_{\text{prefill}}$, where $v_{\text{prefill}}$ is the prefill speed: $2048 / 495 \approx 4.14$ s, as measured. When a user uploads a long document and then asks a question, these seconds are what they wait for.
2. **Prefill speed saturates around 470 to 495 tokens/s**, while a short 32-token prompt manages only 256 tokens/s: a short prompt cannot fill the hardware, so fixed overheads weigh more.
3. **Decode speed hardly changes with prompt length, and drops a little only at 4096 tokens** (from 42.3 to 38.7 tokens/s, about 9%). Besides the weights, every decode step also reads the KV cache of the tokens so far: for 4096 tokens that is 224 MiB (the calculation is on the next page), about 5% of the weights (4.68 GB), which fits in direction and order of magnitude.

## Prefill and Decode: Compute-Bound and Bandwidth-Bound

Prefill is about ten times faster than decode (roughly 470 against 42 tokens/s) because the two phases are limited by different resources:

- **Prefill** processes $L$ tokens at once: reading the weights from memory once pays for the computation of $L$ tokens. There is a lot of computation, so it is limited by compute (compute-bound). However long the prompt is, the speed saturates, as the 470 to 495 tokens/s above show.
- **Decode** processes one token at a time: it also has to read the weights once but computes for a single token, so it is limited by memory bandwidth (memory-bound). The speed limit is about the bandwidth divided by the size of the weights; the full derivation is in [GPUs and the Roofline Model](https://dmxsf.com/en/wiki/systems/gpu-and-roofline/).

Check it on this machine: the M2 Max has a memory bandwidth of 400 GB/s (Apple's stated figure) and the model is 4.68 GB, so the limit is $400 / 4.68 \approx 85$ tokens/s. The measured sustained speed of 42 tokens/s corresponds to reading $4.68 \times 42 \approx 198$ GB per second, about half of the bandwidth; the initial 64.2 tokens/s is about 75%. It does not reach the limit because decode also does attention, normalization and sampling, and small-batch kernels cannot saturate the bandwidth anyway.

This rule explains several things. Quantization (4-bit weights) speeds decode up mainly because the weights shrink and fewer bytes are read per step (see [Model Quantization](https://dmxsf.com/en/wiki/inference/quantization/)). Packing requests into a batch raises throughput because one read of the weights serves several requests (see [the next page](https://dmxsf.com/en/wiki/inference/continuous-batching/)). Speculative decoding spreads the bandwidth cost by verifying several tokens per read of the weights (see [Speculative Decoding](https://dmxsf.com/en/wiki/inference/speculative-decoding/)).

## Benchmarking on a Laptop: Warm Up First

A laptop GPU is limited in power and cooling: it runs faster when a load starts and slows down after a while. A benchmark that lasts a few seconds is therefore too optimistic, and worse, **whichever configuration runs first gets the benefit of the cold machine**. In the experiment below the client sends one request after another for 90 seconds and reports every 15 seconds:

```python
async def drift():
    s, toks = await start()
    t0 = time.perf_counter()
    rows, i = [], 0
    while time.perf_counter() - t0 < 90:  # one request after another
        r = await request(s, piece(toks, i, 1024), 64, t0)
        rows.append((r["sent"], r["srv"]["prompt_per_second"],
                     r["srv"]["predicted_per_second"]))
        i += 1
    print("seconds  prefill(tok/s)  decode(tok/s)  requests")
    for w in range(0, 90, 15):
        win = [r for r in rows if w <= r[0] < w + 15]
        print(f"{w:>3}-{w + 15:<3} {st.mean(r[1] for r in win):14.0f} "
              f"{st.mean(r[2] for r in win):14.1f} {len(win):9d}")
    await s.close()

asyncio.run(drift())
```

```text
seconds  prefill(tok/s)  decode(tok/s)  requests
  0-15             580           50.0         5
 15-30             508           43.7         5
 30-45             497           42.8         4
 45-60             495           42.5         4
 60-75             501           43.1         4
 75-90             498           42.2         5
```

In the first 15 seconds prefill runs at 580 tokens/s and decode at 50.0 tokens/s; from second 30 on it stays near 495 and 42.5, about 15% lower, and does not change after that. I also measured that after 45 to 60 seconds or more of idling, the speed returns to the initial level, and that changing `-t` (CPU threads) from the default to 2 makes no difference (all the computation happens on the GPU).

Hence every experiment on this page, and on the next, follows these rules:

1. **Warm up first.** Before each measurement, hold the load for at least 40 seconds with the `warm_up` function of the client above, then start timing.
2. **Alternate when comparing.** To compare configurations A and B, run A, B, A, B, two passes each, instead of finishing all of A before B.
3. **Report the sustained numbers**, or report both states and say which is which.
4. **Record the environment**: machine, power, model and quantization, engine version (commit), the distribution of prompt and output lengths, and the concurrency.

Other hardware has similar problems (GPU throttling, other jobs on a shared machine, burstable cloud instances), only in different amounts. When you read a benchmark of inference engines, first check whether it states these conditions: the same model and quantization format, the distribution of prompt lengths, concurrency and sampling parameters. With different conditions the numbers are not comparable.

## Choosing an Engine

These are the common open-source inference servers; the table follows their official documentation as read in November 2026:

| Engine | What it is for | Hardware | Concurrency and caching | Quantization and formats |
| --- | --- | --- | --- | --- |
| llama.cpp (`llama-server`) | Lightweight and portable: personal computers and edge devices | CPU, Apple Metal, CUDA, Vulkan and more; CPU and GPU can be mixed | Continuous batching (default), slots (`-np`), prefix reuse per slot | GGUF, many low-bit quantizations |
| Ollama | Ready-to-use local model management and serving | macOS, Windows, Linux; CPU and GPU | `OLLAMA_NUM_PARALLEL` (default 1), queue limit `OLLAMA_MAX_QUEUE` (default 512) | Mostly GGUF quantizations in its model library |
| vLLM | High-throughput online serving on GPU servers | GPUs from NVIDIA, AMD and Intel and several CPUs, plus hardware plugins for TPU, Gaudi and others | PagedAttention, continuous batching, chunked prefill, prefix caching | FP8, INT8, INT4, GPTQ, AWQ, GGUF and more |
| SGLang | High-throughput serving, strong at prefix reuse and structured output | GPU, TPU, NPU, CPU, Apple silicon | RadixAttention (a prefix cache managed as a radix tree), continuous batching (both in the SGLang paper) | See the official documentation |
| TGI | Maintenance mode, not recommended for new projects | Mostly GPU | Continuous batching | bitsandbytes, GPTQ, AWQ, FP8 and more |

A few notes:

- **llama.cpp and Ollama** differ in packaging: Ollama adds a model library, automatic loading and unloading and a REST API on top of the llama.cpp ecosystem, which makes it easy to use and gives less control over low-level parameters. Parallel requests in Ollama multiply the context by the number of parallel requests (the official FAQ's example: a 2K context with 4 parallel requests becomes an 8K context), and the required memory grows with `OLLAMA_NUM_PARALLEL` times `OLLAMA_CONTEXT_LENGTH`.
- **vLLM** makes the mechanisms discussed so far the default behavior and offers an OpenAI-compatible server (`vllm serve <model>`) and Prometheus metrics. To start one:

  ```bash
  vllm serve Qwen/Qwen2.5-7B-Instruct --max-model-len 8192
  ```

  The parameters you adjust most often are `--max-model-len` (maximum context), `--max-num-seqs` (requests handled at once), `--max-num-batched-tokens` (the token budget per step) and `--gpu-memory-utilization` (the share of GPU memory to use); [the next page](https://dmxsf.com/en/wiki/inference/continuous-batching/) explains what they do. This command was not run on this machine, so follow the documentation of the version you use.
- **SGLang**'s paper introduced RadixAttention and compressed finite state machines (which speed up decoding for structured output); its features overlap with vLLM's, and both are worth comparing on your own workload.
- **TGI**: Hugging Face states in its README that the project is in maintenance mode, accepting only minor bug fixes and documentation improvements, and recommends vLLM, SGLang and local engines such as llama.cpp or MLX.

A first cut by scenario:

| Scenario | Consider first |
| --- | --- |
| Personal computer, laptop, edge device | llama.cpp or Ollama |
| Small team, little concurrency, quick API | Ollama, or vLLM on a single GPU |
| Multi-user online service on GPU servers | vLLM or SGLang |
| Highly repetitive prompt prefixes (agents, RAG, multi-turn chat) or structured output | SGLang, or vLLM with prefix caching |

Whichever you pick, benchmark on your own workload before going live, **with the same model version, quantization, prompt and output length distributions, concurrency and sampling parameters, and make sure the tokenizer and chat template are identical**; if the same model gets a different template its output can suddenly get worse, and the engine is not to blame.

## What to Monitor

Once the service is live, there are four groups of metrics to watch. The two engines name them differently, with similar meanings:

| Group | vLLM (Prometheus) | llama-server (`--metrics`) |
| --- | --- | --- |
| Latency | `vllm:time_to_first_token_seconds`, `vllm:inter_token_latency_seconds`, `vllm:e2e_request_latency_seconds`; to split them, `vllm:request_queue_time_seconds`, `vllm:request_prefill_time_seconds`, `vllm:request_decode_time_seconds` | `timings` in every response; in aggregate `llamacpp:prompt_tokens_seconds`, `llamacpp:predicted_tokens_seconds` |
| Load | `vllm:num_requests_running`, `vllm:num_requests_waiting` | `llamacpp:requests_processing`, `llamacpp:requests_deferred` |
| KV cache | `vllm:kv_cache_usage_perc`, `vllm:num_preemptions`, `vllm:prefix_cache_hits` and `vllm:prefix_cache_queries` | `llamacpp:prompt_tokens_cached_total` (prompt tokens reused) |
| Throughput | `vllm:prompt_tokens`, `vllm:generation_tokens`, `vllm:request_success` (by finish reason) | `llamacpp:prompt_tokens_total`, `llamacpp:tokens_predicted_total` |

The vLLM names follow the latest documentation as read in November 2026 and may differ between versions; trust the `/metrics` output of the version you run. Look at latency percentiles (p50, p95, p99) rather than the mean: a few very long requests pull the tail up and the mean does not show it.

When something goes wrong, sort the symptom with the table below (slow TTFT, low throughput, a bad tail and running out of memory are often different problems):

| Symptom | Look at first | Common causes | Action |
| --- | --- | --- | --- |
| Slow first token | TTFT split into queueing time and prefill time | Queueing: concurrency above the number of slots. Prefill: prompt too long, prefix cache not hit | Limit input length; put stable content first so the prefix cache hits; add capacity or rate limits |
| Choppy output (large, jittery TPOT) | Percentiles of the token gap; whether long-prompt prefills share the batch | Batch too large; prefill chunks so large that they interrupt requests that are decoding | Lower the concurrency limit; reduce the per-step token budget (chunked prefill) |
| Low throughput, machine not busy | Requests running, batch size | Too little concurrency; very different request lengths with static batching | Turn on continuous batching; raise the concurrency limit |
| Long queue, high KV usage, frequent preemption | `kv_cache_usage_perc`, `num_preemptions` | Not enough KV cache | Lower the maximum context and concurrency, raise the memory share, quantize, add parallelism |
| Bad p99 with a normal mean | The distribution of request lengths, percentiles of end-to-end latency | A few very long requests hold up the queue | Limit input and output length, set timeouts and cancellation, route long requests elsewhere |

## Calculate goodput from request traces

The two LLM serving lectures in [CMU ML Systems](https://mlsyscourse.org/schedule) cover batching and caching, then speculative decoding. To compare such optimizations, follow [DistServe](https://arxiv.org/abs/2401.09670) and set separate service-level objectives (SLOs) for time to first token and mean time per output token. For a fixed observation window, **goodput** is the number of successful requests that meet both objectives divided by the window duration. To find sustainable capacity, also define the minimum acceptable fraction of requests that meet the objectives and sweep the offered request rate.

The following traces are synthetic. Both runs receive the same requests in the same window. Every request completes or times out during the window, and every completed request produces at least two tokens. The example ran on an Apple M2 Max with Python 3.14.3 and has no third-party dependencies.

```python
# Each row is (completed, TTFT in ms, TPOT in ms).
traces = {
    "Baseline": [(True, 90, 15)] * 5 + [(True, 130, 25)] * 3
        + [(False, None, None)] * 2,
    "Candidate": [(True, 80, 15)] * 4 + [(True, 95, 25)] * 6,
}
window_seconds = 2
ttft_limit, tpot_limit = 100, 20

def rates(requests):
    completed = sum(ok for ok, _, _ in requests)
    within_slo = sum(
        ok and ttft <= ttft_limit and tpot <= tpot_limit
        for ok, ttft, tpot in requests
    )
    return completed / window_seconds, within_slo / window_seconds

baseline, candidate = map(rates, traces.values())
assert candidate[0] > baseline[0] and candidate[1] < baseline[1]
for name, requests in traces.items():
    throughput, goodput = rates(requests)
    print(f"{name}: {throughput:.1f} req/s, {goodput:.1f} good req/s")
```

```text
Baseline: 4.0 req/s, 2.5 good req/s
Candidate: 5.0 req/s, 2.0 good req/s
```

The candidate completes more requests, but fewer meet both objectives because most completed requests exceed the TPOT threshold. For a real comparison, fix arrival times, input and output length distributions, sampling settings, and the model quality criterion. Report attainment, timeouts, and results by length slice. When studying [prefix caching and prefill/decode disaggregation](https://dmxsf.com/en/wiki/inference/prefix-caching/), measure cold and warm caches separately and account for cross-node transfers.

## Capacity Planning: Concurrency, Latency and the Number of Machines

"How many machines do I need" can be estimated with **Little's law**: in steady state, the number of requests in the system $L$ equals the arrival rate $\lambda$ (requests per second) times the average time $W$ a request spends in the system:

$$
L = \lambda W
$$

The residence time $W$ is the end-to-end latency above, and it depends on the concurrency: the higher the concurrency, the slower each request and the longer it stays. So the calculation iterates: first let the product decide the minimum speed per user (say at least 17 tokens/s; the number is only there to make the example easy), find in the measured curve of concurrency against per-request speed (the concurrency experiment on the next page) how many requests one machine can serve, then compute $W$, and finally the total concurrency and the number of machines. That example is left to the exercises below, using the curve measured on the next page.

## Trace an alert to a production regression

The [operations chapter of CMU's Machine Learning in Production](https://mlip-cmu.github.io/book/13-planning-for-operations.html) treats observability and updates as design requirements. Link deployment manifests, request traces, and task outcomes to follow an alert to the affected stage.

Suppose resolution drops after a documentation assistant switches indexes. Find which deployment versions and task categories account for the failures, then replay the same requests. If answerable requests often lack evidence, inspect ingestion freshness, the index version, and retrieved evidence. If evidence is present but citations fail, inspect prompt assembly, truncation, and generation. For unfinished requests, separate queueing, first-token latency, and decoding. Include timeouts and rejections so the investigation covers requests that never returned a response.

| Signal | Evidence to narrow the cause | Check after recovery |
| --- | --- | --- |
| More tool timeouts | Dependency latency, retries, and final state under the same trace ID | Replay fixed tasks and inspect successes and duplicate side effects |
| Lower retrieval coverage in the candidate | Compare evidence from old and new indexes by document age and language | Restore a compatible index and configuration, then measure coverage on independent samples |
| Slower first token with stable generation speed | Compare input lengths, queue waits, prefill, and cached-token counts | Measure goodput across load levels using the same arrival distribution |

Use these signals to form hypotheses. If a deployment and its traffic mix changed together, use fixed-traffic replay or a controlled release to separate their effects before deciding whether to roll back, increase capacity, or repair data. Add representative failures to the [evaluation set](https://dmxsf.com/en/wiki/evaluation/building-eval-sets/) to verify the next fix.

## A Checklist Before Going Live

Between "it runs" and "it can go live" lies a body of engineering work. The first time you hand an LLM service to other people, at least cover:

- A fixed model version, quantization format and configuration, plus a fixed set of regression samples (to compare output quality at release and rollback).
- A standard input and output protocol (such as an OpenAI-compatible API) and one chat template.
- A health-check endpoint, so that a bad instance can be taken out of rotation.
- Request timeouts and cancellation, an input length limit, and a rate limit or queue limit (fail fast when exceeded instead of queueing forever).
- Request and error logs that let you trace a slow request, and the metrics in the tables above wired into monitoring and alerts.
- A rollback plan: when a new model, quantization format or engine goes live, be able to switch back to the old version quickly.

## Summary and Exercises

**Key points:**

1. The time of a request consists of queueing, prefill and decode: $T_{\text{e2e}} = \text{TTFT} + (N-1)\,T_{\text{tpot}}$, and TTFT is queueing plus prefill.
2. Prefill is compute-bound, at about 470 to 495 tokens/s here, and TTFT is proportional to the prompt length; decode is memory-bandwidth-bound, reads the weights once per token, and its speed limit is about the bandwidth divided by the size of the weights.
3. A laptop under sustained load is about 15% slower than at the start: warm up for at least 40 seconds before measuring, alternate configurations when comparing, and report the sustained state.
4. Use llama.cpp or Ollama on personal computers and edge devices, vLLM or SGLang for online services on GPU servers; TGI is in maintenance mode.
5. Monitor four groups of metrics: latency (queueing and prefill separated, percentiles), load, KV cache and throughput; estimate capacity with Little's law.

### Quick quiz

**1. What does the time to first token (TTFT) consist of?**

- [ ] The sum of the time of every decode token
- [x] Queueing time plus prefill time
- [ ] Network round-trip time
- [ ] Model loading time

> The first token appears when prefill ends, so TTFT = queueing + prefill.

**2. When the prompt grows from 512 tokens to 4096 tokens, roughly how does TTFT change in this page's experiment?**

- [ ] Hardly at all
- [x] About 8 times, from 1.10 s to 8.50 s
- [ ] About 2 times
- [ ] It gets shorter

> Prefill speed saturates around 470 to 495 tokens/s, so TTFT is roughly proportional to the prompt length.

**3. Why is the decode phase limited by memory bandwidth?**

- [ ] Because decode has an especially large number of matrix multiplications
- [x] Every generated token reads all the weights from memory but computes for only one token
- [ ] Because decode runs on the CPU
- [ ] Because decode needs the network

> Little computation and a lot of reading: the speed limit is about the bandwidth divided by the size of the weights.

**4. Which is the most sensible way to compare the speed of two configurations on a laptop?**

- [ ] Run each for 5 seconds and average
- [ ] Run all of A, then all of B
- [x] Warm up, then alternate A, B, A, B and report the sustained numbers
- [ ] Keep only the fastest run

> A machine is faster when a load starts, so the configuration that runs first benefits; warming up and alternating remove that bias.

**5. A request stays in the system for 12 seconds on average and 0.5 requests arrive per second. How many requests are in the system on average in steady state?**

- [ ] 0.5
- [ ] 12
- [x] 6
- [ ] 24

> Little's law: $L = \lambda W = 0.5 \times 12 = 6$.

**Exercises:**

1. Use the numbers of this page: a prompt of 3000 tokens, a prefill speed of 485 tokens/s, 200 output tokens, a decode speed of 42 tokens/s, and no queueing. What are the TTFT and the end-to-end latency?
2. One user complains that "it waits a long time before any text appears", another that "the text streams in jerks". Which metric should you look at first in each case? Give one common cause and one remedy for each.
3. A GPU with a memory bandwidth of 3.35 TB/s runs Qwen2.5-7B (7.616 B parameters). What is the upper limit of the decode speed of a single request with FP16 weights, and with the Q4_K_M weights (4.68 GB) used on this page? Why is it only an upper limit?
4. Each user must get at least 17 tokens/s, each request produces 200 tokens on average, and 0.8 requests arrive per second at peak. Using the concurrency experiment on [the next page](https://dmxsf.com/en/wiki/inference/continuous-batching/) (at concurrency 4 a request gets 17.3 tokens/s and the mean time to first token is 0.47 s; at concurrency 6 the speed drops to 12.2 tokens/s), estimate: how many requests can one such machine serve at once? How long does a request stay in the system? How many machines are needed?
5. An article says "engine X is 30% faster than engine Y". Which four questions do you need to ask, at the very least, to judge whether the number can be trusted?

<details>
<summary>Reference answers</summary>

1. TTFT $= 3000 / 485 \approx 6.19$ s; end to end $= 6.19 + 199 / 42 \approx 10.9$ s. Prefill takes more than half of it, so for requests with long prompts the thing to optimize is TTFT (prefix caching, shorter prompts).
2. "Waits a long time before any text appears" points to TTFT, which you split into queueing time and prefill time: a long queue means the concurrency exceeds the number of slots, so add capacity or rate-limit; a long prefill means the prompt is too long or the prefix cache missed, so shorten the input and put stable content first. "Streams in jerks" points to the percentiles of the token gap (TPOT, ITL): common causes are a batch that is too large or prefill chunks so large that they interrupt requests that are decoding, and the remedy is to lower the concurrency limit or reduce the per-step token budget.
3. Decode reads the weights once per token, so the limit is about the bandwidth divided by the size of the weights. FP16: $7.616 \times 10^9 \times 2 = 15.2$ GB, so $3350 / 15.2 \approx 220$ tokens/s; Q4_K_M: $3350 / 4.68 \approx 715$ tokens/s, about 3.3 times higher. It is only an upper limit because decode also does attention (reading the KV cache), normalization and sampling, and the kernels cannot saturate the bandwidth; the M2 Max on this page reaches only about half of its bandwidth limit.
4. At concurrency 4 one request gets 17.3 tokens/s, still at least 17; at concurrency 6 it drops to 12.2, which is not enough, so one machine can serve at most 4 requests at once. The residence time is $W \approx 0.47 + 200 / 17.3 \approx 12.0$ s. The total concurrency is $L = \lambda W = 0.8 \times 12.0 \approx 9.6$ and each machine holds 4, so you need $\lceil 9.6 / 4 \rceil = 3$ machines (two have only 8 slots, not enough). The arrival rate one machine can take is $4 / 12.0 \approx 0.33$ requests per second.
5. For example: (1) are the model, quantization format, hardware and engine version the same? (2) are the distributions of prompt and output length and the concurrency the same, and is it per-request speed or total throughput that is compared? (3) was there a warm-up, are the numbers from the sustained state, and were the runs alternated? (4) is it a mean or percentiles (p95, p99), and are the sampling parameters and chat template the same?

</details>

## Further Reading

- The setup, client and measurement method of this page continue on [Continuous Batching and PagedAttention](https://dmxsf.com/en/wiki/inference/continuous-batching/): the concurrency sweep, the continuous batching comparison, KV-cache paging and prefix caching.
- vLLM documentation: [Production Metrics](https://docs.vllm.ai/en/latest/usage/metrics.html) (metric names and meanings) and [Optimization and Tuning](https://docs.vllm.ai/en/latest/configuration/optimization.html).
- Kwon et al., [Efficient Memory Management for Large Language Model Serving with PagedAttention](https://arxiv.org/abs/2309.06180); paper explainer: [vLLM and PagedAttention](https://dmxsf.com/en/blog/vllm-pagedattention/).
- Zheng et al., [SGLang: Efficient Execution of Structured Language Model Programs](https://arxiv.org/abs/2312.07104).
- Repositories: [llama.cpp's llama-server](https://github.com/ggml-org/llama.cpp/tree/master/tools/server), [Ollama FAQ](https://github.com/ollama/ollama/blob/main/docs/faq.mdx) and the [TGI README](https://github.com/huggingface/text-generation-inference).
- Related pages: [KV Cache and Inference Performance](https://dmxsf.com/en/wiki/inference/kv-cache/), [Model Quantization](https://dmxsf.com/en/wiki/inference/quantization/) and [Speculative Decoding](https://dmxsf.com/en/wiki/inference/speculative-decoding/).

- Wu et al., [FastServe](https://arxiv.org/abs/2305.05920) (2023) and Sun et al., [Llumnix](https://arxiv.org/abs/2406.03243) (2024): skip-join scheduling and live request migration to relieve head-of-line blocking.
- Ong et al., [RouteLLM](https://arxiv.org/abs/2406.18665) (2024): query routing between strong and weak models, trading acceptable quality for cost.
- For cache reuse and prefill/decode separation, see [prefix caching and PD disaggregation](https://dmxsf.com/en/wiki/inference/prefix-caching/).
- [Production evaluation](https://dmxsf.com/en/wiki/evaluation/production-evaluation/)

## Companion code

[Serving: continuous batching, paged KV memory, prefix cache, TTFT, capacity](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/continuous-batching): Roofline and exact batched decoding, static against continuous scheduling on paper and on a real model, a paged KV pool with copy-on-write, a hash-based prefix cache, and what a request costs (TTFT, TPOT, capacity). Read the ratios, not the milliseconds.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run inference/continuous-batching`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/continuous-batching/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/continuous-batching/README.en.md)
- [`serving.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/inference/serving.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#continuous-batching)

## FAQ

### Which latency metrics matter most for an inference service?

Three: time to first token (TTFT: from sending the request to receiving the first token, which is queueing plus prefill), time per output token (TPOT, also called inter-token latency or ITL: the gap between two consecutive tokens, which decides whether the text streams smoothly) and end-to-end latency (TTFT plus N−1 TPOTs, where N is the number of output tokens). On top of these comes the throughput of the whole server, the number of tokens generated per second. TTFT depends mostly on prompt length and queueing, TPOT mostly on batch size and the amount of KV cache read, so look at them separately.

### How should I choose between llama.cpp, Ollama, vLLM and SGLang?

On a personal computer, laptop or edge device use llama.cpp or Ollama, which is built on the same ecosystem: it has many quantization formats, can mix CPU and GPU, and starts a server with one command. For multi-user online services on GPU servers start with vLLM or SGLang: continuous batching, a paged KV cache and prefix caching give far higher throughput. This is only a first-round judgment; benchmark with your own prompt-length distribution, concurrency and hardware.

### Is TGI (Text Generation Inference) still worth using?

Hugging Face states in the README of the TGI repository that it is in maintenance mode: only minor bug fixes, documentation improvements and lightweight maintenance are accepted, and vLLM, SGLang and local engines such as llama.cpp and MLX are recommended instead (as read in November 2026). Existing TGI deployments can keep running, but a new project is better started on vLLM or SGLang.

### Why is the speed in the first seconds of a laptop benchmark different from the rest?

A laptop is faster when a load starts than under sustained load. The M2 Max measured on this page reaches 580 tokens/s of prefill and 50.0 tokens/s of decode in the first 15 seconds, then settles near 495 and 42.5, about 15% lower, and recovers after roughly a minute of idling. So warm up for at least 40 seconds before measuring, alternate configurations (A, B, A, B) when comparing them, and report the sustained numbers.

### How do I estimate how many concurrent slots or machines I need?

Use Little's law: in steady state, the number of requests in the system equals the arrival rate times the average time a request spends there. That time is queueing plus prefill plus the number of output tokens divided by the per-request speed. First decide the minimum tokens/s each user must get, then read from a measured curve of concurrency against per-request speed how many requests one machine can serve at that speed, and work back from the residence time to the total concurrency.

### Which metrics must be monitored once the service is live?

At least four groups: latency (TTFT, token gaps and end-to-end latency at p50, p95 and p99, with queueing time and prefill time separated), load (requests running and waiting), KV cache (usage, number of preemptions, prefix-cache hit rate), and throughput and errors (tokens per second, the share of timeouts and failures). Without them you cannot tell whether a problem comes from queueing, prefill, an oversized batch or running out of memory.
