Skip to content

LLM inference optimization: prefill, decode, KV cache and the techniques that speed up answers

What happens between Enter and the first word: prefill and decode, KV cache, quantization, PagedAttention, continuous batching, prefix caching and speculative decoding, with analogies and numbers.

Ramon Gomes 18 min read Level: Intermediate

Also available in: Español, Français, Português

When someone says "the model is slow" or "the GPU bill blew up", the problem is almost never the model itself. It's how the model is being served. The same model, on the same GPU, can serve one user at a time or dozens at once, depending on how memory and requests are organized.

This article explains, from scratch, what happens between you hitting Enter and the first word showing up on screen, where the bottleneck is, and what each well-known technique does. No formulas too early: first the analogy, then the mechanism, then the numbers.

An Analogy to Start

Picture a restaurant kitchen.

  • The cook reads the whole order before starting: appetizer, main course, allergies, how the steak should be done. He reads it all at once, fast, because he can see the whole ticket. That's prefill.
  • Then he builds the plate one item at a time, and each item depends on the one before. You can't add the sauce before the meat. That's decode: one token at a time, each one looking at all the previous ones.
  • So he doesn't have to reread the ticket for every item, he leaves notes on the counter: what's done, what's left. Those notes take up space. With many tables at once, the counter fills up. That's the KV cache.

Almost every inference optimization is one of these ideas: a shorter ticket, a better organized counter, more plates going out together, or a helper running ahead so the chef only has to check.

Busy professional kitchen, a cook seen from behind assembling several plates lined up on a stainless steel counter, order tickets clipped to a rail above, pots on the stove in the background
A kitchen doesn't get faster with a more talented cook. It gets faster with an organized counter and several plates going out at the same time.

What Happens When You Send a Prompt

A language modelAI model trained on large amounts of text to predict the next word, which lets it chat, summarize, translate and write code. generates text one token at a time (if the term is new to you, the article on what tokens are explains it). To generate the next one, it has to consider all the previous tokens. That creates two phases that behave very differently.

Two-panel infographic with GPU cards: in prefill, the seven prompt tokens appear together and the compute meter is high; in decode, five tokens form a sequence and the memory-read meter is high, with little compute.
In prefill the GPU computes a lot at once. In decode it spends most of its time reading memory.
Phase What it does Bound by Metric it affects
Prefill Processes all prompt tokens in parallel Compute (the GPU stays busy) Time to first token
Decode Generates one token at a time, in sequence Memory (reading weights and KV cache for every token) Time between tokens

Databricks' inference engineering post sums it up: generating the first token is usually compute-bound, and the decoding that follows is memory-bound. The practical consequence is big: during decode, the GPU spends a good part of its time waiting for data to arrive from memory, not computing. That's why so many optimizations target memory.

The Metrics That Matter

Before optimizing, you need to know what to measure. There are four numbers:

  • TTFT (time to first token): how long until the first word shows up. It's what the user feels as "slow to start".
  • TPOT or ITL (time per output token): the gap between one token and the next. It sets the "typing speed". Databricks gives a reference: 100 ms per token is 10 tokens per second, faster than most people read.
  • Total latency: TTFT plus TPOT times the number of generated tokens. A 500-token answer with a 0.5 s TTFT and a 30 ms TPOT takes about 0.5 + 0.03 × 500 = 15.5 seconds.
  • Throughput: how many tokens per second the server generates across all users. It's what sets the cost per request.

Latency and throughput pull against each other. Putting more users in the same batch raises throughput (the GPU gets more done), but each user may wait a bit longer. Optimizing means picking the right point in that trade-off for your product: a chat wants low TTFT; an overnight document job wants high throughput.

The KV Cache: The Counter That Fills Up

During decode, the model has to "look at" all the previous tokens. Recomputing everything for every token would be far too slow, so it stores two vectors per token in each layer, the keys (K) and the values (V). That's the KV cache.

Three memory boards in perspective, with 1, 8 and 20 users: the blue space for weights stays fixed while purple KV cache slices grow to the red GPU memory limit line.
The weights have a fixed size. The KV cache grows with every token and with every concurrent user.

The math is simple: 2 (K and V) × number of layers × KV heads × head dimension × bytes per number. For Llama 3.1 8B, using the values from the model's config file (32 layers, 8 KV heads, dimension 128, 2 bytes in bf16):

2 × 32 × 8 × 128 × 2 = 131,072 bytes, about 128 KiB per token.

It looks small until you multiply: 8K tokens of context come to 1 GiB, per user. Twenty users with long conversations at the same time take up more memory than the model weights themselves (about 16 GB in 16 bits). On Llama 3.3 70B, the same math gives about 320 KiB per token, or roughly 40 GiB for a single 128K-token context.

These models already use an architecture trick for this: GQA (grouped-query attention), where several attention heads share the same keys and values. Llama 3.1 8B has 8 KV heads for 32 query heads; without GQA, the cache would be 4 times bigger. The GQA paper shows quality close to full attention, with speed close to the leaner version.

The Techniques, One by One

Quantization: Smaller Weights

A model's weights are usually stored at 16 bits per number. Quantizing means storing them in 8 or 4 bits. The model gets smaller, fits on a cheaper GPU and, since decode is memory-bound, it also gets faster: fewer bytes to read for every token.

A 24 GB GPU card and three bars on the same scale: the 8B model takes approximately 16 GB at 16 bits, 8 GB at 8 bits and 4 GB at 4 bits; the green area available for KV cache grows.
Quantizing doesn't just make the model fit: the space left over becomes KV cache, which means more users at the same time.
  • LLM.int8() (2022) showed you can cut memory in half while keeping quality, by handling the few extreme values (outliers) separately in 16 bits.
  • GPTQ (2022) quantizes a 175 billion parameter model to 3 or 4 bits in about four GPU hours, with negligible accuracy loss according to the authors, and sped up inference by about 3.25 times on an A100.
  • AWQ (2023, best paper award at MLSys 2024) starts from one observation: protecting just the 1% most important weights already cuts the error a lot.
  • FP8 is supported in hardware starting with NVIDIA's Hopper generation (H100), which, according to NVIDIA, computes in FP8 at four times the A100's rate per multiprocessor.

The catch: quantization is a trade-off. At 8 bits the loss is usually small; at 4 bits it depends on the method and the task. Measure it on your own evaluation, don't rely only on the vendor's benchmark.

PagedAttention: The Organized Counter

Older servers reserved, for each request, a contiguous block of memory sized for the longest answer it could produce. If the answer came out short, the reserved space sat empty. The vLLM launch post estimated that systems at the time wasted 60% to 80% of KV cache memory to fragmentation and over-reservation.

PagedAttention, the core idea behind vLLM (2023), copies what the operating system does with RAM: it splits the KV cache into small fixed-size blocks and allocates them on demand, without needing contiguous space. Waste dropped to under 4%.

Two memory boards side by side: on the left, three requests reserve large strips with striped empty areas; on the right, PagedAttention fits six requests into 21 small blocks labeled with their request number.
Reserving for the worst case wastes memory. On-demand blocks fit more conversations on the same card.

Spare memory turns into a bigger batch: the vLLM paper measured 2 to 4 times more throughput at the same latency, compared to the best systems of the time.

Continuous Batching: More Plates Going Out Together

Grouping several requests into a batch makes the GPU get more done, because it reads the weights once and uses them for everyone. The problem with the traditional batch: it only finishes when the longest answer finishes. Whoever asked for a short sentence waits for the neighbor who asked for a long text, and the slot sits idle.

Continuous batching (also called iteration-level scheduling, from the Orca paper, 2022) swaps the batch on every token: when one answer finishes, another request takes the slot right away. Orca measured 36.9 times more throughput on GPT-3 175B, at the same latency, against FasterTransformer. Anyscale reached up to 23 times by combining continuous batching with vLLM's memory optimizations.

Two timelines with four answers each, next to server racks and clocks: in a static batch, short answers leave striped idle areas until the longest ends; in continuous batching, green new requests fill these slots.
In a static batch, the longest answer holds everyone up. In a continuous one, a free slot gets filled right away.

Prefix Caching: Don't Reread the Same Ticket

Many requests start the same way: the same long system prompt, the same instructions, the same reference document. Without a cache, prefill reprocesses that beginning on every question.

Prefix caching stores the KV cache for that prefix and reuses it when a new request starts the same way. vLLM's docs call it "almost a free lunch": it doesn't change the model's output, it just avoids repeated work. SGLang has its own version, RadixAttention, which organizes prefixes in a tree.

If you use an APIContract that defines how one program asks another for data or actions: which endpoints to call, what to send and what comes back. On the web, usually HTTP with JSON., it's the same idea as the prompt caching that OpenAI, Anthropic and Google offer: the repeated part of the prompt gets cheaper and faster, as long as it stays at the beginning and is identical across calls.

FlashAttention: Fewer Round Trips to Memory

Attention is the part of the model that compares each token with the others. The naive implementation writes and reads intermediate matrices to the GPU's main memory several times. FlashAttention (2022) reorganizes the computation into blocks that fit in the chip's fast memory, computing the exact same result with far fewer reads and writes.

The series kept going: FlashAttention-2 doubled the speed of the first one, and FlashAttention-3 (2024) was built for the H100, reaching 75% of the card's theoretical peak in FP16. You rarely use this directly: inference engines already ship it by default.

Speculative Decoding: The Helper Runs Ahead, the Chef Checks

During decode, the GPU spends its time waiting on memory, with compute to spare. Speculative decoding uses that slack: a small, fast model (the draft) guesses several tokens ahead, and the big model checks them all at once, in a single pass. The right tokens are accepted; at the first wrong one, the big model corrects it and the cycle starts over.

Two server racks represent the small and large models: the small one drafts The, cat, climbed, in; the large one checks in a single pass, accepts the first three in green and corrects in to onto in red. Score: three accepted and one corrected. The output is the same.
When the draft is right, you get several tokens for the cost of one pass of the big model.

The detail that makes the technique so popular: the output is the same. The Leviathan et al. paper (2022) showed a 2 to 3 times speedup on T5-XXL with identical outputs, without retraining anything. Variants like Medusa and EAGLE replace the draft model with extra heads on the model itself; EAGLE reports 2.7 to 3.5 times on Llama 2 Chat 70B, keeping the output distribution.

The gain depends on the draft's hit rate: on predictable text (code, fixed formats) it pays off a lot; on creative text, less.

Cartoon of a slow robot chef writing an order word by word, while a small robot helper has already written several words ahead on a sheet and the chef just checks it with an approved stamp
The helper writes fast, the chef just stamps. When the draft is good, there's time left over for everyone.

Parallelism and Splitting the Phases

When the model doesn't fit on one GPU, it gets split. Tensor parallelism divides each layer across several GPUs in the same server; it's the option vLLM's docs point to first for this case.

A more recent idea is running prefill and decode on different GPUs, since the two phases have opposite bottlenecks and get in each other's way when they share a card. DistServe (2024) measured up to 7.4 times more requests served within TTFT and TPOT targets.

The Map: Which Technique Targets What

Technique Improves Cost or risk
Quantization Memory, decode, GPU cost Can lose quality, especially at 4 bits
PagedAttention Users per GPU (throughput) None for the user: it comes with the engine
Continuous batching Throughput, GPU utilization Individual latency can rise with a full batch
Prefix caching TTFT and cost on repeated prompts Only helps if the start of the prompt is identical
FlashAttention Attention speed, long contexts None for the user: it comes with the engine
Speculative decoding Time per token (TPOT) Needs a good draft; gain drops on unpredictable text
GQA KV cache size It's an architecture choice: it comes with the model
Tensor parallel and phase splitting Large models, latency targets More GPUs and more operational complexity

Inference Engines in 2026

Nobody needs to implement PagedAttention by hand. The work is picking the right engine and configuring it well.

Engine What it's for Version (11/21/2026)
vLLM Production GPU serving, the de facto standard in the open ecosystem 0.34.0
SGLang Production GPU serving, strong at reusing prefixes (RadixAttention) 0.5.23
TensorRT-LLM Maximum performance on NVIDIA GPUs, with more configuration work 1.3.0
llama.cpp CPU, Mac and modest GPUs, with quantized models (GGUF) 1.0.0
Ollama Running models locally with one command, great for development 0.40.17

A heads-up if you're following an old tutorial: TGI (Text Generation Inference, from Hugging Face) is in maintenance mode and its repository is archived. The README itself recommends moving to vLLM, SGLang, llama.cpp or MLX.

Where to Start

  1. Measure first. TTFT, TPOT and throughput with traffic close to the real thing. Without a baseline, you can't tell whether anything improved.
  2. Use a modern engine. Swapping a homemade server for vLLM or SGLang gets you PagedAttention, continuous batching and FlashAttention in one go.
  3. Turn on prefix caching and always put the fixed part of the prompt at the beginning.
  4. Test a quantized version (8 bits first, then 4 bits) and compare it on your quality evaluation.
  5. Keep context size in check. Every extra token in the prompt costs prefill and KV cache; summarizing history and cutting what doesn't help is worth as much as any GPU trick.
  6. Speculative decoding and parallelism last, once the earlier steps are in place.

If you use an API (OpenAI, Anthropic, Google) and don't serve your own model, half the list still applies: prompt cachingModel provider feature that stores the repeated start of an already processed prompt, charging less and answering faster on later calls., a lean context, streaming so the user sees the answer as it's written, and a smaller model for simple tasks. In an agent, which calls the model several times per task, that care multiplies, as I showed in the guide to AI agents from scratch.

Quick check

1. Which inference phase is usually memory-bound?
Show answer

Answer: Decode, which generates one token at a time

During decode, for every token the GPU reads the full weights and KV cache to do very little compute. That's why it spends most of its time waiting on memory.

2. What does speculative decoding change in the model's answer?
Show answer

Answer: Nothing: the output follows the same distribution, it just comes out faster

The big model checks every proposed token. The accepted ones follow the same distribution it would generate on its own.

3. An assistant's prompt starts with the current date and time and then has 3K tokens of fixed instructions. What should you do?
Show answer

Answer: Move the date after the fixed instructions

The prefix cache only reuses an identical beginning. With the date at the start, the prefix changes every minute and nothing gets reused.

4. Why does continuous batching raise throughput?
Show answer

Answer: Because it fills the slot of a finished answer with a new request right away

In a static batch, the short answers' slots sit idle until the longest one ends. In a continuous one, the GPU never has an empty slot.

Frequently Asked Questions

What's the difference between training and inference?

In training, the model adjusts its weights from examples (including in fine-tuning). In inference, the weights are fixed and the model only generates answers. Training happens now and then; inference happens on every question, which is why it dominates day-to-day cost.

Does quantizing always make the model worse?

It always changes something, but at 8 bits the difference is usually small and, at 4 bits, methods like GPTQ and AWQ keep much of the quality. The right answer comes from your evaluation, with your cases.

Do I need a GPU to run a model locally?

For small, quantized models, not necessarily: llama.cpp and Ollama run on CPU and on Mac. To serve many users with low latency, a GPU is still the way to go.

vLLM or SGLang?

Both ship the main techniques. SGLang stands out when many requests share prefixes (agents, chained calls). The smart choice is to test both with your traffic.

What are tokens per second, and how much is good?

It can be per user (how fast the answer appears on screen) or summed across the server (throughput). For human reading, 10 tokens per second per user already keeps up with reading; for batch processing, what counts is the total.

References

Source: https://ramongomessilva.com.br/blog/llm-inference-optimization · Accessed on December 02, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. LLM inference optimization: prefill, decode, KV cache and the techniques that speed up answers. Ramon Gomes, 24 nov. 2026. Disponível em: https://ramongomessilva.com.br/blog/llm-inference-optimization. Acesso em: 2 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, November 24). LLM inference optimization: prefill, decode, KV cache and the techniques that speed up answers. Ramon Gomes. https://ramongomessilva.com.br/blog/llm-inference-optimization

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026llminferenceoptimization,
  author = {Gomes, Ramon},
  title = {{LLM inference optimization: prefill, decode, KV cache and the techniques that speed up answers}},
  organization = {Ramon Gomes},
  year = {2026},
  month = nov,
  date = {2026-11-24},
  url = {https://ramongomessilva.com.br/blog/llm-inference-optimization},
  urldate = {2026-12-02}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles