What a hit is worth
- : the hit rate.
- : the cost, in money or in milliseconds.
A cache with a 40 percent hit rate on a request costing 2 seconds and 1 cent turns those into 1.2 seconds and 0.6 cents on average.
The saving is linear in the hit rate, so the whole engineering problem is raising without returning stale or wrong answers.
The three caches in a model application
An exact cache is a dictionary. It is correct by construction, trivially invalidated, and it only fires on repeated identical requests.
A semantic cache embeds the query and returns a stored answer when a close enough one exists, which raises the hit rate and introduces a real risk.
That threshold is a correctness decision, not a tuning knob. Two questions can sit at 0.97 similarity and have different answers, and the cache will confidently return the wrong one.
Prompt caching, which is the provider's own
The attention keys and values for a prefix are stored on the provider's side, so a long shared system prompt is processed once rather than per request.
Reading cached tokens typically costs about a tenth of processing them, and writing costs slightly more than normal input.
The prefix must match exactly, from the first token.
That is the constraint everything else follows from: anything that varies must go after everything that does not, or the cache never hits.
A timestamp at the top of a system prompt is the classic mistake, and it costs the entire discount.
One caching layer, in order
- Normalise the request: trim whitespace, sort any unordered fields, and fix the parameter set.
- Look up the exact cache first, since it is free and always right.
- Fall back to the semantic cache if one is in use, with a conservative threshold.
- On a miss, call the model and write both caches.
- Record the hit rate per layer, because a cache nobody measures is usually not working.
What must never be cached
Anything personalised, unless the key includes the user identity, or one person's answer is served to another.
A cached response for a creative request returns the same output every time, which may be exactly what was not wanted.
Time-sensitive answers need a time to live short enough to bound the staleness, and the honest default for anything derived from live data is not to cache it at all.
Memory is finite, so entries leave.
Least recently used is the standard policy and it is a poor fit for a long tail of rare but expensive queries, which is where a cost-aware policy earns its complexity.