AI Fundamentals
How LLM Inference Works
What happens between sending a prompt and receiving the answer: prefill, decode, the KV cache, and prompt caching, measured on a local model, and what they mean for latency, memory, and cost.
On this page · 9 sections
Here are two requests to the same model, on the same laptop, a few seconds apart. Both send the same document, about 2,100 tokens long, followed by a short question:
request time to first token
document, question 1 2,770 ms
same document, question 2 45 ms
Same model, same document, almost the same prompt length. The second answer started about sixty times sooner.
Nothing about the model changed between the two requests. What changed is that the server had already read the document once, and kept its notes. To understand why that matters, and why long prompts are slow, long answers are slower, and context windows cost memory, you need a picture of what actually happens after you send a prompt.
So far, this series has treated the model as a function: text goes in, text comes out. This article opens the box just far enough to make engineering decisions about latency, memory, and cost.
Try to Understand It This Way
Imagine a consultant who answers questions about documents.
You hand them a 30-page brief and a question. First they read the brief. Reading is fast: their eyes take in whole lines at once, and they take notes as they go, so they never need to reread a page.
Then they write the answer, one word at a time. Writing is slow in a different way: before each word, they glance back over all their notes, choose the word, write it, and only then start on the next one. No amount of skill lets them write word ten before word nine.
Hand them the same brief again with a new question, and they skip the reading entirely: the notes are still on the desk. Hand them the question first and the brief after it, and the notes don’t line up anymore, so they read everything again.
That’s inference. Reading the brief is prefill. Writing the answer is decode. The notes are the KV cache. And keeping notes from one question to the next is prompt caching.
What Happens to a Request
“What Is an LLM and How Does It Actually Work? (opens in a new tab)” described a model as something that predicts the next token. Inference is the machinery that runs that prediction, over and over, until the answer is complete:
your prompt
│
▼
tokenize text → token ids
│
▼
load the model only if it isn't already in memory ("cold start")
│
▼
PREFILL process every prompt token, in parallel;
│ store a key and a value for each token in each layer (the KV cache)
▼
DECODE ◄───┐ compute the next token's probabilities from the weights and the KV cache,
│ │ pick one (the sampler), add its keys and values to the cache
└────────┘ repeat, one token per step
│
▼
stop an end token, a stop sequence, or the token limit
Two phases do almost all the work, and they behave very differently.
Prefill processes the prompt’s tokens in parallel within each layer of the model. All of them are known up front, so the hardware can process them together, as large batches of matrix multiplication. (Real serving systems may split a long prefill into chunks or schedule it alongside other work, but the tokens within a chunk are still processed together.) That’s the kind of work GPUs are built for.
Decode can’t do that. In ordinary autoregressive decoding, each next token depends on the one before it, so the model runs once per output token. And every run reads the model’s weights from memory, plus the growing KV cache. For a small number of users, decode is limited mostly by how fast memory can be read, not by how fast the chip can calculate.
The KV cache is what makes decode affordable at all. Attention, the mechanism that lets each token look back at earlier ones, needs a key and a value vector for every earlier token, in every layer. Without the cache, the model would recompute those for the whole conversation at every step. With it, each step only computes the new token’s keys and values and appends them.
The Experiment
The companion demo measures each of these pieces with Ollama on an Apple M4 Pro, mainly with llama3.2:3b. Ollama reports its own timings in every response: how long it spent on prefill, how long on decode, how many prompt tokens it reused from cache, and how long loading took. The demo adds one measurement of its own, the time until the first piece of text arrives, and repeats every setting three times.
Implementation note: the exact setup
Runtime: Ollama 0.40.16, /api/generate with streaming
Hardware: Apple M4 Pro, 24 GB unified memory; on battery, Low Power Mode off
Models: llama3.2:3b (a80c4f17acd5, Q4_K_M, 2.02 GB)
llama3.2:1b (baf6a787fdff, Q8_0, 1.32 GB)
Settings: temperature 0; Ollama's default 4,096-token context and f16 KV cache
Runs: each setting 3 times, medians reported
Controls: for the prefill, decode, and model-size measurements, each request
starts with a unique line, so earlier prompt content can't be
reused (the short chat-template header still can be); the
prompt-caching test deliberately repeats prefixes
Date: 2026-11-12
Timings are not repeatable to the digit. The numbers below come from the Python run. The JavaScript version, run straight after it, produced the same token counts and KV cache sizes, and timings within about 15%.
Prefill: the prompt sets the wait for the first token
The first test keeps the answer at 32 tokens and grows the prompt:
llama3.2:3b, 32-token answer
input tokens time to first token prefill speed
256 0.30 s 800 tok/s
466 0.53 s 851 tok/s
886 1.01 s 869 tok/s
1,726 2.07 s 831 tok/s
2,668 3.40 s 783 tok/s
Time to first token grows almost exactly in proportion to the prompt: about 1.3 milliseconds per input token on this machine, because prefill speed barely changes with length. The user waits for the whole prompt to be read before they see anything.
Decode: the answer sets the total time
The second test keeps the prompt short and grows the answer:
llama3.2:3b, short prompt
output tokens time to first token total time
16 83 ms 0.24 s
64 50 ms 0.77 s
256 54 ms 2.95 s
The first token arrives in well under a tenth of a second, because there’s almost nothing to read. Then every output token costs about 11 milliseconds, one after another: decode ran at roughly 84 to 99 tokens per second in these tests, a little lower with the longest prompt.
Put the two tests side by side: this model reads a prompt about nine to ten times faster per token than it writes an answer. A 2,000-token prompt with a 300-token answer works out at roughly 2.4 seconds of reading and 3.3 seconds of writing, on this machine. Both halves matter, and they respond to different fixes.
The KV cache: memory you can predict
The size of the KV cache follows directly from the model’s shape. Every token stores one key and one value vector, per KV head, per layer:
bytes per token = layers × KV heads × (key size + value size) × bytes per value
llama3.2:3b: 28 × 8 × (128 + 128) × 2 bytes = 114,688 bytes (112 KiB per token)
At Ollama’s default context of 4,096 tokens, that predicts 448 MiB. Ollama’s server log shows what it actually allocated:
llama_kv_cache: size = 448.00 MiB ( 4096 cells, 28 layers, 1/1 seqs), K (f16): 224.00 MiB, V (f16): 224.00 MiB
The prediction matched exactly at 4,096 and at 8,192 tokens (896 MiB), and for llama3.2:1b (32 KiB per token, 128 MiB at 4,096).
Now extend the same arithmetic. llama3.2:3b supports a context of 131,072 tokens. Filling it would take 112 KiB × 131,072 = 14 GiB of KV cache for one fully populated request, before the 2 GB of weights and the runtime’s other memory. And that’s per request being served at once. This is why the context window you allow is a memory decision, not just a prompt decision. “Tokens, Context Windows, and Why They Matter (opens in a new tab)” warned about the hidden cost of “just send everything” in latency and price; the server pays it in memory too.
Prompt caching: reuse the reading, if the prefix matches
The opening table came from this test. The same document, about 2,100 tokens, is sent four times with the question in different places:
llama3.2:3b input tokens reused computed time to first token
1. document, question 1 2,141 20 2,121 2,770 ms
2. same document, question 2 2,140 2,125 15 45 ms
3. question 2, then the document 2,140 20 2,120 2,743 ms
4. document, question 1 again 2,141 2,125 16 88 ms
Request 2 starts with exactly the same tokens as request 1: the whole document. The server reused the keys and values it had already computed for them and only processed the 15 new tokens. Request 3 contains the same words, but the question comes first, so from the very first word after the chat header, the tokens differ. Nothing after the first difference can be reused, so the whole document was read again.
The basic rule of prefix caching is simple: only an unchanged prefix can be reused. Once the tokens differ, nothing after that point can be reused as part of the same prefix. OpenAI’s guide puts it this way: “Cache reuse requires the entire rendered prefix to match,” and it recommends you “Put stable developer instructions and shared reference material first.” The exact cache boundaries, the minimum prompt length, how long entries are kept, and how requests are routed to them depend on the serving system.
Prompt caching takes the KV cache from the previous section one step further. The KV cache holds the keys and values of the current request, so decode doesn’t recompute them. A prompt cache keeps that state for a reusable prefix after the request ends, and restores it when a later request starts with the same prefix. OpenAI’s guide confirms what is kept: “The prompt cache stores key-value (KV) tensors, not the tokens themselves.” The data is the same kind of KV state; what changes is how long the server keeps it, and when it can reuse it.
Request 4 shows a detail of this particular server: it still had the document’s prefix after a different request in between. How many prefixes a server keeps, and for how long, depends on the implementation. Anthropic’s cache, for example, has a “5-minute lifetime” by default, refreshed each time it’s used.
Hosted providers turn this into price. Anthropic’s pricing note says “Cache read tokens are 0.1 times the base input tokens price” (with per-model exceptions), while writing to the cache costs 1.25 times the base price for the default 5-minute lifetime. OpenAI describes reused tokens as “discounted up to 95%.” Prompt caching is one of the rare optimizations that cuts latency and cost at the same time, as long as the prompt is structured for it.
Model size: why smaller models write faster
The last test compares two model sizes:
model weights generation speed idealized weight-read ceiling
llama3.2:1b 1.32 GB 145.5 tok/s 207 tok/s (70%)
llama3.2:3b 2.02 GB 86.7 tok/s 135 tok/s (64%)
The ceiling is simple arithmetic: if generating each token means reading all the weights from memory once, at the full memory bandwidth, then tokens per second can’t exceed bandwidth divided by the size of the weights. Apple’s specification gives the M4 Pro “273GB/s of memory bandwidth”; divide by 2.02 GB and you get about 135 tokens per second for the 3B model. It’s an idealized single-request ceiling, not a prediction: real generation also reads the KV cache, never gets the full theoretical bandwidth, and has runtime overhead. Across three runs, both models reached 64% to 79% of their ceilings, and the smaller model was 1.6 to 1.7 times faster: a little more than the 1.5 ratio of their sizes.
That’s the practical meaning of “decode is memory-bound”: generation speed is mostly a question of how many bytes have to move for each token. Smaller models, and more aggressively quantized ones, move fewer bytes.
The first request after a model is unloaded pays one more cost: loading the weights. Across runs, that took between 0.5 and 1.5 seconds for llama3.2:3b, depending on whether the file was already in the operating system’s cache. A user who arrives after an idle period waits for it.
Local Is Not the Whole Picture
Everything above was measured with one user on one laptop. Hosted inference changes some of the trade-offs:
- Batching. A server handling many users at once can combine their decode steps, so one read of the weights serves many requests. That raises total throughput, and it’s why hosted decode speed doesn’t follow the single-user bandwidth bound above.
- KV cache memory becomes the constraint. With many requests in flight, the KV caches, not the weights, fill the memory. The vLLM paper describes this cache as “huge and grows and shrinks dynamically”. Using PagedAttention to manage KV cache memory more efficiently, and to share it where possible, it reports 2–4× higher throughput at the same latency than the serving systems it compared against.
- Memory runs out before the model does. Imagine a server with enough memory for the weights and the KV caches of ten long-context requests. A sudden rise in concurrent requests exhausts the memory reserved for KV caches, even though the model itself still fits. The server then has to queue, reject, or otherwise manage requests rather than simply generate more tokens. Context length and concurrency have to be planned together.
- Prefill and decode compete. A long prompt arriving on a busy server takes compute that would otherwise produce tokens for other users. Providers schedule around this, and how they do it affects both your time to first token and everyone else’s generation speed.
The mechanics don’t change: prefill, decode, KV cache, prefix reuse. The numbers do, and so does who pays for which inefficiency.
Engineering Decisions Before Production
1. Measure time to first token and total time separately
They have different causes. On the model server, time to first token is affected by queueing, loading, and prefill, which grows with the prompt. What the user experiences also includes everything your application does first, such as retrieval, tool calls, and network time, so a slow first token isn’t always a model problem. After the first token, generation time is driven mainly by answer length and decode speed. Track both, as percentiles, not averages. And stream the response: with a short prompt in the tests above, the first text arrived after about 50 to 85 ms, while the full 256-token answer took nearly 3 seconds.
2. Treat every prompt token as a recurring cost
A prompt is read in full on every request, unless it’s cached. A 3,000-token system prompt and retrieval context sent with every question costs prefill time and input-token charges every time. Trim what doesn’t help, retrieve fewer and better chunks, and measure what each addition is worth.
3. Structure prompts for caching
Order the prompt from most stable to least stable: tools and system instructions, then reference documents, then the conversation, then the new question. Anything that changes per request (a timestamp, a user name, a request id) belongs at the end. Put a changing timestamp at the beginning of the prefix you want cached, and you prevent reuse of everything after it. A shorter prefix before the timestamp may still be reusable, if the serving system supports a cache boundary there.
4. Budget the answer, not just the prompt
Output tokens are the slow part, one at a time. Ask for concise answers when that’s what users need, set a token limit (as “Temperature, Top-P, and Other LLM Parameters Explained (opens in a new tab)” showed, and handle the truncation it can cause), and prefer compact structured outputs over verbose prose when code is the consumer.
5. Size the context window as a memory decision
If you serve models yourself, plan memory for the weights plus the KV cache for every request you serve at once, at the context length you allow. Allowing the maximum context “just in case” can cost several times the memory of the weights, and fewer concurrent users per machine.
6. Choose model size by the latency you need
A smaller model generates faster on the same hardware, and if its quality is enough for the task, that’s a real latency win. For latency-sensitive features, keep models loaded rather than paying a cold start after every idle period.
7. Measure on your own setup
Every number in this article belongs to one laptop on battery. Hardware, runtime, quantization, batch size, and the provider’s load all change them. Measure the shapes on the system you’ll actually run.
What to Take Away
- Inference has two phases. Prefill reads the whole prompt in parallel; decode writes the answer one token at a time.
- The prompt sets the wait; the answer sets the total. Time to first token grew with the prompt, about 1.3 ms per token here. Total time grew with the answer, about 11 ms per token.
- The KV cache is predictable memory. 112 KiB per token for this model, exactly as the arithmetic said, and it grows with every token of context you allow.
- Prompt caching reuses an exact prefix. The same document with a new question started 60 times sooner. The same words in a different order got no benefit.
- Decode speed is mostly about bytes moved. A model with 1.5 times smaller weights generated 1.6 to 1.7 times faster.
Think About These Use Cases
-
A RAG chatbot feels slow: Users wait four seconds for the first word. Which measurements would tell you whether to fix retrieval size, the prompt, the model, or the infrastructure?
-
A long system prompt: Your system prompt is 2,500 tokens and starts with the current date and the user’s name. What would you change, and what would you expect to see in time to first token?
-
Self-hosting: You want to serve a 7B model with a 32K context to 20 concurrent users on one GPU. How would you estimate whether the memory fits?
-
Choosing a model: A smaller model is 5% less accurate on your test suite but generates twice as fast. How do you decide?
-
Batch jobs versus chat: You summarize 100,000 documents overnight, and you also run a live chat feature. Which inference properties matter for each?
If you want to talk one of these through, take it to GPT along with this article. Ask GPT ↗️
Related Sources
- llm-inference: The companion demo for this article, in Python and JavaScript: KV cache prediction versus allocation, prefill and decode timing, prompt caching, and model size versus generation speed, on local Ollama models.
- Ollama API: Generate: The timing fields every measurement here comes from, including the count of prompt tokens read from the cache. The model shapes used in the KV cache arithmetic come from Ollama’s model metadata (
/api/show), which the demo prints. - OpenAI: Prompt caching: How prefix reuse works, what is stored, and how to structure prompts for it.
- Anthropic: Prompt caching: Cache breakpoints, lifetimes, and pricing for cache writes and reads.
- Kwon et al.: Efficient Memory Management for Large Language Model Serving with PagedAttention (2023): Why KV cache memory limits how many requests a server can handle, and how vLLM manages it.
- Apple: M4 Pro and M4 Max: The memory bandwidth figure used for the upper bound.
What’s Next?
This article closes the first phase of the series: what a model is, how it represents text, how to instruct it, constrain it, connect it to tools, catch its mistakes, and run it.
The next phase is about building. In the next article, we’ll look at Building Your First LLM-Powered Application: how the pieces from these ten articles fit together into one small application, from the first request to something you’d be comfortable putting in front of users.