Prompt Caching
Slash AI latency and token costs by up to 90 percent using Anthropic and OpenAI prompt caching breakpoints.
TL;DR
- Put stable
systemcontent first and changing user content last. - Mark Claude cache breakpoints with
cache_control; OpenAI caches prefixes automatically. - Confirm hits by checking
cache_read_input_tokensin the usage data.
Anthropic Cache Breakpoints
System Cache ControlAttach ephemeral cache breakpoint to static system instructions.
const system = [
{
type: 'text',
text: largeStaticDocumentation,
cache_control: { type: 'ephemeral' },
},
];Tool Cache BreakpointsCache extensive tool definition schemas to avoid re-billing.
const cachedTools = tools.map((t, i) => ({
...t,
...(i === tools.length - 1
? { cache_control: { type: 'ephemeral' } }
: {}),
}));Multiple Breakpoint LimitsConfigure up to four distinct cache checkpoints per request.
// Breakpoint 1: System prompt
// Breakpoint 2: Static reference book
// Breakpoint 3: Conversation history
// Dynamic: Final user questionOpenAI Automatic Caching
Prefix AlignmentOrder prompt components strictly from static to dynamic.
// 1. Static system prompt (> 1024 tokens)
// 2. Static documents
// 3. Dynamic runtime user query
// OpenAI caches shared prefixes automaticallyInspect Cached TokensVerify cache hits through prompt_tokens_details usage field.
const u = res.usage as any;
const cached =
u.prompt_tokens_details?.cached_tokens ?? 0;
console.log(`Cached: ${cached}`);Exact Prefix MatchEnsure identical character prefix to achieve cache hits.
const match = prev.startsWith(prefix);
// Any change invalidates subsequent cacheCache Hit Verification
Anthropic Cache UsageRead cache creation and cache read metrics from response.
const u = res.usage;
const w = u.cache_creation_input_tokens;
const r = u.cache_read_input_tokens;
console.log(`Write: ${w}, Read: ${r}`);Calculate Cost SavingsCompute monetary savings realized through cached tokens.
function calcSavings(
readTokens: number,
rate: number
) {
const full = (readTokens / 1e6) * rate;
return full * 0.90; // 90% cache discount
}Cache TTL MonitoringTrack 5-minute ephemeral cache window expiration.
const isWarm = Date.now() - lastRequestTime < 300000;
// Keep cache warm with recurring queriesArchitectural Best Practices
Document PinningPin massive background context above conversation turns.
const messages = [
{ role: 'user', content: cachedDocBlock },
{ role: 'user', content: dynamicUserQuestion },
];Remove Dynamic VariablesStrip dynamic timestamps and request IDs from cached blocks.
// Bad: `Current time: ${new Date().toISOString()}`
// Good: Place timestamp in dynamic user prompt onlyMulti-Turn Dialogue CachingCache conversation history up to the second-to-last turn.
const turns = history.map((h, i) => ({
...h,
...(i === history.length - 2
? { cache_control: { type: 'ephemeral' } }
: {}),
}));Tips
- Put static context first and the changing user question last, so
cache_read_input_tokensstays high on every request. - The default cache lasts five minutes and refreshes on every hit. For slower traffic, set
ttl: '1h'on the breakpoint instead of sending keep-alive pings.
Warnings
- Avoid timestamps or random IDs in the
systemprompt, because changing even one token invalidates everything cached after it. - Check the minimum cacheable prefix for your model, roughly 512 to 4096 tokens, because shorter prompts silently skip
cache_control.
In Practice
Configures cache_control breakpoints on a large system prompt and logs cache hit metrics.
- Construct large static documentation block exceeding 1024 tokens.
- Attach cache_control ephemeral breakpoint to system block.
- Dispatch messages request with Anthropic prompt-caching beta header.
- Inspect usage object for cache_read_input_tokens savings.
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
async function queryCachedDocs(question: string) {
const res = await client.messages.create({
model: 'claude-sonnet-5-5',
max_tokens: 250,
system: [{
type: 'text',
text: 'API SPEC: '.repeat(200),
cache_control: { type: 'ephemeral' },
}],
messages: [{ role: 'user', content: question }],
});
const u = res.usage;
const read = u.cache_read_input_tokens;
return { text: res.content[0], read };
}
console.log(await queryCachedDocs('Auth setup'));FAQ
When an AI provider encounters a prompt prefix identical to one processed recently, it skips recomputing transformer key-value attention weights. Instead, it reads the precomputed states from memory, slashing time-to-first-token and cost.
OpenAI caches prompt prefixes automatically without requiring code changes when prompts exceed 1024 tokens. Anthropic requires explicit cache_control: { type: 'ephemeral' } breakpoint markers on up to four content blocks.
Cache hits typically provide a 90% discount on input token pricing across both Anthropic and OpenAI, along with up to an 80% reduction in time-to-first-token latency.