I worked on an LLM product last year where the average request had 14,000 tokens of system prompt, tool definitions, and retrieved context - and 50 tokens of actual user input. We were paying $0.21 per request for the privilege of re-reading the same 14,000 tokens every single time. Latency was 2.5 seconds because the model had to process all of that preamble before generating a single output token.

Then we turned on prompt caching. Same outputs. Same quality. Cost dropped 80%. Latency dropped to 600ms. It was, frankly, embarrassing that we hadn't done it earlier.

Prompt caching is one of those optimizations that sounds too good to be true and mostly is true. The catch - and there's always a catch - is that you have to understand what kind of caching your provider supports, structure your prompts to actually hit the cache, and instrument it well enough to know whether it's working. This article walks through all three.

Why Prompt Caching Matters

Two numbers drive every LLM product: cost per request and time to first token. Both are dominated by input token processing for any non-trivial prompt.

Here's the breakdown for a typical RAG request:

Plain TextCopy 

Request: 8,000 token system prompt + 4,000 token retrieved docs + 50 token user query
↓
Total input: 12,050 tokens

  • System prompt: $0.024 (re-processed every request)
  • Retrieved docs: $0.012 (re-processed every request)
  • User query: $0.0001 (the only part that actually changes)

Output: 300 tokens: $0.006
Total: $0.042 per request, of which 99.5% is paying to re-process the same prompt

At 10,000 requests/day, that's $420/day you're burning on redundant computation. Prompt caching turns that $420 into $84, with no changes to your application logic beyond prompt structure.

The latency win is even more important than the cost win. Processing 12,000 input tokens takes the model ~1-2 seconds. Processing 50 tokens takes ~50ms. If 11,950 of those tokens are cached, your time-to-first-token drops from 2s to 100ms. That's the difference between a chatbot that feels snappy and one that feels broken.

The Three Kinds of Prompt Caching

People use "prompt caching" to mean three different things. Conflating them causes most of the confusion in this area.

1. Provider-side prefix caching (automatic)
OpenAI, Anthropic, Google, and DeepSeek all now cache the model's internal KV (key-value) cache for repeated prompt prefixes. You don't do anything - if your request starts with the same tokens as a recent request, the provider reuses the cached KV state and bills you at a discount.

  • OpenAI: automatic, no opt-in. Caches prefixes ≥1024 tokens. Cache TTL: 5-10 min idle. Discount: 50% on cached input tokens.
  • Anthropic: explicit opt-in via cache_control markers. Caches prefixes ≥1024 tokens (Claude 3.5 Sonnet). Cache TTL: 5 min default, 1 hour with extended-cache-ttl. Discount: 90% on cached tokens, but you pay 25% extra to write them.
  • DeepSeek: automatic. Caches any prefix. Discount: 90% on cached tokens.
  • Google Gemini: explicit context caching API. You create a cache object, reference it by ID. TTL configurable from minutes to days. Good for very large static contexts.

2. Application-level exact-match caching
You hash the full prompt and store the response. Next time the same prompt comes in, return the cached response without calling the LLM at all. Cheap, fast (sub-ms), but only works when prompts are identical. Useful for deterministic tasks (classification, structured extraction) but useless for chat.

3. Semantic caching
Embed the prompt, store it in a vector DB. Next request, embed and search for similar prompts. If similarity > threshold, return the cached response. Sounds great in theory, in practice produces subtle quality regressions because "similar" prompts can require different answers. Use with caution.

Type Hit rate in practice Quality risk Implementation effort Best for
Provider prefix 30-90% None Low (just structure prompts) RAG, chat, agents
Exact match 5-20% None Low Classification, extraction
Semantic 10-40% Medium-high Medium FAQ-style chat, low-stakes Q&A

The rest of this article focuses on provider-side prefix caching (the high-value, low-risk option) and shows how to layer semantic caching on top when it makes sense.

How Prefix Caching Actually Works

When an LLM processes a prompt, it doesn't recompute everything from scratch. The transformer layers produce a "KV cache" - the keys and values for every attention head, for every token. This cache is what makes autoregressive generation fast: each new token only attends to the cached states of prior tokens, not the raw tokens themselves.

Plain TextCopy 


plaintext
Without caching:
Prompt: [A B C D] [E]
Model processes: A, B, C, D, E from scratch
Time: O(n²) attention over all 5 tokens

With prefix caching:
Prompt: [A B C D] [E]
KV cache for A B C D exists → reuse
Model processes: only E (attending to cached A B C D)
Time: O(n) for the new token only


plaintext

The KV cache is large - roughly 1MB per 1000 tokens for an 8B model. Providers don't cache everything; they cache recent prefixes and evict on a TTL. That's why you see "cache hit rate" drop if your traffic is bursty or your prompts vary in their prefix.

The key constraint: the cache is prefix-based. If your prompt is [system] [docs] [user] and you change anything in [system], the entire cache is invalidated. If you change [user], only [system] [docs] is cached. This is why prompt structure matters so much.

Structuring Prompts for Cache Hits

The rule: static content first, dynamic content last. Anything that varies per request goes at the end.

Plain TextCopy 


json
Bad (cache never hits):
[
{"role": "user", "content": "Question: {user_input}"}, // varies
{"role": "system", "content": "{8k_token_system_prompt}"}, // static
{"role": "user", "content": "Context: {retrieved_docs}"} // varies
]

Good (cache hits on system prompt):
[
{"role": "system", "content": "{8k_token_system_prompt}"}, // static, cached
{"role": "user", "content": "Context: {retrieved_docs}"}, // varies, not cached
{"role": "user", "content": "Question: {user_input}"} // varies, not cached
]

Best (cache hits on system + docs):
[
{"role": "system", "content": "{8k_token_system_prompt}"}, // static, cached
{"role": "user", "content": "Knowledge base:\n{static_kb_docs}"},// static-ish, cached
{"role": "user", "content": "Question: {user_input}"} // varies, not cached
]


plaintext

The third structure caches both the system prompt and the knowledge base docs. If your KB is the same for every request (or changes slowly), this can get you 80%+ cache hit rates. If retrieved docs vary per query (true RAG), you'll only cache the system prompt - usually 30-50% hit rate.

For Anthropic, you also need to add explicit cache breakpoints:

PythonCopy 


python

anthropic_caching.py

import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
system=[
{
"type": "text",
"text": SYSTEM_PROMPT, # 8k tokens of static instructions
"cache_control": {"type": "ephemeral"} # mark as cacheable
},
{
"type": "text",
"text": KB_DOCS, # 4k tokens of static knowledge base
"cache_control": {"type": "ephemeral"}
}
],
messages=[
{"role": "user", "content": user_query} # not cached
]
)

Response tells you what hit the cache

print(response.usage)

MessagesUsage(input_tokens=85, cache_creation_input_tokens=12124,

cache_read_input_tokens=12039, output_tokens=312)

cache_read_input_tokens = tokens served from cache (billed at 10% of normal)

cache_creation_input_tokens = tokens written to cache this request (billed at 125%)

input_tokens = uncached input tokens (billed normally)


plaintext

The cache_creation_input_tokens is the write cost - you pay 25% extra to populate the cache, then 10% of normal on every subsequent read until TTL expires. The break-even is roughly 2 reads within the TTL window.

For OpenAI, there's no opt-in - just structure your prompts well and you'll see cached_tokens in the usage response:

PythonCopy 


python

openai_caching.py

from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": SYSTEM_PROMPT}, # static
{"role": "user", "content": f"Context: {kb_docs}\n\nQuestion: {query}"}
]
)

Usage breakdown

print(response.usage)

CompletionUsage(prompt_tokens=12124, completion_tokens=312,

total_tokens=12436, prompt_tokens_details={

"cached_tokens": 8192 # served from cache, billed at 50%

})


markdown

OpenAI caches automatically if your prefix is ≥1024 tokens and you've sent it recently. No code changes needed beyond prompt structure.

Building a Semantic Cache Layer

Provider prefix caching is great for static prefixes, but it doesn't help when prompts vary semantically. "What's the weather in Tokyo?" and "How's the weather in Tokyo?" produce identical responses but never hit the prefix cache.

Semantic caching closes that gap. Embed the prompt, store it in a vector store with the response. New request: embed, find nearest neighbor, if similarity > threshold return cached response.

PythonCopy 


python

semantic_cache.py

import json
import hashlib
import time
import numpy as np
import redis
from openai import OpenAI

Redis with the RediSearch module gives you vector + metadata in one store

Alternative: Qdrant, Weaviate, or pgvector

class SemanticCache:
def init(
self,
redis_url: str = "redis://localhost:6379",
embedding_model: str = "text-embedding-3-small",
similarity_threshold: float = 0.95, # cosine similarity required for a hit
ttl: int = 3600, # 1 hour
):
self.redis = redis.Redis.from_url(redis_url, decode_responses=False)
self.openai = OpenAI()
self.embedding_model = embedding_model
self.similarity_threshold = similarity_threshold
self.ttl = ttl
# Ensure the Redis index exists
self._ensure_index()

def _ensure_index(self):
try:
from redis.commands.search.field import VectorField, TextField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType

schema = (
TextField("prompt"),
VectorField(
"embedding",
"FLAT",
{
"TYPE": "FLOAT32",
"DIM": 1536,
"DISTANCE_METRIC": "COSINE",
},
),
)
definition = IndexDefinition(index_type=IndexType.HASH)
self.redis.ft("semantic_cache").create_index(
schema, definition=definition
)
except Exception:
# Index already exists
pass

def _embed(self, text: str) -> np.ndarray:
resp = self.openai.embeddings.create(
input=text, model=self.embedding_model
)
return np.array(resp.data[0].embedding, dtype=np.float32)

def get(self, prompt: str) -> str | None:
"""Return cached response if a similar prompt exists, else None."""
embedding = self._embed(prompt).tobytes()

from redis.commands.search.query import Query

q = (
Query("*=>[KNN 1 @embedding $vec AS score]")
.return_fields("score", "response")
.dialect(2)
)
results = self.redis.ft("semantic_cache").search(
q, query_params={"vec": embedding}
)

if not results.docs:
return None

score = float(results.docs[0].score)
# cosine distance is 0 (identical) to 2 (opposite)
# convert to similarity: similarity = 1 - distance/2
similarity = 1 - score / 2

if similarity >= self.similarity_threshold:
# Refresh TTL on hit
self.redis.expire(results.docs[0].id, self.ttl)
return results.docs[0].response.decode()

return None

def set(self, prompt: str, response: str, metadata: dict | None = None):
"""Store a prompt-response pair."""
embedding = self._embed(prompt).tobytes()
key = f"cache:{hashlib.sha256(prompt.encode()).hexdigest()[:16]}"

self.redis.hset(
key,
mapping={
"prompt": prompt,
"response": response,
"embedding": embedding,
"metadata": json.dumps(metadata or {}),
"ts": int(time.time()),
},
)
self.redis.expire(key, self.ttl)


plaintext

Now wrap your LLM call:

PythonCopy 


python

cached_llm.py

import os
from openai import OpenAI
from semantic_cache import SemanticCache

class CachedLLM:
def init(self):
self.client = OpenAI()
self.cache = SemanticCache(
redis_url=os.getenv("REDIS_URL", "redis://localhost:6379"),
similarity_threshold=0.97, # high threshold = conservative
)

def chat(self, messages: list[dict], **kwargs) -> str:
# Build a cache key from the user-facing portion of the prompt
# Include system prompt so different system prompts don't collide
cache_input = "\n".join(
f"{m['role']}:{m['content']}" for m in messages
)

# Check cache
cached = self.cache.get(cache_input)
if cached:
return cached

# Miss - call the LLM
response = self.client.chat.completions.create(
messages=messages,
**kwargs,
)
result = response.choices[0].message.content

# Store in cache (only cache non-empty responses)
if result:
self.cache.set(cache_input, result, metadata={
"model": kwargs.get("model", "gpt-4o"),
"prompt_tokens": response.usage.prompt_tokens,
})

return result


markdown

The similarity threshold is the most important knob. Too low (0.85) and you start returning wrong answers for similar-but-different questions. Too high (0.99) and you never hit. Start at 0.95 and tune based on your data.

When Semantic Caching Goes Wrong

I want to be honest about this: semantic caching is a footgun. Here are the failure modes I've seen in production:

Failure 1: "What's the weather in Tokyo?" cached for "What's the weather in Paris?"
Both questions have nearly identical embeddings - they're the same template with one entity swapped. Cosine similarity 0.96. Your cache returns the wrong answer.
Fix: Pre-process prompts to detect entities (use NER) and include entities in the cache key. Or use a stricter threshold for templated queries.

Failure 2: Cached response becomes stale.
"What's the latest news on X?" cached yesterday. Today the user asks the same question and gets yesterday's answer.
Fix: Add a max_age field to cache entries and check it on read. For time-sensitive queries, set TTL to minutes, not hours.

Failure 3: Cached response includes a timestamp or session ID.
LLM output occasionally includes "as of {date}" or references to the conversation. Returning a cached response with yesterday's date breaks user trust.
Fix: Post-process responses to strip dynamic fields before caching, or don't cache responses that contain dynamic markers.

Failure 4: Embedding cost exceeds cache savings.
If your cache hit rate is 5% and you're paying $0.0001 per embedding, you might be spending more on embeddings than you save on LLM calls. Run the numbers.
Fix: Add a cheaper exact-match cache layer in front. Most requests that would hit semantic cache have already hit exact-match cache.

The pattern I recommend: exact-match cache (cheap, fast) → semantic cache (medium) → provider prefix cache (free, automatic) → LLM call. Each layer filters out requests that can be served cheaper.

Measuring Cache Hit Rate

You can't optimize what you don't measure. Track these metrics per request:

  • cache_layer_hit: which layer served the request (exact / semantic / provider / miss)
  • cache_hit_latency: time saved by the cache hit
  • cache_cost_saved: dollars saved
  • cache_creation_cost: dollars spent writing to cache (Anthropic's 25% write premium)

Here's a simple instrumentation wrapper:

PythonCopy 


python

metrics.py

import time
import logging
from dataclasses import dataclass
from contextlib import contextmanager

logger = logging.getLogger("cache_metrics")

@dataclass
class CacheMetrics:
layer: str # "exact", "semantic", "provider_prefix", "miss"
tokens_cached: int # tokens served from cache
tokens_input: int # total input tokens
tokens_output: int
latency_ms: float
cost_saved_usd: float
cost_incurred_usd: float

@property
def hit_rate(self) -> float:
if self.tokens_input == 0:
return 0.0
return self.tokens_cached / self.tokens_input

class CacheInstrumentedLLM:
def init(self, inner_llm, cache):
self.inner = inner_llm
self.cache = cache

def chat(self, messages: list[dict], **kwargs) -> tuple[str, CacheMetrics]:
start = time.monotonic()

# Layer 1: exact match
cache_key = self._exact_key(messages)
cached = self.cache.exact_get(cache_key)
if cached:
elapsed = (time.monotonic() - start) * 1000
return cached, CacheMetrics(
layer="exact", tokens_cached=0, tokens_input=0,
tokens_output=0, latency_ms=elapsed,
cost_saved_usd=0, cost_incurred_usd=0
)

# Layer 2: semantic cache
semantic_input = self._semantic_input(messages)
cached = self.cache.semantic_get(semantic_input)
if cached:
elapsed = (time.monotonic() - start) * 1000
return cached, CacheMetrics(
layer="semantic", tokens_cached=0, tokens_input=0,
tokens_output=0, latency_ms=elapsed,
cost_saved_usd=0, cost_incurred_usd=0
)

# Layer 3: provider prefix cache (handled automatically)
response = self.inner.chat(messages, **kwargs)
elapsed = (time.monotonic() - start) * 1000

usage = response.usage
cached_tokens = getattr(
usage.prompt_tokens_details, "cached_tokens", 0
) if usage.prompt_tokens_details else 0

# Pricing - adjust for your model
PRICE_INPUT = 0.0025 / 1000 # per token
PRICE_CACHED = 0.00125 / 1000 # 50% discount
PRICE_OUTPUT = 0.01 / 1000

cost_incurred = (
(usage.prompt_tokens - cached_tokens) * PRICE_INPUT

  • cached_tokens * PRICE_CACHED
  • usage.completion_tokens * PRICE_OUTPUT ) cost_saved = cached_tokens * (PRICE_INPUT - PRICE_CACHED)

metrics = CacheMetrics(
layer="provider_prefix" if cached_tokens > 0 else "miss",
tokens_cached=cached_tokens,
tokens_input=usage.prompt_tokens,
tokens_output=usage.completion_tokens,
latency_ms=elapsed,
cost_saved_usd=cost_saved,
cost_incurred_usd=cost_incurred,
)

# Populate caches for next time
self.cache.exact_set(cache_key, response.choices[0].message.content)
self.cache.semantic_set(semantic_input, response.choices[0].message.content)

return response.choices[0].message.content, metrics

def _exact_key(self, messages):
import hashlib, json
return hashlib.sha256(
json.dumps(messages, sort_keys=True).encode()
).hexdigest()

def _semantic_input(self, messages):
return "\n".join(m["content"] for m in messages if m["role"] == "user")


markdown

Ship these metrics to Prometheus, Datadog, or your observability tool of choice. Build a dashboard that shows: cache hit rate by layer, average cost per request, p95 latency. When the dashboard goes red, you'll know.

Cache Invalidation

The hardest part of any caching layer. With LLMs, invalidation triggers are:

  1. System prompt changes: bump a version string in the system prompt. The prefix changes, all caches miss, and you repopulate.
  2. Knowledge base updates: if you cache retrieved docs, invalidate when the KB changes. Either version the KB contents (include a version hash) or use TTL aggressive enough that staleness is bounded.
  3. Model upgrades: when you switch from gpt-4o-2024-08-06 to gpt-4o-2024-11-20, all cached responses are technically stale. Most teams just flush the cache on model upgrade.
  4. Behavior changes (new guardrails, new system prompt wording): flush.

A clean pattern:

PythonCopy 


python

versioning.py

import os

CACHE_VERSION = os.getenv("CACHE_VERSION", "v1")

def build_system_prompt(base_prompt: str) -> str:
"""Every system prompt gets a version prefix so cache invalidation
is just bumping an env var."""
return f"[{CACHE_VERSION}]\n{base_prompt}"

When you ship a prompt change, bump CACHE_VERSION. Old caches become unreachable and expire naturally. No manual flushing needed.

Common Mistakes

1. Putting dynamic content at the start of the prompt.
The single most common mistake. A timestamp in the system prompt. The user's name first. A "current date" header. Any of these invalidate the entire cache. Move dynamic content to the end of the message list.

2. Not checking the usage object.
You enabled caching, but did it actually hit? Check response.usage.cache_read_input_tokens (Anthropic) or response.usage.prompt_tokens_details.cached_tokens (OpenAI). I've seen teams go three months thinking caching was working when their hit rate was 5% because of a prompt structure bug.

3. Caching the wrong things.
Don't cache streaming responses until you've fully buffered them. Don't cache tool-calling responses where the tool output changes between requests. Don't cache responses that include dynamic data.

4. Setting similarity thresholds too low for semantic cache.
0.85 sounds reasonable until you realize that "summarize this article" and "summarize this article in 3 bullets" have cosine similarity 0.93. Different intent, same embedding. Set the threshold to 0.95+ and only lower it if hit rate is too low.

5. Forgetting cache TTL.
Provider caches expire (5-10 min for OpenAI, 5 min default for Anthropic). If your traffic is bursty with >10 min gaps, your hit rate will be near zero. Either increase traffic or use the extended TTL (Anthropic's 1-hour option, billed slightly higher).

6. Not accounting for cache write cost.
Anthropic charges 25% extra for tokens written to cache. If your cache hit rate is <2 reads per write, you're losing money. Run the math before enabling.

Troubleshooting: Real Production Issues

Issue: Provider cache hit rate is 5% but should be 80%.
Cause: Something in your prompt prefix is changing. Most likely a timestamp, request ID, or session token.
Diagnosis: Log the first 200 characters of every prompt you send. Sort by frequency. Anything that should be static but varies is your culprit.
Fix: Find the dynamic element, move it to the end of the prompt.

Issue: Anthropic cache write costs exceed savings.
Cause: Cache entries are being written but never read. Either TTL is expiring before next request, or your prompts aren't actually repeating prefixes.
Diagnosis: Check cache_creation_input_tokens vs cache_read_input_tokens over time. Ratio should be ≥5:1 reads:writes for caching to pay off.
Fix: Either increase traffic, extend TTL to 1 hour, or stop caching prompts that don't repeat.

Issue: Semantic cache returns wrong answers.
Cause: Threshold too low, or two semantically similar questions have different correct answers.
Diagnosis: Sample 100 cache hits, manually check 20% for correctness. Calculate precision.
Fix: Raise threshold to 0.97. Add entity-based cache key pre-processing. Or disable semantic cache for high-stakes queries.

Issue: Latency increases after enabling caching.
Cause: Embedding computation for semantic cache adds 50-100ms per request, but cache hit rate is low.
Diagnosis: Measure end-to-end latency before and after. Look at cache miss path specifically.
Fix: Only run semantic cache check after exact-match cache misses. Use a faster embedding model (e.g., text-embedding-3-small instead of large).

Issue: Redis memory grows unbounded.
Cause: TTL not being set on cache entries, or you're storing full prompt + response without size limits.
Fix: Always set TTL. Cap individual cache entries at 32KB. Use Redis eviction policy allkeys-lru.

Cost Comparison: Caching vs Not Caching

For a real workload - 1M requests/month, average 8k token system prompt + 500 token user input + 300 token output, using GPT-4o:

Scenario Input cost Output cost Total Savings
No caching $21,000 $3,000 $24,000 -
Provider prefix only (50% hit) $13,125 $3,000 $16,125 33%
Provider prefix + exact match (60% hit) $9,450 $2,400 $11,850 51%
All three layers (70% hit) $6,615 $2,100 $8,715 64%

Adding semantic cache on top typically gets you another 5-10 percentage points but introduces quality risk. The provider prefix layer alone - which requires zero code beyond prompt structuring - gets you a third of the way. That's where to start.

For Anthropic with the same workload (Claude 3.5 Sonnet pricing):

Scenario Cost Savings
No caching $45,000 -
Provider cache (90% read discount, 70% hit rate) $18,900 58%

Anthropic's deeper discount (90% vs OpenAI's 50%) means caching matters even more. Worth the 25% write premium if your traffic is steady.

Real-World Use Cases

  • RAG systems: System prompt + retrieved docs as the cached prefix, user query at the end. Easy 60-80% hit rate on the system prompt.
  • Coding assistants (Cursor, Copilot-style): Repository context as cached prefix. Same repo across many requests, very high hit rate.
  • Customer support chatbots: Knowledge base as cached prefix, conversation history + new message at the end. Per-conversation cache hits.
  • Document processing: Classifying or extracting from a 50-page document with the same instructions. One cache write, many reads.
  • Agent systems: Tool definitions and system prompt as cached prefix. Especially valuable for agents that make many LLM calls per task.
  • Multilingual products: System prompt in the user's language. Cache per language.

Conclusion

Prompt caching is the single highest-leverage optimization for most LLM applications. The provider-side version is free, automatic (or near-automatic), and reduces cost by 30-60% with zero quality risk. The semantic version is more powerful but more dangerous - use it carefully, measure it relentlessly, and don't be afraid to disable it if quality regresses.

The order of operations: first, restructure your prompts so static content comes first. Second, enable Anthropic's explicit cache markers or rely on OpenAI's automatic caching. Third, instrument your usage so you can actually see hit rates. Fourth, only then consider semantic caching for specific high-volume, low-stakes query types.

Don't skip step three. I've seen too many teams "enable caching" without measuring it, ship to production, and discover six months later that their hit rate was 8%. The models won't tell you. You have to look.

Originally published on Mango Developer.