Prompt Caching Explained: How to Cut AI Costs and Latency by 90%
Prompt Caching Explained: How to Cut AI Costs and Latency by 90%
Introduction: The Endless Pizza Order Problem
Imagine you have a favorite local pizzeria. You order dinner from them every single evening.
Now imagine that every time you call, the restaurant insists on a bizarre rule: before you can say what you want to eat, you must slowly recite your full legal name, home address, dietary allergies, favorite sports team, and your entire 16-digit credit card number.
Every. Single. Night.
By day five, you'd be exhausted. You'd yell into the phone: "Can't you just save my details on file and let me order my pepperoni pizza?!"
For the past three years, that is essentially how every single Large Language Model (LLM) API has operated.
Whenever you chat with an AI assistant or run an AI agent, you don't just send your latest question. You send the entire conversation history, the system prompt, guidelines, and perhaps a 50-page company document.
With traditional LLM processing, the model had to re-read, re-tokenize, and re-compute every single word from scratch on every single turn.
That meant:
- Huge computational waste on graphics cards (GPUs).
- Sluggish responses (high latency), making users wait 5 to 10 seconds before the AI even started typing.
- Painfully expensive API bills that scaled out of control.
Enter Prompt Caching—arguably one of the most consequential architectural breakthroughs in generative AI since the release of GPT-4.
In this guide, we'll break down exactly what prompt caching is, how it works under the hood, why it slashes costs by up to 90%, and how you can structure your prompts to take full advantage of it.
1. What Exactly is Prompt Caching?
Prompt Caching is an optimization technique where an AI provider stores the intermediate mathematical state of frequently used prompt prefixes in high-speed GPU memory. When a new request arrives with the same prefix, the model skips the expensive reading phase and jumps straight to generating the answer.
Think of it like bookmarking a page in a textbook.
Instead of re-reading chapters 1 through 10 every time you want to answer a question about chapter 11, you leave sticky notes on the first 10 chapters. When the teacher asks a question, you open right to the bookmark and get straight to work.
TRADITIONAL LLM CALL (No Caching):
[ 10,000 Tokens: System Prompt + 50-page PDF ] ──> Full GPU Recomputation ──> [ Answer ] (Slow & Expensive)
PROMPT CACHING (Cache Hit):
[ 10,000 Tokens: Cached in Memory ] ──────────────> Read from GPU Cache (Instant) ──┐
[ 20 Tokens: New User Question ] ──────────────> Compute only new tokens ──┼──> [ Answer ] (Fast & 90% Cheaper!)
2. Under the Hood: How Transformers Read Prompts
To truly appreciate prompt caching, we need a brief peek into how Transformer models process text.
When you send a prompt to an LLM like Claude 3.5 Sonnet, GPT-4o, or Gemini 1.5, execution happens in two distinct phases:
Phase 1: The "Prefill" Phase (The Heavy Lift)
The model takes all your input tokens (your prompt) and computes internal mathematical representations called Key-Value (KV) tensors across dozens of attention layers.
Because self-attention compares every token against every other token, processing a 50,000-token prompt requires massive mathematical computation and high memory bandwidth. This phase is responsible for the Time to First Token (TTFT)—the agonizing delay before the AI starts answering.
Phase 2: The "Generation" Phase (The Output)
Once the input is processed, the model predicts the next token one by one. Generating tokens is fast, but it relies on looking back at the KV pairs computed in Phase 1.
The Problem With Yesterday's Approach
In standard multi-turn conversations, every turn re-sent the previous conversation. That meant Phase 1 had to be re-run on the exact same text again and again.
The Breakthrough: Storing the KV Cache
With Prompt Caching, the AI provider saves the calculated KV pairs in fast GPU high-bandwidth memory (HBM) or ultra-fast storage.
When your next request begins with the exact same sequence of tokens:
- The model checks its cache table.
- It detects a Cache Hit.
- It loads the pre-computed KV tensors directly into memory without performing any matrix multiplications!
- It only computes Phase 1 for the brand-new tokens at the end of the prompt.
3. The 3 Huge Benefits of Prompt Caching
┌────────────────────────────────────────────────────────────────────────┐
│ THE TRIPLE IMPACT OF PROMPT CACHING │
├───────────────────────┬───────────────────────┬────────────────────────┤
│ COST REDUCTION │ LATENCY REDUCTION │ ARCHITECTURAL FREEDOM│
│ 50% to 90% Cheaper │ Up to 80% Faster │ Long-Context Agents & │
│ Input Token Rates │ Time-to-First-Token │ Massive System Prompts│
└───────────────────────┴───────────────────────┴────────────────────────┘
1. Astronomical Cost Savings (Up to 90% Off)
Input tokens are typically the biggest driver of LLM API expenses, especially for document analysis, coding assistants, and chatbots.
Major providers offer dramatic discounts on cached tokens:
- Anthropic Claude: Cached tokens are 90% cheaper than standard input tokens ($0.30 per million tokens vs. $3.00 on Claude 3.5 Sonnet).
- OpenAI GPT-4o: Cached input tokens are 50% cheaper automatically.
- DeepSeek V3: Cached input tokens are an astounding 90%+ cheaper ($0.014 per million tokens).
- Google Gemini: Significant discounts on context caching for long sessions.
If you run an AI customer support bot handling thousands of turns a day over a company manual, prompt caching can reduce your monthly API bill from $2,000 down to under $300!
2. Lightning-Fast Responses (Sub-Second Latency)
Processing 100,000 tokens of documentation usually takes between 4 to 12 seconds just to calculate the prefill. With prompt caching, that delay drops to under 500 milliseconds. Users experience near-instant replies, transforming sluggish bots into snappy, responsive interfaces.
3. Freedom to Build Real "Context-Rich" AI Agents
Before prompt caching, developers had to aggressively compress prompts: deleting conversation turns, cutting down few-shot examples, and writing terse system instructions.
With prompt caching, you can comfortably feed the model:
- The complete documentation of your product.
- Hundreds of lines of strict behavioral guidelines.
- 20 realistic few-shot conversation examples.
- Complete database schemas.
Since you only pay the full price for that context once, keeping it in the prompt permanently is virtually free!
4. How Major Providers Implement Caching
Different AI providers handle prompt caching in two different flavors: Automatic Caching and Explicit Caching.
| Provider / Model | Caching Type | Minimum Tokens Required | Time to Live (TTL) | Discount on Cache Hits |
|---|---|---|---|---|
| OpenAI (GPT-4o, o1) | Automatic | 1,024 tokens | 5–10 minutes of inactivity | 50% off input tokens |
| Anthropic (Claude 3.5) | Explicit (cache_control) |
1,024 to 2,048 tokens | 5 minutes (refreshed on each hit) | 90% off input tokens |
| Google Gemini (1.5 Pro) | Explicit & Automatic | 32,768 tokens (explicit) | Configurable (minutes to hours) | 75% off input tokens |
| DeepSeek (V3 / R1) | Automatic | 64 tokens | Dynamic GPU eviction | 90%+ off input tokens |
OpenAI: Automatic Prefix Caching
OpenAI inspects your prompts automatically. If any prompt over 1,024 tokens shares an identical prefix with a recent prompt (from the past 5 to 10 minutes), OpenAI automatically applies the 50% discount and speeds up execution. You don't need to change a single line of API code!
Anthropic: Explicit Breakpoints
Anthropic gives developers fine-grained control using the cache_control parameter. You can define up to 4 cache breakpoints in your request (e.g., at the end of your system prompt, and at the end of a reference document).
{
"role": "user",
"content": [
{
"type": "text",
"text": "Here is the entire 200-page employee handbook: ...",
"cache_control": {"type": "ephemeral"}
},
{
"type": "text",
"text": "How many days of paid vacation do employees get?"
}
]
}
5. The Golden Rule of Prompt Caching: "Static First, Dynamic Last"
Because prompt caching works via prefix matching, the order of information in your prompt is critical.
A single changed word at the beginning of your prompt invalidates everything that follows!
❌ WRONG (Cache Invalidation on Every Call):
[ Today's Date: Oct 17, 2026 ] ──> Changes every day! (Busts the cache)
[ 50-page Employee Handbook ] ──> Must be re-computed from scratch!
[ User Question ]
✓ CORRECT (Maximum Cache Hits):
[ 50-page Employee Handbook ] ──> 100% Identical every time (CACHE HIT!)
[ Fixed System Guidelines ] ──> 100% Identical every time (CACHE HIT!)
[ Today's Date & User Query ] ──> Dynamic elements placed at the very end
The Ideal Prompt Layout:
- System Persona & Global Instructions (Fixed)
- Tools & Function Definitions (Fixed)
- Large Grounding Knowledge / Documents (Fixed)
- Few-Shot Examples (Fixed)
- Conversation History (Appended turn-by-turn)
- Current User Message (Dynamic, at the bottom)
6. Hands-On Python Example: Inspecting Cached Tokens
Let's see how you can verify prompt caching in Python using the official OpenAI client:
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
# Create a long static reference document (> 1024 tokens)
static_context = (
"You are an expert tutor for Vidhyai, an online AI education platform.\n"
"Here is the platform policy and syllabus overview:\n"
+ ("All students must receive clear, intuitive, and real-world explanations. " * 150)
)
def ask_question(question_text: str):
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": static_context},
{"role": "user", "content": question_text}
]
)
usage = response.usage
cached = getattr(usage.prompt_tokens_details, "cached_tokens", 0) if usage.prompt_tokens_details else 0
print(f"Total Input Tokens: {usage.prompt_tokens}")
print(f"Cached Input Tokens: {cached}")
print(f"AI Answer: {response.choices[0].message.content[:100]}...\n")
# Call 1: Cold start (Cache Miss - writes to cache)
print("--- Request 1 (Cold Start) ---")
ask_question("What is the core philosophy of Vidhyai?")
# Call 2: Identical prefix (Cache Hit!)
print("--- Request 2 (Subsequent Call) ---")
ask_question("Can you explain how students learn best?")
What the Output Looks Like:
--- Request 1 (Cold Start) ---
Total Input Tokens: 1285
Cached Input Tokens: 0
AI Answer: The core philosophy of Vidhyai is providing students with clear, accessible, and intuitive...
--- Request 2 (Subsequent Call) ---
Total Input Tokens: 1285
Cached Input Tokens: 1280
AI Answer: Students learn best when complex technical concepts are grounded in relatable analogies...
Notice that on Request 2, 1,280 out of 1,285 tokens were served straight from cache! You got billed at 50% discount and the response started generating in a blink.
7. Common Pitfalls to Avoid
- The Timestamp Trap: Putting
Current time: 17:45:22in your system prompt changes every second and breaks caching completely. Put timestamps in the user message instead. - Random Whitespace / Formatting Changes: Caching operates on exact token sequences. If your code formatter changes line breaks or spacing in your prompt template, the cache will miss.
- Small Prompts: Providers only cache prompts above minimum thresholds (e.g., 1,024 tokens). Short 50-word prompts won't trigger caching (nor do they need to).
- Cache Eviction: Cached entries are stored in high-speed GPU memory and typically expire after 5 to 10 minutes of inactivity. For continuous workloads, keep a steady heartbeat or set appropriate TTLs.
Key Takeaways
- Prompt Caching eliminates redundant GPU computations by saving the attention KV matrices of static text.
- It delivers up to a 90% discount on input costs and cuts initial response latency by up to 80%.
- Place all static, heavy content at the beginning of your prompts and keep dynamic user inputs at the end.
- Whether you're building multi-turn chatbots, code assistants, or document search engines, prompt caching is now an essential tool in every AI engineer's toolkit.