Response Caching and Semantic Caching
Avoid paying twice for the same answer with exact, semantic and intermediate-result caches, while keeping answers fresh and private.
Intermediate · about 3 hours · difficulty 3/5
Learn first: Prompt Caching and Batch Processing, Text Embeddings
Provider prompt caching speeds up repeated prefixes, but your own application caches can skip model calls entirely.
Layers of caching
- Exact-match cache: hash the normalized request (model, prompt version, messages, parameters) and store the response in Redis or a database. Perfect for deterministic tasks such as classification or extraction of the same document.
- Semantic cache: embed the user query and return a cached answer when a previous query is similar enough. Useful for FAQ-style traffic, risky for anything personal or time-sensitive.
- Intermediate caches: cache embeddings, retrieved results, document summaries and tool results, which are often more reusable than final answers.
Getting it right
- Keys must include everything that changes the answer: prompt version, model, user or tenant id when content is personalized, and relevant document versions.
- Invalidation: set time-to-live values and clear entries when source documents change.
- Thresholds for semantic caches need tuning with evals; too loose and users get answers to a different question.
- Privacy: never serve one user's cached personal answer to another user.
Measuring value
Track hit rate, cost saved and any quality impact. A cache that saves 5% of calls but causes wrong answers is a net loss.
Good enough to move on
You can add an exact-match cache with correct keys and TTLs to an AI endpoint, explain when a semantic cache would be safe, and report its hit rate and savings.
Key concepts
- Exact-match response cache
- Semantic caching
- Caching embeddings and retrieval
- Cache keys and versioning
- TTLs and invalidation
- Tenant isolation
Mini project
Add a Redis cache to a document summarization endpoint keyed on document hash, model and prompt version, invalidate on document change, and log hit rate and cost saved over a day of simulated traffic.
Check yourself
What must be part of the cache key for a support bot that answers questions about each user's own orders?
Free resources
- Redis documentation (Redis)
- Anthropic docs: prompt caching (Anthropic)