Retrieval-result cache: remembering which chunks a search returned
A retrieval-result cache stores the chunk ids that a search returned for a query and its filters. Use it when many users ask the same questions and the index changes less often than people ask.
Retrieval-result cache in 60 seconds
- What: a cache that maps a normalised query, its filters, and the index version to the list of chunk ids a search returned.
- What it saves: the embedding call, the vector search, and any reranking step. It does not skip the model's answer.
- Best for: repeated queries over a stable index, such as help-centre questions or popular product searches.
- Weak spots: stale results after the index changes, and results shown to users who should not see them.
- Key rule: put the index version and the access scope in the cache key, so a rebuild or a permission change cannot serve old data.
Where this type fits
In the Types of caching in AI systems hub, the retrieval-result cache is in the second family: caches controlled by the application. Unlike the KV cache and prefix cache, which live inside the model server, this one sits in your own code between the user's question and the search index. It is a close cousin of the general caching component, applied to the search step of a retrieval pipeline such as simple RAG.
The problem it solves
Retrieval is not free. For each question, a typical pipeline embeds the query into a vector, searches an index for the nearest chunks, applies filters, and often reranks the top results with a second model. Together these steps can take a fair share of the time before the language model (LLM) even starts to write. They also cost money, either as model calls or as search capacity you must provision for peak load.
Meanwhile, real traffic is repetitive. A few questions make up a large part of volume: 'how do I reset my password', 'what is your returns policy', and the like. Users phrase them in slightly different ways, but after cleaning up case, spacing, and punctuation, many become identical. Running the full search again for each one repeats work with the same result.
A retrieval-result cache remembers the answer to 'which chunks match this query under these filters'. On a repeat, the pipeline skips straight to building the prompt. The risk is that the remembered list may be wrong now: documents change, the index is rebuilt, or the user's permissions differ. So the design is mostly about the key and about when to throw entries away.
How it works
- Normalise the query: lower-case it, trim spaces, collapse repeated whitespace, and remove trailing punctuation. Keep meaning-bearing words intact.
- Build the key: combine the normalised query, the filters (such as product, language, and access scope), the retrieval settings (number of results, reranker on or off), and the index version.
- Look up: hash the key and check the cache.
- On a hit: read the stored chunk ids, fetch the chunk text from the document store, and go straight to the prompt.
- On a miss: embed the query, search the index, apply filters, rerank, and store the resulting chunk ids with a time to live.
- Invalidate: when the index is rebuilt, the version changes and old keys stop matching. Also expire entries by age.
The middle box carries the design. A key made only from the query text would be unsafe, since the same words can deserve different results under different filters or on a newer index. Putting filters and the index version into the key means a different situation is a different entry, and a miss is the safe outcome.
The warning box describes the cheapest invalidation method there is. You do not hunt for entries to delete. You change the version number, and every old key becomes unreachable. The stale entries then expire on their own.
A worked example
Acme Support runs a help bot over 4,000 article chunks. The index version is idx-2026-11-20. Retrieval is set to return the top 5 chunks after reranking.
Request 1. A customer in the UK types: ' How do I RESET my password? '
- Normalised query:
how do i reset my password. - Filters:
lang=en,scope=public. - Key material:
how do i reset my password | lang=en | scope=public | k=5 | rerank=on | idx-2026-11-20, hashed tok_7f3a.... - Lookup: miss.
- Search: embed the query, find the nearest 30 chunks, rerank, keep 5. Result:
[c-118, c-402, c-97, c-1203, c-55]. - Store: the five ids under the key, with a time to live of 6 hours.
- Prompt built from the five chunks, and the LLM answers.
Request 2, ten minutes later. A different customer types: 'how do I reset my password'. After normalising, the key is identical. Lookup: hit. The five ids come straight back, the chunk text is read from the document store, and the embedding call, the vector search, and the rerank are all skipped.
Request 3, a staff member. The same query, with scope=internal. The filter differs, so the key differs. Lookup: miss. This user gets internal chunks as well, and the entry is stored separately. The public entry cannot leak to staff-only content, and the staff entry cannot leak to the public.
Re-index. At night, the team rebuilds the index after editing the password article. The version becomes idx-2026-11-21. Every earlier key now fails to match. The next password question runs a fresh search and returns the updated chunks.
{
"key_parts": {
"query": "how do i reset my password",
"filters": { "lang": "en", "scope": "public" },
"settings": { "top_k": 5, "rerank": true },
"index_version": "idx-2026-11-20"
},
"value": { "chunk_ids": ["c-118", "c-402", "c-97", "c-1203", "c-55"] },
"stored_at": "2026-11-20T09:14:00Z",
"ttl_seconds": 21600
}Building it
The code below caches chunk ids, not chunk text. The ids are small, and the text is fetched fresh, so an edited article shows its latest wording even on a hit. The cache store, search function, and document store are placeholders.
# Placeholders: cache, search_index, reranker, and docs are stand-ins.
import hashlib
import json
import re
TTL_SECONDS = 6 * 3600 # bound staleness even if the version never changes
MAX_QUERY_CHARS = 500 # very long queries are rarely repeated; skip caching
TOP_K = 5
def normalise(query):
q = query.strip().lower()
q = re.sub(r"\s+", " ", q)
return q.rstrip("?.! ")
def make_key(query, filters, index_version):
parts = {
"q": normalise(query),
"filters": filters, # includes the access scope
"k": TOP_K,
"rerank": True,
"index": index_version, # a rebuild changes this and misses all
}
raw = json.dumps(parts, sort_keys=True)
return "ret:" + hashlib.sha256(raw.encode()).hexdigest()
def retrieve(query, filters, index_version):
cacheable = len(query) <= MAX_QUERY_CHARS
key = make_key(query, filters, index_version) if cacheable else None
if key:
hit = cache.get(key)
if hit is not None:
# Fetch fresh text by id so edits show up even on a hit.
# Drop ids that no longer exist instead of failing.
return [d for d in docs.get_many(hit["chunk_ids"]) if d is not None]
vector = embed(query) # placeholder
candidates = search_index.query(vector, filters=filters, limit=30)
ranked = reranker.rank(query, candidates)[:TOP_K]
chunks = [c for c in ranked]
if key and chunks: # do not cache empty results
cache.set(key, {"chunk_ids": [c.id for c in chunks]}, ttl=TTL_SECONDS)
return chunks
Design decisions
- What to store: store chunk ids, not text. Ids are compact and the text stays current. Store text only if your document store is slow and documents rarely change.
- Key contents: include the normalised query, filters, access scope, retrieval settings, and the index version. Leaving out any of these is the usual source of wrong results.
- Access control: the scope or user group must be part of the key, and the document fetch should still check permissions. Never share an entry between users with different rights.
- Time to live: a recommended default is a few hours for fast-changing content and a day for stable content. The TTL is a safety net, with the version change as the main invalidation.
- Storage: use a shared in-memory store so every application instance sees the same entries. A local per-process cache is simpler but fills slowly and duplicates work.
- Size and eviction: set a maximum entry count and evict the least recently used. Entries are small, so a modest store covers the popular queries.
- Failure handling: if the cache is down or slow, skip it and search directly. A cache must never be the reason a question fails.
Measuring it
- Hit rate: hits divided by lookups, tracked per index version. Compare it with the share of repeated queries in your logs to see if the key is too strict.
- Latency saved: the median retrieval time on a miss minus the time on a hit, multiplied by the hit rate, gives the average gain per request.
- Staleness errors: sample cached results and compare them with a fresh search. The share where the top chunks differ shows how stale entries get.
- Answer quality by path: run the same evaluation questions through cached and uncached retrieval. Quality should match, apart from small ranking changes.
- Cost avoided: embedding and reranking calls skipped, multiplied by their unit cost.
def staleness_rate(sample_queries, filters, index_version):
stale = 0
for q in sample_queries:
cached = cache.get(make_key(q, filters, index_version))
if cached is None:
continue
fresh_ids = [c.id for c in fresh_search(q, filters)] # bypasses the cache
overlap = len(set(cached["chunk_ids"]) & set(fresh_ids))
stale += 1 if overlap < len(fresh_ids) else 0
return stale / max(len(sample_queries), 1)
When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Many users ask the same questions | Yes | Repeated queries skip embedding, search, and reranking. |
| The index changes rarely, or in planned rebuilds | Yes | A version in the key makes invalidation simple and safe. |
| Every query is unique, such as long pasted text | No | The hit rate would be near zero, and the cache only adds work. |
| Documents change every few seconds | No | Entries go stale almost at once, so the benefit is small. |
| Results depend on the user's private data | Only with the user in the key | Otherwise one person's results can leak to another. |
| Retrieval is already fast and cheap | Maybe not | The gain may not justify the extra moving part. |
| Search latency or reranking cost is a real bottleneck | Yes | This is where the cache saves the most. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Same results as a fresh search while entries are valid. Stale entries can return outdated chunks. | Version the key, set a TTL, and sample for staleness. |
| Latency | A hit skips embedding, search, and reranking. | Track hit rate and tune normalisation so near-identical queries share an entry. |
| Cost | Fewer embedding, search, and rerank calls. | Size the cache for the popular queries only. |
| Complexity | Adds a key design, a store, and an invalidation rule. | Keep the key in one function and test it. |
| Failure modes | Stale results, results shown across permission boundaries, and cache outages. | Include scope in the key, fetch text fresh, and fall back to direct search. |
Compared with related types
An embedding cache remembers the vector for a piece of text, and so saves only the embedding step. The retrieval-result cache saves the search and rerank steps too, but it is more sensitive to index changes. A semantic cache goes further and stores the final answer for similar questions, which saves the model call but carries more risk of a wrong match.
The retrieval-result cache sits in the middle: it keeps the generation step live, so the answer is always written fresh from current text, while still trimming the slow search path.
What this means for your role
Common mistakes
Further reading
- Types of caching in AI systems: the hub page for all caching types.
- Caching: the general rules for keys, expiry, and invalidation.
- Vector search and chunking: how chunks and indexes work.
- Simple RAG: a retrieval pipeline where this cache fits.
A retrieval-result cache is a small, careful optimisation. Make the key honest about everything that changes the result, and it will save time without changing answers.