How do provider prompt caching and self-hosted prefix caching work, how do you structure prompts to benefit, and how is a semantic response cache different?
Answer
Model answer, written in a candidate's voice
In short
- Prefix caching reuses KV for identical token prefixes, exact match from the start, with provider-specific TTLs and discounted cached-token pricing at some providers
- Self-hosted prefix caching does the same idea inside your own serving stack, with your own eviction/TTL and operational control
- Structure prompts static-first: system prompt, tools, documents, few-shot examples, then variable content last; no timestamps/random IDs early; append-only history
- Semantic caches return stored answers for similar queries, not reused computation; risks include wrong answers, cross-user leakage, staleness
- Mitigate semantic cache with similarity thresholds, tenant/user scoping, TTLs, invalidation, and track hit rate and savings
In full
Prefix caching reuses the KV computation for an identical token prefix, so the cache only helps when the beginning of the prompt is byte-for-byte stable; providers may bill cached tokens at a discount and expire entries after a provider-specific TTL, while self-hosted prefix caching gives you the same idea inside your own serving stack with your own eviction, TTL, and operational burden. To benefit, I put static content first—system prompt, tool definitions, documents, few-shot examples—and variable content last, and I avoid timestamps, random IDs, or reordered history early in the prompt; conversation history should be append-only so earlier turns stay cacheable. A semantic response cache is different: it stores answers and returns a stored response for a similar query, rather than reusing KV computation, so it can serve a stale or subtly wrong answer, leak across users, or miss freshness requirements. I would only use it for idempotent, low-risk queries, with a conservative similarity threshold, tenant/user scoping, TTLs, and invalidation on relevant changes. I would track hit rate, token/cost savings, latency, and false-hit rate so I can tell whether the cache is actually helping rather than just looking busy.
What a strong answer covers
- Prefix caching reuses KV for identical token prefixes; exact match from the start; TTLs; discounted cached tokens at some providers
- Static content first (system prompt, tools, documents), variable content last; no timestamps or random IDs early; append-only history
- Semantic caches return stored answers for similar queries — risk of wrong answers to subtly different questions, cross-user leakage, staleness → thresholds, scoping, TTLs
- Track hit rate and savings
Common mistakes
- Today’s date at the top of the system prompt
- a semantic cache shared across tenants