Invalidating Prompt Cache in LLM API: Avoiding Outdated Responses
Caching prompts reduces the cost and latency of LLM API, but it introduces the risk of serving outdated responses. The issue arises when the system prompt, model version, knowledge base content, or business logic rules change, yet the cache continues to return results based on the previous configuration. In this article, I discuss a practical scheme for invalidation: how to build cache keys, what fields to include in the version, how to tag records, and how to organize cascading resets.
Why a Simple TTL is Insufficient
TTL limits the lifetime of a record but does not account for changes in input data. If a prompt is updated a minute after being cached, with a TTL of an hour, users will receive an outdated response. Conversely, with a short TTL, the cache barely saves tokens.
Correct invalidation relies on two mechanisms:
- Key versioning — any change in input data alters the key, making the old record unreachable.
- Explicit reset — upon updates to external dependencies (documents, rules), records are marked as invalid by tags.
TTL remains as a safeguard against garbage accumulation but not as the primary mechanism.
Cache Key Structure
The key should include everything that influences the response. The minimal set of fields:
| Field | Purpose | Example Value |
|---|---|---|
prompt_hash |
Hash of the final prompt after variable substitution | sha256:9f2c... |
prompt_version |
Version of the template from the prompt registry | v14 |
model_id |
Model and snapshot identifier | model-x-2026-01 |
params_hash |
Hash of temperature, top_p, max_tokens, stop | sha256:41ab... |
tools_hash |
Hash of tool schemas if tool calling is used | sha256:77de... |
kb_version |
Version of the knowledge base or RAG index | kb-2026-02-11 |
locale |
Response language | ru |
If any field changes, the key changes, and the request goes to the model. This eliminates most of the problem without manual intervention.
import hashlib, json
def cache_key(prompt: str, prompt_version: str, model_id: str,
params: dict, tools: list, kb_version: str, locale: str) -> str:
payload = {
"prompt": hashlib.sha256(prompt.encode()).hexdigest(),
"prompt_version": prompt_version,
"model_id": model_id,
"params": hashlib.sha256(
json.dumps(params, sort_keys=True).encode()
).hexdigest(),
"tools": hashlib.sha256(
json.dumps(tools, sort_keys=True).encode()
).hexdigest(),
"kb_version": kb_version,
"locale": locale,
}
raw = json.dumps(payload, sort_keys=True).encode()
return "llm:" + hashlib.sha256(raw).hexdigest()
Related concepts: Prompt Cache, Prompt Versioning, Semantic Caching.
Tags and Cascading Invalidation
Key versioning does not help when an external resource changes but the key remains the same. Example: a document in the knowledge base is updated, but kb_version is not incremented. Solution — store a set of tags alongside the record and invalidate by them.
{
"key": "llm:8c1f...",
"value": "...",
"tags": ["kb:policy-docs", "prompt:summary-v14", "tenant:42"],
"created_at": "2026-02-11T09:14:00Z",
"ttl_seconds": 86400
}
Upon updating the policy-docs document, the service calls invalidate_by_tag("kb:policy-docs"). All records with this tag are deleted or marked as stale.
flowchart LR
A[Document Update] --> B[Event kb.updated]
B --> C[Invalidate by tag kb:policy-docs]
C --> D[Cache record deletion]
D --> E[Next request goes to model]
E --> F[Write new response]
The cascade is built by levels: a prompt change invalidates records with the tag prompt:<name>, a model change — with the tag model:<id>, a tenant rule change — with the tag tenant:<id>. A request can have multiple tags, and any of them can reset it.
Strategies for Partial Changes
Full reset is expensive. If one section of the knowledge base changes, there's no need to invalidate the entire cache. I apply three approaches:
- Granular tags. The tag corresponds not to the entire base but to a specific section or document. Invalidation affects only related records.
- Section-level versioning. The key includes
section_versionfor each source that enters the context. A section change alters the key only for requests that used it. - Soft invalidation. The record is marked as stale but remains available as a fallback when the model is unavailable. This reduces the risk of total failure.
Soft invalidation is useful in conjunction with provider fallback: if the primary provider is unavailable, an outdated but valid response is served, not an error.
Observability and Metrics
Without metrics, it's impossible to understand if invalidation is working. I track:
| Metric | What it shows | Target Value |
|---|---|---|
cache_hit_rate |
Proportion of requests served from cache | 0.4–0.7 |
stale_serve_rate |
Proportion of responses from outdated records | < 0.02 |
invalidation_lag |
Delay between event and reset | < 5 s |
invalidation_fanout |
Number of deleted records per event | control outliers |
A sudden rise in invalidation_fanout indicates that tags are too broad. A drop in cache_hit_rate under stable load suggests that the key includes a mutable field, such as timestamp or session identifier.
Tracing is convenient through LLM Observability Tracing, adding attributes cache_key, cache_status, and invalidation_tags to spans.
Typical Mistakes
- Timestamp in the key. Any field with current time makes the cache useless.
- User identifier in the key without necessity. Personalization should go through tags, not through the full key, otherwise hit rate drops to zero.
- Invalidation without prompt version. Template updates do not reset the cache, users see old responses.
- Resetting the entire cache on each deployment. Leads to peak API load and cost increase.
- Lack of TTL. Records accumulate, memory grows, storage cost exceeds savings.
Implementation Checklist
- Fix the fields of the key and cover them with tests.
- Introduce a prompt registry with versions and link it to the key.
- Tag records when saving.
- Subscribe to knowledge base and model update events.
- Set up hit rate, stale rate, and lag metrics.
- Limit invalidation fanout and alert on exceedance.
- Keep TTL as a safeguard, not as the primary mechanism.
Practical implementation of caching is described in the guide LLM API Caching Strategies: Strategies and Practical Implementation, and the overall economics in the post llm-cache-strategies.