Forward Deployed EngineeringAI EngineeringInference Optimization
How does prompt caching work, and when does it actually pay off?
Question 51 of 73 · Updated
On this page
Interview-ready answer#
Prompt caching avoids repeating inference work for a prompt prefix that has already been processed. In a typical decoder-only Transformer, the serving engine can reuse the attention key/value (KV) state of an identical prefix instead of recomputing its prefill on every request. It still processes the new suffix and generates a fresh response.
It pays off when a substantial, stable prefix is reused frequently enough, within the cache's lifetime and routing scope, to offset any write, storage and lookup costs. Long system instructions, tool schemas, few-shot examples and repeated questions over the same document are good candidates. Short, mostly unique prompts and frequently changing prefixes usually offer less benefit.
I would optimize for reused input tokens, time to first token, and total cost per successful request, not just the percentage of requests with a cache hit. I would also protect prompt correctness and tenant isolation rather than sacrifice them to increase reuse.
1. What is actually cached?#
During prefill, a causal Transformer computes representations of the input sequence and stores attention keys and values for each layer. Earlier positions cannot attend to later positions, so their states can be reused when the same token prefix is evaluated under compatible model and inference conditions.
Only the shared prefix is reusable. The second request still attends to that prefix when processing its suffix and generating new tokens. Cached tokens generally continue to occupy logical context positions; caching does not enlarge the context window or make attention to the prefix free.
| Cache | Reuses | Scope |
|---|---|---|
| Ordinary decoding KV cache | Previously processed tokens | Within one generation or retained session |
| Prompt/prefix cache | Compatible prefilled prefix state | Across requests |
| Response cache | Previously generated final answer | Repeated equivalent requests |
Prefix reuse differs from response caching: two questions over the same document can share prefill state while receiving completely different answers. A response cache can skip generation entirely but has much stronger equivalence, freshness and authorization requirements. Hosted services may abstract the implementation; do not assume every product labeled prompt caching exposes the same internal representation.
2. Design for actual cache eligibility#
Put stable, shared material before request-specific content where doing so preserves the model's expected input format and task quality. For example, a document-review service may use a versioned system prompt, stable tool definitions and an authorized document snapshot, followed by a changing question.
Prefix matching is generally token-level rather than semantic. A changed timestamp or reordered schema near the beginning can reduce the longest matching prefix. The reusable prefix must also be compatible with the checkpoint, tokenizer, adapter, positional configuration and other inference settings that affect the cached state. Implementations may reuse only complete cache blocks.
Hosted providers differ in automatic versus explicit caching, minimum eligible prefix lengths, retention periods, cache-write and storage charges, and routing or isolation scope. Check the deployed contract; these are not universal defaults.
Invalidation: changing document revisions or instructions changes the relevant prefix. Version these inputs and ensure subsequent requests use the current authorized content. Expiration, eviction, model upgrades and routing to a worker without the cached state can turn a previously warm prefix into a miss. Never use cache reuse as authorization: a fresh access decision is still required for every request. In self-hosted deployments, partition cache keys and reuse scope according to the actual trust boundary, including tenant or security domain where necessary.
3. When does caching pay off?#
Let p be the ordinary input cost of one reusable prefix, w the multiplier charged when writing it, r the cached-read multiplier, M the number of chargeable writes/misses, H the number of hits, and F the additional cache fee over the observation period.
- Without caching: (M + H)p.
- With caching: Mwp + Hrp + F.
- Savings: Mp(1 − w) + Hp(1 − r) − F.
This model assumes every miss is charged as a write, all prefixes have the same cost, and suffix/output costs are unchanged. Adapt the calculation to the provider's actual billing for misses, partial prefix hits and explicit storage.
For N = M + H > 0, positive p, and w > r, define h = H/N. Caching is cheaper when:
h > (w − 1 + F/(Np)) / (w − r).
Worked example#
Assume a 10,000-token prefix costs $0.02 at an illustrative input rate of $2 per million tokens. Assume writes cost 1.25 times ordinary input, reads cost 0.1 times ordinary input, and there is no separate storage charge.
| 100 requests | Uncached | Cached |
|---|---|---|
| 10 writes / misses | $0.20 | $0.25 |
| 90 hits | $1.80 | $0.18 |
| Total prefix cost | $2.00 | $0.43 |
The prefix saves $1.57, or 78.5%. The break-even hit rate is approximately 21.74%; at exactly that theoretical rate the costs are equal. A single cold request costs more with this pricing, whereas one write followed by one hit already saves money. These figures are hypothetical, not provider prices or measured savings. They exclude the suffix and generated output, so the whole-request saving percentage will be lower when those costs are substantial.
Tested calculation helper#
PYTHONfrom fractions import Fraction def prefix_savings(misses, hits, prefix_cost, write, read, fee=0): p, w, r, f = map(Fraction, (prefix_cost, write, read, fee)) if any(type(n) is not int or n < 0 for n in (misses, hits)) or min(p, w, r, f) < 0: raise ValueError('nonnegative counts and costs required') return (misses + hits)*p - (misses*p*w + hits*p*r + f)
Pass decimal prices and multipliers as strings for exact arithmetic. Python 3.13.5 passed 1,929 checks: 1,920 combinations against an independent integer-scaled cost identity, three worked-example checks and six invalid-input cases. This validates the cost model, not live billing.
4. Performance and operational trade-offs#
Prefix caching primarily reduces prefill work and can improve time to first token (TTFT). It does not eliminate sequential decoding, network latency, queueing or the cost of attending to long cached contexts. A long-output workload may therefore see little improvement in final-response latency even when TTFT improves substantially.
In a self-hosted system, cached KV blocks consume accelerator memory that could otherwise support active sequences. Eviction, CPU offloading and cache-aware routing introduce trade-offs: retaining popular prefixes may increase reuse, while routing all requests for a prefix to an overloaded worker can worsen tail latency. Measure the balance between memory occupancy, admission capacity and saved prefill work.
A useful request-level hit rate is the fraction of requests with any cached input. However, a one-block hit and a nearly complete prefix hit are not equivalent. Track cached-token ratio as total cached input tokens divided by total input tokens, alongside cache writes, cold/warm TTFT, end-to-end p95 latency, eviction or expiration, and actual billed costs. Where available, separate queue time from prefill and decode time.
5. Customer decision#
For an internal document-review assistant with repeated queries over a stable authorized document, caching can amortize expensive prefill across many different questions. For a RAG assistant whose first retrieved passage changes on every request, cache the stable instructions and tool definitions first; do not reorder evidence merely for a hit if it harms answer quality or relevance.
I would replay representative request arrival patterns, including cold starts, document revisions and traffic gaps, comparing the uncached baseline against the cache-enabled version with the same model and task contract. In self-hosted systems, include competing workloads and eviction pressure. Validate that source access and freshness remain correct and that any savings exceed the additional operational complexity.
References
- 1.OpenAI — Prompt caching (not live-verified)platform.openai.com
- 2.Anthropic — Prompt caching (not live-verified)docs.anthropic.com
- 3.
- 4.
- 5.
Related questions
- KV-caching in autoregressive decoding: what does it store, why does it cut latency, and how does its memory cost scale?
- Prefix caching in a multi-turn chatbot: how do client-side and server-side caching cut redundant compute, and what breaks correctness?
- Walk me through what actually happens when an LLM generates a response.
Explore other topics:AI AgentsAI System DesignLarge Language Models