Skip to content

Exact and semantic response caching: eligibility, freshness and invalidation

14 min reading

Distinguish exact response caching, semantic caching and prefix caching with authority and freshness rules.

Page details

GenAI · Lesson 35 of 45 · 5 / 5.3

Sources · 14 min reading · 30 min with practice

Published · Last edited:

More
20px

Progress is saved in this browser when storage is available.

View guided paths and progress

Know first: LoRA/QLoRA serving and prefix/KV reuse; separate adapter identity from cache identity. Optional help: GenAI foundations.

Optional background references

Hypothetical scenario. Northwind’s prefix eligibility rules are explicit. Dev now proposes reusing complete answers to similar questions. Maya notices that an answer for a sealed product was offered for an opened one; Priya asks whether the callers also shared the same permitted evidence.

Maya: “The wording is similar, but the policy condition changed.”

Dev: “A semantic match can suggest a cache candidate.”

Priya: “It still needs task equivalence, current evidence and the caller’s access checks.”

You will distinguish exact response caching, semantic reuse and prefix/KV reuse. Follow their different eligibility conditions and accounting units so a successful lookup does not conceal a stale or unauthorized answer.

When does a similar request deserve the same answer?

Exact response caching reuses a completed result under a matching request-and-policy key. Semantic response caching looks for a sufficiently similar request, then still needs explicit task equivalence, authorization and freshness checks. Prefix caching instead reuses compatible intermediate KV state during generation; it need not reuse the previous answer at all. A vector-distance threshold is not a substitute for the other two eligibility checks.

Hypothetical scenario. Out of 20 chosen requests, six have matching exact-response keys. Of the remaining 14, four pass a separately defined semantic-equivalence and policy check. Response generation is still needed for 20 − 6 − 4 = 10. Some of those ten may reuse prefix state, but they remain ten generated responses. Adding prefix hits to completed-response hits would double-count different kinds of saved work.

The cached answer belongs to a different policy condition

Northwind receives many questions about returns. Dev adds a semantic cache so similar wording can reuse an earlier answer. Priya discovers that a question about an opened product receives an answer generated for a sealed one. Sam notices another risk: the nearest cached question came from a caller with access to a different document collection.

Both failures can look like successful cache hits. The service avoided model generation and returned fluent text. The missing check is whether the prior answer remains valid for this caller, evidence and task. Similarity can help find a candidate; reuse still needs a contract that explains why that candidate is appropriate.

Make semantic answer reuse a disclosure decision

Hypothetical scenario. A semantic cache finds a close question whose saved answer cites policy revision 11. The current caller is subject to revision 12 and a different permission scope. Similarity proposes reuse; the application must still establish task equivalence and current evidence eligibility.

Make semantic answer reuse a disclosure decision
ArtifactConcrete evidenceDecision boundary
Cache candidatequestion features, answer, source refsPossible reuse
Eligibilitycaller scope, source/ACL versions, task settingsDisclosure rule
Fill generationexpected source version and statePrevent regression
Candidate only: Similar question → Equivalence / authority.Candidate only: Similar question → Equivalence / authority. Similar question to Equivalence / authority: candidate only; Equivalence / authority to Answer reuse or recompute: current evidence determines eligibility.Similar questionEquivalence /authorityAnswer reuse orrecomputecandidate onlycurrent evidence determines eligibility
Candidate only: Similar question → Equivalence / authority. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

An exact key needs the dimensions that change the allowed result, while a semantic candidate needs additional validation against those dimensions. TTL does not renew source evidence or retract an already disclosed answer. A delayed old fill can race invalidation, so retain source versions and reject obsolete publication where the implementation supports it. When equivalence cannot be established, compute a fresh eligible result or return the declared unsupported outcome.

Response reuse, exact keys and prefix computation are different mechanisms

An exact response cache looks up a defined request identity. A semantic response cache searches for a nearby representation and proposes a previously produced answer. Prefix computation caching reuses intermediate work for a compatible input prefix rather than directly returning a stored final answer. These mechanisms can coexist, but their hit definitions and validity requirements differ.

The vLLM automatic prefix-caching documentation describes computation reuse in its serving engine. It is not evidence that a final response can be returned to a different caller merely because the input prefix resembles a prior request. Application authorization and evidence selection remain necessary.

A response cache also cannot establish that an action should happen again. Returning a prior “refund completed” sentence does not execute a new authorized operation, and repeating the original refund can be incorrect. Restrict response reuse to tasks whose semantics support it and keep side-effect state outside the cache-hit decision.

Restrict the candidate space before interpreting similarity

Begin with the caller's authorized scope and the task's allowed evidence. Partition or filter cache candidates accordingly before selecting a response. A globally nearest entry followed by a casual tenant check can already expose sensitive metadata or let an unavailable candidate displace the valid one. Design storage and retrieval so the authorization boundary is enforced.

The identity record should include the task contract, effective model and prompt revision, evidence dependencies and relevant input conditions. The particular fields depend on the task. A policy answer may depend on document revision, product category and jurisdictional policy configuration; a personalized account answer may be unsuitable for semantic sharing at all.

Do not assume an embedding represents every condition that matters. Negation, quantities, dates and identifiers can be decisive even when surrounding words are almost identical. Use explicit equality or validity checks for those conditions where possible, and bypass reuse when the needed equivalence cannot be established.

A similarity threshold is a search setting, not a correctness certificate

A vector score ranks candidates under a chosen encoder and metric. A threshold selects which candidates deserve consideration. Its numerical value is not a calibrated probability that the answers are interchangeable. Changing the encoder, corpus or query distribution can change the threshold's behavior even when the dimension stays the same.

Evaluate accepted hits and rejected candidates against a labeled equivalence policy. Include near-matching requests whose correct answers differ, such as opened versus sealed items or permission changes. Track false reuse separately from misses. A miss spends extra computation; an incorrect hit can return an unsuitable answer confidently and quickly.

Redis's RedisVL LLM cache guide is a primary implementation reference for semantic lookup and cache controls. Inspect its behavior against the application contract rather than interpreting the presence of a distance threshold as proof of safe reuse.

A candidate cache hit crosses identity and freshness checksThe authorized request restricts cache candidates. A similarity search proposes one response. Evidence and task validation determine whether it can be returned; otherwise the system generates and validates a new response before storing it with dependency identities.Authorized scopeand task identityFind a similarcache candidateValidate dependenciesand required conditionsReuse valid answeror generate anewStore result withversioned dependencies

Derive savings only for valid reusable answers

Hypothetical scenario. Choose 1,000 requests, a valid-hit fraction of 0.6, a cache-hit service cost of $0.001 and a miss-generation cost of $0.02. There are 1,000 × 0.6 = 600 valid hits and 400 misses. Selected subtotal is 600 × $0.001 + 400 × $0.02 = $0.60 + $8 = $8.60.

Without reuse, generation under the same selected per-request cost is 1,000 × $0.02 = $20. The selected difference is $11.40. Now add an assumed $0.002 lookup and validation cost to every request: 1,000 × $0.002 = $2. Total becomes $10.60 and the difference becomes $9.40. These are toy prices and workloads, not a vendor cost comparison.

If an audit finds five invalid reuses among 600 returned hits, the observed invalid-hit fraction is 5 / 600 ≈ 0.8333%. Those outcomes cannot remain in a “valid-hit” savings claim without qualification. Their consequences may exceed the saved computation. Report validity alongside cache latency and cost instead of optimizing the hit counter alone.

Expiration bounds age; dependency checks address known changes

A time-to-live chooses an age after which an entry is no longer reusable. It does not guarantee that a dependency stayed unchanged during that interval. A policy revision immediately after insertion can invalidate an answer long before the selected TTL expires.

For a hypothetical insertion at minute zero with a ten-minute TTL, a policy change at minute two can leave up to eight minutes of stale reuse if age is the only check. The calculation is 10 − 2 = 8 minutes. Versioned evidence or an authoritative invalidation signal can reject the known-stale result earlier. Actual propagation delays still need an explicit contract.

Store dependency identities with the answer. A coarse global corpus revision is simple and may invalidate many otherwise useful entries. More precise dependencies can preserve reuse but require complete tracking of what influenced the answer. An incomplete dependency record gives misleading confidence rather than precise invalidation.

Replicated caches add a propagation and race problem

If several regions or workers retain response entries, removing one local copy does not establish that all copies are unavailable. Define how invalidation reaches replicas, how readers verify versions and what happens when the version service cannot be consulted. A task may require bypassing the cache when validity cannot be established.

Consider an answer generated from an old evidence revision while a document update is being processed. If the answer is inserted after an invalidation message, a simple delete can miss it. Compare the answer's dependency revision with the current accepted revision when writing and reading, rather than relying solely on the order of delete operations.

Authorization changes require the same care. A caller who once accessed a document may no longer be entitled to a response derived from it. Recheck the relevant scope at reuse time. Do not treat a historic permission decision embedded in a cache key as a permanent grant.

In the wild: semantic and prefix caches expose distinct reuse boundaries

RedisVL documents semantic response caching, while vLLM documents reusable prefix computation. They are concrete implementations of different ideas. Their documentation helps identify what the mechanism reuses; the application still decides whether its own task and data contract allow that reuse.

Hypothetical scenario. Northwind updates a return-policy paragraph and clears one cache region. Another region returns an old answer to a caller whose access was also revoked. The response is fast but fails both freshness and authority. Suspend reuse for the affected scope, verify dependency identities and authorization, and inspect all copies before restoring the cache path.

Cache stable equivalence rather than every fluent answer

Semantic reuse can help repetitive informational tasks with stable evidence and an evaluable equivalence rule. It is a poor default for personalized account state, changing quotes, ambiguous requests or actions with effects. Exact keys may be preferable when the relevant conditions are easy to enumerate; fresh generation may be preferable when validity is expensive to establish.

Measure the complete path, including embedding lookup, dependency validation and misses. A low-hit cache can add latency and cost to most requests. Preserve an explicit bypass and monitor whether the deployed workload still matches the cache's evaluated domain.

Deletion and retention must cover cached responses and their diagnostic copies, not only the retrieval corpus. A response can contain source-derived information even if it has no copied paragraph. Track the relationship between source withdrawal, cache validity and retained logs according to the application's documented policy.

Evaluate misses as well as accepted hits

A very strict threshold may avoid false reuse while returning almost no valid hits. A permissive threshold may increase savings and introduce unacceptable substitutions. Compare both against the task's equivalence policy and include lookup and validation overhead on misses. The useful operating point depends on the consequence of a wrong answer, not a universal similarity value.

Keep an independent test when tuning the cache encoder or threshold. Repeatedly selecting settings from the same convenient questions can conceal weak generalization to changed policy wording, negation or new identifiers. A bypassed request can still succeed through the ordinary validated generation path.

Test the cache candidate boundary

The cache hit is fast and textually accurate but reveals a revoked source. Is it accepted?

Reveal the design reasoning

No. Evaluate disclosure and current applicability with the same outcome. Invalidate or reauthorize derived text, including summaries, not merely vector hits.

Decision: Reuse answers only under explicit task, evidence and permission equivalence.

Treat every hit as a candidate decision

Two questions are close in embedding space but differ by “not.” Is a threshold enough?

No. Similarity can miss a condition that reverses the answer. Check the task's required fields or bypass reuse when equivalence cannot be established. Evaluate near-matching requests with different correct answers.

A policy changes two minutes into a ten-minute TTL. Is the cached answer valid for another eight minutes?

Not because of age alone. Eight minutes is the potential stale interval under the selected TTL-only policy. Reject known-stale dependencies using version checks or invalidation according to the freshness contract.

A cached sentence says a refund completed. Can it answer a new refund request without an executor?

No. Response reuse does not establish the new operation's authorization or completion. Keep side effects under their own operation identity and reconciliation contract. A prior sentence is not a new transaction result.

Northwind decision log

  1. Restrict candidates by authority and task identity before accepting semantic reuse.
  2. Validate evidence revisions and relevant conditions independently of similarity.
  3. Report valid-hit economics and retain a bypass for uncertain freshness or equivalence.

Go deeper: cache placement and time

Check the mechanism in this lesson

Why should prefix hits not be added to exact-response hits as though both count completed answers?

Compare the explanation

A prefix hit reuses intermediate state while still requiring response generation. A response hit reuses a completed result. Counting both as completed answers mixes distinct denominators and can double-count work.

Carry the decision forward

Northwind can distinguish eligible response reuse from compatible prefix computation. Page 36 moves to serving topology: replicas, model partitions and routing must match the work each admitted request requires.