Prefix cache: reusing the work done on a shared prompt start
A prefix cache keeps the computed state for the opening part of a prompt, so later requests with the same opening skip that work. Use it when many requests share a long system prompt, tools or documents.
Prefix cache in 60 seconds
- What: the server stores the computed state for the start of a prompt and reuses it when a new request begins with the same tokens.
- Saves: the prefill work on the shared part, so time to first token falls and compute cost per request falls.
- Needs: an exact token match from the first token. One changed token near the start breaks the match for everything after it.
- Design rule: put stable content first (instructions, tools, policy) and variable content last (user question, timestamps).
- Does not change answers: the model output is the same as without the cache, apart from normal sampling variation.
Where this type fits
The prefix cache lives inside the model server, next to the KV cache and KV cache compression. The caching hub groups all three as server-side caches. The difference is scope. The KV cache serves one request. The prefix cache shares the KV cache between many requests.
The problem it solves
Most real prompts are long and repetitive. A support assistant may send a 3,000-token system prompt, a list of tool definitions and a policy document with every message. Only the last 50 tokens, the customer's question, are new. Without a prefix cache, the model reads the whole prompt from scratch on each request. This first stage is called prefill. It is compute-heavy and it happens before the first word of the answer appears, so users wait for it.
The waste scales with traffic. If a thousand requests an hour share the same 3,000 tokens, the server does the same prefill a thousand times. You pay in GPU time, and users pay in time to first token. Under load, the extra work also lengthens queues for everyone.
A prefix cache removes the repeat. The server computes the shared opening once, keeps the resulting key and value tensors, and starts each later request from that saved state. Only the new tokens need prefill.
How it works
- Tokenise: the server turns the incoming prompt into tokens.
- Match: it compares the tokens from the start against stored prefixes, usually in a tree or block table, and finds the longest match.
- Reuse: for the matched part it points the new request at the stored KV blocks instead of computing them.
- Prefill the rest: only the unmatched tokens go through prefill.
- Store: the new blocks are added to the cache, so later requests can match further.
- Evict: when memory is short, the least recently used blocks that no running request needs are removed.
Two research ideas make this practical. The PagedAttention paper (Kwon et al., 2023) stores the KV cache in fixed-size blocks, like pages of virtual memory. Blocks can then be shared between requests with little wasted memory. SGLang (Zheng et al., 2023) goes further with RadixAttention, which keeps the cache in a radix tree so requests with a shared prefix reuse it. A tree suits prompts that branch: many requests share the system prompt, and subsets share a document too.
Matching is strictly left to right. The model's state for token 500 depends on tokens 1 to 499. If token 3 changes, every state after it is different, so nothing after it can be reused. This is why a timestamp at the top of a prompt can wipe out the whole benefit.
A worked example
Acme runs a returns assistant. Every request starts with a 2,400-token system prompt, 600 tokens of tool definitions and a 1,000-token returns policy. That is 4,000 shared tokens. Each customer message adds about 60 tokens.
- Request A (9:00:01): a cold cache. The server processes 4,060 tokens and stores the first 4,000 as blocks.
- Request B (9:00:09): the first 4,000 tokens match exactly. The server reuses them and prefills only the 55 new tokens. Time to first token drops sharply.
- Request C (9:00:15): the team had added the line 'Current time: 09:00:15' to the top of the system prompt. Token 5 differs, so the match fails and all 4,055 tokens are processed again.
- The fix: move the time line to the end, after the policy and before the customer message. Now the shared 4,000 tokens match again.
- Request D (next day): the policy document is updated. The first 3,000 tokens still match, so those are reused, and the changed policy and later tokens are processed once and stored.
Building it
Most serving engines provide prefix caching as a setting. Your main job is prompt layout. The code shows a prompt builder that keeps the stable part first and byte-identical, and a small model of how a server matches prefixes.
import hashlib
SYSTEM = 'You are the Acme returns assistant. Follow the policy below.' # fixed text
TOOLS = '[tool definitions in a fixed order]' # sort once, never reshuffle
POLICY = '[returns policy v7]' # change only on a real update
def build_prompt(user_message, now_text, memory_note=''):
# Stable parts first, in a fixed order: the cache can match them.
stable = '\n'.join([SYSTEM, TOOLS, POLICY])
# Variable parts last: time, per-user notes and the question.
variable = '\n'.join(filter(None, [now_text, memory_note, user_message]))
return stable + '\n' + variable
class ToyPrefixCache:
"""Models block-wise matching; a real server stores GPU tensors, not strings."""
BLOCK = 16 # tokens per block, as in paged caches
MAX_BLOCKS = 10_000 # cap memory; evict least recently used beyond this
def __init__(self):
self.blocks = {} # chain hash -> last-used counter
self.clock = 0
def _chain(self, tokens):
h = ''
for i in range(0, len(tokens) - len(tokens) % self.BLOCK, self.BLOCK):
block = ' '.join(map(str, tokens[i:i + self.BLOCK]))
# Each hash includes the one before it: a change early breaks every later block.
h = hashlib.sha256((h + block).encode()).hexdigest()
yield h
def match(self, tokens):
"""Return how many leading tokens are already cached."""
self.clock += 1
matched = 0
for h in self._chain(tokens):
if h not in self.blocks:
break # first miss ends the shared prefix
self.blocks[h] = self.clock
matched += self.BLOCK
return matched
def store(self, tokens):
for h in self._chain(tokens):
self.blocks[h] = self.clock
while len(self.blocks) > self.MAX_BLOCKS:
oldest = min(self.blocks, key=self.blocks.get)
del self.blocks[oldest] # evict the least recently used block
Notice the chained hash. Each block's hash includes the hash before it, so a changed early token changes every later key. This mirrors the left-to-right rule in real servers. Notice also the cap on blocks and the eviction. Cached prefixes take GPU memory, so they must be bounded.
Design decisions
- Prompt order: stable first, variable last. Make this a rule in code review, since one stray timestamp can undo the saving.
- Shared or per-tenant prefixes: share the system prompt freely, but keep prefixes that contain one customer's documents scoped to that customer. Check your engine's isolation behaviour before mixing tenants.
- Memory budget: cached blocks compete with running requests for GPU memory. Cap the cache and let the engine evict least recently used blocks.
- Affinity routing: send requests with the same prefix to the same replica, since each server has its own cache. Route by a hash of the prefix or a session id.
- Warm-up: after a deploy, send a few requests with the common prefix before taking real traffic, so the first users do not pay the cold cost.
- Versioning: when you edit the system prompt, expect a cold start. Roll out prompt changes gradually, not on every replica at once.
- Failure handling: a miss is not an error. The request is simply slower, so alert on hit rate and not on single misses.
Measuring it
- Prefix hit rate: cached prompt tokens divided by total prompt tokens, from server metrics. This is more useful than the share of requests with any hit.
- Time to first token: compare p50 and p95 for requests with a long hit against cold requests.
- Prefill tokens per request: the average number of tokens actually computed. It should fall as the hit rate rises.
- Cost per request: GPU seconds or billed input tokens per request before and after enabling the cache.
- Output equivalence: with sampling fixed, check that outputs with and without the cache are equal on a test set, to catch bugs in block reuse.
- Eviction rate: how often prefixes are evicted before reuse. A high rate means the cache is too small or prefixes are too varied.
def prefix_hit_rate(request_logs):
"""request_logs: list of dicts with prompt_tokens and cached_tokens."""
total = sum(r['prompt_tokens'] for r in request_logs)
cached = sum(r['cached_tokens'] for r in request_logs)
return cached / total if total else 0.0
When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Long system prompt shared by all requests | Yes | The shared opening is computed once and reused. |
| Many questions about the same long document | Yes | The document sits in the prefix and only the question is new. |
| Agents that resend a growing history each step | Yes | Earlier steps stay the same, so only the newest step is new. |
| Short prompts under a few hundred tokens | No | There is little prefill to save. |
| Prompts that start with a timestamp or user id | Fix the prompt first | Variable content at the start prevents any match. |
| Prompts that differ for every request | No | There is no shared opening to reuse. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | No change in answers, because the same state is reused | Run an equivalence check after each engine upgrade. |
| Latency | Lower time to first token on a hit, normal on a miss | Track p95, since misses set the worst case. |
| Cost | Less prefill compute per request, which lowers cost at high volume | Measure the token-weighted hit rate, not the request hit rate. |
| Complexity | Prompt layout becomes a design constraint | Add a prompt-building helper and a test that checks the stable part is unchanged. |
| Failure modes | Cross-tenant leakage if isolation is wrong, and silent loss of hits after small prompt edits | Scope private prefixes and alert on hit-rate drops after releases. |
Compared with related types
The KV cache works inside one request. The prefix cache extends that reuse across requests, but only for an identical opening. Compared with the exact-match response cache, the prefix cache still runs the model and writes a fresh answer. It only skips repeated reading. The response cache skips the model entirely, but only when the whole request repeats.
KV cache compression is a good partner. Shared prefixes can be large, and compressing them leaves room for more of them to stay resident.
What this means for your role
Common mistakes
Further reading
- Types of caching in AI systems: the hub that compares every cache type.
- SGLang, Zheng et al., 2023: its RadixAttention technique keeps KV cache in a radix tree so requests that share a prefix reuse it.
- PagedAttention, Kwon et al., 2023: stores the KV cache in fixed-size blocks, like pages of virtual memory, which reduces wasted memory and lets requests share blocks.
- KV cache: the per-request cache that prefix caching shares.
- Inference serving: scheduling, batching and memory in a model server.
A prefix cache rewards tidy prompts. Keep the shared part first and unchanged, and the server does the repeated work only once.