Article
AI engineering · Fundamentals
Before the First Token: What an LLM Does With Your Prompt
Send a prompt again with a new last line and the model reads it in 0.3 seconds instead of 19. Change the start and the gain is gone. The machinery behind that, with the math, the code and measurements you can repeat.
Start readingI sent a prompt of about 1,000 tokens to a small model on my laptop. Reading it took 18.89 seconds. I sent the same prompt again with a different last line, and that took 0.29 seconds. Then I changed one number in the first few tokens, and it took 18.81 seconds. Those are medians across repeated runs, and how I took them is in section 4.
Nothing about the model changed between those runs. What changed is how much work the server could skip. One LLM request is really two workloads, prefill and decode, with a growing cache between them. Most of what you see in latency and in prompt caching rules follows from those three things.
These are one small model’s numbers on one laptop CPU, as of November 2026. Your numbers will differ. The shapes are the point, and the full script is at the end so you can check them.
1. The expensive way to generate text
A language model does one thing: given a sequence of tokens, it produces a probability for every possible next token. To generate text, you pick a token, append it, and run the model again.
Done naively, each run processes the whole sequence again from the start. The thousandth token repeats the work of the first 999, and since attention compares tokens with the ones before them, one step’s attention costs about n² for n tokens. With a cache, a step handles one new token and reads n stored entries, which one recent study describes as going “from quadratic to linear”. Each step still costs more as n grows, which matters in section 4. To see why that cache can exist at all, you need one formula.
2. Attention, as far as the cost needs it
Attention is the operation that lets a token use the tokens around it. The original Transformer paper describes it this way: “An attention function can be described as mapping a query and a set of key-value pairs to an output.” Each token gets three vectors. Its query asks what it is looking for, its key says what it offers, and its value is what it passes on:
Attention(Q, K, V) = softmax(Q Kᵀ / √d_k) V
In a language model a token may look only at positions before it. The paper’s wording is that a prediction “can depend only on the known outputs at positions less than” its own. So when a new token arrives, the keys and values of the earlier tokens do not change. They can be stored, and only the new token needs computing. This sketch shows one attention head with the rest of the model left out:
def attend(q, k, v):
return softmax(q @ k.T / sqrt(k.shape[-1])) @ v
# Without a cache: compute keys and values for all tokens, at every step.
out = attend(query(x[-1:]), key(x), value(x))
# With a cache: compute them for the new token only, and append.
past_k = concat([past_k, key(x[-1:])])
past_v = concat([past_v, value(x[-1:])])
out = attend(query(x[-1:]), past_k, past_v)
The two branches give the same answer. I checked the cached version against the full masked computation on random data, and they match.
3. The KV cache, and what it costs in memory
That store of keys and values is the KV cache. Its size follows directly from the model’s config, and every layer holds its own copy:
bytes = 2 × layers × KV heads × head dimension × bytes per value × tokens
The 2 is one key and one value. For the model I measured, that is 112 KB per token, assuming 16-bit values, or 896 MB at 8,192 tokens. PagedAttention, the paper behind the vLLM server, works the same sum for the 13B OPT model: 800 KB per token and up to 1.6 GB for one 2,048-token request.
The cache grows with every token, and an edit discards what follows it
2 × 28 layers × 8 heads × 128 × 2 bytes = 112 KB per token
224 MB for this one request
Edit after 512 tokens. Those 56 MB can be kept. The other 1,536 tokens are recomputed.
Config source: the model file I measured, read with ollama show
| Model | The sum | 256 tokens | 8,192 tokens | Config source |
|---|---|---|---|---|
| Llama 3.2, 3B | 2 × 28 layers × 8 heads × 128 × 2 bytes = 112 KB per token | 28 MB | 896 MB | the model file I measured, read with ollama show |
| OPT 6.7B | 2 × 32 layers × 32 heads × 128 × 2 bytes = 512 KB per token | 128 MB | 4.0 GB | the facebook/opt-6.7b config |
| OPT 13B | 2 × 40 layers × 40 heads × 128 × 2 bytes = 800 KB per token | 200 MB | 6.3 GB | the facebook/opt-13b config |
An edit keeps the tokens before it. It and every token after it are recomputed.
This is why serving is often limited by memory and not only by compute. The cache “grows and shrinks dynamically”, every request in a batch needs its own, and in the systems PagedAttention measured, “only 20.4% - 38.2% of the KV cache memory is used to store the actual token states”. The rest was lost to fragmentation, which meant fewer requests fit in a batch.
4. Prefill and decode, measured
The cache also splits a request into two phases that behave very differently. Sarathi-Serve, a paper on serving LLMs on GPUs, puts it precisely: “The prefill phase is compute-bound because it processes all tokens of an input prompt in parallel”, and “the decode phase is memory-bound because it processes only one token per-request at a time.”
| Prefill | Decode | |
|---|---|---|
| What it does | Reads the whole prompt and fills the cache | Makes one token, reads the cache, adds one entry |
| Tokens per step | Many, in parallel | One per request |
| Limited by (on GPUs, per Sarathi-Serve) | Compute | Memory |
| What you see | Time to first token | Time per output token |
One request, from text to the last token
Step 1
Tokenise
Server
The text becomes token IDs. The new request's cache is empty.
Step 2
Look for a stored prefix
Server
If the server still holds the state for the start of this prompt, it can reuse it and skip those tokens.
Step 3
Prefill the rest
ModelPrefillOn GPUs, limited by: compute
The remaining prompt tokens run through the model. The cache now holds keys and values for the whole prompt.
Step 4
Pick the first token
ModelPrefillOn GPUs, limited by: compute
The output at the last position gives the next-token probabilities. Time to first token ends here.
Step 5
Decode, one token at a time
ModelDecodeOn GPUs, limited by: memory
The new token computes its own keys and values, reads every entry in the cache, and appends. Repeat until the model stops.
I measured both phases at growing context, using Llama 3.2 (3B, quantized) on a laptop CPU. Both get slower per token as context grows. Prefill goes from 14.57 ms per token over the first 280 or so tokens to 26.79 ms for the burst ending at about 4,440, or 1.84 times. Decode goes from 93.10 ms to 227.25 ms over the same range, or 2.44 times. Generating a token took about 6 times as long as reading one at short context and about 8.5 times at the deep end.
In my test, every extra token of context made the next token slower
DecodePrefill
Milliseconds per token
Tokens in context, about
Tokens in context, about 4,442: Decode 227.25 ms, Prefill 26.79 ms.
| Tokens in context, about | Decode (ms) | Prefill (ms) | Decode range | Prefill range |
|---|---|---|---|---|
| 282 | 93.10 | 14.57 | 92.41 to 94.12 | 14.34 to 14.83 |
| 544 | 98.59 | 16.64 | 89.56 to 98.86 | 16.41 to 17.16 |
| 827 | 106.38 | 17.16 | 105.08 to 107.81 | 17.03 to 17.50 |
| 1,096 | 114.35 | 18.36 | 113.97 to 114.47 | 18.03 to 18.89 |
| 1,374 | 122.29 | 18.80 | 122.04 to 123.46 | 18.52 to 19.13 |
| 1,645 | 129.89 | 19.85 | 129.55 to 132.07 | 19.30 to 19.95 |
| 1,916 | 137.17 | 20.02 | 136.15 to 142.83 | 19.96 to 20.88 |
| 2,183 | 144.03 | 21.18 | 142.28 to 150.02 | 20.53 to 21.49 |
| 2,564 | 155.79 | 22.24 | 150.33 to 162.99 | 21.78 to 23.06 |
| 2,867 | 160.93 | 22.62 | 147.17 to 162.89 | 21.67 to 23.20 |
| 3,165 | 171.82 | 23.32 | 167.90 to 176.14 | 22.68 to 23.95 |
| 3,466 | 182.94 | 24.41 | 177.70 to 193.31 | 23.88 to 25.48 |
| 3,717 | 194.27 | 24.92 | 187.56 to 198.67 | 23.55 to 25.39 |
| 3,954 | 200.26 | 25.65 | 192.13 to 207.34 | 24.30 to 26.10 |
| 4,204 | 216.52 | 25.88 | 210.06 to 236.16 | 24.81 to 27.15 |
| 4,442 | 227.25 | 26.79 | 211.07 to 244.32 | 25.53 to 29.13 |
If each token costs more than the one before, total time grows faster than prompt length. In my test, long context was not just more tokens at a fixed cost. Hosted systems may differ, and what you pay on an API is set by its price list, not by this curve.
I can’t tell you why from this data. The obvious suspect is attention, whose cost “grows quadratically with sequence length”. But the same Sarathi-Serve paper found that “linear operators still contribute more than 80% to the total time even at high sequence lengths”, on its GPU setups. Decode’s rise fits its statement that “attention cost depends on the accumulated context length”, but I did not isolate the cause in my test, and memory effects may contribute too.
5. Why an edit near the start is so expensive
Now the opening numbers make sense. Each token’s stored state was computed by looking at everything before it. Keep the start of a prompt identical and all of that state is still correct. Change an early token, and everything after it was computed from something that is no longer there. That is why a changed last line cost 0.29 seconds and a changed number at the start cost 18.81.
Hosted APIs state the same rule, though not this reason, which is my explanation. Anthropic’s docs say “Cache hits require 100 percent identical prompt segments”, and OpenAI’s say “Cache reuse requires the entire rendered prefix to match”. Both also charge for it separately. As of November 2026, Anthropic charges 1.25 times the base input price to write to its default 5-minute cache and 0.1 times to read, with lower read rates on some models. OpenAI discounts cached input by “up to 95%” and, on GPT-5.6 and later, charges 1.25 times to write.
Don’t assume more than that about what happens on their servers. OpenAI’s docs warn that the cache lifetime “does not guarantee that every request reuses stored KV tensors or has lower latency”. A cache hit is a billing fact first.
The practical rule is short: put what stays the same first and what changes last. A timestamp or a request ID at the top of a system prompt can lose you the whole cache, on every call.
6. What changes with many users
On a shared server these two phases collide. Older systems batched whole requests, so “requests that have finished earlier than other requests in a batch cannot return to the client”, and new arrivals had to wait for the batch to finish. Orca fixed that in 2022 by scheduling one model iteration at a time, so requests can join and leave between steps.
That creates a new problem. If a long prefill runs between decode steps, everyone already generating has to wait for it. Sarathi-Serve reports that such a stall in vLLM “can last over several seconds”. Its fix is to split a prefill into chunks and run them alongside the ongoing decodes, and it reports “almost negligible overhead” with a token budget of 2048.
If this sounds familiar, it is the trade-off from Scalable Is Not Fast: throughput and latency meet in a queue. Prefill and decode are what is in that queue, and a long prompt is the large job that holds up the small ones.
7. What to do with this
If you call an API:
- Order prompts for cache hits: tools and system text first, changing content last.
- Track time to first token and time per output token separately. They have different causes.
- Measure what long context does on your provider. On my laptop it cost more per token in both phases, and hosted systems may differ.
If you serve models:
- Estimate KV cache memory from the config before you choose a batch size.
- Measure prefill and decode separately, and watch what long prefills do to decode latency.
To run it yourself, here is the script as one file. It needs Ollama, ollama pull llama3.2, and any long English text file. It takes a while, because it waits for the CPU to cool before every call. The thermal checks rely on a macOS reading I have only tested on an Intel Mac. Where that reading is missing they switch off, so watch for throttling yourself and expect more noise.
"""Time prefill and decode at growing context depth, in short bursts, through a local Ollama server.
Usage: python3 measure_kv.py some-long-english-text.txt
Needs: Ollama running, and `ollama pull llama3.2`. Standard library only.
"""
import json
import random
import re
import statistics
import subprocess
import sys
import threading
import time
import urllib.request
MODEL = "llama3.2"
URL = "http://127.0.0.1:11434/api/generate"
OPTIONS = {"num_predict": 32, "temperature": 0, "seed": 1, "num_ctx": 8192, "num_thread": 4}
REPEATS, STEPS, WORDS_PER_STEP = 5, 16, 192 # each step adds about 250 tokens
COOL_LIMIT, MIN_LIMIT = 90, 40 # start a call at this CPU speed limit; drop it if it falls below this
def speed_limit():
"""The CPU speed limit on macOS, from 0 to 100. None elsewhere, which turns the thermal checks off."""
try:
out = subprocess.run(["pmset", "-g", "therm"], capture_output=True, text=True).stdout
except OSError:
return None
found = re.search(r"CPU_Speed_Limit\s*=\s*(\d+)", out)
return int(found.group(1)) if found else None
def generate(prompt):
started = time.time()
while (limit := speed_limit()) is not None and limit < COOL_LIMIT and time.time() - started < 300:
time.sleep(5)
samples, done = [limit] if limit is not None else [], threading.Event()
def sample():
while not done.wait(5):
if (value := speed_limit()) is not None:
samples.append(value)
threading.Thread(target=sample, daemon=True).start()
body = {"model": MODEL, "prompt": prompt, "stream": False, "keep_alive": "30m", "options": OPTIONS}
request = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
with urllib.request.urlopen(request, timeout=1800) as response:
reply = json.load(response)
done.set()
return {
"tokens": reply["prompt_eval_count"],
"prefill_s": reply["prompt_eval_duration"] / 1e9,
"decode_ms": reply["eval_duration"] / 1e6 / max(reply["eval_count"], 1),
"cool": not samples or min(samples) >= MIN_LIMIT,
}
def main(path):
corpus = open(path).read().split()
rng = random.Random()
session = int(time.time()) # a server can keep old prompts, so never send the same text in two runs
excerpt = lambda n: [corpus[(start + i) % len(corpus)] for start in [rng.randrange(len(corpus))] for i in range(n)]
generate("warm up")
# Grow one prompt. The server keeps the prefix, so each call evaluates only the new step.
results = {}
for repeat in range(REPEATS):
text, previous = excerpt(WORDS_PER_STEP * STEPS), 0
for step in range(1, STEPS + 1):
run = generate(f"Run {session}-{1000 + repeat}. " + " ".join(text[: WORDS_PER_STEP * step]))
new_tokens, previous = run["tokens"] - previous, run["tokens"]
if run["cool"]:
results.setdefault(step, []).append((run["tokens"], 1000 * run["prefill_s"] / new_tokens, run["decode_ms"]))
print("depth prefill ms/token decode ms/token runs kept")
for step, rows in sorted(results.items()):
depth, prefill, decode = (statistics.median(column) for column in zip(*rows))
print(f"{depth:5.0f} {prefill:16.2f} {decode:15.2f} {len(rows):9d}")
# The same prefix three times: first send, a changed last line, a change near the start.
print("\n first s repeat s early edit s")
for repeat in range(REPEATS):
base = " ".join(excerpt(770)) # about 1,000 tokens
first = generate(f"Run {session}-{2000 + repeat}. {base}\nName one topic above.")
again = generate(f"Run {session}-{2000 + repeat}. {base}\nName one person above.")
edited = generate(f"Run {session}-{3000 + repeat}. {base}\nName one topic above.")
print(" ".join(f"{run['prefill_s']:12.2f}" if run["cool"] else f"{'hot':>12}" for run in (first, again, edited)))
if __name__ == "__main__":
main(sys.argv[1])
This single file combines the two scripts behind the numbers above, using the same settings. My published numbers came from the two-file version.
Sources
- Attention Is All You Need, Vaswani et al., 2017
- Efficient Memory Management for Large Language Model Serving with PagedAttention, Kwon et al., SOSP 2023
- Orca: A Distributed Serving System for Transformer-Based Generative Models, Yu et al., OSDI 2022
- Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve, Agrawal et al., OSDI 2024
- Comparative Characterization of KV Cache Management Strategies for LLM Inference, Mamo et al., 2026
- Prompt caching, Anthropic docs, read 3 November 2026
- Prompt caching, OpenAI docs, read 3 November 2026