Prompt Caching
Slash AI latency and token costs by up to 90 percent using Anthropic and OpenAI prompt caching breakpoints.
TL;DR
- Place static instructions at request start to enable
prompt-caching. - Mark cache breakpoints in Anthropic using the
cache_controlproperty. - Monitor
cache_read_input_tokensmetrics to verify ninety percent cost savings.
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 as any;
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
- Structure prompts with static context first and dynamic user questions last to maximize
cache-hit-ratemetrics. - Maintain cache warmth by sending periodic keep-alive ping requests within the five-minute
ephemeral-cachewindow to preserve fast response times.
Warnings
- Avoid dynamic timestamps or random IDs in system prompts because changing even one token invalidates all subsequent
cached-prefixes. - Note that Anthropic enforces a minimum prompt size of 1024 tokens for
claude-3-5-sonnetbefore caching activates.
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-3-5-sonnet-20241022',
max_tokens: 250,
system: [{
type: 'text',
text: 'API SPEC: '.repeat(200),
cache_control: { type: 'ephemeral' },
}],
messages: [{ role: 'user', content: question }],
});
const u = res.usage as any;
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.