
A KV cache is the working memory a large language model keeps while it generates text. For every token in the conversation so far, the model stores two small vectors, a key and a value, for every layer of the network. The next token gets computed from those stored vectors instead of from scratch. That shortcut is the reason a chatbot can answer in seconds instead of minutes, and it is also the reason long conversations get slow and expensive. The cache grows with every token, it lives in scarce GPU memory, and it sets a hard limit on how many users one server can handle at once.
I first noticed the KV cache as a cost line, not as a concept. A prototype agent with a 60,000-token context window ran fine for one user and fell over for ten. The model was the same, the prompt was the same, and the only thing that changed was the memory held for each conversation in flight. Once I understood the cache, the fix was obvious: shorten the shared prefix, cache it once, and stop paying to recompute it. This article explains what the KV cache is, why it grows so fast, what the big providers charge for it, and the five techniques that shrink it.
A transformer model reads a prompt in two phases. In the prefill phase, it processes the whole input at once and computes attention scores between every token and every token before it. In the decode phase, it generates one token at a time, and each new token needs attention over everything that came before. Without a cache, each decode step would recompute attention over the full history. With a cache, the model stores the key and value vectors from the prefill phase and reuses them, so each new token costs roughly one step of work instead of a full pass over the conversation.
Three things live in GPU memory during inference, and people mix them up. Model weights are the trained parameters, loaded once and shared by every request. Activations are temporary numbers computed during a single forward pass and discarded right after. The KV cache sits between the two: it persists across decode steps for the life of one request, and it grows by a fixed amount with every token the conversation gains. Weights stay flat, activations come and go, and the cache climbs.
The cache exists because attention is expensive. Attention compares each token against each earlier token, so the work grows with the square of the sequence length when nothing is stored. Storing keys and values turns that repeated work into a memory lookup. The trade is memory for speed, and for short prompts the trade is a clear win.
The cache grows in direct proportion to sequence length. Every token you add, whether it comes from the system prompt, a retrieved document, a tool result, or the model reply, adds its own keys and values to the cache. A 2,000-token chat holds a small cache. A 200,000-token agent loop holds one a hundred times larger. Nothing in the mechanism slows that growth down. The cache has no summary step, no forgetting, and no compression unless you add one deliberately.
Fragmentation makes the problem worse. Early inference servers allocated one long, unbroken block of memory per request, sized for the maximum possible length. A request that used a tenth of its block still held the rest, and the gaps between blocks could not serve other requests. Modern runtimes fix this with paged memory, covered in the techniques section below, but the underlying growth curve stays the same.
Cache size caps batch size, and batch size decides cost. A GPU earns its keep by processing many requests together in one batch. Each request in the batch needs its own cache, so the total cache size across the batch must fit in the memory left after the weights. Double the context length and you roughly halve the number of requests that fit. Halve the batch and the cost per token climbs, because the same GPU now serves fewer users per second.
Long-context agents feel this first. An agent that loops through tool calls, each time appending results to the conversation, can watch its cache grow across dozens of turns. I have seen agent runs where the final turns cost more than the first ten combined, purely because the cache had grown so large that the batch shrank to one. If you build agents, the KV cache is not an academic detail. It is the main reason your agent gets slower and pricier the longer it works.
The size follows a simple formula: two vectors (one key, one value) times the number of layers times the size of each vector times the bytes per number, multiplied by the number of tokens. Take a 70-billion-parameter class model with 80 layers, 8 key-value heads of 128 dimensions each, stored in 16-bit precision. The arithmetic gives about 0.3 MB per token. A 10,000-token conversation then needs roughly 3 GB of cache. A 100,000-token conversation needs roughly 30 GB. Those numbers are my own back-of-the-envelope calculation from the published architecture, not a vendor claim, and they assume 16-bit storage with no compression.
Three things change the result. More layers or wider vectors raise the per-token cost. Lower precision, such as 8-bit storage, cuts it in half. Fewer key-value heads, the grouped-query attention design used by most current models, cuts it further. The exact number varies by model, but the shape of the answer never changes: cache size scales linearly with tokens, and long contexts need gigabytes per conversation.
That scale explains a design choice you see everywhere in production systems: keep the shared part of the prompt identical across requests. When two requests share the same opening tokens, a good runtime stores that prefix once and reuses it for both. The saving is real. A 50,000-token system prompt and document block, cached once, can serve a hundred conversations for the memory cost of one. Put the static content first, the changing content last, and the cache works for you instead of against you.
All three major providers now offer prompt caching, and the terms differ enough to matter when you pick a model for a long-context workload. The table below uses the numbers from each provider official documentation, current as of this writing. Prices and minimums change often, so treat the docs as the source of truth and check them before you commit to a design.
| Provider | Minimum cacheable prompt | Cache hit discount | Cache write cost | Cache lifetime |
|---|---|---|---|---|
| OpenAI | 1,024 tokens (GPT-5.6 and later) | Up to 95 percent off cached input tokens | 1.25 times the standard input price | Managed by OpenAI, enabled by default |
| Anthropic | 512 tokens for current Claude models | Cache reads at 0.1 times the base input price | 2 times the base input price for a 1-hour lifetime | 5 minutes standard, 1 hour extended |
| Google Gemini | 2,048 tokens (Gemini 2.5), 4,096 tokens (Gemini 4 and 3.x) | Implicit caching enabled by default | Explicit cache storage at 0.50 dollars per 1M tokens per hour through Dec 31, 2026, then 1.00 dollar from Jan 1, 2027 | Managed by Google |
OpenAI turns caching on by default for supported models and discounts reused input tokens by up to 95 percent, with cache writes priced at 1.25 times the standard rate. Anthropic reports cost reductions of up to 90 percent and latency reductions of up to 85 percent for long prompts, with cache reads at a tenth of the base input price. Google takes a different route: implicit caching is enabled by default for Gemini 2.5 and newer models, and Gemini 4 caches the full previous request only when the new request adds at least 2,050 tokens.
Researchers and engine builders have attacked the KV cache from five directions, and each one helps a different workload. You do not need all five. Pick the one that matches your bottleneck.
Grouped-query attention cuts the number of key-value heads. Standard multi-head attention keeps one key-value head per query head. Multi-query attention keeps a single key-value head for all query heads. Grouped-query attention sits between the two, with a handful of key-value heads shared by groups of query heads. The GQA paper reports that existing checkpoints can be uptrained into this form with about 5 percent of the original pretraining compute, which is why most current open models ship with it.
Multi-head latent attention compresses the cache into a low-rank latent vector. DeepSeek-V2 introduced this design, and the paper reports a KV cache reduction of 93.3 percent compared with DeepSeek 67B, alongside a 5.76 times increase in maximum generation throughput. The model keeps 236 billion total parameters with 21 billion activated per token and a 128K context window.
Paged attention fixes fragmentation. vLLM stores the cache in fixed-size blocks, like pages in an operating system, instead of one long allocation per request. Blocks get shared between requests when the prefix matches, and freed blocks return to a pool immediately. The vLLM paper reports throughput improvements of 2 to 4 times at the same latency compared with the systems it benchmarked against. SGLang takes the same idea further with RadixAttention, a tree structure for shared prefixes, and reports up to 6.4 times higher throughput on its benchmarks.
Sliding windows with attention sinks handle infinite streams. StreamingLLM keeps a fixed-length cache by holding on to the first few tokens, the attention sink, plus a sliding window of recent tokens, and discarding the middle. The paper shows stable language modeling with up to 4 million tokens and no fine-tuning. The trade is clear: you lose access to the middle of the conversation, so this fits streaming and monitoring workloads, not tasks that need full recall of a long document.
Quantization shrinks each stored number. Storing keys and values in 8-bit or 4-bit precision instead of 16-bit cuts the cache in half or more, the same way quantizing the KV cache the same way you quantize weights trades a small amount of precision for a large memory saving. Most engines now support 8-bit KV cache with minimal quality impact. I use 8-bit as the default for long-context serving and only reach for 4-bit when memory is the binding constraint.
Start with the prompt. Put the static content first: system instructions, fixed document chunks, stable examples. Put the changing content last: the user message, the latest tool result, the new question. This ordering lets the provider cache the long stable prefix and only process the short tail fresh. It costs nothing to do and it is the highest-return change on this list.
Then measure what you have. Track your cache-hit rate as a production metric, next to latency and cost per request. Most providers report cache hits in the usage object of each response, so add cache-hit-rate metrics in your LLM observability stack and watch the number for a week. A hit rate under 50 percent means your prefixes are churning. A hit rate above 90 percent means the cache is doing its job.
Choose the cache lifetime deliberately. Anthropic gives you 5 minutes or 1 hour, and the longer lifetime costs double the write price. Pick 5 minutes for chatty, bursty traffic and 1 hour for agent loops and batch jobs that revisit the same context. For self-hosted serving, turn on automatic prefix caching in your runtime and pick a model with grouped-query attention. If you run models locally, remember that a self-hosted runtime where the KV cache hits your own VRAM makes the same tradeoffs, and a paged engine like vLLM uses that VRAM far better than a naive one.
It is the short-term memory a language model keeps while it writes. For each token it has already seen, the model stores a key and a value vector. When it writes the next token, it reads those stored vectors instead of recomputing them. The cache makes generation fast, and it grows with every token in the conversation.
It makes each token faster to generate, because the model skips recomputation. It makes the system slower at scale when the cache grows large enough to shrink batch sizes, because fewer requests fit on one GPU at once. The net effect depends on context length: short chats get faster, very long chats can get slower unless the cache is managed.
No. The KV cache is the mechanism, the stored keys and values inside the model. Prompt caching is the provider feature that reuses a KV cache across API calls when the prompt prefix matches. One is how the memory works, the other is how you get billed for reusing it. If you want the full pricing picture, read provider-side prompt caching discounts and compare them with the table above.
The KV cache is invisible until it bites. It shows up as a latency spike on long conversations, a cost line that grows faster than usage, or an agent that slows down the longer it works. The fixes are unglamorous: order the prompt with static content first, measure the hit rate, pick the right lifetime, and choose a runtime that pages memory well. None of them needs a new model. All of them need you to look at the cache instead of the model.
Pick one workload this week, apply the checklist, and watch the hit rate for a few days. If your prompts share long stable prefixes, you should see the cache-hit rate climb and the cost per request fall. Then read how long context quietly breaks your coding agent to see the other half of the story, because the cache is only one of the ways long context strains a system. Leave a comment with the hit rate you measured. I read every one, and the numbers from real workloads teach more than any benchmark.
Sources: vLLM PagedAttention paper, SGLang RadixAttention paper, DeepSeek-V2 MLA paper, StreamingLLM paper, OpenAI prompt caching docs, Anthropic prompt caching docs, Gemini API pricing.