Many requests begin with the same tokens. They may share a system prompt, tool definitions, a long document, few-shot examples, or an earlier conversation. Running prefill over that prefix every time repeats the same work.
Prefix caching stores the KV cache produced for a token prefix and reuses it when a later request begins with the same prefix under a compatible model configuration. It reduces repeated prefill work. It does not reduce the cost of decoding new output tokens.
In this post, you will learn about:
- How a cached token prefix avoids repeated prefill work
- How block identity and compatibility determine safe cache reuse
- How prompt layout and cache capacity affect the benefit
Let’s get started.

Prefix Caching and Prompt Reuse.
Photo by K. Mitch Hodge. Some rights reserved.
Overview
This post is divided into five parts; they are:
- Reusing Prefill Work
- Finding the Longest Cached Prefix
- Block Hashes, Radix Trees, and Compatibility
- Designing Prompts for Reuse
- Capacity and Measurement
Reusing Prefill Work
During prefill, every layer computes keys and values for every prompt token. If a later request has the same first $P$ tokens, those cached tensors are reusable because causal attention prevents the first $P$ positions from depending on later tokens.
The cache hit occurs on token IDs, not similar-looking text. Whitespace, capitalization, chat templates, tool ordering, and tokenizer versions can all change the token sequence. Two prompts with the same meaning do not share cache state unless their encoded prefixes match.
Suppose two prompts are:
|
1 2 |
[system instructions][tool definitions][document A][question 1] [system instructions][tool definitions][document A][question 2] |
The first three regions can be reused if they tokenize identically. Only the different question suffix needs new prefill work. The reused KV cache still occupies memory, so the system trades cache capacity for lower time to first token and higher prefill throughput.
Prefix caching differs from response caching. A response cache returns a previous answer. A prefix cache reuses internal model state and still runs the model on the unmatched prompt suffix and generated output.
Finding the Longest Cached Prefix
The following educational cache maps complete token prefixes to placeholder cache handles. It finds the longest stored prefix of a new request.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class TokenPrefixCache: def __init__(self): self.entries = {} def store(self, token_ids, cache_handle): key = tuple(token_ids) if not key: return self.entries[key] = cache_handle def longest_match(self, token_ids): tokens = tuple(token_ids) for length in range(len(tokens), 0, -1): key = tokens[:length] if key in self.entries: return length, self.entries[key] return 0, None cache = TokenPrefixCache() cache.store([10, 20, 30, 40], cache_handle="kv-blocks-7-9") matched, handle = cache.longest_match([10, 20, 30, 40, 50, 60]) print(matched, handle) |
The result is four matched tokens. A runtime would attach the corresponding KV blocks to the new request and prefill only tokens 50 and 60.
This dictionary is intentionally simple. It stores a separate tuple for every cached prefix and searches backward one token at a time. Production systems use block hashes, tries, radix trees, or related indexes. They also store the actual per-layer KV blocks, reference counts, and compatibility metadata.
The matched prefix must end at a boundary the runtime can address. A block-based implementation may reuse only complete blocks. If the block size is 16 tokens, a 47-token match may provide only 32 reusable tokens unless the runtime supports a finer matching unit.
Block Hashes, Radix Trees, and Compatibility
An exact-prefix table is simple but duplicates prefix keys. Two common alternatives organize shared prefixes more efficiently.
Block-hash lookup divides token IDs into fixed-size blocks. The key for a block includes the parent prefix hash and the tokens in the current block. The parent hash makes the same token block distinct when it follows a different prefix. A lookup walks blocks from the beginning until one is missing.
Radix-tree lookup stores token sequences along shared tree edges. Requests with a common prefix follow the same path and diverge only where their tokens differ. This supports longest-prefix matching and makes shared structure explicit.
Fixed-size hashes align naturally with a paged KV cache. Radix trees can represent variable-length edges and prefix relationships directly. The best choice depends on the cache allocator, lookup cost, eviction policy, and concurrency model.
Finding the same token prefix is only the first compatibility check. Reusing KV state is valid only when the model would produce the same keys and values for the shared positions. The cache identity must therefore include every relevant input, such as:
- Model architecture, checkpoint revision, and LoRA adapter
- Tokenizer and chat-template version used to produce the token IDs
- Position assignment and attention configuration
- KV cache dtype or quantization scheme
- Multimodal embeddings or other model inputs associated with the prefix
Random sampling settings do not affect prompt KV values and need not be part of this identity. Model-side randomness, however, must be disabled for ordinary inference because it could change the cached states themselves.
Position-dependent models require the cached prefix to occupy the same positions. Reusing a token sequence from position 1,000 at position zero is not generally valid. A runtime that edits or compresses history must treat the resulting position scheme as part of the cache identity.
Hash lookup adds another correctness concern: collisions. A collision-resistant hash reduces the chance that unrelated prefixes resolve to the same entry, but the runtime must still use a sufficiently strong hash or verify the complete identity before reuse.
Shared services must also consider isolation. A faster prefill can reveal that another request populated a guessed prefix. Cache namespaces or per-request salts can restrict reuse to an authorized trust group.
Reference counting prevents a block from being overwritten while active requests still use it. Copy-on-write lets requests share complete prefix blocks and allocate private blocks when their suffixes diverge. These mechanisms are similar to the branch sharing discussed in Decoding Policies in a Serving Engine.
When memory is scarce, cached but inactive blocks can be evicted. Eviction changes performance, not correctness: an evicted prefix is recomputed on the next request. Active blocks cannot be evicted without preemption, offload, or recomputation.
Designing Prompts for Reuse
Place stable content before request-specific content. A useful prompt order is:
|
1 2 3 4 |
[stable system prompt] [stable tool definitions] [shared examples or document] [user-specific question] |
If a timestamp, request ID, or user name appears near the beginning, it breaks the match for everything after it. You can move volatile metadata later when the application semantics allow it.
Canonicalization also helps. You can use one chat template, stable whitespace, deterministic tool ordering, and versioned shared documents. Do not normalize text after tokenization or change user content merely to improve cache hits; prompt meaning and security boundaries come first.
The following example enables automatic prefix caching and reports how many prompt tokens each request retrieves from the cache:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
from vllm import LLM, SamplingParams model_name = "facebook/opt-125m" shared_prefix = ( "You are an assistant answering questions about this policy.\n" "Customers may return an unused product within 30 days. " "A receipt or order number is required. " "Refunds are issued to the original payment method. " "Opened software and personalized products cannot be returned. " "Return shipping is free only when the product is defective. " "A refund is processed within five business days after inspection.\n" ) prompts = [ shared_prefix + "Question: How long is the return period?", shared_prefix + "Question: When is return shipping free?", ] llm = LLM( model=model_name, enable_prefix_caching=True, ) params = SamplingParams(temperature=0.0, max_tokens=32) for request_number, prompt in enumerate(prompts, start=1): output = llm.generate([prompt], params)[0] print( f"request {request_number}: " f"{len(output.prompt_token_ids)} prompt tokens, " f"{output.num_cached_tokens or 0} retrieved from cache" ) print(output.outputs[0].text) |
With a newly created engine, the first request starts with an empty prefix cache and should report no cached prompt tokens. It also populates cache blocks. The second request begins with the same policy text and should report a nonzero num_cached_tokens. The number may be smaller than the full shared prefix because vLLM reuses complete cache blocks.
This output demonstrates a cache hit more directly than elapsed time. Timing can vary because of warmup and unrelated system activity. For a performance benchmark, keep the generated output short, repeat the experiment, and label cold-cache and warm-cache measurements separately.
Capacity and Measurement
A cache admission policy decides which completed prefix blocks remain reusable. Keeping every prefix can displace active KV state or more valuable entries. Useful signals include prefix length, reuse frequency, recomputation cost, recency, and tenant quota.
Least-recently-used eviction is a reasonable baseline, but a long prefix that is reused hourly may save more computation than a short prefix reused every minute. Cost-aware policies can estimate saved prefill tokens per byte of retained cache.
When measuring the performance of prefix caching, the token-level hit rate is often more informative than request-level hit rate. A request that matches 4,000 of 4,100 prompt tokens and one that matches 16 of 4,100 are both request hits, but they save very different amounts of work.
Prefix caching mainly improves prefill. It will not materially improve a workload dominated by long generated answers, and it provides no benefit when prompts do not share exact prefixes.
Further Reading
Below are some resources you may find useful:
- vLLM documentation. Automatic Prefix Caching. This guide explains how to enable prefix caching and which workloads benefit.
- vLLM documentation. Automatic Prefix Caching Design. This document describes block hashes, reference counts, eviction, and cache salting.
- Lianmin Zheng et al. (2023). SGLang: Efficient Execution of Structured Language Model Programs. This paper introduces RadixAttention for automatic reuse across shared prompt prefixes.
- Woosuk Kwon et al. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. This paper describes block-based KV cache management and sharing.
Summary
In this post, you learned that prefix caching reuses KV state for an exact token prefix under a compatible model configuration. It saves repeated prefill work but does not accelerate generation after the prompt. Block hashes and radix trees provide efficient longest-prefix lookup, while reference counts and copy-on-write protect shared cache blocks.
You also learned that tokenization, model revisions, adapters, positions, cache formats, and security namespaces belong in the compatibility boundary.






No comments yet.