Caching Long Prefixes
Cost control with prompt caching.
Caching Long Prefixes is a free AI Prompt Engineering lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Prompt Engineering learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Prefix Caching Exists
Every long prompt pays prefill cost to encode its tokens before generating. When the same long prefix repeats across many calls — a system prompt, a tool spec, a large reference document — prompt caching lets the provider reuse the already-computed attention state instead of recomputing it.
- Cache hits cut latency and input cost dramatically.
- The savings scale with prefix size and reuse frequency.
Caching Is Prefix-Anchored
Caches key on an exact token-prefix match from the start of the prompt. The cached span runs from the beginning up to the first point of divergence. Change anything early and everything after it misses the cache.
Implication: the layout that maximizes hits puts the most stable content first and the most variable content last.
# Cache reuse covers: [identical prefix .... first difference)
# One early edit invalidates the whole downstream cache.Order by Stability
Arrange content from most to least stable: immutable system rules and tool definitions, then large stable reference material, then session-stable context, then the volatile per-request input and question last.
- Stable -> front (cacheable).
- Volatile -> back (the only part recomputed).
This single ordering principle drives most caching wins.
prompt = [
SYSTEM_RULES, # never changes
TOOL_SPECS, # rarely changes
REFERENCE_CORPUS, # stable for the session
USER_TURN # changes every call -> keep last
]Cache Breakpoints
Some providers let you mark explicit cache breakpoints. Place them at the end of each stable segment so the system can cache up to that point. Mark the largest stable block (the reference corpus or long system prompt) as cacheable.
Without explicit markers, structure stability-ordering anyway so implicit prefix matching still helps.
blocks = [
{'text': SYSTEM_RULES, 'cache': True},
{'text': REFERENCE_CORPUS, 'cache': True}, # big win
{'text': user_turn} # uncached
]Beware Hidden Prefix Drift
Subtle, unintentional changes silently break caching: a timestamp in the system prompt, a per-request id injected early, reordered tool definitions, or non-deterministic JSON key order. Each shifts the prefix and forces a full recompute.
Audit your prefix for anything that varies between calls and move it after the cached region.
# BAD: dynamic value early -> kills cache
# system = 'Session ' + str(uuid4()) + ' rules: ...'
# GOOD: keep system static; put the id in the tail user turn.TTL and Cache Lifetime
Caches expire after a provider-defined time-to-live, often refreshed on each hit. Cold misses recur if calls are too sparse. For bursty, high-frequency workloads caching pays off; for rare, scattered calls the cache may expire between uses.
Match your traffic pattern to the TTL, and consider keep-alive pings for valuable prefixes.
Cost Model of Caching
Caching typically charges a small premium to write a cache entry and a steep discount to read it. The economics favor reuse: one write amortized over many reads is a large net saving; a single use that only writes can cost slightly more.
- High reuse -> cache aggressively.
- One-shot prefixes -> caching may not pay.
def worth_caching(prefix_tokens, expected_reuses, write_mult, read_mult):
no_cache = expected_reuses
cached = write_mult + read_mult * (expected_reuses - 1)
return cached < no_cache # in normalized prefix-cost unitsDesigning Stable System Blocks
Make your system prompt and tool specs deterministic and version-pinned. Sort tool definitions canonically, avoid embedding dynamic data, and change them only on deliberate releases. A stable system block becomes a long-lived, high-hit cache entry shared across all requests.
Treat the cached prefix as an artifact with a version, not a string you tweak casually.
TOOLS = sorted(tool_defs, key=lambda t: t['name']) # canonical order
SYSTEM_VERSION = 'v3' # change deliberately, not per requestCaching in Multi-Turn Agents
In agent loops, the growing conversation is a natural cache: each turn extends a prefix the next turn reuses. Append new turns at the tail and never rewrite earlier turns, so the prior cache stays valid.
When you must compact, do it in a way that creates a new stable prefix for subsequent turns rather than mutating old ones repeatedly.
Measuring Cache Effectiveness
Instrument it. Most providers report cached vs uncached input tokens per call. Track hit rate, and if it is low, inspect the prefix for drift. A regression in hit rate usually points to a recently introduced dynamic value early in the prompt.
- Log cached_tokens / total_input_tokens.
- Alert when hit rate drops after a deploy.
hit_rate = usage['cache_read_input_tokens'] / max(1, usage['input_tokens'])
assert hit_rate > 0.6, 'prefix drift suspected'A Caching-Aware Prompt Layout
To control cost on long prefixes: order content by stability, mark the largest stable block as a cache breakpoint, eliminate hidden drift, pin and version system/tool blocks, append-only in agent loops, and monitor hit rate. The goal is one big reusable prefix and a small volatile tail recomputed each call.
Quick Check
You reuse a 100k-token reference corpus across thousands of daily queries but your cache hit rate is near zero.
Recap: Caching Long Prefixes
Prompt caching reuses the prefill of an exact, stable prefix, slashing latency and input cost when reuse is frequent. Order content most-stable-first, mark the big stable block as a breakpoint, and push all volatility to the tail. Eliminate hidden drift, pin and version system/tool blocks, append-only in agent loops, and monitor the hit rate so a regression flags a newly introduced early-varying value.
Frequently asked questions
Is the “Caching Long Prefixes” lesson free?
Yes — the full text of “Caching Long Prefixes” is free to read here on the web, and the AI Prompt Engineering course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Prompt Engineering course, upgrade to CoddyKit PRO.
What will I learn in “Caching Long Prefixes”?
Cost control with prompt caching. You practise AI Prompt Engineering with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Prompt Engineering?
No prior experience is required. AI Prompt Engineering on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Caching Long Prefixes” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Prompt Engineering lesson?
Yes. Every AI Prompt Engineering lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Million-Token Context Windows
- Lost in the Middle
- Structuring Huge Prompts
- Caching Long Prefixes