Topic 2 of 5 · 5 min read
Exact-match response caching with safe keys
Goal: Design a response cache key that can never serve one tenant's or one prompt version's answer to another.
An exact-match response cache returns a stored answer only when every input that could change the answer is identical, so the key must contain all of them. A key that leaves one out will, sooner or later, hand someone the wrong answer.
Check yourself · 1 of 3
A response cache is keyed on the user message only. What breaks first when the team edits the system prompt?
Why it matters
A hit costs a lookup instead of a model call: no tokens and a few milliseconds. For repeated requests with a stable answer, such as "summarise this document" run twice or a classification of the same text, that is the largest saving available. A bad key turns the same cache into a leak.
What goes into the key
Hash all of these together:
- the model name and version, because a new model gives different answers
- the prompt template version and the filled-in prompt text
- the sampling parameters: temperature, top-p, max tokens, stop sequences
- the tool and schema definitions, and any structured-output schema
- the scope: tenant id, and user id whenever the answer depends on who asked
- the retrieved context or its document versions, if the answer was grounded in it
Add a time to live (TTL) so entries expire even if you forget a field. Choose it from how fast the underlying facts change, not from a default.
When to cache at all
Cache requests that are deterministic enough to repeat: temperature 0 or a task with one right answer, such as extraction, classification, translation of fixed text. Do not cache calls where variety is the point, such as brainstorming, or calls whose answer depends on live state.
Before and after
Before:
key = hashlib.sha256(prompt.encode()).hexdigest()
Two tenants who send the same prompt share a key. After a prompt-template change, old answers keep being served. After:
key = hashlib.sha256(json.dumps({
"model": model, "tmpl": "refund-v7", "params": params,
"tools": tools_hash, "tenant": tenant_id, "prompt": prompt,
}, sort_keys=True).encode()).hexdigest()
What goes wrong
- Missing scope. The prompt is the same, but the system prompt includes tenant data from a variable you did not hash.
- Unstable serialisation. Dict key order or float formatting changes the hash, so hits vanish silently. Serialise with sorted keys.
- Caching errors and refusals. A timeout or a content filter reply stored for an hour repeats the failure. Store only successful, validated results.
Examples
A key that survives a prompt change
const key = sha256(stableStringify({
model: "model-x-2026-06",
promptVersion: "summarise-v3",
params: { temperature: 0, maxTokens: 400 },
tenantId,
input: documentText,
}));
Bumping summarise-v3 to summarise-v4 makes every old entry unreachable at once, with no purge job.
Per-user answers
A bot answers "What is my plan limit?" using the caller's account data placed in the prompt. The prompt text differs per user, so the hash differs. But if the account data is fetched by a tool and the prompt text is the same, the key must include the user id, or the first user's limit is served to everyone.
Key points
- The key must include every input that can change the answer: model, prompt version, parameters, tools and scope.
- Tenant or user id belongs in the key whenever the answer depends on who asked.
- Always set a TTL based on how fast the underlying facts change.
- Cache deterministic tasks; skip calls that need variety or read live state.
- Never store errors, refusals or unvalidated output as cache entries.
Common mistakes
- Hashing only the user message and ignoring model, template version and parameters.
- Leaving out tenant or user id because "the prompt is the same".
- Using no TTL and relying on manual purges.
- Caching high-temperature creative output, then wondering why users see repeats.
Check yourself · 2 of 3
Which request is the best candidate for an exact-match response cache?
Check yourself · 3 of 3
Why store a TTL on every cache entry even when the key looks complete?
Practice items, not counted towards your mastery.
Start here
- Prompt caching (Claude docs) (opens in a new tab)DocsFree
How a cached prefix is marked, how long it lives and how cache read and write tokens are reported.
- Prompt caching (OpenAI API docs) (opens in a new tab)DocsFree
Automatic prefix caching on another provider, with the rules for what counts as a repeated prefix.
- RedisVL: semantic caching for LLMs (opens in a new tab)DocsFree
A working semantic cache: distance threshold, time to live and filters for scoping entries.
More for this topic
- HTTP caching (MDN) (opens in a new tab)ArticleFree
Freshness, validation and shared versus private caches: the same ideas apply to the key and TTL choices here.