Caching an LLM response can improve gross margin and latency, but only if the system knows when two requests are interchangeable. For a founder, the useful question is not “Can we cache this?” It is “Which outputs are safe to reuse, for whom, and for how long?”
The direct answer: start with deterministic, tenant-scoped exact-match caching. Add provider prompt caching for stable prefixes when it fits your request shape. Introduce semantic caching only for workloads where paraphrases usually deserve the same answer and you can measure false cache hits. Do not cache open-ended generation, personalized advice, or answers that depend on live state unless you have explicit invalidation and evaluation controls.
Four caching mechanisms solve different problems
“LLM caching” covers several mechanisms that are often confused:
- Exact-response cache: A request maps to a previously stored response through an exact key.
- Provider prompt cache: The model provider reuses computation for repeated prompt prefixes. This may lower latency or cost without returning a whole prior answer.
- Semantic response cache: An embedding search finds a similar prompt, and its stored response is returned.
- Intermediate-work cache: A reusable stage result—such as a document summary—is stored and consumed by a later request.
They are not interchangeable. An exact cache can serve identical requests without judging semantic equivalence. A semantic cache expands reuse to paraphrases, but it introduces the risk that two similar requests require different answers. Provider prompt caching preserves model execution and is generally a safer starting point than reusing a final answer. Intermediate caching can be valuable in multi-step RAG or agent workflows, but only when the intermediate result is independent of request-specific context.
What is safe to reuse?\n
Classify each output by the inputs that can change its correctness. A useful cache key should include every material dependency:
- Tenant or account
- User role and permissions
- Model and API version
- System prompt and developer prompt
- Tools and tool permissions
- Relevant application state
- Conversation or memory state
- Retrieval corpus or document version
- Output format or schema
- Safety and policy settings
A practical key for a stateless FAQ might be a hash of tenant + model + prompt_version + retrieval_version + normalized_question. If the answer depends on the customer’s account, do not use only the question as the key. If it depends on live inventory, permissions, or a changing document, include an explicit version or invalidate the entry.
Do not assume that two identical user messages are equivalent. “What is my balance?” is deterministic as a question but not as an answer: tenant, account, authorization, and balance state still matter.
A conservative reuse matrix
| Workload | Initial recommendation | Why |
|---|---|---|
| Fixed support FAQ with stable source content | Exact cache, then supervised semantic cache | Answers tend to be canonical and auditable |
| Repeated extraction from an unchanged document | Exact or intermediate cache | Same source and operation should produce the same result |
| RAG answer from a changing knowledge base | Short TTL plus corpus-version key | Retrieval changes can make old answers stale |
| Creative writing or open-ended ideation | Do not cache final responses | Little semantic equivalence and high quality variance |
| Code generation | Cache only with exact structured inputs | Small requirements changes can change correctness |
| Personalized recommendations | Cache candidate retrieval, not the final answer | Ranking and authorization remain dynamic |
| Support assistant quoting live account state | Usually no final-response cache | The answer may be stale or reveal another customer’s state |
This matrix is a starting policy, not a universal rule. The safest interpretation of “the same request” is “the same request in the same relevant state,” not merely similar wording.
Build exact caching before semantic caching
An exact-match cache is easy to reason about, supports immediate invalidation, and usually has enough value for stable prompts such as FAQ routing, classification, or repeated document operations. It can also establish a clean baseline for later semantic caching.
A minimal implementation pattern is:
import hashlib
import json
def cache_key(*, tenant_id, prompt_version, corpus_version, request):
material = json.dumps(
{
"tenant_id": tenant_id,
"prompt_version": prompt_version,
"corpus_version": corpus_version,
"request": request,
},
sort_keys=True,
separators=(",", ":"),
)
return hashlib.sha256(material.encode()).hexdigest()
The application should then follow this sequence:
- Authenticate the caller and determine the tenant boundary.
- Normalize only cosmetic differences that cannot affect meaning.
- Construct the key from all material request dependencies.
- Look up the cache.
- Return a hit only if its recorded version and policy match the current request.
- On a miss, call the model and store the response with metadata and an expiry time.
A stored record should contain more than the answer text:
{
"answer": "...",
"created_at": "2026-01-01T00:00:00Z",
"expires_at": "2026-01-01T01:00:00Z",
"tenant_id": "tenant_123",
"prompt_version": "support_v4",
"corpus_version": "kb_92",
"model": "provider-model-version",
"source_signature": "..."
}
Do not log prompts or cached answers indiscriminately. A cache can become a sensitive data store because it preserves customer text and model outputs beyond the original request. Apply the same access controls, retention rules, and deletion procedures used for source data. If your workload is highly confidential or tenant-specific, a local or per-tenant cache may be operationally safer than a shared semantic index.
How tenant isolation changes the hit rate
A shared semantic cache may find a close semantic match but still be unsafe to reuse. “How do I reset my password?” from one customer should not retrieve another customer’s answer that happens to contain embedded identifiers or support-specific policy. Conversely, partitioning every tenant severely reduces reuse because each tenant has a smaller corpus of prompts.
Start with this rule: never cross a tenant boundary to return a final response unless the cache entry contains no tenant-specific data and the product explicitly permits cross-tenant reuse. For most founder-operated products, per-tenant namespaces are easier to reason about and audit.
You can still share lower-risk artifacts. For example, cache a generic document summary under a corpus-version key if the source contains no tenant data. Or cache retrieved passages separately from customer-specific generation. This gives you reuse without mixing final answers across security boundaries.
Within a tenant, roles still matter. A cached administrator answer must not be returned to a regular user merely because both asked about the same policy question. Include authorization context or maintain role-specific namespaces.
Why prompt variation lowers or distorts hit rates
An exact cache misses whenever wording changes. Semantic caching attempts to recover those misses by embedding the prompt and searching for a close prior request. This works when variation is superficial, such as:
- “How do I cancel my plan?”
- “Where can I cancel my subscription?”
It fails when small differences carry operational meaning:
- “How do I cancel my plan?”
- “How do I cancel my plan without losing annual credits?”
The second prompt may be semantically close but require a different answer. Another dangerous pair is “What are your business hours?” asked in different time zones or for different locations. Text similarity does not encode every relevant fact.
To understand your hit rate, segment requests by application surface rather than reporting one global number. Track at least:
- Exact-hit rate
- Semantic-hit rate
- Miss rate
- Hit rate by tenant, route, prompt version, and response type
- False-hit rate from reviewed samples
- Cost savings after cache lookup and storage overhead
- Latency saved on hits
- Cache age and stale-answer reports
Do not copy a similarity threshold from a generic tutorial. Embedding models, domains, languages, and query distributions differ. A threshold that performs well for an English FAQ may be inappropriate for code, dates, locations, or long instructions.
The threshold is also only one part of the decision. Use a small labeled set of requests with their acceptable answers, then test candidate thresholds against both goals:
- Maximize valid reuse.
- Reject near matches whose required output differs.
A production system should log the candidate match and similarity score for sampled semantic hits so that operators can inspect failures. Without that evidence, a lower bill can conceal declining answer quality.
When semantic caching creates more complexity than value
Semantic caching requires an embedding model, vector search, a similarity policy, an evaluation set, cache invalidation, and monitoring for silent false hits. It also introduces a new operational dependency. If the embedding service is unavailable, the fallback may be a full model call, a deterministic cache lookup, or an error. Decide that failure path before enabling it.
Skip semantic response caching when:
- The workload is mostly unique.
- Answers depend on live or hidden state.
- Small differences change the task materially.
- Your traffic is too low to produce meaningful reuse.
- The product cannot tolerate a confidently incorrect answer.
- You cannot evaluate whether a hit was acceptable.
For a small application with unpredictable traffic, the savings may not justify the added control surface. Provider prompt caching or deterministic application caching may provide a better return on engineering effort. For higher-volume, repetitive products, semantic caching can become worthwhile, but only after the exact-match baseline and evaluation pipeline are in place.
A staged rollout for an indie developer
Stage 1: Identify the unit economics
Record the average model call cost, latency, and volume by route. Estimate the maximum plausible savings:
Potential monthly savings
= monthly model spend × eligible-request share × validated cache-hit rate
+ avoidable provider prompt-processing charges
- cache lookup, embedding, storage, and evaluation costs
Do not count every request as eligible. Requests with live state, personalization, or sensitive cross-tenant risks should be excluded.
Stage 2: Cache exact outputs
Start with stable, low-risk routes. Use explicit versioned keys, short TTLs, tenant isolation, and deletion hooks. Compare the bill and latency with the uncached baseline.
Stage 3: Test semantic matches offline
Collect representative prompts and define the expected answer or acceptable-answer rules. Evaluate false hits, not just hit rate. A cache that misses often may still be useful; one that returns the wrong answer can destroy trust and make the optimization economically worthless.
Stage 4: Shadow semantic hits
Run semantic lookup in production without returning its response. Compare the candidate with a fresh model result or an authoritative rule. This reveals bad matches without exposing users to them.
Stage 5: Enable by route and tenant class
Release first for low-risk, stable workloads. Keep exact and uncached fallbacks available. Provide a kill switch that bypasses semantic reuse without taking down the product.
Observe the cache as an inference system
Your cache needs the same operational discipline as any API path. Track:
- Hit and miss rates
- Similarity-score distribution for sampled hits
- Response age and time-to-live expiration
- Invalidations
- Cache lookup errors and fallback rates
- User reports of stale or incorrect responses
- Inference cost by route
- End-to-end latency, including embedding and vector lookup
A rising hit rate is not automatically good. It may mean the cache is becoming more aggressive, retrieving less appropriate answers. Pair it with a false-hit metric and a business measure such as successful task completion or support resolution.
For asynchronous jobs, cost control also depends on queueing and concurrency, not only response reuse. The practical cost-control framework for asynchronous AI workloads covers how to manage inference queues, token usage, concurrency, and spend. If demand is spiky or too small to keep inference capacity warm, compare that approach with cold-start vs warm-pool inference cost.
The founder’s decision rule
Use this sequence:
- Is the answer deterministic under the same relevant state? If not, do not cache the final response.
- Can the cache key include every material dependency? If not, fix the key design before launch.
- Is exact matching enough? If yes, stop there.
- Can you label acceptable answers and detect false hits? If not, semantic caching is not production-ready.
- Does the validated hit rate justify embedding, storage, and evaluation overhead? If not, keep the simpler cache.
The best cache is not the one with the highest hit rate. It is the one that lowers inference cost and latency while preserving the correctness, freshness, privacy, and tenant boundaries customers are paying for.







