Leveraging LLM Context Caching: Cut Costs on Repeated Tokens to Up to 75% Off

    High input token costs in production LLM applications often stem from repeated content—multi-turn dialogues, RAG queries, and agent workflows constantly resend identical prefixes. Prompt caching tackles this by reusing computed KV states across requests, with cached tokens typically billed at 10–40% of standard input price. This article explains how context caching works under the hood, breaks down cache pricing models with real formulas, and provides practical strategies to maximize cache hit rates: from structuring prompts with static content first and dynamic content last, to setting explicit cache breakpoints and monitoring cache hit ratios. It also includes concrete cost calculations for typical use cases like multi-turn conversations.

    Why Repeated Input Is the Biggest Cost Driver

    In production environments, input tokens usually far outnumber output tokens. The reason is that many requests repeatedly carry the same content:

    • Multi-turn conversations: Each turn requires re-sending the entire history; the longer the conversation, the longer the repeated portion.
    • Long-document Q&A (RAG): Retrieved snippets, system prompts, and few-shot examples are highly similar across requests.
    • Agent workflows: Task descriptions, tool definitions, and execution records are repeatedly attached to every step’s invocation.
    • Batch processing: Generating summaries or extractions for multiple chunks of the same document yields nearly identical common prefixes.

    When these repeated tokens are billed at full price, costs scale with both user volume and context length. Prompt caching targets exactly this issue. When a matching prefix hits the cache, it’s billed at a discounted rate. Most platforms charge between 10% and 40% of the standard input price for cache hits—with 25% (a “2.5x discount” equivalent) being common.

    How Context Caching Works

    From Single-Request KV Cache to Cross-Request Reuse

    When a Transformer generates text, every token produces Key and Value vectors at each layer. Within a single request, already-computed KV pairs are reused—this is what’s known as the KV Cache.

    Context caching extends this idea across requests. The server persistently stores the KV state for a common prefix for a period of time. If subsequent requests share an identical prefix, they can directly read these stored results, skipping most of the prefill computation. With reduced compute, providers can offer discounted pricing. Fewer prefill operations also shorten time-to-first-token (TTFT), though the exact improvement depends on the model and service provider.

    Cache Hit Conditions

    A cache hit generally requires satisfying three conditions:

    1. Exact token-level prefix match: Comparison starts from the very first token. A single difference—even a changed punctuation mark in the system prompt or an injected timestamp—invalidates everything after that point.
    2. Identical model and parameters: Different model versions or quantization configurations do not share caches.
    3. The cache hasn’t expired: KV states have a time-to-live (TTL), typically ranging from minutes to hours. Some platforms refresh the TTL on each hit; others do not. Always refer to your provider’s documentation.

    Pricing and Amortization

    Cache pricing typically involves three components:

    Fee Type Description
    Cache write Charged when a prefix is first written to cache; usually slightly higher than standard input pricing
    Cache read (hit) Billed at a discount—commonly 10% to 40% of the standard input price
    Uncached input Incremental content beyond the prefix—billed at standard rates

    To calculate the real cost, let’s set the standard input unit price to 1, write price to W, and hit price to H. A prefix of length P is reused N times, with an incremental addition U per request, and total request length T = P + U. The total cost over N requests is:

    C = W·P + (N−1)·H·P + N·U

    Without caching, the cost would be N·T. The ratio between the two gives you your actual cost percentage.

    Example: Each request is 10,000 tokens, with a 9,000-token prefix (90%) and a 1,000-token increment. W = 1.25, H = 0.25, and the prefix is reused N = 20 times.

    • With cache: C = 1.25×9,000 + 19×0.25×9,000 + 20×1,000 = 11,250 + 42,750 + 20,000 = 74,000
    • Without cache: 20×10,000 = 200,000
    • Ratio: 74,000 / 200,000 ≈ 37% (about 3.7x depreciation)

    The more times the prefix is reused, the thinner the write fee is spread. As N approaches infinity, the ratio approaches (H·P + U) / T = (0.25×9,000 + 1,000) / 10,000 = 0.325. In other words, with a 90% prefix ratio, the theoretical lower limit of your total cost is ~32.5%. The 25% discount applies only to the prefix segment—incremental tokens are still billed at full price.

    The price multipliers above are hypothetical examples. Always consult your provider’s actual price sheet.

    How to Maximize Cache Hit Rates

    Put Static Content First, Dynamic Content Last

    This is the most important principle: the unchanging content goes at the beginning of the prompt, and the variable content goes at the end. A recommended ordering is:

    Tool definitions (fixed) → System prompt (fixed) → Few-shot examples (fixed) → Session-level documents (fixed per session) → Dialog history → Current user input

    Watch out for these common anti-patterns:

    • Writing something like Current time: 2026-11-24 19:38 at the very top of the system prompt. Since this value changes with every request, the entire prefix becomes invalid. Move timestamps to the end, or inject them only when needed.
    • Serializing tool definitions with unstable field ordering. Fix the serialization order (e.g., sort by key).
    • Using inconsistent tokenizer versions or templates across multiple deployment replicas, producing different token splits for the same prefix. Standardize the model version and tokenizer.

    Explicitly Set Cache Breakpoints

    Some platforms support explicitly marking cache breakpoints to control granularity. Here’s an example using the Anthropic Messages API, which uses a cache_control parameter to mark breakpoints. Verify that your model and SDK version support prompt caching before relying on it.

    1. import anthropic
    2. client = anthropic.Anthropic() # API key read from environment variable ANTHROPIC_API_KEY
    3. response = client.messages.create(
    4. model="your-model-name", # Replace with a model name that supports caching per official docs
    5. max_tokens=1024,
    6. tools=tool_definitions, # Mark a breakpoint on the last tool to cache all tool definitions
    7. system=[
    8. {
    9. "type": "text",
    10. "text": SYSTEM_PROMPT, # Breakpoint 1: globally fixed content
    11. "cache_control": {"type": "ephemeral"},
    12. },
    13. {
    14. "type": "text",
    15. "text": document_content, # Breakpoint 2: session-level document
    16. "cache_control": {"type": "ephemeral"},
    17. },
    18. ],
    19. messages=[
    20. *dialog_history,
    21. {"role": "user", "content": user_input},
    22. ],
    23. )
    24. print(response.usage)

    Key notes:

    • By setting breakpoints, even if the session document changes, the earlier tool definitions and system prompt still hit the cache.
    • There’s a limit on the number of breakpoints. Anthropic allows up to 4 per request—allocate them by priority.
    • Some platforms accept only a single system message or don’t expose an explicit breakpoint parameter. In that case, follow that platform’s rules—e.g., merge segments into a single string and set the prefix boundary according to the platform’s conventions.
    • Caching matches in order: tools, system prompt, messages. A change anywhere earlier in the sequence invalidates everything after it.

    Reach the Minimum Cacheable Prefix Length

    Caches typically have a minimum prefix length before caching kicks in. Below that threshold, write fees may never pay off. Common thresholds range from 1,024 to 4,096 tokens, and they vary significantly by model and platform. Always check the official documentation.

    For this reason, make your common prefix as “thick” as possible. Including few-shot examples and format specifications in the prefix boosts both the hit rate and the likelihood of crossing the minimum threshold.

    Monitor and Debug Cache Hit Rates

    After going live, watch your hit rate continuously. Different providers return different usage fields with different calculation methods. For Anthropic, the usage object contains input_tokens, cache_creation_input_tokens, and cache_read_input_tokens. The hit rate is the ratio of cache reads to total input:

    1. def calc_cache_hit_rate(usage_list):
    2. read = sum(u.cache_read_input_tokens or 0 for u in usage_list)
    3. write = sum(u.cache_creation_input_tokens or 0 for u in usage_list)
    4. uncached = sum(u.input_tokens for u in usage_list)
    5. total = read + write + uncached
    6. return read / total if total else 0.0

    If you’re using an OpenAI-style interface, prompt_tokens already includes cached tokens; the number of hits is recorded in prompt_tokens_details.cached_tokens. In this case, don’t count the read and total fields separately.

    When the hit rate suddenly drops, run through this checklist:

    1. Has anyone modified the system prompt—even a single punctuation mark?
    2. Is there a new A/B test running that splits the prefix into multiple variants?
    3. Is the TTL too short, causing low-frequency requests to always start cold?
    4. Were dynamic elements (timestamps, random IDs, usernames) inserted into the prefix position?

    Cost Estimates for Common Scenarios

    The estimates below assume: standard input price = 1, write price = 1.25, hit price = 0.25. Output tokens and the small number of tokens per actual question are ignored.

    Multi-turn Conversation

    System prompt prefix: 2,000 tokens. Each turn adds 500 tokens, for 20 turns (k from 0 to 19).

    • Without caching: turn k has input of 2,000 + 500k. Total = Σ(2,000 + 500