AIEP
Cost & EfficiencyValidated in ProductionUpdated 2026-11

Prompt Prefix Caching

Build every prompt stable-first so the provider can reuse the processed prefix at a fraction of the price, and catch the one volatile byte that silently turns every request into a miss.

Runnable example, tested in CISourceTestsJump to code
$cd examples && pytest cost_and_efficiency/test_prompt_prefix_caching.py
costlatencycachingpromptstokens

What It Is

Most model providers can cache the processed form of a prompt's beginning. A later request that starts with exactly the same bytes skips reprocessing that part. It's billed at a small fraction of the normal input price and usually returns its first token sooner. Providers call it prompt caching (Anthropic, OpenAI) or context caching (Google).

The provider does the caching. The pattern is on your side: assemble every prompt so the large, unchanging part comes first and is byte-identical every time, put everything that varies after it, and check continuously that hits are actually happening.

The Problem It Solves

A typical assistant sends the same few thousand tokens on every request: tool definitions, a long system prompt, few-shot examples, maybe a policy document. On an agent loop, it resends the whole conversation every turn. Without caching you pay full price for those tokens every time, and the bill grows roughly with the square of conversation length.

Teams turn caching on, and often it doesn't work, quietly. The cache is an exact prefix match, so any of these near the top defeats it:

  • Current time: {now} or a request ID in the system prompt.
  • Tool definitions serialized from a dict or set whose order isn't fixed.
  • JSON with unsorted keys, or a user's name interpolated into the system prompt.

Every request still succeeds. The only symptom is a bill that never went down.

How It Works

flowchart LR
    T["Tools
(sorted, canonical JSON)"] --> S["System prompt
(frozen, no dates or ids)"] S --> H["Conversation so far"] H --> B(["cache breakpoint"]) B --> V["Per-request context:
date, user plan, retrieved rows"] V --> Q["Question"]
  1. Order by stability. Most providers render tools, then the system prompt, then messages. Put the parts that never change first, rarely-changing parts next, and per-request content last.
  2. Make the stable part deterministic. Sort tools by name and serialize with sorted keys. Freeze the system prompt as a template with no interpolation. Anything per-user or per-request (date, plan, locale) goes in a context block after the cached prefix.
  3. Mark the breakpoint where the shared part ends, where the provider wants an explicit marker (Anthropic's cache_control). Others cache automatically above a minimum length. Either way, a breakpoint after the varying tail buys nothing, because no other request shares those bytes.
  4. Respect the minimum and the TTL. Prefixes below a model-specific minimum aren't cached, and you get no error. Entries expire after a few minutes unless a request reads them, which refreshes the timer. Longer TTLs exist at a higher write price, so pick by the gap between requests that share the prefix.
  5. Verify from usage, continuously. The provider reports cached and written tokens per request (cache_read_input_tokens and cache_creation_input_tokens on Anthropic, cached_tokens on OpenAI). Alert when the read share drops. When it does, diff two consecutive prefixes to find the first changed byte.

When to Use It

  • Prompts share a long prefix: a big system prompt, tool definitions, few-shot examples, a document many questions are asked about.
  • Agent loops and multi-turn chats, where each request resends the conversation so far.
  • Traffic arrives often enough that consecutive requests sharing a prefix land within the cache TTL.

When NOT to Use It

  • The beginning of the prompt is unique per request. If the first thousand tokens differ every time, nothing can be reused, and on providers that charge for writes you only pay the premium.
  • Prompts are short. Below the model's minimum cacheable length the marker is silently ignored. Check the minimum for your model before expecting savings.
  • Traffic is very sparse. If requests sharing a prefix arrive hours apart, entries expire between them. A longer TTL can help, but its write premium needs several reads to pay off.

Trade-offs

  • Writes can cost more than plain input. On Anthropic's API a cache write costs 1.25× the input price for the 5-minute TTL and 2× for the 1-hour TTL, while reads cost about a tenth (less on some newer models). Two requests within the TTL already beat no caching on the 5-minute TTL, and the 1-hour TTL needs at least three. Other providers price differently, and some don't charge for writes at all.
  • Prompt design becomes an ordering constraint. "Just add today's date to the system prompt" is now a cost bug. Reviewers need to know the rule.
  • Caching is scoped. Entries are usually per model and per organization or workspace. Switching models mid-conversation or splitting traffic across workspaces gives up reuse.

Failure Modes

The silent invalidator. Caching worked when it shipped. Months later someone adds {user_name} to the system prompt, and every request misses with no error. Lint the stable prefix for volatile-looking values in CI, and alert on the cached-token share, not just on cost.

Non-deterministic serialization. Tool schemas built from a dict whose order depends on registration order, or json.dumps without sort_keys. The prompt looks identical in logs but differs byte for byte. Sort and canonicalize before rendering, and compare raw bytes when you debug.

Breakpoint after the unique tail. With automatic caching or a marker on the last block, every request writes an entry for content no other request shares. You pay a premium on every call and read nothing. Place the breakpoint at the end of the shared part.

Rewriting history. Editing or dropping an earlier conversation turn changes the prefix from that point on, and everything after it misses. Append instead of editing, and when you must shrink context, compact deliberately (Context Compaction) and accept one miss.

Implementation Example

A stable-first prompt builder, a lint for volatile values in the cached prefix, a diff that names the first changed byte, and a small simulator of provider caching (TTL refreshed by reads, minimum length, write premium, cheap reads). The tests show a timestamp in the system prompt turning every request into a miss, the same timestamp moved after the prefix restoring an 80% hit rate, and tool order not mattering once tools are sorted.

cd examples && pytest cost_and_efficiency/test_prompt_prefix_caching.py
"""Prompt Prefix Caching.
 
Providers can cache the processed prefix of a prompt and bill later requests
that start with the same bytes at a fraction of the input price. The catch:
it's an exact prefix match. One timestamp near the top, a tool list in a
different order, or JSON with unsorted keys, and every request misses while
nothing errors.
 
This module does the two things that make caching work in practice:
1. Builds prompts stable-first: tools (sorted, canonical JSON), then the
   frozen system prompt, then history, then the volatile per-request part.
2. Finds what broke the prefix when the hit rate drops: a lint for
   volatile-looking values in the stable part, and a diff that points at the
   first changed byte.
 
`PrefixCache` is a small simulator of provider behaviour (TTL refreshed on
read, minimum cacheable length, write premium, cheap reads) so the economics
can be tested offline. In production, read the provider's usage fields
(e.g. cache_read_input_tokens) instead.
"""
 
from __future__ import annotations
 
import hashlib
import json
import re
import time
from collections.abc import Callable
from dataclasses import dataclass, field
 
VOLATILE = [
    (re.compile(r"\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}"), "timestamp"),
    (re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.I), "uuid"),
    (re.compile(r"\b(request|session|trace)[_-]?id\s*[:=]", re.I), "per-request id"),
]
 
 
@dataclass(frozen=True)
class Prompt:
    prefix: str  # cacheable: identical across requests that share it
    suffix: str  # volatile: the part that changes every request
 
    @property
    def text(self) -> str:
        return self.prefix + self.suffix
 
 
def render(tools: list[dict], system: str, history: list[str], user: str, context: str = "") -> Prompt:
    """Stable-first assembly. `context` is per-request data (today's date, the user's
    plan, retrieved rows): it goes after the cached prefix, never inside `system`."""
    tool_block = "\n".join(json.dumps(t, sort_keys=True) for t in sorted(tools, key=lambda t: t["name"]))
    prefix = f"<tools>\n{tool_block}\n</tools>\n<system>\n{system}\n</system>\n" + "".join(
        f"<turn>{h}</turn>\n" for h in history
    )
    suffix = (f"<context>{context}</context>\n" if context else "") + f"<user>{user}</user>"
    return Prompt(prefix, suffix)
 
 
def lint_prefix(prefix: str) -> list[str]:
    """Volatile-looking values in the part that is supposed to be identical every time."""
    return [f"{label}: {m.group(0)!r}" for pattern, label in VOLATILE for m in pattern.finditer(prefix)]
 
 
def first_difference(previous: str, current: str, context: int = 30) -> str | None:
    """Where two prefixes that should match stop matching."""
    for i, (a, b) in enumerate(zip(previous, current)):
        if a != b:
            return f"byte {i}: {previous[max(0, i - context):i + context]!r} -> {current[max(0, i - context):i + context]!r}"
    if len(previous) != len(current):
        return f"byte {min(len(previous), len(current))}: one prefix is longer"
    return None
 
 
@dataclass
class Usage:
    cache_read: int = 0
    cache_write: int = 0
    uncached: int = 0
 
    def cost(self, read_x: float = 0.1, write_x: float = 1.25) -> float:
        """In units of 'one uncached input token'."""
        return self.uncached + self.cache_read * read_x + self.cache_write * write_x
 
 
@dataclass
class PrefixCache:
    count_tokens: Callable[[str], int]
    ttl_s: float = 300.0
    min_tokens: int = 1024
    clock: Callable[[], float] = time.monotonic
    entries: dict[str, float] = field(default_factory=dict)  # prefix hash -> expires_at
    total: Usage = field(default_factory=Usage)
 
    def request(self, prompt: Prompt) -> Usage:
        now = self.clock()
        prefix_tokens = self.count_tokens(prompt.prefix)
        usage = Usage(uncached=self.count_tokens(prompt.suffix))
        key = hashlib.sha256(prompt.prefix.encode()).hexdigest()
        if prefix_tokens < self.min_tokens:
            usage.uncached += prefix_tokens  # too short: silently not cached, no error
        elif self.entries.get(key, 0) > now:
            usage.cache_read += prefix_tokens
            self.entries[key] = now + self.ttl_s  # a read refreshes the timer
        else:
            usage.cache_write += prefix_tokens
            self.entries[key] = now + self.ttl_s
        for name in ("cache_read", "cache_write", "uncached"):
            setattr(self.total, name, getattr(self.total, name) + getattr(usage, name))
        return usage
 
    @property
    def hit_rate(self) -> float:
        cacheable = self.total.cache_read + self.total.cache_write
        return self.total.cache_read / cacheable if cacheable else 0.0

Tool Landscape

ToolNotes
Anthropic prompt cachingExplicit cache_control breakpoints (up to 4) or automatic caching; 5-minute and 1-hour TTLs
OpenAI prompt cachingAutomatic for long prompts; cached_tokens reported in usage
Google Gemini context cachingImplicit caching plus explicit cached-content objects with a TTL
vLLM / SGLang prefix cachingAutomatic prefix reuse when you self-host
  • Semantic Caching skips the model call entirely for repeated questions. This pattern makes the calls you do make cheaper. They stack.
  • Token Budget shrinks the prompt. This pattern makes the part you keep cheaper to resend.
  • Context Compaction rewrites history, which breaks the cache from that point. Compact rarely and on purpose.
  • LLM Gateway is a good place to record cached-token share per feature and alert when it drops.

Further Reading

Spotted something wrong or have a production story? Edit this page on GitHub.