13. RAG Caching Strategies¶
Category: Production RAG Engineering
Module: Part VI โ Production Deployment
Difficulty: Advanced
๐ Overview¶
Caching is one of the most important techniques for making production RAG systems:
A naive RAG request may execute:
User Query
โ
Query Processing
โ
Embedding
โ
Vector Search
โ
Keyword Search
โ
Fusion
โ
Reranking
โ
Context Assembly
โ
LLM
โ
Validation
If the same or similar request is repeated, executing every stage again can waste:
A production RAG architecture should therefore consider caching at multiple levels:
RAG CACHE LAYERS
โ
โโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโ
โผ โผ โผ
Embedding Cache Retrieval Cache Rerank Cache
โ โ โ
โโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโ
โผ
Context Cache
โ
โผ
Semantic Cache
โ
โผ
Response Cache
However:
Caching in RAG is harder than caching a normal API response because knowledge, authorization, indexes, models, prompts, and retrieval strategies can all change.
The core challenge is therefore:
๐ฏ Learning Objectives¶
After completing this chapter, you will be able to:
- Understand why caching is important in RAG
- Identify different RAG caching layers
- Design embedding caches
- Design retrieval caches
- Design reranking caches
- Design context caches
- Design semantic caches
- Design response caches
- Design tenant-aware caches
- Design authorization-aware caches
- Design version-aware cache keys
- Select appropriate TTL strategies
- Design cache invalidation
- Handle document updates
- Handle index updates
- Handle embedding model changes
- Handle prompt changes
- Prevent cache stampedes
- Handle cache penetration
- Handle cache avalanche
- Use cache warming
- Use distributed caching
- Understand cache consistency
- Measure cache effectiveness
- Optimize cache cost
- Design cache observability
- Integrate caching with CI/CD
- Design production-grade RAG caching architecture
๐ง 1. Why Cache RAG?¶
Consider a request:
Suppose:
Total:
A cache hit could reduce the request to:
depending on the cache layer.
๐ง 2. RAG Cost Model¶
A simplified request cost can be viewed as:
Caching can reduce repeated execution of some or all of these stages.
๐ง 3. RAG Cache Taxonomy¶
flowchart TD
A["User Query"] --> B["Query Cache"]
B -->|Miss| C["Embedding Cache"]
C -->|Miss| D["Embedding Model"]
D --> E["Retrieval Cache"]
E -->|Miss| F["Retrieval"]
F --> G["Rerank Cache"]
G -->|Miss| H["Reranker"]
H --> I["Context Cache"]
I -->|Miss| J["Context Assembly"]
J --> K["Semantic Cache"]
K -->|Miss| L["LLM"]
L --> M["Response Cache"]
Different cache layers solve different problems.
๐ง 4. Main RAG Cache Layers¶
A production RAG platform may use:
1. Document Cache
2. Parsing Cache
3. Embedding Cache
4. Query Embedding Cache
5. Retrieval Cache
6. Reranking Cache
7. Context Cache
8. Semantic Cache
9. Response Cache
10. Model Output Cache
Not every system needs all of them.
๐ง 5. Cache Placement¶
A useful architecture:
USER
โ
โผ
Response Cache
โ
โโโโโโโดโโโโโโ
โ โ
Hit Miss
โ โ
โผ โผ
RESPONSE Semantic Cache
โ
โโโโโโโดโโโโโโ
โ โ
Hit Miss
โ โ
โผ โผ
RESPONSE Retrieval
โ
โโโโโโโโโโโผโโโโโโโโโโ
โผ โผ โผ
Embedding Retrieval Rerank
Cache Cache Cache
๐ง 6. Cache Layer Selection¶
Do not cache everything.
Ask:
Is this operation expensive?
Is the result reusable?
How frequently does the input repeat?
How frequently does the result change?
Is the result security-sensitive?
Can stale data be tolerated?
What is the cost of storing it?
๐ง 7. Embedding Cache¶
Embedding generation is often deterministic for:
Therefore:
๐ง 8. Embedding Cache Architecture¶
flowchart LR
A["Text"] --> B["Content Hash"]
B --> C["Embedding Cache"]
C -->|Hit| D["Vector"]
C -->|Miss| E["Embedding Model"]
E --> F["Vector"]
F --> C
๐ง 9. Embedding Cache Key¶
A weak key:
A stronger key:
Example:
๐ง 10. Why Model Version Matters¶
Suppose:
creates:
Then:
creates:
The old cache must not accidentally return:
for a V2 request.
๐ง 11. Embedding Cache Scope¶
Embedding caches are often good candidates for broader reuse because the vector represents content rather than a user's authorization.
However, sensitive systems should still consider:
especially when cached content itself is stored.
๐ง 12. Query Embedding Cache¶
User queries can also be cached:
This is useful when:
๐ง 13. Retrieval Cache¶
Retrieval caching stores search results:
Cache:
๐ง 14. Retrieval Cache Architecture¶
flowchart TD
A["Query"] --> B["Retrieval Cache"]
B -->|Hit| C["Cached Candidates"]
B -->|Miss| D["Dense / Sparse Retrieval"]
D --> E["Candidate Results"]
E --> B
E --> C
๐ง 15. Retrieval Cache Key¶
A production retrieval key should include the parameters that influence the result.
Example:
Conceptually:
๐ง 16. Why Index Version Matters¶
Suppose:
returns:
After deployment:
returns:
An old retrieval cache must not silently override the new index.
๐ง 17. Reranking Cache¶
Reranking can be expensive.
Example:
If the same candidate set is reranked repeatedly:
can avoid repeated computation.
๐ง 18. Reranking Cache Key¶
Include:
Example:
๐ง 19. Context Cache¶
Context assembly may include:
The resulting evidence package can be cached.
๐ง 20. Context Cache Risk¶
Context can become stale when:
Document Changes
Index Changes
Authorization Changes
Retrieval Strategy Changes
Context Strategy Changes
Therefore context caches need stronger invalidation/versioning than simple application caches.
๐ง 21. Semantic Cache¶
A semantic cache attempts to reuse results for:
rather than exact queries.
Example:
These may be semantically equivalent.
๐ง 22. Exact Cache vs Semantic Cache¶
Exact Cache¶
Semantic Cache¶
๐ง 23. Semantic Cache Architecture¶
flowchart TD
A["New Query"] --> B["Query Embedding"]
B --> C["Semantic Cache Search"]
C --> D{"Similarity > Threshold?"}
D -->|Yes| E["Cached Result"]
D -->|No| F["Normal RAG Pipeline"]
F --> G["Store Result"]
๐ง 24. Semantic Cache Threshold¶
A semantic cache requires a similarity threshold.
Conceptually:
where:
A threshold that is too low may return incorrect answers.
A threshold that is too high reduces cache hits.
๐ง 25. Semantic Cache Is Not Always Safe¶
Consider:
and:
These may be semantically similar but require different answers.
Therefore semantic caching should consider:
๐ง 26. Response Cache¶
The simplest cache:
Example:
๐ง 27. Response Cache Architecture¶
flowchart LR
A["User"] --> B["Response Cache"]
B -->|Hit| C["Response"]
B -->|Miss| D["RAG Pipeline"]
D --> E["Response"]
E --> B
๐ง 28. Response Cache Key¶
A production response cache should consider:
Query
Tenant
Authorization Scope
Prompt Version
Model Version
Retriever Version
Index Version
Language
Application Version
Potentially:
if the response depends on them.
๐ง 29. Response Cache Security¶
This is one of the most important caching concerns.
Unsafe:
Example:
Then:
If access scopes differ, User B may receive unauthorized information.
๐ง 30. Tenant-Aware Caching¶
Use:
as part of the cache key.
Example:
๐ง 31. Authorization-Aware Cache¶
Tenant ID alone may not be enough.
Two users in the same tenant may have different permissions.
A stronger cache scope can include:
or a stable authorization-scope identifier.
๐ง 32. Cache Isolation Strategies¶
Strategy 1 โ Shared Cache + Strong Key¶
Strategy 2 โ Namespace Isolation¶
Strategy 3 โ Dedicated Cache¶
๐ง 33. Shared vs Dedicated Cache¶
| Strategy | Cost | Isolation | Complexity |
|---|---|---|---|
| Shared | Low | Medium | Low |
| Namespaced | Medium | High | Medium |
| Dedicated | High | Very High | High |
The appropriate choice depends on:
๐ง 34. Cache TTL¶
TTL means:
Example:
๐ง 35. TTL Strategy by Cache Type¶
A possible starting point:
Embedding Cache
โ Long TTL
Retrieval Cache
โ Short / Medium TTL
Reranking Cache
โ Short / Medium TTL
Semantic Cache
โ Short / Medium TTL
Response Cache
โ Depends heavily on freshness requirements
These are starting points, not universal values.
๐ง 36. Freshness-Based TTL¶
Instead of one global TTL:
Static Policy
โ Long TTL
Frequently Changing Data
โ Short TTL
Real-Time Data
โ Very Short TTL / No Cache
๐ง 37. Data Volatility¶
Classify knowledge:
LOW VOLATILITY
Policies
Documentation
MEDIUM VOLATILITY
Product Information
HIGH VOLATILITY
Inventory
Prices
Transactions
REAL-TIME
Account Balance
Market Data
Live Status
Caching strategy should reflect volatility.
๐ง 38. Cacheability Matrix¶
| Data | Cache? | Typical Strategy |
|---|---|---|
| Static Documentation | Yes | Long TTL |
| Enterprise Policies | Yes | Version-aware |
| Product Documentation | Yes | Version-aware |
| Frequently Updated Data | Carefully | Short TTL |
| Transaction Data | Carefully | Very short / bypass |
| User-Specific Data | Carefully | User-scoped |
| Highly Sensitive Data | Restricted | Strong isolation |
| Real-Time Data | Usually limited | Bypass / short TTL |
๐ง 39. Cache Invalidation¶
One of the hardest problems in production RAG is:
Potential invalidation triggers:
Document Update
Document Delete
Index Update
Embedding Model Update
Retriever Update
Reranker Update
Prompt Update
Model Update
Authorization Update
Tenant Policy Update
๐ง 40. Invalidation Strategies¶
Common approaches:
TTL
Explicit Invalidation
Versioned Keys
Event-Driven Invalidation
Write-Through
Write-Behind
Cache Busting
๐ง 41. Versioned Cache Keys¶
One of the safest techniques:
When the index changes:
Old entries naturally become unused.
๐ง 42. Versioned Cache Architecture¶
No need to delete every old entry immediately.
๐ง 43. Event-Driven Invalidation¶
flowchart LR
A["Document Updated"] --> B["Change Event"]
B --> C["Cache Invalidation"]
C --> D["Affected Entries Removed"]
B --> E["Index Update"]
๐ง 44. Document-Level Invalidation¶
Suppose:
changes.
Invalidate cache entries referencing:
This requires maintaining relationships:
๐ง 45. Invalidation Granularity¶
Possible levels:
Smaller invalidation scope generally reduces unnecessary cache misses but increases implementation complexity.
๐ง 46. Cache Invalidation Architecture¶
flowchart TD
A["Document Change"] --> B["Event Bus"]
B --> C["Identify Affected Index"]
C --> D["Identify Affected Cache Entries"]
D --> E["Invalidate"]
E --> F["Next Request"]
F --> G["Fresh Retrieval"]
๐ง 47. Cache Stampede¶
A cache stampede occurs when many requests simultaneously miss the same cache entry.
1000 Requests
โ
โผ
Cache Miss
โ
โโโ Retrieval
โโโ Retrieval
โโโ Retrieval
โโโ Retrieval
โโโ ...
This can overload:
๐ง 48. Preventing Cache Stampede¶
Use:
Request Coalescing
Single Flight
Distributed Lock
Jittered TTL
Probabilistic Refresh
Background Refresh
๐ง 49. Request Coalescing¶
Request A โโ
Request B โโค
Request C โโผโโโ One Computation
Request D โโค
Request E โโ
Other requests wait for the same result.
๐ง 50. Single-Flight Pattern¶
Conceptually:
if cache.exists(key):
return cache.get(key)
if computation_in_progress(key):
return await existing_computation(key)
create_computation(key)
result = compute()
cache.set(key, result)
return result
๐ง 51. Distributed Lock¶
For distributed applications:
Other requests:
Use carefully to avoid deadlocks and excessive waiting.
๐ง 52. TTL Jitter¶
If many entries expire simultaneously:
This can create a load spike.
Instead:
๐ง 53. Cache Avalanche¶
A cache avalanche occurs when many entries expire or become invalid at once.
Example:
Mitigation:
๐ง 54. Cache Penetration¶
Cache penetration occurs when requests repeatedly ask for data that does not exist.
Repeated malicious or invalid queries can overload the backend.
๐ง 55. Cache Penetration Mitigation¶
Use:
Example:
๐ง 56. Negative Caching¶
Example:
If retrieval repeatedly returns no evidence:
for a short TTL.
Do not use a long TTL because knowledge may later appear.
๐ง 57. Semantic Cache False Positive¶
Suppose:
A naive semantic cache may consider them similar.
Result:
Therefore semantic caches should incorporate:
๐ง 58. Semantic Cache Guardrails¶
A semantic cache hit should satisfy:
Semantic Similarity
+
Same Tenant
+
Compatible Authorization
+
Compatible Filters
+
Compatible Time Scope
+
Compatible Knowledge Version
๐ง 59. Query Normalization¶
Before exact caching, normalize queries.
Examples:
Depending on application semantics, normalization may include:
Do not normalize away meaningful information.
๐ง 60. Query Fingerprinting¶
Create a stable representation:
import hashlib
def fingerprint(query: str) -> str:
normalized = query.strip().lower()
return hashlib.sha256(
normalized.encode("utf-8")
).hexdigest()
Production implementations should normalize according to domain semantics.
๐ง 61. Cache Key Design¶
A general cache key:
For example:
query
+
tenant
+
authorization_scope
+
retriever_version
+
index_version
+
prompt_version
+
model_version
๐ง 62. Cache Key Hierarchy¶
This makes operational inspection easier.
๐ง 63. Cache Namespaces¶
Possible namespaces:
Example:
๐ง 64. Distributed Cache¶
A distributed cache such as Redis can provide:
Typical architecture:
๐ง 65. Local vs Distributed Cache¶
Local Cache¶
Advantages:
Limitations:
Distributed Cache¶
Advantages:
Trade-off:
๐ง 66. Two-Level Cache¶
A powerful architecture:
Request
โ
L1 Local Cache
โ
โโโ Hit โ Return
โ
โโโ Miss
โ
L2 Distributed Cache
โ
โโโ Hit โ Populate L1
โ
โโโ Miss โ Compute
๐ง 67. Two-Level Cache¶
flowchart LR
A["Request"] --> B["L1 Local Cache"]
B -->|Hit| C["Response"]
B -->|Miss| D["L2 Distributed Cache"]
D -->|Hit| E["Populate L1"]
E --> C
D -->|Miss| F["RAG Pipeline"]
F --> G["Populate L2"]
G --> H["Populate L1"]
H --> C
๐ง 68. Cache Serialization¶
Cache entries may contain:
Choose based on:
๐ง 69. What Should Be Cached?¶
Good candidates:
Embeddings
Stable Retrieval Results
Reranking Results
Stable Evidence Packages
Repeated FAQ Responses
Poor candidates:
๐ง 70. Cache Compression¶
Large cached evidence can consume significant memory.
Use compression when:
Trade-off:
๐ง 71. Cache Warming¶
Pre-populate frequently requested entries.
Useful for:
๐ง 72. Cache Warming Pipeline¶
flowchart LR
A["Golden Queries"] --> B["Warmup Job"]
B --> C["RAG Pipeline"]
C --> D["Cache"]
D --> E["Production"]
๐ง 73. Cache Refresh¶
Instead of waiting for expiration:
Users continue receiving the previous valid value while the new result is computed.
๐ง 74. Stale-While-Revalidate¶
Conceptually:
Useful when:
Avoid for strict real-time or highly regulated data where stale information is unacceptable.
๐ง 75. Cache Consistency Models¶
Possible models:
RAG often uses:
for knowledge indexes and caches.
But some security-related state may require stronger guarantees.
๐ง 76. Security State Should Not Be Stale¶
Be particularly careful with:
A stale authorization cache can become a security vulnerability.
๐ง 77. Authorization Cache¶
If authorization decisions are cached:
should be considered in the key.
Also define:
for sensitive environments.
๐ง 78. Cache and Document Updates¶
Suppose:
Then:
is published.
Potential stale path:
Therefore:
๐ง 79. Cache and Prompt Updates¶
If:
produces:
then:
should not necessarily reuse the old response.
Use:
in the response cache key.
๐ง 80. Cache and Model Updates¶
Similarly:
and:
may generate different outputs.
Therefore include:
where response correctness depends on it.
๐ง 81. Cache and Retriever Updates¶
Changing:
can change:
Therefore retrieval caches should include:
๐ง 82. Cache and Context Strategy¶
Changing:
can change final evidence.
Therefore context cache keys should include:
๐ง 83. Cache Dependency Graph¶
flowchart TD
A["Document"] --> B["Index"]
B --> C["Retrieval"]
D["Retriever Version"] --> C
C --> E["Reranking"]
E --> F["Context"]
G["Prompt Version"] --> H["Response"]
F --> H
I["Model Version"] --> H
A cache should be invalidated when one of its dependencies changes.
๐ง 84. Dependency-Aware Cache¶
Think of a cached response as:
Response
โ
โโโ Query
โโโ Tenant
โโโ Authorization
โโโ Retrieval
โโโ Index
โโโ Context
โโโ Prompt
โโโ Model
Changing any critical dependency may invalidate the result.
๐ง 85. Cache Dependency Fingerprint¶
A practical pattern:
dependency_fingerprint =
hash(
index_version
+
retriever_version
+
prompt_version
+
model_version
+
policy_version
)
Use the fingerprint as part of the cache key.
๐ง 86. Cache Hit Rate¶
Basic metric:
Example:
๐ง 87. Cache Miss Rate¶
Example:
๐ง 88. Cache Effectiveness¶
Hit rate alone is not enough.
Consider:
A cache with:
may still be poor if the cached operation is cheap.
๐ง 89. Cache Metrics¶
Monitor:
Hit Rate
Miss Rate
Eviction Rate
Entry Count
Memory Usage
Latency
Refresh Rate
Invalidation Rate
Error Rate
Stampede Events
๐ง 90. RAG-Specific Cache Metrics¶
Track:
Embedding Cache Hit Rate
Retrieval Cache Hit Rate
Reranking Cache Hit Rate
Semantic Cache Hit Rate
Response Cache Hit Rate
Also:
๐ง 91. Cost Savings¶
Approximate:
Track actual savings rather than assuming every cache hit has the same value.
๐ง 92. Cache Latency¶
Track:
The cache itself must not become a bottleneck.
๐ง 93. Cache Capacity Planning¶
Estimate:
plus overhead.
๐ง 94. Example¶
Suppose:
Raw payload:
Actual memory requirement is higher due to:
๐ง 95. Cache Eviction¶
Common policies:
LRU¶
Good for workloads where recent queries are more likely to repeat.
LFU¶
Useful when popular queries should remain cached.
๐ง 96. RAG Cache Eviction Strategy¶
A combination can be useful:
For example:
๐ง 97. Cache Admission¶
Not every result deserves caching.
Example:
Potential admission signals:
๐ง 98. Cost-Aware Cache Admission¶
Cache expensive operations first.
Example:
Cheap Retrieval
โ Low Priority
Expensive Reranking
โ High Priority
Expensive LLM Response
โ High Priority
๐ง 99. Query Frequency¶
A simple strategy:
First Request
โ
Compute
Second Request
โ
Compute
Third Request
โ
Cache
Repeated Requests
โ
Cache
This avoids filling the cache with one-time queries.
๐ง 100. Cache Pollution¶
Cache pollution occurs when low-value entries consume memory.
Examples:
Mitigate with:
๐ง 101. Bot Traffic¶
Bots can generate:
which can cause:
Use:
๐ง 102. Cache Security¶
Protect cached data with:
๐ง 103. Sensitive Cache Data¶
Be careful caching:
Possible policies:
๐ง 104. Cache Encryption¶
Consider:
๐ง 105. Cache and Compliance¶
Compliance requirements may influence:
A cache is still a data store.
๐ง 106. Cache Deletion¶
When a user or document must be deleted:
Deletion workflows should account for derived cached data where required.
๐ง 107. Cache Invalidation on Deletion¶
flowchart TD
A["Document Deleted"] --> B["Deletion Event"]
B --> C["Delete From Index"]
B --> D["Invalidate Retrieval Cache"]
B --> E["Invalidate Context Cache"]
B --> F["Invalidate Response Cache"]
๐ง 108. Cache Observability¶
Every cache operation should ideally emit:
Avoid logging sensitive key contents.
๐ง 109. Example Cache Log¶
{
"cache": "retrieval",
"result": "hit",
"tenant": "tenant-a",
"latency_ms": 3,
"index_version": "v17"
}
๐ง 110. Distributed Cache Failure¶
What happens if Redis fails?
Do not assume:
Prefer:
when backend capacity allows.
๐ง 111. Cache as an Optimization¶
A critical principle:
The cache should usually accelerate the system, not become the system's only source of truth.
Architecture:
๐ง 112. Cache Failure Strategy¶
flowchart TD
A["Request"] --> B["Cache"]
B -->|Available| C{"Hit?"}
C -->|Yes| D["Return"]
C -->|No| E["RAG Pipeline"]
B -->|Unavailable| E
E --> F["Response"]
๐ง 113. Circuit Breaker for Cache¶
If cache infrastructure becomes unhealthy:
This prevents cache failure from increasing application latency.
๐ง 114. Cache Warmup After Restart¶
After a cache restart:
Mitigate with:
๐ง 115. Cache Warmup Priorities¶
Warm:
rather than everything.
๐ง 116. Cache Precomputation¶
For known workloads:
Useful for:
๐ง 117. Cache and Streaming¶
Response caching can be more complicated when responses stream.
Possible approach:
Do not cache incomplete or failed responses.
๐ง 118. Cache Only Validated Responses¶
Prefer:
rather than:
Otherwise invalid output can be reused.
๐ง 119. Cache Poisoning¶
A cache poisoning scenario occurs when incorrect or malicious output becomes cached.
Potential causes:
Mitigation:
๐ง 120. Semantic Cache Poisoning¶
Semantic caches require extra caution.
A bad answer for:
could be incorrectly reused for:
Therefore semantic cache entries should carry:
๐ง 121. Cache Provenance¶
A response cache entry can store:
{
"response": "...",
"document_ids": [
"doc-123",
"doc-456"
],
"index_version": "v17",
"retriever_version": "v8",
"prompt_version": "v9",
"model_version": "v4",
"validated": true
}
This enables stronger invalidation and auditing.
๐ง 122. Cache Dependency Graph¶
The further downstream a cache is placed, the more dependencies it typically has.
๐ง 123. Cache Complexity¶
Conceptually:
Embedding Cache
โ
Few Dependencies
Retrieval Cache
โ
More Dependencies
Context Cache
โ
More Dependencies
Response Cache
โ
Many Dependencies
Therefore:
Downstream caches generally require stronger invalidation and versioning strategies.
๐ง 124. Cache Architecture Recommendation¶
A mature production RAG system may use:
L1:
Local Cache
L2:
Distributed Cache
Pipeline:
Embedding Cache
Retrieval Cache
Reranking Cache
Application:
Semantic Cache
Optional:
Response Cache
Do not automatically enable every layer.
๐ง 125. Recommended Cache Selection¶
Low Traffic¶
Medium Traffic¶
High Traffic¶
FAQ Workload¶
Highly Dynamic Workload¶
๐ง 126. Cache Architecture¶
flowchart TD
A["User"] --> B["L1 Cache"]
B -->|Hit| C["Response"]
B -->|Miss| D["L2 Distributed Cache"]
D -->|Hit| E["Response"]
D -->|Miss| F["RAG Orchestrator"]
F --> G["Embedding Cache"]
G --> H["Retrieval Cache"]
H --> I["Reranking Cache"]
I --> J["Context Engine"]
J --> K["Semantic Cache"]
K --> L["LLM"]
L --> M["Validation"]
M --> N["Citation"]
N --> O["Response"]
O --> D
O --> B
๐ง 127. Cache Strategy by Pipeline Stage¶
| Stage | Cache Candidate | Main Concern |
|---|---|---|
| Document Parsing | Yes | Source version |
| Embedding | Yes | Model version |
| Retrieval | Yes | Index version |
| Reranking | Yes | Candidate/version changes |
| Context | Yes | Evidence freshness |
| Semantic | Yes | False positives |
| Response | Yes | Security/freshness |
๐ง 128. Cache Decision Tree¶
Is the operation expensive?
โ
โโโ No โ Probably don't cache
โ
โโโ Yes
โ
โผ
Is the result reusable?
โ
โโโ No โ Don't cache
โ
โโโ Yes
โ
โผ
Can stale results be tolerated?
โ
โโโโโโดโโโโโ
โผ โผ
Yes No
โ โ
โผ โผ
Cache Short TTL /
Versioning /
Invalidation
๐ง 129. Cache Strategy by Risk¶
LOW RISK
โ
Aggressive Caching
MEDIUM RISK
โ
Version + TTL
HIGH RISK
โ
Strict Invalidation
REAL-TIME / SECURITY CRITICAL
โ
Bypass or Minimal Cache
๐ง 130. Cache Testing¶
Caching must be tested independently.
Test:
Hit
Miss
Expiration
Invalidation
Concurrent Requests
Cache Failure
Cache Restart
Version Change
Tenant Isolation
Authorization Change
Document Update
๐งช 131. Cache Unit Tests¶
Test:
๐งช 132. Cache Integration Tests¶
Verify:
Test:
๐งช 133. Cache Security Tests¶
Test:
Tenant A โ Tenant A Cache โ
Tenant A โ Tenant B Cache โ
Authorized User โ Response โ
Unauthorized User โ Response โ
๐งช 134. Cache Stampede Test¶
Simulate:
for the same missing key.
Expected:
rather than:
๐งช 135. Cache Invalidation Test¶
Scenario:
Expected:
๐งช 136. Cache Failure Test¶
Simulate:
Expected:
provided the backend can safely absorb the load.
๐งช 137. Cache Performance Test¶
Measure:
๐งช 138. Cache Load Test¶
Test:
๐ง 139. Cache Monitoring Dashboard¶
A production dashboard should show:
Cache Hit Rate
Cache Miss Rate
Cache Latency
Eviction Rate
Memory Usage
Entry Count
Invalidation Rate
Stampede Events
Backend Load
LLM Calls Avoided
Cost Saved
๐ง 140. Cache Cost Model¶
A distributed cache has its own cost:
Therefore:
should generally be the goal.
๐ง 141. Cache ROI¶
A simple conceptual model:
More sophisticated analysis should include:
๐ง 142. Cache Anti-Patterns¶
Anti-Pattern 1 โ Global Response Cache¶
without authorization-aware keys.
Anti-Pattern 2 โ Cache Without Versioning¶
Anti-Pattern 3 โ Infinite TTL¶
This creates stale knowledge.
Anti-Pattern 4 โ Cache Everything¶
This causes:
Anti-Pattern 5 โ No Stampede Protection¶
Anti-Pattern 6 โ Cache Before Validation¶
Invalid answers may become reusable.
Anti-Pattern 7 โ Ignore Deletion¶
Anti-Pattern 8 โ Treat Cache as Source of Truth¶
A cache should generally be a derived optimization.
๐ง 143. Production Cache Checklist¶
โ Cache layers identified
โ Cache ownership defined
โ Cache keys versioned
โ Tenant isolation implemented
โ Authorization scope considered
โ TTL defined
โ Invalidation strategy defined
โ Document update invalidation handled
โ Index version handled
โ Embedding version handled
โ Prompt version handled
โ Model version handled
โ Cache stampede protection
โ Cache avalanche protection
โ Cache penetration protection
โ Negative caching considered
โ Cache warming considered
โ Cache failure fallback
โ Cache encryption
โ Cache observability
โ Cache capacity planning
โ Cache load testing
โ Cache security testing
โ Cache cost tracking
๐ง 144. Recommended Production Pattern¶
A strong default architecture is:
REQUEST
โ
โผ
L1 Cache
โ
โโโโโโดโโโโโ
โผ โผ
Hit Miss
โ โ
โ โผ
โ L2 Distributed
โ Cache
โ โ
โ โโโโโโดโโโโโ
โ โผ โผ
โ Hit Miss
โ โ โ
โ โ โผ
โ โ RAG Pipeline
โ โ โ
โ โ โโโโโโผโโโโโ
โ โ โผ โผ โผ
โ โ Embed Retrieve Rerank
โ โ Cache Cache Cache
โ โ โ โ โ
โ โ โโโโโโผโโโโโโโ
โ โ โผ
โ โ Context
โ โ โ
โ โ โผ
โ โ Semantic
โ โ Cache
โ โ โ
โ โ โโโโดโโโ
โ โ โผ โผ
โ โ Hit Miss
โ โ โ โ
โ โ โ LLM
โ โ โ โ
โ โ โ Validate
โ โ โ โ
โ โ โ Citation
โ โ โ โ
โโโโโโดโโโโโโโดโโโโโโ
โ
โผ
RESPONSE
๐ง 145. Final Mental Model¶
RAG caching should be thought of as:
RAG CACHING
โ
โโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโ
โผ โผ โผ
SPEED COST SCALABILITY
โ โ โ
โโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโ
โผ
CORRECTNESS
โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโ
โผ โผ โผ
Freshness Security Versioning
โ โ โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโ
โผ
INVALIDATION
โ
โผ
OBSERVABILITY
๐ง 146. Cache Strategy Formula¶
A useful architectural mental model:
A cache that is fast but returns unauthorized or stale information is not a successful production cache.
๐ง 147. Final Key Takeaways¶
- Caching can significantly reduce RAG latency and cost.
- RAG should generally use multiple cache layers selectively.
- Embedding caching avoids repeated embedding computation.
- Retrieval caching avoids repeated search operations.
- Reranking caching avoids repeated expensive ranking.
- Context caching can avoid repeated evidence assembly.
- Semantic caching enables reuse across similar queries.
- Response caching provides the largest potential savings but also carries the highest correctness and security risk.
- Exact caching is safer than semantic caching because the reuse condition is explicit.
- Semantic caching requires similarity thresholds and strong contextual guardrails.
- Cache keys must include every important dependency that can change the result.
- Tenant identity should generally be included in security-sensitive cache keys.
- Authorization scope must be considered when caching protected responses.
- Index version should be included in retrieval-related cache keys.
- Embedding version should be included in embedding-related cache keys.
- Retriever version should be included in retrieval cache keys.
- Prompt version and model version should be considered for response caches.
- TTL alone is rarely sufficient for enterprise RAG.
- Versioned cache namespaces provide a powerful invalidation mechanism.
- Event-driven invalidation is useful for knowledge-driven systems.
- Document-level invalidation can reduce unnecessary cache eviction.
- Cache stampedes can overload downstream RAG components.
- Single-flight, request coalescing, locks, jitter, and background refresh can mitigate stampedes.
- Cache avalanche can occur when many entries expire simultaneously.
- Cache penetration can occur when invalid or nonexistent queries repeatedly bypass the cache.
- Negative caching can reduce repeated no-result queries.
- Cache admission policies prevent cache pollution.
- Cache warming can reduce cold-start load.
- Stale-while-revalidate can improve latency when controlled staleness is acceptable.
- Cache failure should ideally degrade the system rather than bring down RAG.
- A cache should generally be an optimization layer, not the authoritative source of truth.
- Cached responses should preferably be validated before they become reusable.
- Cache entries can carry provenance and dependency metadata.
- Cache invalidation must account for document, index, model, prompt, retriever, and authorization changes.
- Two-level caches can combine local speed with distributed consistency.
- Cache eviction policies such as LRU and LFU help manage finite memory.
- Cache observability should include hits, misses, latency, evictions, invalidations, memory, and backend load.
- Measure LLM calls and tokens avoided to quantify RAG cache value.
- Cache cost must be compared against the cost saved.
- Sensitive information may require restricted or disabled caching.
- Cache deletion must be included in data deletion workflows.
- Cache testing should include concurrency, failure, invalidation, security, and stampede scenarios.
- The best cache architecture is not the one with the most cache layers.
- The best architecture is the one that maximizes safe reuse while preserving correctness, freshness, security, and operational simplicity.
๐งญ 148. Chapter Navigation¶
Part VI โ Production RAG Deployment & Operations¶
Previous:
12. RAG Deployment Patterns
Next:
14. Multi-Tenant RAG
Production RAG Engineering Path¶
01 Prompt Assembly
โ
02 Context Selection & Context Engineering
โ
03 Response Validation
โ
04 Citation & Source Attribution
โ
05 Enterprise Response
โ
06 RAG Evaluation & Benchmarking
โ
07 RAG Observability
โ
08 RAG Performance Optimization
โ
09 RAG Cost Optimization
โ
10 Production Retrieval Architecture
โ
11 Building Production RAG Systems
โ
12 RAG Deployment Patterns
โ
13 RAG Caching Strategies
โ
14 Multi-Tenant RAG
โ
15 RAG Testing Frameworks
โ
16 RAG Failure Patterns
Enterprise AI Engineering Handbook
Building Production-Grade Enterprise AI Systems โ One Chapter at a Time.