7 min read· by Awab Tech Lover

Reduce LLM API Costs with Prompt Caching

Discover how to reduce LLM API costs with prompt caching. Learn how it works, see real-world benchmark numbers, and cut input token expenses by up to 90%.

Reduce LLM API Costs with Prompt Caching

How to Cut LLM API Costs with Prompt Caching (With Real Numbers)

Scaling an AI product often brings a painful realization: input tokens will quietly drain your engineering budget. Whether you run a retrieval-augmented generation (RAG) system with a deep reference corpus, an agent equipped with dozens of tool schemas, or an interactive document assistant, re-sending thousands of identical tokens on every API call is wildly inefficient. The single most effective strategy to reduce LLM API costs prompt caching provides is eliminating the need to process that identical context from scratch every single time.

By persisting token representations across requests, prompt caching slashes input expenses by 50% to 90% while dramatically reducing time-to-first-token (TTFT).

Below, we break down how prompt caching works under the hood, analyze the exact pricing across major frontier model providers, calculate real-world financial savings, and share architectural best practices to maximize your cache hit rates.


What Is Prompt Caching and How Does It Work?

Large language models are autoregressive: to generate token $N+1$, the model must compute attention scores across all preceding tokens ($1$ through $N$). During inference, this computation produces intermediate representations known as Key-Value (KV) pairs.

In traditional stateless API setups, every request recalculates the KV states for the entire context window—including static system prompts, shared background documents, and complex function declarations.

Traditional API Call:
[System Prompt + 10k Context] ---> [Full Attention Calculation] ---> Output

Cached API Call:
[System Prompt + 10k Context] ---> [Memory Lookup: KV Cache]    ---> Output (Instant)

Prompt caching stores the precomputed KV tensors in fast accelerator memory (or low-latency storage clusters) on the provider's infrastructure. When an incoming prompt matches the exact prefix of a previously processed sequence, the model skips recalculating those attention matrices. It loads the cached KV states directly into memory and only computes attention for newly added tokens.

Prefix Matching: The Golden Rule

Prompt caching relies on deterministic prefix matching. The cache only hits if the beginning of the prompt matches an earlier prompt byte-for-byte and token-for-token. If you change a single character at token position 50 in a 10,000-token prompt, the cache invalidates for tokens 50 through 10,000.


The Math Behind the Savings: Real Cost Comparisons

Providers price prompt caching using two distinct mechanics: cache writes (creating the cache entry) and cache reads (fetching the cached tokens).

Here is how the primary frontier providers structure prompt caching pricing as of 2025:

Provider & Model Standard Input Cost (per 1M tokens) Cached Read Cost (per 1M tokens) Cache Write Cost (per 1M tokens) Minimum Threshold
Anthropic Claude 3.5 Sonnet $3.00 $0.30 (90% off) $3.75 (25% premium) 1,024 tokens
Anthropic Claude 3.5 Haiku $0.80 $0.08 (90% off) $1.00 (25% premium) 2,048 tokens
OpenAI GPT-4o $2.50 $1.25 (50% off) $0.00 (No extra fee) 1,024 tokens
OpenAI GPT-4o mini $0.15 $0.075 (50% off) $0.00 (No extra fee) 1,024 tokens
Google Gemini 1.5 Pro $3.50 (for >128k) $0.875 (75% off) $4.50/hour storage 32,768 tokens

Real-World Production Scenario

Consider a production enterprise assistant.

  • Context: A 20,000-token knowledge base (system prompt + reference guidelines + product manuals).
  • Dynamic user input + generation: 500 input tokens, 500 output tokens.
  • Traffic volume: 50,000 queries per day.
  • Engine: Claude 3.5 Sonnet.

Without Prompt Caching:

  • Daily Base Input Tokens: $50,000 \times 20,500\text{ tokens} = 1,025,000,000\text{ tokens}$ (1,025 MTok)
  • Base Input Cost: $1,025 \times $3.00 = \mathbf{$3,075.00\text{ / day}}$
  • Monthly Input Cost: $92,250.00

With Prompt Caching (Assuming a 95% Cache Hit Rate):

  • Cache Writes (refreshing cache every 5 minutes = 288 writes/day):
    • $288 \times 20,000\text{ tokens} = 5.76\text{ MTok}$
    • Write Cost: $5.76 \times $3.75 = $21.60\text{ / day}$
  • Cache Reads (47,500 requests hit cache):
    • $47,500 \times 20,000\text{ tokens} = 950\text{ MTok}$
    • Cached Read Cost: $950 \times $0.30 = $285.00\text{ / day}$
  • Uncached Tokens (dynamic user tokens + cache misses):
    • Misses on static context ($2,500 \times 20,000 = 50\text{ MTok}$): $50 \times $3.00 = $150.00$
    • Dynamic user queries ($50,000 \times 500\text{ tokens} = 25\text{ MTok}$): $25 \times $3.00 = $75.00$
  • Total Daily Input Cost: $$21.60 + $285.00 + $150.00 + $75.00 = \mathbf{$531.60\text{ / day}}$
  • Monthly Input Cost: $15,948.00

Net Savings: $76,302 per month (an 82.7% reduction in total input costs).


Latency Gains: The Hidden Superpower

Cost reduction gets the budget approved, but latency reduction transforms the user experience.

When processing long prompts (10,000 to 100,000+ tokens), the calculation of the attention matrix is compute-bound. It introduces substantial Time-to-First-Token (TTFT) latency, often forcing users to wait 3 to 10 seconds before the model generates its initial word.

By pulling pre-computed KV layers directly from cache:

  • Anthropic benchmarks report TTFT reductions of up to 80% on 50k+ token prompts.
  • OpenAI automatic caching reduces response latencies on repeated context blocks by 30% to 50%.

Users no longer experience the sluggish "thinking" delay caused by heavy prompt overhead.


Architectural Best Practices: Structuring Prompts for Cache Hits

Because prompt caching works strictly from left to right (prefix matching), you must design your context sequences strategically.

1. Order Context by Volatility (Static to Dynamic)

Place your least volatile tokens at the very beginning of the prompt and your most volatile tokens at the very end:

  1. System Directives: Core behavioral rules, output formats, and safety boundaries (Never changes).
  2. Tool / Function Definitions: OpenAPI schemas and agent actions (Rarely changes).
  3. Reference Knowledge: Documentation, codebase snippets, vector search chunks (Changes per session or day).
  4. Conversation History: Multi-turn dialogue (Grows progressively).
  5. User Query: Current message and ephemeral variables (Changes every call).
[System Directives] -> [Tool Schemas] -> [Reference Docs] -> [History] -> [Current Query]
|<---------------------- CACHED PREFIX -------------------->|   (Dynamic)

2. Isolate Timestamps and Dynamic Metadata

A frequent anti-pattern is injecting dynamic metadata at the top of the prompt:

Current Time: 2025-05-12T14:32:01Z
User ID: 89412
You are an expert technical support assistant...

This single line invalidates the entire cache for every unique second or user. Instead, move ephemeral session metadata to the bottom alongside the user's latest query, preserving the cached static block above it.

3. Maintain Consistent Key Ordering

If your application serializes JSON schemas, dictionaries, or tool definitions programmatically, ensure keys are deterministically sorted (e.g., using json.dumps(obj, sort_keys=True)). Unordered dictionaries generate different string representations across runtime restarts, causing unexpected cache misses.


Provider Implementation Patterns

Different LLM providers implement caching with distinct design philosophies.

Anthropic Claude: Explicit Breakpoints

Anthropic uses an explicit cache_control parameter. You flag specific blocks in your message array as cache checkpoints:

{
  "model": "claude-3-5-sonnet-20241022",
  "max_tokens": 1024,
  "system": [
    {
      "type": "text",
      "text": "You are a legal contract analyzer...",
      "cache_control": {"type": "ephemeral"}
    }
  ],
  "messages": [...]
}

Note: Anthropic holds cached blocks for a 5-minute Time-To-Live (TTL), automatically refreshed each time the cache is accessed.

OpenAI: Automatic Prefix Caching

OpenAI requires no custom headers or parameters for models like gpt-4o and gpt-4o-mini. The platform automatically inspects prompt prefixes. If a prompt exceeds 1,024 tokens and matches an existing prefix in their internal cache, the discount is automatically applied and displayed in the usage.prompt_tokens_details.cached_tokens field of the response.


Key Pitfalls to Avoid

  • Sub-threshold prompts: Avoid writing complex caching logic for micro-prompts. If your prefix is under 1,024 tokens, neither OpenAI nor Anthropic will cache it.
  • Short TTL windows during off-peak hours: If your service experiences long gaps between requests (e.g., more than 5 minutes on Anthropic), you may pay the 25% cache write premium repeatedly without benefiting from reads. Keep a steady baseline ping or reserve explicit caching for active user sessions.
  • RAG chunk shuffling: When retrieving document chunks dynamically, sort retrieved chunks deterministically (e.g., by document ID) rather than raw similarity score. If the same five chunks are retrieved in a slightly different order, the prefix breaks.

FAQ

Does prompt caching affect the model's generation quality or randomness?

No. Prompt caching is mathematically identical to recalculating attention from scratch. The model loads the exact numerical tensors (KV states) that it would have computed otherwise. Output quality, deterministic behavior, and temperature sampling remain unchanged.

What happens when the cache expires?

When a cache entry passes its TTL window without being accessed, the provider purges the KV representations from memory. On the subsequent request, the provider treats the prompt as a standard input call (or re-writes the cache), computing the attention states fresh and resetting the TTL timer.

How does prompt caching differ from semantic caching?

Semantic caching stores the final output of an LLM call based on similar past queries (often via vector similarity search), skipping the LLM call entirely. Prompt caching still runs the LLM, but caches the input context processing at the model layer. Prompt caching allows dynamic, unique responses to every query while still cutting input costs.

Can I share prompt caches across different user accounts?

Yes, as long as the shared context is identical and placed at the beginning of the prompt. For instance, if 10,000 users query the same 50-page employee handbook, the cached handbook prefix can serve all users simultaneously, maximizing your hit rate and cost efficiency.

Do cache read discounts apply to output tokens?

No. Prompt caching only applies to input tokens that match the cached prefix. Output tokens (generation) and uncached input tokens are billed at standard provider rates.