Caching layers in an AI system
One AI request can pass eight caches, from the CDN down to the GPU's KV cache. Each saves different latency or dollars; key every one by tenant, permissions and model, prompt and index version.
Analogy: A kitchen: plated dishes waiting at the pass, prepped sauces in the fridge, chopped vegetables on the line. Each shortcut skips a different amount of work, and each needs a label with what's inside and when it expires.
How it works
- A cache is only as good as its key and its invalidation.
- Exact and semantic caches skip the model call; a semantic false hit serves a wrong answer.
- Prompt caching gives ~90% off cached input, but only with static content first and variable content last.
- Key retrieval caches by index version and embedding caches by model, so stale entries simply stop matching.
- Set TTLs by how fast the truth changes, and track hit rate and wrong-hit rate per layer.
Check yourself
Answer to mark it learned; your answers aren't scored.
You enabled provider prompt caching on a 6k-token system prompt plus tool definitions, but input cost and TTFT didn't move. Every prompt starts with Now: {timestamp}, user: {name}, then the instructions. What's the fix?
Go deeper
Full explanation
A cache is only as good as its key and its invalidation. An AI system has several, outside in:
- Client / CDN: identical public answers (FAQ, generated docs). Saves the whole request. Never for personalized output.
- Exact response cache: hash(normalized input, model, params, prompt version) → answer. Saves 100% of a call; low hit rate on free-form chat.
- Semantic caching: embedding similarity above a threshold → stored answer. More hits, but a false hit serves a wrong answer.
- Retrieval-result cache: query → top-k chunk ids. Skips embedding, vector search and Reranking (cross-encoders). Key by index version.
- Tool-result cache: API or DB results with a TTL matching data freshness; also shields rate-limited APIs.
- Embedding cache: hash(text, embedding model) → vector. Makes re-indexing cheap; valid until the model changes.
- Provider Prompt caching: reuses the computed prefix. ~90% off cached input and lower TTFT, but only if the prompt is static first (instructions, tools, documents) and variable last.
- Engine KV cache / prefix caching (vLLM, SGLang): the same idea when you self-host.
Scope every key by tenant, permissions (an ACL hash), model, prompt version and index version. A key without the tenant is a data leak (Multi-tenant isolation in AI apps). Set TTLs by how fast the truth changes, and track hit rate and wrong-hit rate per layer.
Code Scoped keys across response, retrieval and prompt caches
import hashlib, json
MODEL = "claude-sonnet-4-5" # any chat model; part of every key
PROMPT_VERSION = "helpdesk-v14"
INDEX_VERSION = "kb-2026-11-02" # bumped on re-index: old entries just miss
def key(layer: str, **parts) -> str:
blob = json.dumps(parts, sort_keys=True)
return f"{layer}:{hashlib.sha256(blob.encode()).hexdigest()}"
def answer(user, question: str) -> str:
q = normalize(question) # lowercase, trim, collapse spaces
scope = dict(tenant=user.tenant, acl=user.acl_hash, model=MODEL, prompt=PROMPT_VERSION)
rkey = key("resp", q=q, **scope)
if (hit := cache.get(rkey)) is not None: # exact hit: whole call saved
return hit
ret_key = key("ret", q=q, tenant=user.tenant, acl=user.acl_hash, index=INDEX_VERSION)
chunk_ids = cache.get(ret_key)
if chunk_ids is None: # skip embed + search + rerank on hit
chunk_ids = retrieve(q, user)
cache.set(ret_key, chunk_ids, ttl=3600)
out = llm( # Anthropic Messages-style call
system=[{"type": "text", "text": SYSTEM_PROMPT, # static first...
"cache_control": {"type": "ephemeral"}}], # ...marked cacheable
messages=[{"role": "user", "content": render(load(chunk_ids), question)}],
)
cache.set(rkey, out, ttl=86400) # TTL = how fast the truth changes
return outReal example
An IT help-desk bot gets 40,000 questions a day. Measured per layer: the exact cache hits 12% (password-reset phrasing repeats); a semantic cache adds 8% at a 0.93 threshold, after 0.88 confused "reset VPN" with "reset MFA". A 6k-token system prompt plus tool definitions sits first, so the other 80% of calls pay ~0.1× on that prefix. Retrieval results are cached for 1 h, saving ~150 ms per hit, and a re-index bumps the index version, so stale entries simply stop matching.
Trade-offs +3 · −3
+ You gain
- Outer layers cut both cost and latency to near zero on a hit.
- Prefix caching is nearly free: reorder the prompt and repeated input gets ~90% cheaper.
- Versioned keys make invalidation automatic on model, prompt or index changes.
− You pay
- Every layer is one more place to leak data across tenants or permissions.
- Stale or false hits serve wrong answers confidently, and look great on latency dashboards.
- Hit rates on open-ended chat are often low; measure before building a semantic cache.
Use it when
High-volume features with repeated questions or long shared prefixes (system prompts, tool schemas, documents), and RAG pipelines where retrieval is a big share of latency.
Avoid it when
Response caches on personalized, time-sensitive or high-stakes answers (balances, prices, medical), or before you can scope keys by tenant and permissions.
Numbers to know 5
- Anthropic prompt caching: reads ~0.1× base input; 5-minute default TTL refreshed on each hit, 1-hour option at a 2× write.
- OpenAI caches prompts automatically from 1,024 tokens; caches are not shared between organizations.
- Anthropic (2024): caching a 100k-token prompt cut time to first token from 11.5 s to 2.4 s.
- Semantic-cache threshold ~0.90–0.95 cosine (rule of thumb); tune it on labeled query pairs.
- Average latency = hit × cache + miss × origin: 30% hits at 5 ms vs 3 s misses ≈ 2.1 s.
Common pitfalls 4
- Keys without tenant, ACL or prompt version: one user's cached answer is served to another.
- A timestamp, user name or request id at the top of the prompt breaks prefix caching on every call.
- Caching answers from a degraded fallback model with a 24-hour TTL.
- No invalidation on re-index: the retrieval cache keeps returning deleted chunks.
Interview questions 3
Answer out loud first, then reveal.
Walk me through the caches you'd put in a RAG chatbot.Show answer
Outside in. An exact response cache keyed by normalized question, tenant, ACL hash, model and prompt version; a semantic cache only for FAQ-like traffic, with a tuned threshold. A retrieval-result cache keyed by query and index version, and an embedding cache so re-indexing doesn't re-pay. Then I order the prompt static-first so provider prefix caching cuts input cost and TTFT. I track hit rate and wrong-hit rate per layer. The main risk is a cross-tenant leak, so key scope is non-negotiable.
Prompt caching vs semantic caching: what's the difference?Show answer
Prompt caching reuses computation: the provider keeps the state of a repeated prefix, and the model still generates a fresh answer, just cheaper and faster on input. It can't make the answer wrong. Semantic caching reuses the answer: if a new question is close enough to an old one, the model is skipped entirely. It saves far more per hit, but a false hit returns a confident wrong answer. So prompt caching is default hygiene, and a semantic cache is a product decision backed by an eval.
How do you handle invalidation across these layers?Show answer
Mostly by versioning keys instead of deleting entries: model id, prompt version, index version and embedding model go into the key, so a deploy or re-index naturally misses old entries. TTLs follow how fast the truth changes: minutes for tool results like inventory, a day for policy answers, no expiry for embeddings of unchanged text. For deletions with legal weight, like a removed document or a GDPR request, I also purge by tag, because waiting for a TTL isn't acceptable.