AI Engineering

LLM Caching for Agent Systems: Exact, Semantic, and Prompt Caches

Design LLM caching with exact keys, semantic reuse boundaries, stable prompt prefixes, dependency invalidation, and measurable cost and correctness tradeoffs.

· · 8 min read

Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.

LLM caching is a reuse decision with correctness conditions. A cache hit says that earlier computation can satisfy the current request; it does not establish that the earlier answer remains authorized, fresh, or appropriate. Agent systems make that distinction important because their responses can depend on changing tools, retrieved evidence, user identity, and workflow state.

This guide separates three cache layers and develops an illustrative policy-answering service. The architecture and numerical examples are proposed engineering designs, not measured results or a production implementation.

Distinguish what each cache actually reuses

Cache layer Reused object Work that can remain necessary
Exact response cache A previously completed result under a complete matching key Authentication, authorization, dependency checks, response validation
Semantic response cache A result selected through meaning-based similarity plus hard constraints Embedding, candidate filtering, freshness and answer-equivalence checks
Provider prompt cache Internal processing of an identical prompt prefix Processing the changing suffix, generating output, and executing subsequent tools

A response cache can skip generation. A prompt cache changes how a generation request is processed; it does not make a stored final answer interchangeable with a fresh response. Redis explicitly distinguishes semantic response caching from document retrieval and provider prefix reuse. Its implementation guidance combines vector matching with metadata restrictions. Redis semantic cache documentation.

Cache eligibility should be a decision before lookup. An explanation of a public policy can be a candidate. An instruction to approve an expense is an operation with changing authority and side effects. Reusing a sentence saying “approved” cannot establish that the operation occurred for this request.

Build exact keys from the answer's dependencies

For the proposed policy service, a key based only on the question is incomplete. The same text can have different answers across tenants, locales, policy editions, and access scopes. A conceptual key might be:

response_key = hash(canonical_encode({
  task_type,
  normalized_request,
  tenant_scope,
  authorization_scope_fingerprint,
  policy_epoch,
  evidence_snapshot,
  prompt_version,
  model_route_version,
  output_schema_version,
  locale
}))

This is pseudocode. Derive identity and authorization fields from trusted application context, not model-supplied arguments. A fingerprint identifies the applicable scope; it is not a substitute for checking that the caller currently holds it. Avoid putting raw credentials or personal identifiers into observable key names.

Normalization must preserve meaning. Whitespace cleanup may be harmless for an ordinary question but wrong inside source code. Lowercasing an entire payload can alter identifiers. Sorting a list may change a requested ranking. Prefer canonical serialization of structured inputs, and document every normalization rule.

HTTP caching provides an established comparison: RFC 9111 describes matching nominated request headers through Vary and restricts shared reuse of authenticated responses. These are HTTP rules, not an automatic implementation for your LLM cache. The architectural lesson is to enumerate all representation-changing inputs instead of assuming one textual key is sufficient. RFC 9111: HTTP caching.

Treat semantic similarity as candidate discovery

A semantic cache asks whether a previously answered request might be reusable. Similarity alone cannot answer that question. “Can contractors claim this allowance?” and “Can employees claim this allowance?” can occupy nearby embedding space while requiring different policies.

In the proposed design, hard-filter candidates by tenant, authorization class, locale, task type, policy epoch, and compatible output schema before considering similarity. Then reject candidates with conflicting entities, dates, negation, or material qualifiers. Keep the evidence identifiers and original question with each answer so the service can inspect what was actually answered.

Threshold direction depends on the metric and implementation. A distance cutoff generally accepts smaller values, while a similarity cutoff generally accepts larger ones. Do not copy a numeric threshold between different embedding models or metrics. Microsoft documents its semantic-cache policy's threshold behavior and shows a vary-by boundary; that is product-specific behavior rather than a universal threshold convention. Azure API Management semantic caching.

Start with low-risk, stable answer categories. For questions whose answer depends on a live account balance, skip response reuse or revalidate that dependency explicitly. A second LLM that judges equivalence can help prioritize review, but introduces its own cost and false-acceptance risk. It does not turn similarity into authorization.

Keep prompt prefixes stable without hiding current facts

Provider prompt caching is useful when repeated requests share substantial instructions, tool definitions, or context. Anthropic documents prefix-based reuse, cache breakpoints, lifetime behavior, and conditions that invalidate cached sections. Those details vary by product and model; check the current documentation before choosing parameters. Claude prompt caching.

For an illustrative agent request, place stable instructions and stable tool schemas before changing evidence and the current question. Preserve deterministic serialization of tool definitions. A timestamp inserted near the beginning can make later shared content cease to be an identical prefix.

This arrangement must not suppress freshness. Keep a current policy revision in the changing context even if it reduces reuse. Do not reuse an obsolete tool definition merely to protect a hit rate. Prompt caching is a performance mechanism; the request still needs the information and permissions required for the current decision.

Separate prefix hit metrics from response-cache hit metrics. A prefix hit can coexist with a long model output or an expensive tool sequence. Counting both as “requests served from cache” obscures what was actually saved.

Design invalidation as a dependency problem

A TTL limits an entry's age according to the configured expiration behavior. It does not prove that its evidence remains valid during that interval. A policy can change one second after an answer is cached.

For this proposed service, store a dependency manifest with each result: source document revisions, policy epoch, schema version, and authorization scope. A policy update advances the active epoch. Lookups reject entries from older epochs, while background deletion reclaims their storage. This makes correctness less dependent on deleting every old key immediately.

Handle late writers too. A request can start under epoch 8, finish after epoch 9 becomes active, and write an obsolete answer. Before publishing the entry, verify that its dependencies still match the active snapshot. Otherwise retain it only under its old versioned namespace, where current lookups cannot select it.

Access revocation requires the same discipline. A long-lived cached answer must not remain readable because its original requester once had access. For dependency propagation and deletion races, see RAG freshness and index consistency and multi-tenant agent isolation.

Walk through a hypothetical policy change

Assume an employee asks which evidence is needed for a travel allowance. The authenticated request resolves to tenant A, locale EN, and policy epoch 12. An exact lookup misses. A semantic candidate about a different allowance is rejected because its task-specific entity differs.

The service retrieves the active policy, generates an answer, validates its source references, and stores a completed response with the evidence manifest. A paraphrase from another eligible user can reuse it only if their hard constraints match and the answer contains no requester-specific information.

Now a revised policy becomes active at epoch 13. The old answer remains physically present, but the current lookup excludes it. A generation already running under epoch 12 finishes late; its publication check prevents it from populating the active namespace.

If the cache becomes unavailable, the service still applies admission limits to uncached requests. Microsoft's documentation recommends rate limiting after cache lookup to avoid backend overload when the cache is unavailable. The cache is an optimization whose failure should not erase the service's capacity controls. The broader scheduling design belongs in agent backpressure and admission control.

Measure economics together with correctness

An illustrative cost model for semantic response caching is:

expected_cost = lookup_cost + embedding_cost
              + (1 - accepted_hit_rate) * (generation_cost + write_cost)

Suppose lookup costs 0.2 units, embedding costs 0.3, generation costs 10, writing costs 0.1, and the accepted hit rate is 40%. Expected cost is 0.2 + 0.3 + 0.6 × 10.1 = 6.56 units per request. These invented units exclude storage, operations, validation, and incorrect-answer costs; they demonstrate the calculation rather than forecast savings.

Count only hits that satisfy the actual reuse contract. Increasing a similarity threshold to obtain more hits can lower quality and increase repair work. Report wrong-reuse rate, stale-answer rate, cross-scope violations, and task success alongside hit rate and latency. Test negation, changed entities, policy updates, permission revocation, cache outages, and concurrent misses.

Concurrent identical misses can be coalesced, but a waiter must still qualify to reuse the result. Use a bounded lease for the generating worker, and ensure an expired worker cannot overwrite a newer accepted entry. Never coalesce mutations merely because their request text matches; side-effect deduplication needs a separate action identity and enforcement contract.

Frequently asked questions

Can a semantic cache replace RAG?

It can bypass retrieval and generation for eligible repeated questions. New questions and invalidated evidence still need an authoritative answer path. Store source provenance so reuse can be checked against current dependencies.

Does a short TTL make personalized response sharing safe?

No. A fresh answer can still disclose another person's information. Identity boundaries, content eligibility, and current authorization remain necessary regardless of expiration time.

Should every agent step use response caching?

No. Begin with stable read-only computations whose dependencies are explicit. Keep live decisions and external actions behind their normal validation and execution controls, even when prompt-prefix caching improves their model-call efficiency.

Source reference list

LLM Caching
Semantic Caching
Prompt Caching
AI Engineering