Exact-match response cache: skipping the model for repeated requests

An exact-match response cache stores a finished answer under a key built from the whole request, and returns it when the same request arrives again. Use it for repeated, deterministic calls where a stale answer is safe.

Exact-match response cache in 60 seconds

  • What: a lookup table from a hash of the full request to a stored answer, with a short lifetime.
  • Saves: the entire model call, so cost is near zero and latency is a few milliseconds on a hit.
  • Key must include: the model and its version, all settings, the full messages, and the versions of any prompt or data used.
  • Safe when: the answer does not depend on who asks or on when, and a slightly old answer is acceptable.
  • Limit: it only hits on an identical request, so small wording changes produce a miss.

Where this type fits

This is the simplest of the caches your application controls, together with the semantic cache, the embedding cache and the retrieval-result cache. The caching hub lists them all. Unlike the server-side caches, it sits in your gateway or application and skips the model call completely. Its mechanics come from the general caching toolkit.

The problem it solves

Many AI features make the same call again and again. A product page generates a summary for the same item on every visit. A nightly job classifies the same ticket after a retry. A test suite replays the same prompts on every commit. Each call costs tokens and takes seconds, and the answer is the same as last time.

Without a cache, you pay full price for each repeat. Traffic spikes also hit the model provider or your GPU fleet directly, which raises latency for everyone and can trigger rate limits. Retries after a timeout multiply the cost, since each retry is a fresh call.

An exact-match cache removes this waste for the narrow case where the request is truly identical. It is cheap to build, easy to reason about, and has no quality risk from fuzzy matching. If the key matches, the stored answer is what the model produced for that very request.

How it works

  • Build the key: combine the model name and version, temperature and other settings, the full list of messages, tool definitions, and the versions of the prompt template and any data used.
  • Normalise: apply safe canonical rules, such as trimming outer whitespace and sorting JSON keys, so trivial differences do not change the key.
  • Hash: reduce the key to a fixed-length digest, so lookup is fast and keys are compact.
  • Look up: ask the store for that digest. A hit returns the stored answer at once.
  • On a miss: call the model, then store the answer with a short time to live (TTL).
  • Guard what you store: skip caching errors, partial streams, refusals and answers flagged by safety checks.
A hit returns instantly; a miss pays for one model call and fills the cache.

Everything depends on the key. If it leaves something out, you serve wrong answers. If the temperature is missing, a creative request and a precise one share an entry. If the prompt version is missing, an old answer survives a prompt fix. If the user's role is missing, a manager's answer can reach an intern.

It also depends on determinism. With a high temperature, two calls give different answers, and caching freezes one of them. That may be fine, even desirable, for a product description. It is wrong when users expect variety. Decide this on purpose.

A worked example

Acme shows a 'What is this item?' summary on each product page. A request comes in for item 4471, with the model set to version 'm-2', temperature 0, prompt template v3, and product data version 12.

  • Key parts: model m-2, temperature 0, template v3, data v12, and the messages containing the product text for item 4471.
  • Hash: the parts are serialised in a fixed order and hashed, giving a digest such as 9f3c and so on.
  • First visit (miss): the store has no entry. The model is called and returns a 60-word summary in 1.8 seconds. The summary is stored with a TTL of 24 hours.
  • Second visit (hit): the same digest is found. The summary is returned in about 3 milliseconds, with no model cost.
  • Data change: Acme edits the product description and bumps the data version to 13. The digest changes, so the next visit is a miss and a fresh summary is created.
  • Expiry: after 24 hours the entry is removed, even if nothing changed, which bounds how stale it can get.

Building it

An exact-match cache wrapper around a model call (illustrative) (python)
import hashlib, json, time

# Placeholders: llm.generate() is your model call; store is a key-value store
# with get(key) and set(key, value, ttl_seconds), such as an in-memory map or a shared cache.

TTL_SECONDS = 24 * 3600     # bound staleness; shorter for fast-changing data
MAX_VALUE_BYTES = 50_000    # do not cache huge outputs

def make_key(model, settings, messages, tools, prompt_version, data_version, scope):
    payload = {
        'model': model,                  # include the exact model version
        'settings': settings,            # temperature, max tokens, and so on
        'messages': messages,
        'tools': tools,
        'prompt_version': prompt_version,
        'data_version': data_version,    # bump when source data changes
        'scope': scope,                  # tenant or role, so answers never cross audiences
    }
    # sort_keys makes the JSON canonical, so key order cannot change the hash.
    raw = json.dumps(payload, sort_keys=True, separators=(',', ':'))
    return 'resp:' + hashlib.sha256(raw.encode()).hexdigest()


def cached_generate(llm, store, request, metrics):
    if request['settings'].get('temperature', 0) > 0.3:
        # High temperature means users expect variety; skip the cache.
        return llm.generate(request)

    key = make_key(**request['key_parts'])
    hit = store.get(key)
    if hit is not None:
        metrics.count('cache_hit')
        return hit

    metrics.count('cache_miss')
    started = time.time()
    answer = llm.generate(request)       # the only expensive step
    metrics.timing('model_call', time.time() - started)

    # Store only clean, complete, modest-sized answers.
    ok = (answer.get('finish_reason') == 'stop'
          and not answer.get('flagged')
          and len(json.dumps(answer)) <= MAX_VALUE_BYTES)
    if ok:
        store.set(key, answer, TTL_SECONDS)
    return answer

Three guards are worth copying. The TTL limits staleness. The temperature check avoids freezing outputs that should vary. The storage filter keeps errors, truncated answers and flagged content out of the cache. Also note the scope in the key, which keeps different audiences apart.

Design decisions

  • Key contents: include model version, settings, messages, tools, prompt version, data version and access scope. Default to including too much, since a missed hit is cheaper than a wrong answer.
  • TTL: start at hours for stable content and minutes for fast-changing data. Add explicit invalidation by bumping version fields rather than hunting entries.
  • Storage: use a shared store so all application instances benefit. Keep a small in-process layer in front only if lookup latency matters.
  • Access control: never share entries across tenants or roles unless the content is public. Put the scope in the key.
  • What to cache: only clean, complete, non-sensitive answers. Skip errors, partial streams and anything that contains personal data you should not retain.
  • Failure handling: if the cache is down, call the model. A cache outage should cost money, not availability.
  • Stampede control: when a popular entry expires, many requests miss together. Use a short lock or serve the old entry while one request refreshes it.

Measuring it

  • Hit rate: hits divided by lookups. Break it down by route, since averages hide routes that never hit.
  • Saved cost: hits multiplied by the average cost of a miss. This is the number that justifies the cache.
  • Latency split: p50 and p95 for hits and for misses separately.
  • Staleness check: sample hits, re-run the model, and compare the fresh answer with the stored one. Rising disagreement means the TTL is too long or the key misses something.
  • Wrong-audience incidents: count any case where an answer reached a user outside its scope. The target is zero.
  • Eviction and expiry rate: how many entries expire unused, which shows whether the cache is sized and timed sensibly.
Sampling cached answers to detect staleness (illustrative) (python)
import random

def staleness_sample(store, keys, llm, requests_by_key, same, n=50):
    """Re-run n random cached entries and report how many now differ.
    store, llm and same() are placeholders."""
    picked = random.sample(keys, min(n, len(keys)))
    differ = 0
    for k in picked:
        fresh = llm.generate(requests_by_key[k])
        if not same(store.get(k), fresh):
            differ += 1
    return differ / max(len(picked), 1)

When to use it, and when not to

SituationUse this type?Why
Same generated content for many visits, such as item summariesYesThe request repeats exactly and the answer can be reused.
Batch jobs that retry or re-run on the same inputsYesRetries and reruns become free after the first success.
Tests and evaluation runs with fixed promptsYesStable, repeatable and cheaper runs.
Chat where each message differsNoRequests rarely repeat exactly, so hits are rare.
Answers that depend on live data or the current timeOnly with versioned keys and short TTLA stale answer may be wrong or harmful.
Per-user private answersOnly with user scope in the keyWithout scope, one user could see another's answer.

Trade-offs

DimensionEffectWhat to do about it
QualityIdentical to the original answer, but possibly out of dateUse TTLs and data versions in the key.
LatencyMilliseconds on a hit, unchanged on a missReport hit and miss latency separately.
CostZero model cost on a hit; low storage costTrack saved cost per route and drop routes that do not hit.
ComplexityLow, but the key design needs careReview the key fields in code review and add tests.
Failure modesStale answers, wrong-audience answers and frozen bad outputsScope keys, skip flagged outputs and provide an invalidation switch.

The semantic cache relaxes the match, returning a stored answer for questions with the same meaning. It hits more often, but it can return an answer to a slightly different question. The exact cache never does that, so choose it when precision matters more than hit rate.

The prefix cache is different again. It still calls the model and produces a fresh answer, but it skips repeated reading of a shared opening. The two can run together: the response cache catches full repeats and the prefix cache speeds up everything else.

What this means for your role

Common mistakes

Further reading

An exact-match cache is small, safe and effective when requests truly repeat. Build the key carefully, keep lifetimes short, and measure what it saves.

Search topics

↑↓ to move · Enter to open · Esc to close