Exact, semantic and prompt caching
In one line
LLM calls can be cached at three levels: exact caching reuses a whole answer for an identical request, semantic caching reuses an answer for a similar-meaning request (with a risk of wrong answers), and provider prompt caching reuses the processing of a repeated prompt prefix to cut input cost and latency.
What it is
Exact caching stores a response under a hash of everything that affects it: model and version, prompt template version, system prompt, messages, tools, temperature and other parameters. A later request with the same hash gets the stored answer in a millisecond for free. It is always correct for deterministic use cases, but hit rates are low unless many users send exactly the same thing.
Semantic caching embeds the incoming prompt into a vector, searches for the nearest cached prompt, and returns that cached answer if the similarity is above a threshold, for example cosine similarity of 0.95. 'How do I cancel my order?' and 'how can i cancel an order' can share one answer. Hit rates can be much higher on FAQ-style traffic, but every hit is a guess: two prompts can be very similar in wording and different in meaning ('cancel my order' vs 'cancel my subscription').
Provider prompt caching (also called prefix caching) does not cache answers at all. The provider keeps the model's internal state (the attention key-value cache) for a prompt prefix it has just processed. If the next request starts with the same prefix, those input tokens are billed at a large discount and the first token arrives sooner. The answer is still freshly generated, so this is safe for every use case. Self-hosted servers such as vLLM offer the same idea as automatic prefix caching.
Why interviewers ask
Caching is the first lever interviewers expect for cost and latency, and the AI version has a twist: a wrong cache hit is not stale data, it is a confidently wrong answer to a different question, possibly built from another tenant's data. Strong candidates separate the three kinds, explain what each saves, design keys that make leaks impossible, and justify a semantic threshold with measured false-hit rates rather than a guess.
How it works
- 1Decide per feature whether caching is allowed: answers that depend on the user's private data or on time ('what is my balance', 'what is on sale today') are not cacheable across users, or only with a very short TTL and a key that includes the user.
- 2Exact cache key: SHA-256 over a canonical JSON of {tenant_id, model, prompt_version, system, messages, tools, temperature, top_p, max_tokens}. Store in Redis with a TTL (for example 24 hours) and record the hit in usage events.
- 3Semantic cache lookup: embed the normalised user question (an embedding call takes roughly 10 to 50 ms), search a vector index filtered by tenant, model, feature and prompt version, take the nearest neighbour and compare its similarity to the feature's threshold.
- 4Choose the threshold from data: build a labelled set of prompt pairs ('same answer OK' or 'not OK'), compute precision at several thresholds, and pick the one whose false-hit rate is acceptable for the feature, for example under 1% for customer support.
- 5Invalidate correctly: bump prompt_version whenever the prompt template changes; for RAG answers, store the ids of source documents with each cache entry and delete entries when those documents change; use TTLs as a safety net.
- 6Structure prompts for provider prompt caching: put static content first (system instructions, tool definitions, long reference documents, few-shot examples) and dynamic content last (user question, timestamps). Any change early in the prompt, even a date in the first line, breaks the prefix match for everything after it.
- 7Know the provider rules: OpenAI caches prompts of at least 1,024 tokens automatically; Anthropic requires explicit cache_control breakpoints, charges a premium to write the cache and bills cache reads at about 10% of the normal input price; prefixes expire after minutes of inactivity unless a longer TTL is paid for. Check current documentation, since the numbers change.
- 8Measure each layer separately: exact hit rate, semantic hit rate and sampled false-hit rate, and cached-input-token share from provider usage fields. Report money saved, not only hit percentages.
Worked example · Three caches on an e-commerce help assistant
- Traffic: 2M questions a day. Each call sends a 6,000-token system prompt (policies, tool definitions, examples), about 1,000 tokens of conversation and question, and gets 250 output tokens.
- No caching, at an illustrative $2 per million input and $8 per million output tokens: input 2M x 7,000 = 14B tokens = $28,000/day; output 2M x 250 = 500M = $4,000/day. Total $32,000/day.
- Provider prompt caching: the 6,000-token static prefix is identical for every call, so about 12B of the 14B input tokens become cache reads at 10% of the price: 12B x $0.20/M = $2,400, plus 2B uncached x $2/M = $4,000. Input drops from $28,000 to about $6,400/day. Answers are still generated fresh, so there is no correctness risk.
- Exact cache: only 3% of questions are byte-identical (for example the 'Where is my refund?' quick-reply button). It saves 3% of the remaining cost with zero risk.
- Semantic cache at threshold 0.95 on the first user turn only: a labelled set of 2,000 pairs shows a 22% hit rate with a 0.8% false-hit rate. At 0.92 the hit rate rises to 31% but false hits reach 4%, so the team keeps 0.95 and excludes any question that mentions an order id or account detail.
- Result: after prompt caching the bill is about $6,400 input + $4,000 output = $10,400 a day. First turns are about half of all calls, so semantic hits remove roughly 11% of calls overall and exact hits another 3%: about $10,400 x 0.97 x 0.89 = $9,000 a day, plus a little for embeddings. That is about a 72% saving on $32,000, most of it from correct prompt ordering.
Picture it
An exact cache is a shop that keeps photocopies of answers to letters that are word-for-word identical. A semantic cache is a clerk who says 'this letter looks like one we answered last week' and sends the same reply, which is fast but sometimes wrong. Prompt caching is a lawyer who has already read the 200-page contract this morning, so your new question about it is answered faster and billed fewer reading hours, but the answer is still written fresh.
Key patterns
Static first, dynamic last
When: Any prompt with a long reusable part
How: Order the prompt as system instructions, tools, reference documents, examples, then conversation and user input. Never put timestamps or request ids at the top.
Scope keys so leaks are impossible
When: Multi-tenant products
How: Include tenant_id, model, prompt_version and language in every exact key and as hard filters in semantic search. A global semantic cache can return an answer built from another customer's documents.
Threshold from labelled pairs
When: Turning on a semantic cache
How: Label real prompt pairs as 'same answer OK' or not, plot precision and hit rate per threshold, and pick per feature and language. Re-measure when the embedding model changes.
Dependency-tracked invalidation
When: Cached answers built from documents or data
How: Store source document ids with each entry and delete matching entries on document change events, plus a TTL.
Real-world use
Anthropic prompt caching
Developers mark cache breakpoints in the request; later requests with the same prefix are billed at a fraction of the input price and return the first token faster. It is designed for long system prompts, large documents and agent tool definitions that repeat on every turn.
OpenAI automatic prompt caching
For prompts of 1,024 tokens or more, OpenAI caches the longest previously seen prefix automatically and reports cached tokens in the usage field of the response, which you should log for cost tracking.
GPTCache and Redis semantic caching
GPTCache (from Zilliz) is an open-source semantic cache library, and Redis offers vector search that teams use to build semantic caches with per-tenant filters and TTLs.
vLLM automatic prefix caching
The open-source inference server vLLM can reuse the KV cache of shared prefixes across requests on self-hosted GPUs, which raises throughput for chat and RAG workloads with long shared system prompts.
In a project
An Indian insurance aggregator runs a policy-explainer chatbot. Its LLM bill grew 4x during tax-saving season (January to March) as millions of users asked similar questions about Section 80D deductions and claim settlement.
- Reorder the prompt: system instructions, tool schemas and the 8,000-token plan-comparison document go first and never change within a day; the user's profile and question go last. Log cached-token counts from provider usage to verify.
- Add an exact cache for the 40 quick-reply buttons in the app, keyed by tenant, language, prompt version and button id, with a 6-hour TTL.
- Add a semantic cache only for general questions (no policy number, no personal data, detected by a regex and a small classifier), scoped by language and prompt version.
- Label 1,500 real question pairs in English, Hindi and Hinglish; choose threshold 0.96 for Hinglish (more false hits at lower values) and 0.94 for English, based on measured precision.
- Store the document ids used for each cached answer; when a plan's terms change, delete every cache entry built from it.
- Sample 1% of semantic hits daily for an LLM-judge check against a freshly generated answer, and alert if the false-hit rate rises above 1%.
Impact: Input-token cost fell by about 65% from prompt ordering alone, the semantic cache served about a quarter of general questions in under 50 ms, and the measured false-hit rate stayed below 1% across the season.
Trade-offs
Use it when
- Prompt caching: almost always, whenever a long prefix repeats within minutes (system prompts, RAG over the same document, agent tool lists, multi-turn chat)
- Exact cache: deterministic or button-driven requests, classification of repeated inputs, temperature 0 pipelines that re-run on the same data
- Semantic cache: high-volume FAQ-style questions with general (not personal) answers where a rare wrong-but-reasonable answer is acceptable
Avoid it when
- Semantic cache for answers that depend on the user's own data, the current time, or exact numbers such as prices and balances
- Semantic cache in high-stakes domains (medical, legal, payments) unless every hit is verified
- Exact cache when users expect creative variety (story or caption generation) and the product promises fresh results
- Any cache shared across tenants
Common mistakes
- Mixing up the three kinds and calling provider prompt caching 'response caching': it reuses prefix processing, not answers.
- Putting the current date, user name or a request id at the start of the prompt, so the provider prefix cache never hits.
- A semantic cache without tenant scoping, returning answers containing another customer's data.
- Choosing the similarity threshold by intuition (0.8 'looks fine') instead of measuring false hits on labelled pairs.
- Forgetting prompt_version in the key, so answers from an old prompt keep being served after a fix.
- Counting the semantic cache as free: each lookup still costs an embedding call and a vector search, which can exceed the saving for cheap models.
Interview questions
Quick revision
- Exact cache: hash of everything that affects the answer; safe, cheap, low hit rate.
- Semantic cache: embed, nearest neighbour, threshold; higher hit rate, real risk of wrong answers.
- Prompt (prefix) caching: provider reuses processed prefix; cheaper input, faster first token, answer still fresh.
- Prompt order: static (system, tools, documents, examples) first, dynamic (user input, dates) last.
- OpenAI: automatic for prompts of 1,024+ tokens. Anthropic: explicit cache_control, cheap reads, paid writes.
- Keys must include tenant, model, prompt version (and language for semantic).
- Pick semantic thresholds from labelled pairs; track false-hit rate, not just hit rate.
- Invalidate by prompt version and by source document ids; TTL as a backstop.
- Never cache personal or time-sensitive answers across users.
- Report savings in money using cached-token counts from provider usage.
Check yourself
1. Which caching method is safe to use for every request because the answer is still generated fresh?
2. A prompt starts with 'Current time: 2026-10-25 14:03:11' followed by a 5,000-token system prompt. What happens to provider prompt caching?
3. What is the main risk of a semantic cache that is shared across all tenants?
4. How should you choose the similarity threshold for a semantic cache?
See it in a full design
These walkthroughs use this lesson.
Saved on this device. Create a free account to keep it on every device.
Practise this with Sam
A real mock interview, out loud, with an honest scorecard. Free to start.