LLM Response Caching Layer
Implement semantic and exact-match caching for LLM API responses to reduce costs 40-60% and cut P50 latency from seconds to milliseconds.
Activation Triggers
Activate on: "cache LLM responses", "semantic cache", "reduce OpenAI costs", "LLM API caching", "cache embeddings", "deduplicate LLM calls", "response memoization for AI"
NOT for: General HTTP/CDN caching (caching-strategies), browser cache headers (caching-strategies), or database query caching (ORM-specific)
Quick Start
- Classify request types — Deterministic (structured extraction, classification) vs. creative (open-ended generation). Deterministic requests are highly cacheable.
- Choose cache strategy — Exact-match (hash of prompt + params) for deterministic requests, semantic similarity for natural language queries.
- Set up cache store — Redis for exact-match (fast, TTL-native), vector DB for semantic cache (similarity search).
- Integrate as middleware — Wrap your LLM client with a cache-check layer that intercepts before API calls.
- Monitor hit rates — Target 30-50% hit rate for mixed workloads, 70%+ for classification/extraction.
Core Capabilities
| Domain |
Technologies |
Notes |
| Exact-Match Cache |
Redis, DynamoDB, Memcached |
Hash(prompt + model + temperature + params) as key |
| Semantic Cache |
GPTCache, Qdrant, Pinecone, pgvector |
Embed query, find similar cached responses |
| Similarity Threshold |
Cosine similarity >= 0.95 typical |
Tune per use case; lower = more hits, more risk |
| Cache Invalidation |
TTL-based, version-tagged, manual purge |
LLM responses rarely need real-time freshness |
| Observability |
Cache hit/miss rates, cost savings, latency delta |
Essential for ROI justification |
Architecture Patterns
Pattern 1: Two-Tier LLM Cache
LLM Request
│
▼
[Exact Match Cache (Redis)] ──hit──→ Return cached response (< 5ms)
│ miss
▼
[Semantic Cache (Vector DB)] ──hit (similarity > 0.95)──→ Return cached response (< 50ms)
│ miss
▼
[LLM API Call] ──→ response ──→ Store in both caches ──→ Return response
# Two-tier caching middleware
import hashlib, json, numpy as np
class LLMCacheMiddleware:
def __init__(self, redis_client, vector_db, embedder, threshold=0.95):
self.redis = redis_client
self.vdb = vector_db
self.embedder = embedder
self.threshold = threshold
def cache_key(self, prompt: str, model: str, **params) -> str:
blob = json.dumps({"prompt": prompt, "model": model, **params}, sort_keys=True)
return f"llm:{hashlib.sha256(blob.encode()).hexdigest()}"
async def query(self, prompt: str, model: str, **params) -> str:
# Tier 1: Exact match
key = self.cache_key(prompt, model, **params)
cached = await self.redis.get(key)
if cached:
return json.loads(cached)["response"] # < 5ms
# Tier 2: Semantic match
query_emb = self.embedder.embed(prompt)
results = self.vdb.search(query_emb, top_k=1)
if results and results[0].score >= self.threshold:
return results[0].payload["response"] # < 50ms
# Cache miss: call LLM
response = await llm_call(prompt, model, **params)
# Store in both tiers
await self.redis.setex(key, 86400, json.dumps({"response": response}))
self.vdb.upsert(query_emb, {"prompt": prompt, "response": response})
return response
Pattern 2: Cache-Aware Request Classification
Incoming Request
│
▼
[Classify Cacheability]
├── temperature == 0 AND structured output → HIGHLY CACHEABLE (TTL: 7 days)
├── temperature == 0 AND free-form → CACHEABLE (TTL: 24 hours)
├── temperature > 0 AND repeated pattern → SEMANTIC CACHE ONLY (TTL: 1 hour)
└── temperature > 0 AND unique/creative → DO NOT CACHE
Pattern 3: Versioned Cache with Model Upgrades
Cache Key = hash(prompt + model_version + system_prompt_version + params)
Model upgrade (gpt-4o-2026-01 → gpt-4o-2026-03):
→ All cache keys change automatically (model_version in hash)
→ Old cache entries expire via TTL
→ No manual invalidation needed
Anti-Patterns
- Caching creative/high-temperature responses — Temperature > 0.7 means the user expects variety. Caching returns identical responses and feels broken.
- Global similarity threshold — A 0.95 threshold works for factual Q&A but is too loose for code generation and too tight for casual chat. Tune per endpoint.
- No cache versioning on model upgrades — Switching from GPT-4o to Claude returns stale GPT-4o responses. Include model version in cache keys.
- Infinite TTL — Even deterministic responses can become stale when underlying data changes. Set TTL based on data freshness requirements (hours to days, not forever).
- Caching without cost tracking — You cannot prove ROI without measuring: cache hit rate, tokens saved, dollars saved, latency improvement.
Quality Checklist
1---
2license: Apache-2.0
3name: llm-response-caching-layer
4description: 'Implement semantic and exact-match caching for LLM responses to reduce cost 40-60% and latency. Activate on: LLM caching, semantic cache, reduce API costs, cache AI responses. NOT for: general web caching (caching-strategies), CDN config (cloudflare-worker-dev).'
5allowed-tools: Read,Write,Edit,Bash(python:*,pip:*,npm:*,npx:*)
6category: Backend & Infrastructure
7tags:
8 - caching
9 - llm
10 - cost-reduction
11 - semantic-cache
12 - redis
13pairs-with:
14 - skill: caching-strategies
15 reason: General cache architecture patterns inform LLM-specific cache tiers
16 - skill: llm-cost-optimizer
17 reason: Caching is a primary lever for LLM cost reduction
18 - skill: ai-engineer
19 reason: Cache layer integrates into LLM application pipelines
20metadata:
21 source: https://skillmd.com/skills/curiositech/llm-response-caching-layer
22---
23
24# LLM Response Caching Layer
25
26Implement semantic and exact-match caching for LLM API responses to reduce costs 40-60% and cut P50 latency from seconds to milliseconds.
27
28## Activation Triggers
29
30**Activate on**: "cache LLM responses", "semantic cache", "reduce OpenAI costs", "LLM API caching", "cache embeddings", "deduplicate LLM calls", "response memoization for AI"
31
32**NOT for**: General HTTP/CDN caching (caching-strategies), browser cache headers (caching-strategies), or database query caching (ORM-specific)
33
34## Quick Start
35
361. **Classify request types** — Deterministic (structured extraction, classification) vs. creative (open-ended generation). Deterministic requests are highly cacheable.
372. **Choose cache strategy** — Exact-match (hash of prompt + params) for deterministic requests, semantic similarity for natural language queries.
383. **Set up cache store** — Redis for exact-match (fast, TTL-native), vector DB for semantic cache (similarity search).
394. **Integrate as middleware** — Wrap your LLM client with a cache-check layer that intercepts before API calls.
405. **Monitor hit rates** — Target 30-50% hit rate for mixed workloads, 70%+ for classification/extraction.
41
42## Core Capabilities
43
44| Domain | Technologies | Notes |
45|--------|-------------|-------|
46| **Exact-Match Cache** | Redis, DynamoDB, Memcached | Hash(prompt + model + temperature + params) as key |
47| **Semantic Cache** | GPTCache, Qdrant, Pinecone, pgvector | Embed query, find similar cached responses |
48| **Similarity Threshold** | Cosine similarity >= 0.95 typical | Tune per use case; lower = more hits, more risk |
49| **Cache Invalidation** | TTL-based, version-tagged, manual purge | LLM responses rarely need real-time freshness |
50| **Observability** | Cache hit/miss rates, cost savings, latency delta | Essential for ROI justification |
51
52## Architecture Patterns
53
54### Pattern 1: Two-Tier LLM Cache
55
56```
57LLM Request
58 │
59 ▼
60[Exact Match Cache (Redis)] ──hit──→ Return cached response (< 5ms)
61 │ miss
62 ▼
63[Semantic Cache (Vector DB)] ──hit (similarity > 0.95)──→ Return cached response (< 50ms)
64 │ miss
65 ▼
66[LLM API Call] ──→ response ──→ Store in both caches ──→ Return response
67```
68
69```python
70# Two-tier caching middleware
71import hashlib, json, numpy as np
72
73class LLMCacheMiddleware:
74 def __init__(self, redis_client, vector_db, embedder, threshold=0.95):
75 self.redis = redis_client
76 self.vdb = vector_db
77 self.embedder = embedder
78 self.threshold = threshold
79
80 def cache_key(self, prompt: str, model: str, **params) -> str:
81 blob = json.dumps({"prompt": prompt, "model": model, **params}, sort_keys=True)
82 return f"llm:{hashlib.sha256(blob.encode()).hexdigest()}"
83
84 async def query(self, prompt: str, model: str, **params) -> str:
85 # Tier 1: Exact match
86 key = self.cache_key(prompt, model, **params)
87 cached = await self.redis.get(key)
88 if cached:
89 return json.loads(cached)["response"] # < 5ms
90
91 # Tier 2: Semantic match
92 query_emb = self.embedder.embed(prompt)
93 results = self.vdb.search(query_emb, top_k=1)
94 if results and results[0].score >= self.threshold:
95 return results[0].payload["response"] # < 50ms
96
97 # Cache miss: call LLM
98 response = await llm_call(prompt, model, **params)
99
100 # Store in both tiers
101 await self.redis.setex(key, 86400, json.dumps({"response": response}))
102 self.vdb.upsert(query_emb, {"prompt": prompt, "response": response})
103 return response
104```
105
106### Pattern 2: Cache-Aware Request Classification
107
108```
109Incoming Request
110 │
111 ▼
112[Classify Cacheability]
113 ├── temperature == 0 AND structured output → HIGHLY CACHEABLE (TTL: 7 days)
114 ├── temperature == 0 AND free-form → CACHEABLE (TTL: 24 hours)
115 ├── temperature > 0 AND repeated pattern → SEMANTIC CACHE ONLY (TTL: 1 hour)
116 └── temperature > 0 AND unique/creative → DO NOT CACHE
117```
118
119### Pattern 3: Versioned Cache with Model Upgrades
120
121```
122Cache Key = hash(prompt + model_version + system_prompt_version + params)
123
124Model upgrade (gpt-4o-2026-01 → gpt-4o-2026-03):
125 → All cache keys change automatically (model_version in hash)
126 → Old cache entries expire via TTL
127 → No manual invalidation needed
128```
129
130## Anti-Patterns
131
1321. **Caching creative/high-temperature responses** — Temperature > 0.7 means the user expects variety. Caching returns identical responses and feels broken.
1332. **Global similarity threshold** — A 0.95 threshold works for factual Q&A but is too loose for code generation and too tight for casual chat. Tune per endpoint.
1343. **No cache versioning on model upgrades** — Switching from GPT-4o to Claude returns stale GPT-4o responses. Include model version in cache keys.
1354. **Infinite TTL** — Even deterministic responses can become stale when underlying data changes. Set TTL based on data freshness requirements (hours to days, not forever).
1365. **Caching without cost tracking** — You cannot prove ROI without measuring: cache hit rate, tokens saved, dollars saved, latency improvement.
137
138## Quality Checklist
139
140- [ ] Request types classified by cacheability (deterministic vs. creative)
141- [ ] Exact-match cache uses hash of full request (prompt + model + params)
142- [ ] Semantic cache threshold tuned per use case (tested on sample queries)
143- [ ] Cache key includes model version for automatic invalidation on upgrades
144- [ ] TTL set based on data freshness requirements (not infinite)
145- [ ] High-temperature (> 0.7) requests excluded from caching
146- [ ] Cache hit/miss rates monitored with alerting on rate drops
147- [ ] Cost savings calculated and reported: tokens saved, dollars saved per day
148- [ ] Cache store sized for expected working set (Redis memory, vector DB storage)
149- [ ] Graceful degradation: cache failure falls through to LLM API (never blocks)