Types of caching in AI systems
AI requests are slow and expensive because the model reads every token again each time. Caching reuses work at several layers. This guide explains each type, how it works, how to keep it correct, and when it hurts more than it helps.
Caching for AI in 60 seconds
- Why cache: a model call costs money and time in proportion to the tokens it reads and writes.
- Six layers: the model itself reuses processed tokens (KV cache, prefix cache); the application reuses answers (exact and semantic caches); and it reuses embeddings and search results.
- Correctness is the hard part: an answer can be cached only if the key includes everything that changes it: model, settings, prompt template, user permissions, and document version.
- Biggest win for most teams: stable prompt prefixes and embedding caches, which are safe and easy to measure.
- Riskiest cache: semantic caching, because a similar question is not always the same question.
Why AI needs caching more than ordinary web services
A web page is usually cheap to build. A model response is not. Each token the model reads or writes costs compute, and long prompts repeat the same instructions, documents, and tool descriptions on every request. Most of the work in a busy AI product is therefore repeated work. Caching removes the repetition, and the saving shows up twice: in the bill and in the time the user waits.
The difference from a web cache is the question of equality. Two web requests for the same URL return the same page. Two AI requests with the same words may need different answers if the model, the temperature, the user's permissions, or the document version differ. Every AI cache therefore needs a key that captures everything the answer depends on. Most caching bugs in AI systems are key bugs.
The layers at a glance
A request can meet several caches on its way to an answer. The order below matches cost: the cheapest checks come first, so a hit there avoids the rest. The model-side caches sit inside the inference server and are used whether or not the application caches anything.
A guide to each type
Every type on this page has its own in-depth guide with a diagram, a worked example, code, design decisions, metrics, and notes for your role.
- KV cache
- KV cache compression
- Prefix cache
- Exact response cache
- Semantic cache
- Embedding cache
- Retrieval cache
Part 1: caches inside the model server
These caches are managed by the inference engine that runs the model. You usually enable or configure them rather than build them.
1. KV cache
When a model generates text, it looks back at every earlier token through attention. For each token, the model computes two vectors called the key and the value. Recomputing them for the whole prompt on every new token would be wasteful, so the engine stores them in memory: this is the KV cache. Generating token number 500 then needs only the work for that one new token, plus lookups into the stored keys and values.
The cost is memory. The KV cache grows with the number of tokens in every active sequence, multiplied by the number of layers and the size of the attention heads. A long context or a large batch can fill the GPU before compute runs out. Engines therefore allocate the cache in small blocks and free them as sequences finish, which is the idea behind paged attention. The operational lesson is simple: context length is a memory budget, not just a limit on input.
# Rough KV cache size for one sequence.
# Keys and values are stored per layer, per token, per KV head.
def kv_cache_bytes(tokens, layers, kv_heads, head_dim, bytes_per_value=2):
# 2 = one key vector and one value vector
return 2 * tokens * layers * kv_heads * head_dim * bytes_per_value
# Example: 32 layers, 8 KV heads, head size 128, 16,000 tokens, 16-bit values
size = kv_cache_bytes(tokens=16_000, layers=32, kv_heads=8, head_dim=128)
print(f'{size / 1024**3:.2f} GiB for one sequence')
Read the full guide to the kv cache: how it works, a worked example, code, design decisions, and how to measure it.
2. KV cache compression and quantisation
When memory is the limit, the engine can store the cache in less precision, for example 8-bit instead of 16-bit values, or keep fewer entries by evicting tokens that the model rarely attends to. Both save memory and let more sequences run at once. Both can lower quality, sometimes only on long or precise tasks, so measure answers on your own evaluation set before you turn them on. Compression is a trade of memory for accuracy, and the right setting depends on the task.
Read the full guide to the kv cache compression: how it works, a worked example, code, design decisions, and how to measure it.
3. Prefix (prompt) cache
Many requests begin with the same material: a system prompt, a tool list, a long policy document, or an earlier part of a conversation. A prefix cache keeps the processed state of that shared beginning, so a later request that starts the same way skips the work for the shared part. Only the new suffix is processed. This is often the biggest saving for chat products and document question answering, because the shared part is the largest part of each request.
Prefix caching depends on exact matching of the beginning of the prompt. A timestamp, a random ID, or a reordered tool list in the first lines breaks the match, and the cache never hits. Place stable content first and changing content last.
# Illustrative: keep the cacheable part first and identical across requests.
SYSTEM_PROMPT = 'You are a support assistant for Acme. Follow the policy below.' # never changes
POLICY_DOC = load_policy_text() # changes only when the policy is republished
def build_messages(user_question, retrieved_chunks):
return [
{'role': 'system', 'content': SYSTEM_PROMPT + '\n\n' + POLICY_DOC}, # cacheable prefix
{'role': 'user', 'content': f'Context:\n{retrieved_chunks}\n\nQuestion: {user_question}'}, # varies per request
]
# Bad: putting the current time or a request ID into SYSTEM_PROMPT breaks the prefix cache for every call.
Read the full guide to the prefix cache: how it works, a worked example, code, design decisions, and how to measure it.
Part 2: caches the application controls
These caches sit in front of the model. They are the ones you design, measure, and sometimes regret, so the rest of this guide spends most of its time on them.
4. Exact-match response cache
The simplest application cache stores a complete answer under a key made from the request: the model name, the settings, the messages, and any tool definitions. An identical request returns the stored answer without calling the model. This is safe only when the answer is repeatable. With a sampling temperature above zero, the same request may legitimately produce different text, so caching the first one changes the behaviour. Keep this cache for deterministic settings, for shared, non-personal questions, and for answers with a short, explicit lifetime.
# Illustrative: cache only deterministic, non-personal requests.
# cache is a key-value store with expiry (for example, Redis); call_model() is a placeholder.
import hashlib, json
def cache_key(model, settings, messages, tools, policy_version):
payload = json.dumps({'m': model, 's': settings, 'msgs': messages,
'tools': tools, 'policy': policy_version}, sort_keys=True)
return 'resp:' + hashlib.sha256(payload.encode()).hexdigest()
def answer_cached(request, user):
if request.settings.get('temperature', 1.0) != 0 or user.is_personal_request:
return call_model(request) # do not cache
key = cache_key(request.model, request.settings, request.messages,
request.tools, request.policy_version)
hit = cache.get(key)
if hit is not None:
return hit
answer = call_model(request)
cache.set(key, answer, ttl_seconds=3600) # short lifetime limits stale answers
return answer
Read the full guide to the exact response cache: how it works, a worked example, code, design decisions, and how to measure it.
5. Semantic cache
Users rarely ask the same question in exactly the same words. 'How do I reset my password?' and 'I forgot my password, what now?' want the same answer. A semantic cache embeds each question and stores the answer with its embedding. A new question searches the cache, and if a stored question is close enough, the stored answer is returned. The benefit is high hit rates on support and FAQ traffic. The risk is the false hit: two questions can be close in meaning and still need different answers, such as 'cancel my order' and 'cancel my subscription'. A similarity threshold controls the trade, and it has to be tuned on real traffic.
# Illustrative: return a cached answer only when the match is close enough.
# embed(), vector_cache and call_model() are placeholders.
SIMILARITY_THRESHOLD = 0.95 # raise it to reduce false hits; tune on real traffic
def semantic_answer(question, user):
if user.is_personal_request(question):
return call_model(question) # never serve another user's answer for personal data
vector = embed(question)
match = vector_cache.nearest(vector, top_k=1)
if match and match.score >= SIMILARITY_THRESHOLD and match.policy_version == CURRENT_POLICY:
return match.answer
answer = call_model(question)
vector_cache.add(vector, answer=answer, policy_version=CURRENT_POLICY, ttl_seconds=86400)
return answer
Read the full guide to the semantic cache: how it works, a worked example, code, design decisions, and how to measure it.
6. Embedding cache
Embedding a document is a real cost, and most documents do not change between runs. An embedding cache stores each vector under a hash of the text and the embedding model's name and version. When the same text appears again, the stored vector is reused. The cache is safe and easy to measure, which makes it the first cache most teams should add. The key must include the model version, because vectors from two models are not comparable.
Read the full guide to the embedding cache: how it works, a worked example, code, design decisions, and how to measure it.
7. Retrieval-result cache
Popular queries, such as the top questions about a product, hit the search index again and again. A retrieval-result cache stores the list of matching chunk IDs for a query, with a short lifetime. It must be invalidated when the index changes, or users see removed documents. Store the index version in the key, and the cache expires itself when the index is rebuilt.
Read the full guide to the retrieval cache: how it works, a worked example, code, design decisions, and how to measure it.
Keeping caches correct
Every cache needs three answers: what the key contains, how long an entry lives, and what removes it early. For AI caches the key is the hard part. It should include the model and its version, the sampling settings, the prompt template version, the policy or system prompt version, the index version when retrieval is used, and the user's access group when the answer depends on permissions. Leave any of these out and the cache will eventually serve an answer that is wrong for someone.
- Key by everything that changes the answer: model, settings, templates, policy version, index version, and access group.
- Set a lifetime by how fast the content changes: minutes for news, days for stable policies, and until-republished for reference documents.
- Invalidate on change: bump a version number in the key when a template, policy, or index changes, so old entries are never read again.
- Protect against stampedes: when a popular entry expires, many requests may miss at once. Let only one request rebuild it while the others wait or receive the stale value.
- Never share personal answers: a cache that serves one user's private answer to another is a data leak, not a performance feature.
# Illustrative: only one request recomputes an expired entry; the rest wait briefly.
# lock is a distributed lock (for example, Redis SET NX with expiry); cache and call_model() are placeholders.
import time
def get_or_build(key, build, ttl_seconds=600):
value = cache.get(key)
if value is not None:
return value
if lock.try_acquire(f'build:{key}', ttl_seconds=30):
try:
value = build()
cache.set(key, value, ttl_seconds=ttl_seconds)
return value
finally:
lock.release(f'build:{key}')
for _ in range(50): # wait up to about 5 seconds for the builder
time.sleep(0.1)
value = cache.get(key)
if value is not None:
return value
return build() # give up waiting and compute directly
The types compared
| Cache | Where it lives | What it saves | Main risk | Start here? |
|---|---|---|---|---|
| KV cache | Inference engine memory | Recomputing attention over earlier tokens | Memory use grows with context and batch size | Enabled by default in most engines |
| KV compression | Inference engine memory | Memory, so more sequences fit | Quality loss on long or precise tasks | Only when memory is the bottleneck |
| Prefix cache | Inference engine or provider | Processing of a shared prompt beginning | Breaks when the prefix changes | Yes, with stable prompt structure |
| Exact response cache | Application | A whole model call | Stale or wrong answers for changing content | Yes, for deterministic, non-personal requests |
| Semantic cache | Application | Calls for near-duplicate questions | False hits between similar questions | Only after measuring false hits |
| Embedding cache | Application | Re-embedding unchanged text | Mixing vectors from different model versions | Yes, first |
| Retrieval-result cache | Application | Repeated index searches | Serving removed or old documents | Yes, with index versioning |
Choosing a caching strategy
- Measure first. Log prompt tokens, output tokens, cache hits, and latency for a week. The biggest repeated part is where caching pays off.
- Enable the model-side caches that your inference engine or provider offers, and structure prompts so the shared part comes first.
- Add an embedding cache before anything else in the application layer. It is safe and cheap.
- Add an exact response cache only for deterministic requests with a short lifetime.
- Add a semantic cache only when a sample of real traffic shows many near-duplicate questions, and tune its threshold against labelled examples of false hits.
What this means for your role
Common mistakes
Further reading
- Caching (system design component), the general pattern this page builds on.
- Rate limiting in AI systems, the companion control for cost and fairness.
Caching works best when measured. Start with the logs of prompt tokens and hit rates, then add one cache at a time and check its effect on both cost and answer quality.