L1 Beginner · Module 0: Orientation

0.2The life of a request: tokens in, tokens out

Follow a single prompt from the moment you press Enter to the last streamed word, through tokenization, scheduling, prefill, decode and streaming. Each stage is a place where latency hides.

GPU optional✦ Interactive~20 min

By the end you will be able to

  • ✓Name the six stages a request passes through in an inference server
  • ✓Explain what prefill and decode each do, and why they behave so differently
  • ✓Decompose end-to-end latency into TTFT and TPOT
  • ✓Measure TTFT and TPOT of a real server yourself

You type “Explain the KV cache in one sentence.” and press Enter. About a fifth of a second later words start appearing, and they keep streaming until the answer is done. Here is everything that happened in between.

speed
  1. 1Request
  2. 2Tokenize
  3. 3Schedule
  4. 4Prefill
  5. 5Decode
  6. 6Stream & finish

Prompt → token IDs (illustrative)

Explain the KV cache in one sentence.

Streamed output

KV cache (one slot per token)0 tokens

prompt (written in prefill) generated (one per decode step)

Request. The client POSTs JSON to an OpenAI-compatible endpoint (/v1/chat/completions) with the messages, max_tokens, temperature and stream: true. The API server validates it and applies the chat template.

TTFT = 165 ms (network + tokenize + queue + prefill)TPOT = 30 ms per tokent = 0 ms

Timings are illustrative, chosen to show the shape of a request, not measured.

fig. 0.2One request, start to finish. Press Play, or Step through each stage and each decoded token. Watch the KV cache fill in during prefill and then grow by one slot per decode step.

1. The request arrives

Almost every inference server speaks the OpenAI-compatible API. A chat request is plain JSON:

POST /v1/chat/completions
{
"model": "Qwen/Qwen2.5-0.5B-Instruct",
"messages": [{ "role": "user", "content": "Explain the KV cache in one sentence." }],
"max_tokens": 64,
"temperature": 0,
"stream": true
}

The API server validates it and applies the model’s chat template, which wraps the messages in the special tokens the model was trained with. It then hands the request to the engine.

2. Tokenize

Models don’t read characters. They read token IDs, integers that index into a vocabulary of roughly 32K to 200K entries. A tokenizer (usually BPE) splits text into sub-word pieces:

"Explain the KV cache" → ["Explain", " the", " KV", " cache"] → [ ... four integers ... ]

The rule of thumb for English is about 0.75 words per token. Tokenization runs on the CPU and is cheap, but every cost in this curriculum is counted in tokens, so it pays to know your prompt’s real length.

3. Wait in the scheduler

The engine runs a scheduler loop. On every step it decides which requests run. A new request is admitted only if there is room in the batch and enough free KV-cache memory to hold its prompt. When the server is busy, requests wait in a queue.

4. Prefill: read the whole prompt at once

All prompt tokens go through the model in one forward pass, in parallel. At every layer, the keys and values of every prompt token are written into the KV cache (1.5 explains why). The logits at the last position are sampled to produce the first output token.

Prefill does many FLOPs per byte loaded: one weight read is reused across all N prompt tokens. So it is compute-bound, and its time grows roughly linearly with prompt length (quadratically for attention on very long prompts).

5. Decode: one token per step

Now the loop begins. Each decode step:

  1. Feeds in only the newest token.
  2. Computes that token’s Q, K, V at every layer, and appends the new K and V to the cache.
  3. Attends over all cached keys and values, the prompt plus everything generated so far.
  4. Samples the next token from the logits (1.4).

Each step reads every weight and the whole KV cache to produce a single token. That makes decode memory-bound, as you saw in 0.1. A step takes about the same time whether the prompt was 10 tokens or 1,000, though a growing KV cache slowly adds to it.

6. Stream and finish

Every new token ID is detokenized back into text and sent immediately as a server-sent event (data: {...} lines over HTTP). That is why you see words appear one by one. When the model emits its end-of-sequence token, or hits max_tokens, the request finishes and its KV-cache memory is freed for the next request in the queue.

Putting numbers on it

The latency a user feels splits into two parts:

end-to-end latency  =  TTFT⏟queue + prefill  +  (nout−1)×TPOT⏟one decode step\text{end-to-end latency} \;=\; \underbrace{\text{TTFT}}_{\text{queue + prefill}} \;+\; (n_{\text{out}} - 1) \times \underbrace{\text{TPOT}}_{\text{one decode step}}
Set byGrows withBound by
TTFTqueue + prefillprompt length, server loadcompute (prefill), scheduling
TPOTdecode step timebatch size, context lengthmemory bandwidth

Lab: time a real request 🟡

measure_ttft.py streams one request from any OpenAI-compatible server and reports TTFT and TPOT. It uses only the Python standard library. You don’t need a GPU: Ollama or llama.cpp will run a 0.5B model on a laptop CPU.

labs/m00/0.2/measure_ttft.py (core loop)
t0 = time.perf_counter()
stamps = []
for piece in stream_chat(base, model, prompt, max_tokens): # parses "data: {...}" SSE lines
stamps.append(time.perf_counter())
ttft = (stamps[0] - t0) * 1000
gaps = [(b - a) * 1000 for a, b in zip(stamps, stamps[1:])]
tpot = sum(gaps) / len(gaps)
Terminal window
# CPU: Ollama with a tiny model
ollama pull qwen2.5:0.5b
python labs/m00/0.2/measure_ttft.py --base http://localhost:11434 --model qwen2.5:0.5b
# GPU: vLLM
vllm serve Qwen/Qwen2.5-0.5B-Instruct
python labs/m00/0.2/measure_ttft.py --base http://localhost:8000 --model Qwen/Qwen2.5-0.5B-Instruct

Sources

Check your understanding

0 / 4 answered
  1. 1.You double the prompt length but keep max_tokens fixed. What changes most?

  2. 2.What does a single decode step add to the KV cache, per layer?

  3. 3.A server has TTFT = 200 ms and TPOT = 25 ms. Roughly how long until a 101-token answer is complete?

  4. 4.Your single-request benchmark shows a 90 ms TTFT, but users report about 1.5 s at peak hours. What is the most likely culprit?