AlgoViz

KV cache and prefix caching

medium 40 min

While a model writes, it saves the key and value vectors of every token it has already seen, so each new token costs one small step instead of a pass over the whole text.

Theory

Read or listen first. About 3 min.

What it is

A language model writes one token at a time. To choose the next token, every layer of the model runs attention: the newest token asks a question (its query) and compares it with a label (a key) of every earlier token, then mixes their contents (their values). The KV cache is the store of those keys and values, one pair per token, per layer, per key-value head.

Keys and values of an earlier token never change once they are computed, because a token can only look backwards. So the model computes them once, saves them, and on every later step computes keys and values for the one new token only. That is the whole trick.

Prefix caching stretches the same idea across requests. If many requests start with the same tokens, such as a long system prompt, the saved keys and values of that start can be kept and reused. Engines such as vLLM and SGLang do this inside one server. Model providers sell the same idea as prompt caching: cached input tokens are billed at a fraction of the normal price.

Why it exists

Without a cache, writing token 1,000 would mean recomputing keys and values for the 999 tokens before it, and then token 1,001 would repeat almost all of that again. Total work grows with the square of the length. With a cache, each step adds one token's worth of new work, and the old work is only read back from memory.

The price is memory. On Qwen3-8B, one token's cache takes 144 KiB, so one chat of 8,192 tokens takes 1.125 GiB. On an 80 GB GPU that leaves room for a few dozen such chats at once, and that number, not the weights, usually decides how many users one GPU can serve. Prefix caching then saves both compute and memory, because one copy of a shared start can serve many requests.

A short history

  1. 2017

    "Attention Is All You Need" (arXiv, 12 June 2017) introduces the Transformer, where every token attends to keys and values of the others.

  2. 2019

    Noam Shazeer's multi-query attention paper (arXiv, 6 November 2019) names the memory bandwidth of loading keys and values as the bottleneck of step-by-step decoding, and shares one key-value head across all query heads.

  3. 2023

    The GQA paper (arXiv, 22 May 2023) proposes grouped-query attention, between one key-value head and one per query head. In June the vLLM blog introduces PagedAttention, and the paper follows on 12 September 2023 (SOSP 2023).

  4. 2023

    SGLang's paper (arXiv, 12 December 2023) introduces RadixAttention: a radix tree of cached prefixes with least-recently-used eviction of leaves.

  5. 2024

    DeepSeek-V2 (arXiv, 7 May 2024) introduces multi-head latent attention and reports a 93.3% smaller KV cache than its earlier 67B model. OpenAI announces automatic prompt caching on 1 October 2024, and Anthropic's prompt caching becomes generally available in December 2024.

Inside this chapter

Chapter sources
Token
A piece of text the model reads or writes, often part of a word.
Query, key, value
Three vectors made from each token in each attention head. The query asks, keys are compared with it, values are mixed by the result.
KV cache
The saved keys and values of tokens already processed, kept in GPU memory for the rest of the request.
Prefill
The first phase: all prompt tokens are processed at once and their keys and values are written to the cache.
Decode
The second phase: one new token per step, reading the whole cache each time.
KV head
A set of keys and values shared by one or more query heads. Fewer KV heads mean a smaller cache.
Block or page
A fixed number of tokens' keys and values stored together, for example 16 tokens. Engines manage memory in blocks.
Block table
A list per request saying which physical blocks hold its tokens, in order. Like a page table in an operating system.
Prefix cache hit
Leading blocks of a new request that are already in the cache, so they need no prefill.
TTFT and TPOT
Time to first token, set mostly by prefill, and time per output token, set by decode.

How it works

Step through the idea, or press Play.

Step 1 of 4

Prefill. All prompt tokens at once, keys and values written

Understand it

Start here

A paper chain workshop

Asha makes paper chains for a school fair. Every link carries one word, and a chain spells a message. To write the next word well, Asha reads every link already on the chain. Lee helps hang finished chains on a wall of hooks. Customers Noor, Sam and Max bring cards with the messages they want.

Chains on a wall of hooks
again, againLink 5? First remake 1 to 4Remake every link

Reading the chain is cheap. Remaking it is what costs. A shared start hangs once.

Recall

Attention in one minute

Inside each layer, every token turns into three vectors through three learned matrices: a query, a key and a value. To update token t, the model takes token t's query, scores it against the keys of tokens 1 to t, turns the scores into weights with softmax, and adds up the values with those weights. A model has many heads doing this side by side, and dozens of layers stacked.

One head, one new token

outt=∑i=1tsoftmax⁡i ⁣(qt⋅kid)viki=WKxi,  vi=WVxi\text{out}_t = \sum_{i=1}^{t} \operatorname{softmax}_i\!\left(\frac{q_t \cdot k_i}{\sqrt{d}}\right) v_i \qquad k_i = W_K x_i,\; v_i = W_V x_i
d is the head size, for example 128. Only q_t, k_t and v_t are new at step t. Every k_i and v_i with i below t was already computed at an earlier step and does not change.

Why do old keys and values not change? A model that writes text uses a causal mask: a token may look at itself and earlier tokens, never later ones. So the inputs of layer 1 for token 5 are the same at step 6, step 60 and step 600. The same holds layer by layer. That is what makes caching exact, not an approximation.

One decode step in one layer

Compute grows by one token per step. Reading grows with the whole cache.

The saving

Without and with a cache

Key and value projections for n new tokens after a prompt of p

no cache: ∑t=pp+n−1t  ≈  pn+n22cache: p+n\text{no cache: } \sum_{t=p}^{p+n-1} t \;\approx\; pn + \tfrac{n^2}{2} \qquad \text{cache: } p + n
Counted in token projections per layer. For p = 32 and n = 224, as in the code below: about 32,000 against 256. Attention scores still grow with length in both cases.
Python
# Count key and value projections, no model needed.def projections(prompt, new, cache):    if cache:        return prompt + new                 # each token once    return sum(range(prompt, prompt + new)) # all earlier tokens, every stepfor p, n in [(32, 224), (1000, 500), (8000, 1000)]:    a, b = projections(p, n, False), projections(p, n, True)    print(f"prompt {p:5}, write {n:5}: no cache {a:12,}  cache {b:7,}  ratio {a / b:7.1f}")
The ratio grows with length. The full toy model with real attention is in the Code tab.
Edit and run it in your browser

What the toy model in the Code tab measures

RunMultiplicationsSame output?
No cache, 32 prompt tokens, 224 new4,643,072reference
KV cache, same run561,408yes, difference 0.0
One head of size 8, our own toy. The time ratio on your machine will be close to the multiplication ratio, about 8 times.

Two phases

Prefill and decode

A request has two phases that behave very differently. Prefill processes all prompt tokens together. That is many large matrix multiplications, so the GPU's arithmetic units are busy: prefill is compute-bound. Decode makes one token per step. For each step the GPU must read every weight and the whole cache of each request in the batch, but does little arithmetic per byte read: decode is memory-bandwidth-bound.

One chat request

Time to first token is mostly prefill. Time per output token is decode, and it grows as the cache grows.

Prefill against decode

PrefillDecode
Tokens per stepthe whole promptone per request
Limited byarithmeticmemory bandwidth
KV cachewrittenread in full, one entry appended
User seestime to first tokentime per output token
Batching helps bylittle: already fulla lot: one weight read serves many requests
Prefix caching savesthe matched partnothing

A floor for one decode step

tstep≳weights+∑cachesbandwidth=16.4 GB+54 GB3.35 TB/s≈4.9+16.1=21 mst_{\text{step}} \gtrsim \frac{\text{weights} + \sum \text{caches}}{\text{bandwidth}} = \frac{16.4\ \text{GB} + 54\ \text{GB}}{3.35\ \text{TB/s}} \approx 4.9 + 16.1 = 21\ \text{ms}
Our example: Qwen3-8B in 16-bit on an H100 SXM (3.35 TB/s, NVIDIA's page), with a full 54 GB cache pool. Reading the cache costs three times more than reading the weights. Real steps are slower; this is a lower bound.

Size

How big is the cache?

Bytes per token, then per request

bytes per token=2×L×Hkv×dhead×bbytes=bytes per token×tokens\text{bytes per token} = 2 \times L \times H_{kv} \times d_{head} \times b \qquad \text{bytes} = \text{bytes per token} \times \text{tokens}
2 for key and value, L layers, H_kv key-value heads, d_head numbers per head, b bytes per number (2 for 16-bit, 1 for 8-bit). Read L, H_kv and d_head from config.json: num_hidden_layers, num_key_value_heads, head_dim. If head_dim is missing, use hidden_size / num_attention_heads.

Worked: Qwen2.5-72B-Instruct at 8,192 tokens

2×80×8×819264×2=327,680 B=320 KiB×8,192=2.5 GiB≈2.68 GB2 \times 80 \times 8 \times \tfrac{8192}{64} \times 2 = 327{,}680\ \text{B} = 320\ \text{KiB} \qquad \times 8{,}192 = 2.5\ \text{GiB} \approx 2.68\ \text{GB}
From its config.json: 80 layers, 64 query heads, 8 key-value heads, hidden size 8,192, so head size 128, stored in bfloat16. One 8k chat needs 2.5 GiB next to 145 GB of weights.

KV cache of open models, 16-bit, from their config.json

ModelLayersKV heads x sizePer token8,192 tokens32,768 tokens
Qwen3-8B368 x 128144 KiB1.125 GiB4.5 GiB
Qwen3-32B648 x 128256 KiB2 GiB8 GiB
Qwen2.5-72B808 x 128320 KiB2.5 GiB10 GiB
Mistral-7B v0.1328 x 128128 KiB512 MiB, window 4,096512 MiB
gpt-oss-120b36: 18 full, 18 window 1288 x 6436 KiB on full layersabout 0.29 GiBabout 1.13 GiB
DeepSeek-V361one latent of 512 + 6468.6 KiB0.54 GiB2.1 GiB
Read 27 November 2026 from each model's config.json on Hugging Face. Our arithmetic. Window layers keep at most their window, so their part stops growing: Mistral's 4,096-token window caps all layers, and gpt-oss adds a fixed 4.5 MiB for its 18 window layers. Llama configs are gated, so they are not in the table.

Shrink it

Fewer key-value heads: MHA, MQA, GQA, MLA

The formula has four factors, and each has an idea that attacks it. The oldest is to cut H_kv. In standard multi-head attention every query head has its own keys and values. Multi-query attention shares one key-value head across all query heads. Grouped-query attention sits in between: groups of query heads share one. The GQA paper reports quality close to multi-head attention at speed close to multi-query attention.

Who shares keys and values

Qwen3-8B has 32 query heads and 8 KV heads: groups of four. With 32 KV heads its cache would be 576 KiB per token instead of 144.

Every factor has a lever

FactorLeverExampleCost
KV headsgrouped or multi-query attentionQwen3: 8 KV heads for 32 query heads, 4 times smallerset at training time
Head size x headslatent attention: store one compressed vectorDeepSeek-V3: 576 numbers per layer instead of 40,960extra math, special kernels
Tokenssliding window on some layersgpt-oss: half the layers keep only 128 tokensthose layers forget older text
Bytes per number8-bit cacheFP8 in vLLM with kv_cache_dtypesmall accuracy risk, calibrate scales
Copiesprefix sharingone system prompt for many requestsonly helps identical starts

DeepSeek-V3: latent attention against plain multi-head

61×(512+64)×2⏟latent=70,272 Bvs61×128×(192+128)×2⏟128 full heads≈5.0 MB\underbrace{61 \times (512 + 64) \times 2}_{\text{latent}} = 70{,}272\ \text{B} \quad \text{vs} \quad \underbrace{61 \times 128 \times (192 + 128) \times 2}_{\text{128 full heads}} \approx 5.0\ \text{MB}
From config.json: kv_lora_rank 512, qk_rope_head_dim 64, 128 heads with key size 128 + 64 and value size 128. Our arithmetic: about 71 times smaller per token. The comparison model is hypothetical.

Deeper treatment of these variants and of attention kernels lives in attention kernels, KV heads and long context. Quantization formats are covered in quantization.

Capacity

Memory decides the batch size

A GPU's memory holds three things: the weights, the cache blocks of all running requests, and working space for the current step. Whatever is left after weights and working space is the cache pool. Divide it by the cache per request and you have the most requests that can run at once.

One GPU serving many chats

Chat users send prompts to a scheduler inside our inference server. The scheduler looks up block tables, which give addresses in the KV block pool on one GPU with 80 GB of memory. On that GPU, weights of about 16 GB and the 54 GB block pool are both read every step into working space, which writes one new key and value back into the pool and sends the next tokens back to users.
Every step reads all weights and all live blocks. Only one key and value per request per layer is written.

How many 8k chats fit? Qwen3-8B on one 80 GB GPU

80×0.9⏟72−16.4⏟weights−2⏟work≈53.6 GB53.6 GB147,456 B≈363,000 tokens≈44×8,192\underbrace{80 \times 0.9}_{72} - \underbrace{16.4}_{\text{weights}} - \underbrace{2}_{\text{work}} \approx 53.6\ \text{GB} \qquad \frac{53.6\ \text{GB}}{147{,}456\ \text{B}} \approx 363{,}000\ \text{tokens} \approx 44 \times 8{,}192
Our assumptions: keep 10% of memory free, 2 GB of working space. 8.2 billion parameters from the model card, times 2 bytes. At 32,768 tokens per chat, only 11 fit. With an 8-bit cache, about 88 chats of 8k fit.

Same GPU, same model, different plans

Context per request16-bit cache8-bit cache
2,048 tokensabout 177 requestsabout 355
8,192 tokensabout 44about 88
32,768 tokensabout 11about 22
131,072 tokensabout 2about 5
Our arithmetic from the example above. Most chats are shorter than their limit, so engines allocate blocks as tokens arrive instead of reserving the limit.

Paging

PagedAttention and block tables

Early servers reserved one contiguous slab per request, sized for the longest possible answer. Most of it stayed empty, and free memory broke into gaps too small to use. The vLLM team's June 2023 post put the waste in existing systems at 60% to 80% of KV memory, and under 4% with their approach.

PagedAttention borrows from operating systems. The cache is cut into fixed blocks, each holding the keys and values of a fixed number of tokens. A request gets blocks one at a time as it grows, from anywhere in the pool, and a block table lists them in order. The attention kernel follows the table. A block can appear in several tables, which is how requests share a prefix or the branches of parallel sampling.

Sam's request, 40 tokens, blocks of 16

Logical blockTokensPhysical blockFilled
01 to 16316 of 16
117 to 32916 of 16
233 to 4048 of 16, grows as tokens arrive
Waste is at most one partly filled block per request. Our example numbers.

The life of one block

Only full blocks get a hash and can be reused. While a block is Full, every new request that matches it adds one to its count. Cached blocks have a count of zero and are evicted least recently used first.

What if the pool runs out in the middle of decoding? The engine preempts a request: it frees that request's blocks and later either recomputes them with a fresh prefill or brings them back from CPU memory. Users see this as a sudden pause. A full cache shows up as latency spikes before it shows up as errors. Scheduling around a full pool is covered in batching, decoding and serving caches.

Reuse

Prefix caching: hash the blocks

Once the cache lives in blocks, reuse across requests is a lookup. vLLM's design gives every full block a hash made of three things: the hash of the block before it, the token IDs in the block, and extra keys such as a LoRA adapter ID, image hashes or a cache salt. Because each hash includes its parent, a block can only match when everything before it matched too.

Python
import hashlibdef block_hashes(tokens, block=4, salt=""):    parent, out = salt, []    for i in range(0, len(tokens) // block * block, block):        text = parent + "|" + " ".join(tokens[i:i + block])        parent = hashlib.sha256(text.encode()).hexdigest()[:8]        out.append(parent)    return out          # a partly filled last block gets no hasha = "you help a bike shop be kind my brake squeaks".split()b = "you help a bike shop be kind do you fix tyres".split()c = "09:41 you help a bike shop be kind my brake squeaks".split()print(block_hashes(a))print(block_hashes(b))print(block_hashes(c))   # one token in front: nothing matches
Requests a and b share the first block. Request c has the same words shifted by one token, so every hash differs.
Edit and run it in your browser

Request B after request A

Our example: a 6,000-token system prompt is exactly 375 blocks of 16. Only full matching blocks count.

What one hit saves on Qwen3-8B

6,000×2×8.2×109≈98 TFLOP skipped6,000×147,456 B≈885 MB stored once6{,}000 \times 2 \times 8.2 \times 10^9 \approx 98\ \text{TFLOP skipped} \qquad 6{,}000 \times 147{,}456\ \text{B} \approx 885\ \text{MB stored once}
Rule of thumb: a forward pass costs about 2 x parameters operations per token, attention aside. The stored blocks serve every request that starts the same way.

Lay out a prompt for hits

PositionPut hereNever here
FirstTool definitions in a fixed order, system prompt, policy textTimestamps, request IDs, user names
MiddleLong shared documents, examplesLists shuffled per request, JSON with unstable key order
LastThe conversation, appended onlyEdits to earlier turns
Very lastToday's date, the user's message, retrieved snippets
The Manus team, writing in July 2025, calls KV-cache hit rate the most important metric for a production agent and warns about timestamps at the start of the system prompt.

Sharing patterns

Radix trees

SGLang stores cached prefixes in a radix tree: a tree whose edges are labelled with runs of tokens. A path from the root spells a prefix, and the node at its end points at the cached keys and values. A new request walks down as far as its tokens match, reuses everything on that path, and adds a new branch for the rest. Agent loops, few-shot prompts, tree search and multi-turn chat all produce this shape.

Three conversations in one tree

The system prompt is stored once. Each turn of chat A extends its own path, so the whole history is reused next turn.

Two ways to find a cached prefix

vLLMSGLang
Indexhash table from block hash to blockradix tree of token runs
Unitfull blockspages of one token in the paper
Matchleading blocks, one by onewalk down the tree
EvictionLRU free queue, a request's last block firstLRU, leaves first
Isolationcache salt in the first block's hashnot covered in the paper
Scheduling ideanot part of the hashing designlonger matches first for batch work
From vLLM's prefix caching design page and the SGLang paper, read 27 November 2026.

Both reach the same goal by different roads. The SGLang paper reports up to 6.4 times higher throughput than other systems of the time across its workloads.

Eviction

When the pool is full

What a typical engine does

  1. 1

    Count users per block

    Every block has a reference count: the number of running requests reading it. A block with a count above zero is never evicted.

  2. 2

    Free means cached

    When a request ends, its full blocks keep their hashes and join a free queue. They are free to reuse and still match until someone takes them.

  3. 3

    Oldest unused first

    New allocations take from the front of that queue: the least recently used block. If it was cached, its hash is dropped.

  4. 4

    Ends before starts

    vLLM adds a finished request's blocks to the queue in reverse order, so its last blocks go first. SGLang evicts leaves first. Both keep shared starts longest.

  5. 5

    Still full

    If every block is in use, the scheduler waits, or preempts a running request and recomputes it later.

  • Too little pool

    Hits fall as soon as traffic rises, because shared blocks are evicted between requests.

  • Too many tenants

    500 different 6,000-token prompts on Qwen3-8B need about 442 GB of cache. No single GPU holds that.

  • Bursty traffic

    A prompt used once an hour is gone by its next use unless a slower tier keeps it.

  • Long answers

    Decode-heavy work gains little: prefix caching only removes prefill.

Providers

Prompt caching in model APIs

Hosted APIs run the same mechanism on their own servers and pass part of the saving on. You pay less for input tokens that hit, and the first token arrives sooner. The rules differ in three ways: whether caching is automatic, how long entries live, and what a write and a hit cost. These change often, so every fact below carries the date we read it.

Prompt caching rules, last checked 27 November 2026

AnthropicOpenAIGoogle Gemini
Turn it oncache_control on blocks, or one top-level field for automaticautomatic on supported modelsimplicit by default on 2.5 and newer; explicit caches on some models
Ordertools, then system, then messageshash of the first tokens, tools includedcommon content first
Smallest prompt512 to 4,096 tokens by model1,024 visible tokens on GPT-5.6 and later2,048 on 2.5 models, 4,096 on newer
Lifetime5 minutes, or 1 hour; refreshed on each hit30 minutes default on GPT-5.6 and later, 12 hours optionexplicit: 60 minutes by default, settable
Cache read price0.1x input on most models, lower on some0.1x on GPT-5.6 and latercached tokens 90% off on Vertex AI
Cache write price1.25x for 5 minutes, 2x for 1 hourno surcharge statedstandard input; explicit adds storage per hour
Isolationnever across organizations; per workspace on the Claude APInever across organizationsnever across projects on Vertex AI
Shown incache_read_input_tokens, cache_creation_input_tokenscached_tokenstotal_cached_tokens
Read on the providers' own documentation pages on 27 November 2026. Prices and minimums depend on the model: check the page for yours before you plan.

Worked cost: 10,000 requests in an hour, 6,000 shared tokens each

no cache: 104×6,200×$3106=$186cache: $0.02⏟1 write+$18.00⏟9,999 reads+$6.00⏟200 new each≈$24\text{no cache: } 10^4 \times 6{,}200 \times \frac{\$3}{10^6} = \$186 \qquad \text{cache: } \underbrace{\$0.02}_{\text{1 write}} + \underbrace{\$18.00}_{\text{9,999 reads}} + \underbrace{\$6.00}_{\text{200 new each}} \approx \$24
Anthropic's listed rates for Sonnet 4.6 on 27 November 2026: 3permillioninputtokens,3 per million input tokens, 3.75 for a 5-minute write, $0.30 for a read. Traffic every few seconds keeps the 5-minute entry alive. Our example traffic. Output tokens are not included.

Caching was enabled but the bill did not drop

Each question maps to one rule in the provider table.

Tiers

Quantised caches and offloading

Two more levers make room. An 8-bit cache stores each number in one byte instead of two, which halves the per-token size and doubles the tokens that fit. vLLM supports FP8 caches with kv_cache_dtype and recommends calibrated scales for the best accuracy. Offloading moves blocks that are not needed right now to CPU memory, local disk or a shared store, and brings them back instead of prefilling again.

Hot, warm and cold blocks

Requests reach a cache-aware router in our serving cluster. The router sends a request whose prefix is cached to replica A and an unmatched one to replica B. In each replica, blocks evicted from GPU memory are kept in CPU memory. Replica A writes blocks back to a shared KV store, and replica B fetches them from the store to skip prefill.
A miss on the GPU can still be a hit in CPU memory or in the shared store. Fetching must be faster than prefilling for this to pay.

Where cached blocks can live

TierReachShared byExample
GPU memorythe running stepone replicavLLM and SGLang prefix caches
CPU memorya copy over PCIeone machineSGLang HiCache level 2
Disk or remote storenetwork or local diskmany replicas, if configuredSGLang HiCache level 3 with Mooncake and others, LMCache
SGLang's HiCache design page names GPU, host memory and storage back ends. LMCache's paper describes a layer that moves caches out of vLLM and SGLang for reuse across engines and queries.

Routing

Send each request to its cache

A cache only helps the replica that holds it. With ten replicas and random routing, a shared prefix gets computed ten times and each replica keeps its own copy. A cache-aware router looks at the first blocks of a prompt, or at a session or tenant ID, and sends the request where those blocks already are, unless that replica is overloaded. OpenAI's guide says the same about its own service: requests are routed by a hash of the first tokens, and very busy prefixes overflow to other machines.

Many tenants, one system prompt each

500 tenants send prompts with their system prompt first to a gateway in our platform, which turns the tenant ID into a cache salt. A router hashes the first blocks and sends each tenant to the same replica: tenants 1 to 250 to replica 1, tenants 251 to 500 to replica 2. Both replicas report hits and misses to metrics, which show hit rate per tenant.
Same tenant, same replica, same blocks. The salt stops one tenant's blocks from matching another tenant's prompt.

Safety

Shared caches can leak

A cache hit is faster than a miss, and that timing difference can reveal what someone else sent. In "Auditing Prompt Caching in Language Model APIs" (ICML 2025), Gu and co-authors detected caching through timing and found global cache sharing across users at seven providers, including OpenAI at the time. Providers now state their isolation, as the table above shows.

Bugs in cache memory are worse than timing. Cloudflare reported on 26 October 2026 that, from 27 August to 9 September 2026, 155 responses from one model on Workers AI contained data from other customers' requests. Their write-up names two causes: a prefill cache pool smaller than the model's context window, and an SGLang bug in disaggregated mode where an over-length request read stale cache pages. They resized the pool, patched SGLang to reject such requests before any transfer, and sent the fix upstream.

Do

  • Salt the cache per tenant, as vLLM's cache_salt does
  • Check that the cache pool can hold the longest allowed request
  • Clear or overwrite blocks before reuse where the engine allows it
  • Use a cryptographic block hash in multi-tenant setups

Avoid

  • One global cache across customers with secrets in prompts
  • Non-cryptographic block hashes when tenants share a server
  • Trusting that a rejected request read nothing
  • Assuming the KV cache is a response cache that stores answers

Debugging

Failure modes

SymptomLikely causeFix
Hit rate near zeroChanging text early in the prompt: time, IDs, tool orderStable first, volatile last; sort tools and JSON keys
Out of memory under loadPlanned for weights onlyBudget cache per request times concurrency
Sudden pauses mid-answerPool full: preemption and recomputeFewer concurrent requests, smaller cache, more memory
Hits fall at peakShared blocks evicted between usesBigger pool, offload tier, cache-aware routing
Agent gets slower and dearer each turnHistory rewritten, so the cache resetsAppend-only context; summarise at the end, not in place
Answers contain someone else's dataStale blocks read after a bugIsolation per tenant, pool sized for max context, patch the engine

Tools today

What to reach for

Tools, last checked 27 November 2026

ToolWhat it does for the cache
vLLMPaged blocks, automatic prefix caching, FP8 cache, hit-rate metrics
SGLangRadixAttention, HiCache tiers, cache-aware scheduling
LMCacheMoves caches out of vLLM and SGLang for reuse and transfer
MooncakeDistributed KV store used as an SGLang HiCache back end
NVIDIA Dynamo and llm-dDisaggregated serving and KV-aware routing
Provider prompt caching is in the table above.

Measure before you tune. vLLM exposes the counters vllm:prefix_cache_hits and vllm:prefix_cache_queries, both in tokens: the hit rate is the rise in the first divided by the rise in the second. Started with --enable-prompt-tokens-details, it also returns cached_tokens per request.

Summary

The whole topic in one minute.

Attention compares each new token's query with the keys of all earlier tokens and mixes their values. Those keys and values never change, so the model saves them: that is the KV cache. Prefill writes the whole prompt into it at once. Decode adds one token per step and reads everything back, so decode is limited by memory bandwidth, not arithmetic.

The cache size is 2 x layers x KV heads x head size x bytes per number x tokens. Read the first four from the model's config.json. Grouped-query attention, latent attention, sliding windows and 8-bit caches all attack one of those factors. Whatever is left decides how many requests fit next to the weights.

Engines store the cache in fixed blocks with a block table, which ends fragmentation and lets requests share blocks. A prefix cache keys each full block by a hash of its tokens and everything before it, so a hit needs an identical start. Put stable content first and changing content last, evict unused blocks least recently used first, isolate tenants, and route each request to the replica that already holds its prefix.

  • Keys and values of earlier tokens never change, so the model saves them: the KV cache.
  • Prefill writes the prompt into the cache at once and is compute-bound. Decode adds one token per step, reads the whole cache, and is memory-bound.
  • Bytes per token = 2 x layers x KV heads x head size x bytes. Qwen3-8B: 144 KiB, so 1.125 GiB for 8,192 tokens.
  • GQA, MQA, latent attention, sliding windows and 8-bit caches each shrink one factor.
  • Free memory after weights, divided by cache per request, is your concurrency.
  • PagedAttention stores the cache in blocks with a block table: little waste, easy sharing.
  • Prefix caching hashes each full block with everything before it. Same prefix, same blocks, free prefill.
  • Stable content first, volatile content last, history append-only.
  • Evict least recently used blocks that no running request holds. Route each request to its cache, and isolate tenants.

Sources