Prerequisites
- Know the prompt structure you send to the model (system, developer, user messages).
- Understand the provider's prompt caching docs and that caches match contiguous rendered prefixes.
Implementation decision
- Build a helper that scans prompt parts from the start and collects the longest contiguous leading stable block. Use a conservative token estimator for that block and compare it to a configured minimum cacheable token threshold.
- If the prefix meets the threshold and there are no later stable parts, prefer implicit caching on modern models for convenience. If the prefix is short or if stable content appears later, choose explicit-only mode so you control where breakpoints occur and avoid accidental cache writes.
- Use cache keys to separate customer/session/workspace reuse and pick TTLs consistent with reuse expectations: shorter for volatile prefixes, longer for shared reference material.
Expected result
- Your application only attempts to reuse prefixes that are both stable and large enough to be worth caching, reducing wasted cache entries and unexpected misses caused by small or misplaced prefixes.
- Cache keys keep unrelated tenants or sessions from collapsing into a single accounting bucket, and explicit-only mode reduces accidental reuse when prompts contain later stable blocks.
One limitation
- This approach uses heuristics and a conservative estimator. It does not guarantee provider-level cache hits or a specific latency improvement—measure actual hit rates and warm/cold latencies in production to confirm benefits. The server will include the verified implementation example.
Working example
export function simpleTokenEstimate(text) {
if (!text) return 0;
// Very small, deterministic estimator: split on whitespace and punctuation groups.
// This is intentionally conservative and inexpensive; real apps should use a tokenizer
// matching the actual model.
return String(text)
.trim()
.split(/\s+|(?=[.,;:!?()\[\]{}"'])|(?<=[.,;:!?()\[\]{}"'])/)
.filter(Boolean).length;
}
export function analyzePromptParts(parts, { model = 'gpt-5.6', minCacheableTokens = 64 } = {}) {
// parts: array of { role: 'system'|'developer'|'user'|'assistant', text: string, stable?: boolean }
// Determine the longest leading contiguous stable prefix (from start) that can be cached.
if (!Array.isArray(parts)) throw new TypeError('parts must be an array');
let prefixParts = [];
let prefixTokenCount = 0;
for (const p of parts) {
if (!p || typeof p.text !== 'string') throw new TypeError('each part must have a text string');
const isStable = Boolean(p.stable);
if (!isStable) break; // only contiguous leading stable parts are cacheable as one prefix
prefixParts.push(p);
prefixTokenCount += simpleTokenEstimate(p.text);
}
const prefixText = prefixParts.map(p => p.text).join('\n');
const isCacheable = prefixTokenCount >= minCacheableTokens;
// Model-specific guidance: on gpt-5.6+, explicit-only is recommended when suffixes are volatile.
const major = String(model).toLowerCase();
const prefersExplicit = major.includes('gpt-5.6') || major.includes('gpt-6') || major.includes('gpt-5.');
// Suggest cache mode: if there are trailing stable parts later (non-leading), explicit is safer.
const hasLaterStable = parts.slice(prefixParts.length).some(p => p.stable);
const suggestedMode = (!isCacheable || hasLaterStable) ? 'explicit' : (prefersExplicit ? 'implicit' : 'explicit');
const contiguousLeadingStableCount = prefixParts.length;
return {
prefixText,
prefixTokenCount,
isCacheable,
minCacheableTokens,
suggestedMode,
// top-level convenience for tests and callers
contiguousLeadingStableCount,
reason: {
contiguousLeadingStableCount,
hasLaterStable,
model,
}
};
}
export function chooseCacheKey(baseKey, { scope = 'global', id = null } = {}) {
// Simple helper to build a cache-accounting key. Do not include secrets here.
if (typeof baseKey !== 'string') throw new TypeError('baseKey must be a string');
const safeScope = String(scope).replace(/[^a-z0-9_:-]/gi, '_');
if (id == null) return `${safeScope}:${baseKey}`;
return `${safeScope}:${id}:${baseKey}`;
}
export default { simpleTokenEstimate, analyzePromptParts, chooseCacheKey };
Read the full article: https://chriseugenerodriguez.com/blog/prompt-prefix-caching-decision