Skip to content
derpx06.dev
WritingExplainersNotesAbout
works on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisationworks on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisation

Learning in public.

A student's notebook on system design, distributed systems and databases. Shared as I learn.

ReadWritingExplainersNotesAbout
ElsewhereGitHubLinkedInHugging FaceLeetCode
Say hellomanaskhairnar1511@gmail.com
derpx06
NORMALmain© 2026 Derpx06Pune, Indiatop ↑
Blog/LLM Systems

What is the KV cache? Why ChatGPT doesn't re-read your whole chat

LLMs answer fast because they save work they already did. Here's the KV cache: what it fixes, what it costs, and how people shrink the cost.

Derpx0627 Mar · 4 min read
Contents
Wait, where's the slow part?The naive way does the same homework againPrefill and decodeSo how does the cache work?The catch: less math, more memoryThe production toolboxWhy any of this matters for productsWhat's still unsolved, plus a checklist
0% read · 4 min leftBack to top ↑
On this page0%
Contents
Wait, where's the slow part?The naive way does the same homework againPrefill and decodeSo how does the cache work?The catch: less math, more memoryThe production toolboxWhy any of this matters for productsWhat's still unsolved, plus a checklist
What you get from this article

You'll see which slow step the KV cache fixes and how much memory it eats. Then we'll meet GQA, PagedAttention, prompt caching and quantized caches. Each one gets a plain explanation right when it first shows up.

One simple idea is why modern LLMs (large language models, the AI behind chatbots) reply fast: don't redo work you already did. It's like writing a note once and reading it later, instead of working the answer out again each time.

1Prompt
2Model reads it
3Saves what it worked out
4Reuses it for every new word
The whole idea in one line

Wait, where's the slow part?

A token is a small piece of text, like a word or part of a word. For each token, the model makes three lists of numbers: a Query (Q), a Key (K) and a Value (V).

Think of it like a library

The Query is the question you ask the librarian. The Key is the label on a book's spine. The Value is what's actually written inside the book.

Attention is the step where a new token looks back at the earlier tokens. It compares its query with their keys, then mixes the matching values. Here's the math:

Text
Query_i = Token_i x W_Q
Key_i   = Token_i x W_K
Value_i = Token_i x W_V
Attention(i -> j) = dot(Query_i, Key_j) / sqrt(d)
Output_i = sum_j softmax(Attention(i -> j)) * Value_j

The model writes one token at a time, and token t+1 depends on token t. So it keeps looking back at the earlier text. This is where work is wasted. The K and V for old tokens never change, but the model keeps rebuilding them anyway.

The naive way does the same homework again

Say the prompt is The capital of France is. Step 1 computes K/V for those tokens and predicts Paris. Step 2 computes the same K/V again. So does step 3. It's like solving problems 1 to 10 all over again every time you start problem 11.

Without KV cacheWith KV cache
Step 1Compute K/V for all prompt tokensCompute prompt K/V once and store it
Step 2Compute old tokens again, plus the new oneCompute only the new token's K/V
Step 3Repeat the old work againReuse all old K/V from memory

Prefill and decode

A model answers in two phases. In prefill, it reads the whole prompt in one go, which GPUs (the chips that do the heavy math) are great at. In decode, it writes one token per step and reads the cache every time.

So how does the cache work?

The KV cache stores the keys and values, for every layer, of tokens the model already processed. A new token makes a fresh query, reads the old K/V from the cache and adds only its own.

And this is exact. It doesn't quietly make the model dumber. Old token states never change in causal decoding (a token only looks at earlier tokens). It's called memoization, which just means saving an answer so you never work it out twice.

Read old K/V from cache
Compute new token K/V
Append to cache
Predict next token
↺ repeat
One decode step
Python
# Simplified decode step
for L in layers:
  k_new = x_new @ W_K[L]
  v_new = x_new @ W_V[L]

  k_all = concat(cache[L].keys, k_new)
  v_all = concat(cache[L].values, v_new)

  y_new = attention(q_new, k_all, v_all)

  cache[L].keys.append(k_new)
  cache[L].values.append(v_new)

The catch: less math, more memory

Nothing's free. The cache swaps repeated math for memory space. Its size grows in a straight line with tokens, layers and head dimensions. It works like phone storage: the more photos you keep, the fuller it gets. Each decode step also has to read big cached tensors (large blocks of numbers). So long contexts are often slowed by memory bandwidth, which just means how fast data moves in and out of memory.

Context length: longer means a bigger cache
Concurrency: more users multiply the VRAM pressure (VRAM is the GPU's own memory)
Precision: lower precision fits more sessions per GPU
Three things set how much memory you need
ConcernImpactTypical fix
Cache size growthFewer requests at once per GPUGQA/MQA, quantized KV
Memory bandwidth at decodeSlow generation at long contextBetter kernels and cache layout
FragmentationWasted VRAM, unstable throughputPagedAttention-style blocks
Prefix mismatchLess cache reuse in chat turnsStable prompt templates

The production toolbox

  • Grouped-Query Attention (GQA) shares K/V across groups of heads. A head is one of the parallel "viewpoints" attention uses. Multi-Query Attention (MQA) shares them across all heads.
  • PagedAttention stores the cache in fixed blocks, the way an operating system splits memory into pages. That cuts fragmentation, which is wasted gaps between chunks.
  • Prefix caching reuses long shared system prefixes (the same starting text many requests have), so you skip the prefill cost.
  • KV quantization stores the cache at lower precision, like saving a photo in a smaller file size. It cuts VRAM use.
A rule of thumb

Slow decode at long context? Fix memory movement. Repeated prefill across similar requests? Use prefix caching. Too few users per GPU? Reach for GQA/MQA and KV quantization.

Why any of this matters for products

The KV cache decides what products are even possible. Without it, long-context assistants, code copilots and document chat would be slower and cost more, especially in follow-up turns. Better caches cut the cost per useful token and keep latency (the waiting time) steady under load.

What's still unsolved, plus a checklist

Long-context models still struggle to find facts buried in the middle, a bit like missing one key line in the middle of a long book. The rules for throwing out cache entries are still mostly guesses. And speculative decoding (a small model drafts tokens ahead) has to leave the cache consistent after rejected drafts.

  • Measure prefill latency and decode tokens/sec separately.
  • Keep prompt templates stable for prefix reuse.
  • Profile VRAM and memory bandwidth, not just FLOPs.
  • Add GQA/MQA and quantization only with quality checks.
  • Alert on drops in cache hit rate, and test with real multi-turn traffic.
Key takeaways
  • The model writes one token at a time and old tokens never change, so their K/V can be saved.
  • The KV cache means each step computes only the new token.
  • The price is memory space and speed, growing with context length and users.
  • GQA/MQA, PagedAttention, prefix caching and KV quantization keep that price manageable.
  • Measure prefill and decode separately, and check quality after every optimization.
ShareXLinkedInEmail
Written by Derpx06A developer who builds AI search tools and the code around them. I explain what I got wrong first, so you can skip it. Spotted a mistake? Tell me — corrections get credited.
Foundations · 3 minWhy is 0.1 + 0.2 not 0.3 in code?Foundations · 4 minHow does Git work inside? (Snapshots, not changes)Distributed Systems · 6 minHow does your computer know the time? (And why it can be wrong)
Start here
01Why is 0.1 + 0.2 not 0.3 in code?02How does Git work inside? (Snapshots, not changes)03How does your computer know the time? (And why it can be wrong)