Chapter 36 of 40 · ~15 min read & lab+60 XP
Chapter 36 · Generative AI

Prompt Caching & Prefix Caching Explained: Cutting LLM API Costs by 50–90%

How RadixAttention / KV-Prefix Caching reuses prefilled system prompts and tool schemas across requests—and the #1 prompt layout rule that breaks cache hits

What Is It?

Prompt Caching (Prefix Caching) stores the precomputed GPU KV-Cache of the static beginning of your prompt so repeated requests skip redundant prefill compute—slashing input token costs by 50%–90% and TTFT by up to 80%.

Why Is It Required?

Agentic and RAG apps resend the same 5,000-token system prompt, tool schemas, and few-shot examples on every single turn; without prefix caching, you pay to recompute identical tokens thousands of times.

Everyday Analogy: Saving a pre-baked pizza crust so when a customer orders toppings, you only bake the last 2 minutes instead of kneading dough from scratch every time.
Why ML Engineers & Data Scientists Actually Need This

Moving one dynamic timestamp from Line 1 to the bottom of your system prompt can instantly cut your monthly OpenAI/Anthropic/Gemini bill in half!

ML / AI Engineer

In vLLM / SGLang (RadixAttention), shared KV prefix trees let hundreds of concurrent users share the exact same system-prompt VRAM blocks.

Data Scientist

Cache-friendly prompt ordering makes 50-turn coding and research agents economically viable.

Interview & Debug Edge

Favorite 2025/2026 practical interview question: 'Why does putting Current time: 14:32:05 at the very top of your system prompt destroy Prompt Caching?'

Step 0 · Test Your Gut Before Any Math!

Which prompt layout maximizes Prompt Caching (KV prefix reuse) across multi-turn agent calls?

What You Will Master in This Chapter
  • Explain why Prompt Caching works ONLY on an exact matching prefix (token 0 through token P) due to Causal Attention.
  • Structure prompts cleanly: Static First (System Prompt → Tool Schemas → Static Docs/Few-Shots) and Dynamic Last (Timestamp, User ID, Live Query).
  • Calculate real-world dollar and TTFT savings from a 90% cache-hit rate on multi-turn agent loops.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 1
Cost=cmissNuncached+chitNcached\text{Cost} = c_{\text{miss}} N_{\text{uncached}} + c_{\text{hit}} N_{\text{cached}}Say aloud:“Cached input token cost”
Plain-English Meaning
Cached prefix tokens typically cost 10%–25% of standard input token price (75%–90% discount).
Everyday Example
10K prefix cached at 90% off costs the same as 1K uncached tokens!
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Because Causal Self-Attention lets every token attend to all earlier tokens, changing one single character at the start ripples through every downstream KV tensor. Keep your prefix byte-for-byte identical across calls, and push all dynamic variables to the very end!

1. The 3 Rules of Cache-Friendly Prompt Engineering

  1. Static First, Dynamic Last: Put system instructions, JSON tool schemas, and static reference docs at the top; put timestamps, user IDs, and live retrieved snippets at the bottom.
  2. Deterministic Tool Ordering: Sort tool definitions alphabetically so dict ordering never jitters between calls.
  3. Append-Only Chat History: Never rewrite earlier turns mid-conversation; append new turns so turns 1..t-1 remain a 100% cache hit on turn t!
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Most providers keep implicit or explicit prefix caches warm for 5 to 60 minutes of inactivity (TTL), refreshing automatically whenever a matching request hits the prefix.

Interactive Visual Lab
Lab Challenge: Watch how KV-cache reuse skips redundant prefill computation across sequential turns.
Interactive Animation • 2.1 Deep Lab

Autoregressive KV-Cache Growth & FLOPs Savings Animator

Watch each generated token append 1 new Key/Value row to the KV-Cache instead of recomputing all previous tokens from scratch.

Cumulative K/V Projections: 1 vs. 1
The
compute K,V
quick
pending
brown
pending
fox
pending
jumps
pending
over
pending
the
pending
dog
pending
0%
Decoding Step t = 1 ("The")
Intuition Takeaway: Order every prompt Static-First, Dynamic-Last with deterministic tool schemas and append-only chat turns to unlock 50%–90% cost savings and much faster TTFT via KV Prefix Caching.
Production NumPy & PyTorch Code Patterns
# Calculate Monthly API Savings From Prefix Caching (Static-First Prompting)
def compare_cache_cost(turns: int, static_prefix_tok: int, new_tok_per_turn: int, price_per_m: float = 3.0, cache_discount: float = 0.90):
    # Without caching: pay full price on prefix + growing history every turn
    no_cache = sum((static_prefix_tok + t * new_tok_per_turn) * price_per_m / 1e6 for t in range(1, turns + 1))
    # With caching: turn 1 pays full prefix; turns 2..N pay discounted rate on prefix + prior turns
    with_cache = (static_prefix_tok + new_tok_per_turn) * price_per_m / 1e6
    for t in range(2, turns + 1):
        cached_part = static_prefix_tok + (t - 1) * new_tok_per_turn
        with_cache += (cached_part * (1.0 - cache_discount) + new_tok_per_turn) * price_per_m / 1e6
    return no_cache, with_cache

raw, cached = compare_cache_cost(turns=10, static_prefix_tok=8000, new_tok_per_turn=500)
print(f"10-turn agent run | No cache: ${raw:.4f} | With 90% prefix cache: ${cached:.4f} ({(1 - cached/raw):.0%} saved!)")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Putting current_time or request_id at the top of the system prompt.
Best Practice: Always place dynamic per-request variables at the very end of the prompt (or in the latest user turn) to preserve 100% prefix cache hits.
Chapter Mastery Check (+60 XP)
Score: 0 / 1
1Why does changing a single word on Line 1 of a 10,000-token prompt invalidate the entire KV prefix cache?

Apply What You Learned — Solve Matching Coding Problems