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. This chapter assumes you have read the chapters on measurement and quality evaluation, and that you can write basic Python.
When an exact-match cache fits
An exact-match cache uses the full request as a key. If the model name and messages are identical, the stored answer is reused. This works well when:
- Many users send the same input, such as a fixed FAQ, a classification of a known label, or a nightly report prompt.
- The answer does not depend on fresh data or on who is asking.
- Sharing one answer across repeated requests is acceptable.
It works poorly for open-ended chat, creative writing where variety matters, or prompts that include timestamps or user IDs. Those make every key unique, so the hit rate stays near zero.
A minimal implementation
The key is a hash of the model and messages. Sorting the JSON keys makes the same content always produce the same string.
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]The first call runs call_fn. Later calls with the same model and messages return the stored result.
What belongs in the key
Anything that changes the answer must be part of the key. The minimal version covers the model and messages. In practice, also include:
- Sampling settings such as temperature and
max_tokens. - Tool definitions and response format settings.
- A prompt version label, so a prompt edit does not serve old answers.
Leaving out a setting is the most common bug. If two requests differ only in temperature but share a key, one will receive the other's answer.
Common errors
| Problem | Effect | Fix |
|---|---|---|
| Key omits a setting that changes output | Wrong answer served | Hash every parameter that affects the response |
| Cache never expires | Stale answers after the underlying facts change | Store a timestamp and apply a time-to-live (TTL) |
| Per-user data in a shared cache | One user sees another's answer | Include the user or tenant in the key, or skip caching |
| Caching failed or low-quality answers | Errors repeat forever | Store only successful, validated responses |
| Unbounded in-memory dict | Memory grows without limit | Use a size limit or an external store such as Redis |
Caching and temperature
At a temperature above zero, the same prompt can produce different answers. A cache freezes one of them. This is often fine for factual or classification tasks. It is a poor fit where users expect variety, such as "give me another idea."
Measure the benefit
Track the hit rate, which is hits divided by total requests. Multiply it by your average cost per request to estimate savings. A 30 percent hit rate on a request that costs $0.002 saves about $0.0006 per request on average. Check this against the baseline you built earlier. If the hit rate is under a few percent, the cache adds complexity for little gain.
Run your evaluation set after turning caching on. Stale or mismatched answers show up as quality drops.
Beyond exact match
Semantic caching reuses answers for similar questions by comparing embeddings. It raises the hit rate but can return an answer to a question that is only close, not the same. Treat it as a separate decision and test it against your evaluation set before use.
Exercise
Your service caches answers keyed on only the model name and the user message. A teammate changes the system prompt to require shorter answers, and users still get long ones. What happened, and how do you fix it?
Show answer
The system prompt is not in the key, so requests with the same user message hit old cached entries made under the previous prompt. Hash the full message list, including the system message, and add a prompt version label to the key. Clear or let expire the old entries.
Exercise
A cache has 1,000 requests per day, a 20 percent hit rate, and each miss costs $0.01. What is the daily saving?
Show answer
Hits are 200 requests. Each avoided call saves $0.01, so the saving is $2.00 per day.