Pidoku

Prefix Caching

Module 17 Lesson 17.f 55 min Difficulty 3/5

Prerequisites 12.m, 17.e


Before you start: words you need#

WordPlain meaning
PrefixThe beginning of a prompt: the first n tokens.
Causal modelA model in which each token’s keys and values depend only on the tokens before it.
Hash chainEach block’s fingerprint includes the previous block’s fingerprint, so it identifies the whole prefix.
Cache hitA block of this prompt is already in the KV cache, so it need not be computed.
Extra keysAnything besides token IDs that changes the KV: a LoRA adapter, an image, a salt.
cache_saltA per-request value that keeps one tenant’s cached prefixes invisible to others.
APCAutomatic prefix caching, vLLM’s name for the feature.
Copy-on-writeCopying a shared block into a private one before writing into it.

1. What is it?#

In a causal language model, the keys and values computed for token i depend only on tokens 0 to i. Two prompts that begin with the same tokens therefore have identical KV cache contents for that shared beginning. vLLM exploits this without being asked: every full block gets a hash that identifies the entire prefix up to and including it, and before a new request is scheduled the engine looks its hashes up. Every block that matches is reused; only the rest of the prompt is computed.

System prompts, few-shot examples, long documents queried repeatedly and the earlier turns of a conversation all become nearly free. It is on by default and never changes outputs. Whether it works for you depends almost entirely on what your prompts have at the front. The general idea, and provider-side prompt caching, are in 12.m; this lesson reads vLLM’s implementation.

Facts checked on 12 November 2026 against vLLM v0.32.0.


2. Why does it matter?#

Prefill is the expensive, compute-bound part of a request (12.c). In chat and agent workloads, most of each prompt is repeated: the same system prompt and tool list on every call, the whole conversation so far on every turn. Without caching, a 20-turn agent loop recomputes its growing history 20 times. With caching, each turn computes only what is new.

It also saves memory: fifty concurrent requests with a common 4,000-token system prompt hold one copy of those 250 blocks, not fifty.


3. Simple analogy#

A library that files photocopies of book chapters under a label made from the chapter and the label of the chapter before it. If you ask for chapters 1 to 5 of a book and the library has chapters 1 to 3 on file, you get those instantly and only chapters 4 and 5 are copied. Because each label includes the previous one, chapter 3 of a different book can never be confused with yours, even if its text is identical.


4. Tiny example#

block size 16, system prompt 50 tokens

request 1: system (50) + question A (20) = 70 tokens   → nothing cached, compute 70
request 2: system (50) + question B (20) = 70 tokens   → blocks 0,1,2 match (48 tokens)
                                                          compute 22

The system prompt is 50 tokens but only 48 hit: hits come in whole blocks, and the 4th block (tokens 48 to 63) mixes system-prompt tokens with the new question.


5. Technical explanation#

The hash is a chain#

A block’s KV depends on every token before it, so its identity must too. Hashing the full prefix for every block would cost time quadratic in the prompt length. Instead each block’s hash includes its parent’s hash (vllm/v1/core/kv_cache_utils.py):

Python
def hash_block_tokens(hash_function, parent_block_hash, curr_block_token_ids, extra_keys=None):
    if not parent_block_hash:
        parent_block_hash = NONE_HASH
    curr_block_token_ids_tuple = tuple(curr_block_token_ids)
    return BlockHash(
        hash_function((parent_block_hash, curr_block_token_ids_tuple, extra_keys))
    )
InputWhy it is there
Parent block’s hashCarries the identity of everything earlier. Equal hashes imply equal prefixes.
This block’s 16 token IDsThe block’s own content
Extra keysAnything else that changes the KV for the same tokens (below)

Two properties follow. Hashing a prompt is linear in its length. And if block k misses, every later block must miss too, so the lookup can stop at the first miss.

Where and when hashes are computed#

Not in the scheduler. When a request arrives in the engine core, the input thread builds the Request object and hashes it immediately, overlapping with whatever the GPU is doing (16.d):

Python
req = Request.from_engine_core_request(request, self.request_block_hasher)

The hasher covers only new full blocks, so it is called again cheaply each time generated tokens complete another block:

Python
while True:
    end_token_idx = start_token_idx + hash_block_size
    if end_token_idx > num_tokens:
        # We only hash full blocks
        break

By the time the scheduler considers the request, request.block_hashes is already a finished list.

The lookup#

In pass 2 of schedule(), once per request, when it has computed nothing yet, KVCacheManager.get_computed_blocks runs:

Python
# NOTE: When all tokens hit the cache, we must recompute the last token
# to obtain logits. Thus, set max_cache_hit_length to prompt_length - 1.
# This can trigger recomputation of an entire block, rather than just
# the single last token, because allocate_slots() requires
# num_computed_tokens to be block-size aligned. ...
max_cache_hit_length = request.num_tokens - 1
computed_blocks, num_new_computed_tokens, num_uncached = (
    self.coordinator.find_longest_cache_hit(request.block_hashes, max_cache_hit_length)
)

and inside, for an ordinary full-attention model (FullAttentionManager.find_longest_cache_hit):

Python
# Phase 1: longest run of cached full blocks from the start. A missing
# block implies every later block misses too (chained hashes).
for block_hash in itertools.islice(full_block_hashes, max_length // block_size):
    cached_block = block_pool.get_cached_block(block_hash, kv_cache_group_ids)
    if not cached_block:
        break
    for computed, cached in zip(computed_blocks, cached_block):
        computed.append(cached)

The matching blocks are then touched (17.e) and placed at the start of the request’s block table. The request begins with num_computed_tokens equal to the hit length.

Three details shape the numbers you see:

  • Hits come in whole blocks. A 50-token shared prefix gives a 48-token hit.
  • The last token is always computed. The cache stores keys and values, not the model’s output. To sample the first new token the model must run on at least one position. So the largest hit is num_tokens − 1, rounded down to a block: an identical 64-token prompt sent twice hits 48 tokens the second time, not 64.
  • With EAGLE speculative decoding, one more block is dropped from the hit, because the draft head needs the tokens just before the generation point recomputed (18.f).

What else goes into the hash#

Identical tokens do not always mean identical KV. generate_block_hash_extra_keys adds whatever else matters:

Extra keyWhenWhy
("lora", name, path)The request uses a LoRA adapter (18.g)An adapter changes the weights and so the KV. The path is included “so that re-pointing a LoRA name at a different adapter” does not reuse old KV.
("mm", identifier, offset)The block overlaps an image, audio clip or video (18.h)The placeholder tokens are identical; the media’s content hash distinguishes them, the offset distinguishes position
("cache_salt", salt)First block only, when the request carries cache_saltTenant isolation (below)
("prompt_embeds", digest)The request supplies embeddings instead of token IDsThere are no meaningful token IDs to hash

cache_salt: isolation between tenants#

A shared prefix cache leaks a little information through timing. If a request’s first token comes back unusually fast, its prefix was already cached, which tells the sender that someone sent that prefix recently. An attacker can probe other users’ prompts one block at a time.

The defence is a per-request salt:

JSON
{
  "messages": [{"role": "user", "content": "..."}],
  "cache_salt": "tenant-7f3a"
}

The salt is hashed into the first block only. Since every later hash includes its parent’s, the whole chain differs, and requests with different salts never share a block. Requests with the same salt share normally. Choose one salt per trust boundary (per customer, typically) and set it in the gateway, not the client (23.i). Isolation costs cache hits across tenants and nothing else.

Which hash function#

--prefix-caching-hash-algo selects it:

ValueSerialisationHashNotes
sha256 (default)Python pickleSHA-256Collision-resistant
sha256_cborCanonical CBORSHA-256Reproducible across languages and versions; use when something outside vLLM must compute the same hashes
xxhashpicklexxHash 128-bitFaster; not cryptographic; needs the xxhash package
xxhash_cborCanonical CBORxxHash 128-bitFaster and reproducible; not cryptographic

A collision would hand one request another request’s KV: wrong output at best, another user’s context at worst. That is why the default is cryptographic, and why the config docstring warns that the alternatives “can cause undefined behavior or even leak private information in multi-tenant environments.”

The chain starts from a seed, NONE_HASH:

  • For SHA-256 it is derived from a fixed string ("vllm-none-hash"), so independent vLLM processes produce identical hashes for identical content. That lets a router, or another node, reason about what a replica has cached.
  • For xxHash it is random per process, because “a predictable seed would let an attacker precompute colliding blocks offline”; vLLM logs a warning saying so.
  • Setting PYTHONHASHSEED overrides both.

6. Under the hood#

The picture#

flowchart LR
  subgraph RQ["New request: system prompt + question B"]
    direction LR
    B0["block 0<br/><small>tokens 0–15</small>"] --> B1["block 1<br/><small>16–31</small>"] --> B2["block 2<br/><small>32–47</small>"] --> B3["block 3<br/><small>48–63</small>"] --> B4["tail<br/><small>64–69</small>"]
  end
  B0 -. "h0 = H(seed, tokens)" .-> M[(":i-search: <b>hash to block</b>")]
  B1 -. "h1 = H(h0, tokens)" .-> M
  B2 -. "h2 = H(h1, tokens)" .-> M
  B3 -. "h3 = H(h2, tokens)" .-> M
  M -->|"h0, h1, h2 found"| HIT[":i-check: <b>reuse 3 blocks</b><br/><small>48 tokens skipped</small>"]
  M -->|"h3 missing: stop"| MISS[":nvidia: <b>compute 22 tokens</b><br/><small>the question</small>"]
  class B0,B1,B2 memory
  class B3,B4 compute
  class M queue
  class HIT neutral
  class MISS compute

Requests and models that skip the cache#

Some requests must not read from the cache (they still populate it). skip_reading_prefix_cache is set for:

  • Prompt logprobs requested (prompt_logprobs or prompt_logprob_token_ids). The cache holds KV, not logits; scoring every prompt token needs a real forward pass over all of them.
  • Pooling requests that need every token’s hidden state.

Prefix caching is switched off entirely at startup (ModelConfig.is_prefix_caching_supported) for encoder-decoder models, attention-free models (pure state-space models; the source calls their support “still experimental”), and the same pooling models that cannot chunk (17.b). Hybrid attention/state-space models are supported (17.i).

Finer than a block: --prefix-match-unit#

For ordinary models the hashing granularity equals the block size, 16 tokens. Some hybrid attention/state-space models need much larger physical blocks, sometimes 1,024 tokens (17.i). With hits rounded down to a block, a 1,000-token shared system prompt would then never hit.

--prefix-match-unit decouples the two. Hashes are computed every prefix_match_unit tokens (say 64) while memory is still managed in large blocks, and a hit may land on a 64-token boundary inside a physical block: find_longest_cache_hit has a “Phase 2 (fine-grained only)” that probes the first non-full block’s interior boundaries, longest first. The new request then cannot write into the shared block, so the scheduler performs a copy-on-write: the block is copied into a fresh one the request owns. Those copies travel to the worker in SchedulerOutput.kv_cache_block_copies.

In v0.32.0 these partial hits are enabled only when every cache group supports them, which in practice means hybrid models with Mamba cache mode align (the default when prefix caching is on). For a standard decoder-only model none of this is active: unit and block size are both 16.

Why your hit rate is low#

Because the chain starts at token 0, a difference at position p invalidates everything from block ⌊p/16⌋ onward. The cache rewards prompts whose stable material comes first.

PatternEffect
Current date or time at the top of the system promptZero hits across requests in different minutes
User name or ID near the topHits only within one user
Retrieved documents before the instructions, in varying orderHits stop at the first document that differs
Tool definitions in a different order per requestHits stop where the order diverges
History rewritten or summarised each turnHits stop where the rewrite begins
A different cache_salt, LoRA adapter or imageNo sharing, by design

Order prompts from most stable to least: fixed instructions, tool definitions, long shared documents, conversation history, and last the new message and anything volatile.

Multi-turn chat is the best case. Turn n+1 contains turn n’s prompt and its answer as a prefix, and the answer’s blocks were cached as they were generated: output tokens fill blocks and receive hashes exactly like prompt tokens. One caveat: the hit depends on the chat template rendering the earlier assistant turn to the same tokens the model produced. Templates that drop reasoning text from past turns break the chain at that point.

The hash chain and the lookup in Go#

SHA-256 as in the default configuration. Eight requests show every rule above.

Go
package main

import (
	"crypto/sha256"
	"encoding/binary"
	"fmt"
)

const blockSize = 16

type hash [32]byte

// noneHash seeds the chain: the "parent" of the first block.
var noneHash = sha256.Sum256([]byte("vllm-none-hash"))

// hashBlock mirrors hash_block_tokens: hash(parent, tokens of this block, extra keys).
func hashBlock(parent hash, tokens []int, extra string) hash {
	h := sha256.New()
	h.Write(parent[:])
	for _, t := range tokens {
		var b [8]byte
		binary.LittleEndian.PutUint64(b[:], uint64(t))
		h.Write(b[:])
	}
	h.Write([]byte(extra))
	var out hash
	copy(out[:], h.Sum(nil))
	return out
}

// blockHashes returns one hash per FULL block. The salt enters the first block only;
// every later block inherits it through its parent.
func blockHashes(tokens []int, salt string) []hash {
	var hs []hash
	parent := noneHash
	for end := blockSize; end <= len(tokens); end += blockSize {
		extra := ""
		if end == blockSize && salt != "" {
			extra = "cache_salt=" + salt
		}
		parent = hashBlock(parent, tokens[end-blockSize:end], extra)
		hs = append(hs, parent)
	}
	return hs
}

type cache map[hash]bool

// lookup returns the number of tokens that can be skipped.
func (c cache) lookup(tokens []int, salt string) int {
	// At least the last token must be recomputed to obtain logits.
	maxHit := len(tokens) - 1
	hit := 0
	for _, h := range blockHashes(tokens, salt)[:maxHit/blockSize] {
		if !c[h] {
			break // chained hashes: one miss means every later block misses too
		}
		hit += blockSize
	}
	return hit
}

func (c cache) store(tokens []int, salt string) {
	for _, h := range blockHashes(tokens, salt) {
		c[h] = true
	}
}

// seq makes n deterministic token IDs from a seed.
func seq(seed, n int) []int {
	out := make([]int, n)
	for i := range out {
		out[i] = (seed*7919 + i*104729) % 50000
	}
	return out
}

func join(parts ...[]int) []int {
	var out []int
	for _, p := range parts {
		out = append(out, p...)
	}
	return out
}

func main() {
	system := seq(1, 50) // a 50-token system prompt
	userA := seq(2, 20)
	userB := seq(3, 20)
	answerA := seq(4, 30)
	followUp := seq(5, 12)

	c := cache{}
	// report looks a prompt up, then stores it together with the answer the model
	// generated for it: output tokens fill blocks and are cached like prompt tokens.
	report := func(name string, prompt []int, salt string, generated []int) {
		hit := c.lookup(prompt, salt)
		fmt.Printf("%-46s %4d tokens  cached %4d  computed %4d\n",
			name, len(prompt), hit, len(prompt)-hit)
		c.store(join(prompt, generated), salt)
	}

	report("1. first request", join(system, userA), "", answerA)
	report("2. same system prompt, different question", join(system, userB), "", nil)
	report("3. next turn of conversation 1", join(system, userA, answerA, followUp), "", nil)
	report("4. timestamp inserted before the system prompt", join(seq(9, 1), system, userA), "", nil)
	report("5. request 1 again, with cache_salt=tenant-b", join(system, userA), "tenant-b", nil)
	report("6. the same, from tenant-b again", join(system, userA), "tenant-b", nil)
	report("7. a 64-token prompt, sent for the first time", seq(7, 64), "", nil)
	report("8. exactly the same 64-token prompt again", seq(7, 64), "", nil)
}

Output:

1. first request                                 70 tokens  cached    0  computed   70
2. same system prompt, different question        70 tokens  cached   48  computed   22
3. next turn of conversation 1                  112 tokens  cached   96  computed   16
4. timestamp inserted before the system prompt   71 tokens  cached    0  computed   71
5. request 1 again, with cache_salt=tenant-b     70 tokens  cached    0  computed   70
6. the same, from tenant-b again                 70 tokens  cached   64  computed    6
7. a 64-token prompt, sent for the first time    64 tokens  cached    0  computed   64
8. exactly the same 64-token prompt again        64 tokens  cached   48  computed   16

How to read it: (2) a 50-token shared prefix gives a 48-token hit, three whole blocks. (3) the follow-up turn reuses the previous prompt and answer. (4) one token at the front destroys everything. (5) a different salt shares nothing; (6) the same salt shares again. (8) an identical prompt hits all but its last block, because the final token must be computed.


7. Performance implications#

For a request with P prompt tokens of which H hit:

prefill work  ∝  P − H        (was P)
decode work   unchanged
memory        the H tokens' blocks are shared, not duplicated
  • TTFT falls roughly in proportion to (P − H) / P.
  • Tokens per second during generation do not change. The feature docs say caching “does not bring performance gain when vLLM spends most of the time generating answers”, nor when requests share no prefix.
  • Hashing costs a little CPU on the input thread, overlapped with GPU work. SHA-256 on long prompts is the usual reason people consider xxHash; measure before switching.

8. Production implications#

Measuring it#

SignalWhere
vllm:prefix_cache_queries, vllm:prefix_cache_hitsPrometheus counters, in tokens. Hit rate = hits ÷ queries over a window.
vllm:external_prefix_cache_queries, ..._hitsThe same for hits found through a KV connector (19.b)
vllm:prompt_tokens_cachedPrompt tokens served from cache
usage.prompt_tokens_details.cached_tokensPer response, with --enable-prompt-tokens-details
vllm:request_prefill_kv_computed_tokensHistogram of prompt tokens actually computed per request
The periodic log lineIncludes Prefix cache hit rate: N%

Statistics are recorded when a request is admitted, not when it is merely looked at, so a request that waits in the queue is counted once.

Getting more from it#

  • Design prompts with stable content first (the table above).
  • Route requests with the same prefix to the same replica (prefix-aware load balancing, 20.f), or share caches across replicas with a KV connector (14.l).
  • Use cache_salt for multi-tenant servers.

9. Common mistakes#

  1. Putting a timestamp or user ID at the top of the system prompt. It disables caching for everyone.
  2. Expecting a 100% hit on an identical prompt. The last block is recomputed.
  3. Switching to xxHash in a multi-tenant service without weighing collision risk.
  4. Expecting faster decoding. Only prefill gets cheaper.
  5. Requesting prompt logprobs and wondering why nothing hits. Those requests skip reading the cache.

10. Hands-on exercise#

  1. Change system to 47 tokens and to 49. What is the hit for request 2 in each case? How many tokens of padding would make a 47-token system prompt cache one more block, and is that ever worth it?
  2. Put a 1-token “date” after system and vary it between requests. What hit do you get?
  3. On a real server with --enable-prompt-tokens-details, send the same long prompt twice and read usage.prompt_tokens_details.cached_tokens. Then add "cache_salt": "x" and repeat.

11. Interview questions#

  1. Why does a block’s hash include the hash of the block before it?
  2. An identical prompt of exactly 160 tokens is sent twice. How many tokens are computed the second time?
  3. Why is the salt applied only to the first block, and why is that enough?
  4. Why is the SHA-256 seed fixed while the xxHash seed is random?
  5. What does --prefix-match-unit solve, and for which models?

12. Further reading#

Checked on 12 November 2026, against the v0.32.0 tag.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in