Sub topic 11
Cache Full Responses
Response caching stores the complete answer to a request and returns it when the same request arrives again. A cache hit costs no tokens and returns in microseconds instead of seconds. This chapter covers how to build an exact-match cache, when it is safe, and the errors that cause stale or wrong answers.
This chapter assumes you can write basic Python, have called an LLM API, and know what temperature does. It also assumes you have a baseline from the measurement chapter, because a cache only pays off if requests actually repeat.
What a response cache is
A response cache maps a request to a stored response. On each request you build a key from everything that can change the answer. If the key exists, you return the stored value. If not, you call the model and store the result.
This differs from provider prompt caching. Provider caching reuses the processed prefix of a prompt, but the model still generates a new answer. Response caching skips the model call entirely.
An exact-match cache
An exact-match cache hashes the full request. Two requests share an entry only if they are identical.
import hashlib
import json
_cache = {}
def cached_call(model, messages, call_fn):
payload = json.dumps({"model": model, "messages": messages}, sort_keys=True)
key = hashlib.sha256(payload.encode("utf-8")).hexdigest()
if key not in _cache:
_cache[key] = call_fn(model, messages)
return _cache[key]Three details matter here:
sort_keys=Truemakes the JSON stable, so dictionaries with the same content always produce the same string.- The key includes the model name, so a model change never returns an answer from the old model.
- The hash gives a fixed-length key, which is easier to store than the full prompt.
The call_fn argument is any function that takes the model and messages and returns a response. That keeps the cache independent of a specific provider SDK.
What must go into the key
The key must include every input that can change the output. If you leave one out, two different requests collide and one user gets the other's answer.
| Input | Why it belongs in the key |
|---|---|
| Model name and version | Different models give different answers |
| Full message list, including the system message | Any wording change can change the answer |
| Temperature, top_p, and max tokens | They change the distribution or length of the output |
| Tool definitions and response format | They change the output structure |
| Seed, if you set one | It selects a particular sampled output |
The example above hashes only the model and messages. If your application also varies temperature or max tokens, add them to the payload. A common source of bugs is adding a new parameter to the API call and forgetting to add it to the key.
When caching is appropriate
Exact-match caching fits when repeated identical requests may share one answer. Typical cases:
- Classification or extraction over a fixed set of inputs, such as tagging product descriptions.
- Frequently asked questions where the wording is often copied verbatim.
- Offline jobs that are re-run during development, where the same prompts recur.
- Evaluation runs, where you re-score the same prompts after changing only the grader.
It fits poorly when:
- Each request contains unique content, such as a timestamp or a user-specific document. The hit rate will be near zero.
- Users expect variety, such as a creative writing tool that should return a different draft each time.
- The answer depends on data that changes, such as live prices or account balances.
Measure the hit rate before investing. If you log requests during your baseline, hash them and count duplicates. A hit rate of 2% rarely justifies the added complexity. A rate of 30% usually does.
Temperature and determinism
Caching a response at nonzero temperature freezes one random sample. Every later caller sees that same sample. This is often fine, and sometimes it is even desirable because answers become consistent. But you should decide it on purpose.
At temperature 0, outputs are mostly stable, but many providers do not guarantee identical outputs across calls. The cache turns "usually the same" into "always the same" for the cached period. That makes behavior easier to test and debug.
If your product depends on varied outputs, do not cache those requests. Or include a variant number in the key and cache a small pool of answers.
Expiry and invalidation
A cached answer can become wrong even when the request is identical. Plan for three causes:
- Time-sensitive facts. An answer about "the latest release" goes stale. Give such entries a time to live (TTL).
- Prompt or code changes. If you edit the system prompt, the key changes automatically, because the prompt is in the key. But if you change post-processing code that runs before caching, old entries keep the old behavior. Add a version string to the key and bump it when you change that code.
- Model updates. If you use an alias such as
latest, the model behind it can change without your key changing. Pin a dated model version where you can.
Here is a version of the cache with a TTL and a version tag. It uses a plain dictionary, so it works only inside one process.
import hashlib
import json
import time
CACHE_VERSION = "v1"
_cache = {}
def make_key(model, messages, params):
payload = json.dumps(
{"v": CACHE_VERSION, "model": model, "messages": messages, "params": params},
sort_keys=True,
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def cached_call_ttl(model, messages, params, call_fn, ttl_s=3600):
key = make_key(model, messages, params)
entry = _cache.get(key)
if entry is not None and time.time() - entry["at"] < ttl_s:
return entry["value"]
value = call_fn(model, messages, params)
_cache[key] = {"value": value, "at": time.time()}
return value
if __name__ == "__main__":
calls = []
def fake_call(model, messages, params):
calls.append(1)
return "answer"
msgs = [{"role": "user", "content": "Hello"}]
cached_call_ttl("m1", msgs, {"temperature": 0}, fake_call)
cached_call_ttl("m1", msgs, {"temperature": 0}, fake_call)
print("model calls:", len(calls))The script prints model calls: 1, because the second request is a hit.
Where to store the cache
An in-process dictionary is fine for a script. It has limits in a real service:
- It is lost on restart.
- Each server process has its own copy, so the hit rate drops as you add processes.
- It grows without bound unless you cap it.
For production, use a shared store such as Redis, with a TTL set by the store itself and a memory limit with an eviction policy. For a single machine, a local database such as SQLite works well for offline jobs.
Safety: what you must not share
A shared cache can leak data between users. If a prompt contains private data, and the cache key is only the prompt, then another user who sends the same prompt gets the cached answer. That is correct for identical prompts. The risk appears when the response depends on something that is not in the key, such as the user's identity or permissions, applied outside the prompt.
A safe rule: if two users could legitimately receive different answers to the same text, include a user or tenant identifier in the key, or do not cache.
Exact match versus semantic caching
Semantic caching embeds the request and returns a stored answer for similar requests, not only identical ones. It raises the hit rate, but it adds an embedding call and a similarity threshold to tune. Its main failure mode is a false hit: "How do I cancel my order?" and "How do I cancel my subscription?" may be close in embedding space yet need different answers.
Start with exact match. Consider semantic caching only after you have evaluated it on your own data using the quality evaluation set from earlier, and have measured the false-hit rate.
Do not cache failures
Cache only successful, complete responses. If the call raises an error, the function above stores nothing, which is correct. Also check for truncated outputs. A response that stopped because it hit the max token limit may be incomplete, and caching it repeats the defect on every hit. Check the finish reason and skip the cache write when it signals truncation.
Checking that the cache helps
Track these numbers in production:
- Hit rate: hits divided by total requests.
- Cost saved: hits multiplied by the average cost per request.
- Latency split: median latency for hits versus misses.
- Staleness complaints or quality-check failures on cached answers.
Sample some cached answers periodically and run them through your evaluation set. A cache that quietly returns outdated answers is a quality regression that your cost dashboard will not reveal.
Summary of decisions
| Question | Guidance |
|---|---|
| Do requests repeat? | Measure the duplicate rate first |
| What goes in the key? | Everything that can change the output |
| How long to keep entries? | Set a TTL based on how fast the facts change |
| Shared across users? | Only if the answer does not depend on who asks |
| Exact or semantic? | Start with exact match |
Exercise
Your service caches responses keyed on a hash of the messages only. A teammate adds a temperature parameter that varies between 0 and 1 depending on the feature, and a second teammate switches the model from one version to another. Name two problems this causes and how to fix each.
Show answer
First, requests that differ only in temperature collide on the same key, so a request meant to be creative can receive a cached low-temperature answer (or the reverse). Add the generation parameters to the key. Second, after the model switch, old entries produced by the previous model are still returned, since the model name is not in the key. Add the model name (pinned to a version) to the key, and bump a cache version string so existing entries are no longer matched.
Exercise
A logged sample of 1,000 requests contains 940 unique prompts. Each request costs about $0.01. Is an exact-match cache worth building for this traffic, and what would you check next?
Show answer
Probably not. Only about 60 requests are duplicates, so the hit rate is around 6% and the savings are about $0.60 per 1,000 requests. Next, check whether near-duplicates exist that differ only in trivial ways, such as whitespace or an embedded timestamp. Normalizing those or removing volatile text from the prompt could raise the hit rate. Otherwise, spend effort on other levers such as prompt trimming or a smaller model.