Optimizing Prompt Caching
Introduction
Welcome back to Reducing LLM Work and Cost in Python. Earlier, we reduced conversation context, controlled output length, and built an application response cache that could return a stored answer without contacting a provider.
This time, each request still reaches the model. However, the provider can reuse work for a repeated prompt prefix and charge reused input at a lower rate. We will use the Responses API with a long support policy followed by changing customer questions. We will inspect cache writes and reads, see why the default breakpoint misses reuse, and then place a breakpoint at the stable boundary.
The prompt_cache_options and prompt_cache_breakpoint controls are OpenAI-defined, but they are not OpenAI-only: the same request shape now appears on other platforms that host these models, including GPT-5.6 Sol, Terra, and Luna on Amazon Bedrock. The deeper ideas — stable prefixes and cache economics — apply broadly.
Think in Stable Prefixes
Imagine three requests with this shape: stable policy + changing question. The full requests differ, but their beginnings are identical. Provider prompt caching can preserve the model's processed state for that identical beginning, then process only the request-specific content needed for a new answer. This is different from the application response cache from the previous lesson: a response cache stores completed text, while prompt caching stores reusable model work and still produces a fresh response.
A cache breakpoint marks the end of the content we want to reuse. More precisely, a cache breakpoint marks the end of a prompt prefix the provider can save and reuse in later requests; the first request writes an eligible prefix to the cache, and a later request looks for the longest matching cached prefix, working backward through eligible breakpoints until it finds a match.
That last detail is the key to this entire lesson, and it is easy to misread. Matching happens at breakpoints, not at arbitrary positions. A later request cannot reuse "however much of the prefix happens to match" — it can only reuse a prefix that some earlier request actually checkpointed. So if the only breakpoint in the system sits after a changing question, two requests sharing thousands of identical leading tokens will still share nothing.
We will make this difference visible with token usage reports. The breakpoint location is therefore a design decision, not just an API setting.
Know the Eligibility Rules Before Measuring
Two rules determine whether caching engages at all, and both fail quietly. Learning them now prevents a confusing first experiment.
A prefix must be long enough. A prompt prefix must meet the model's minimum cacheable token length before it can be cached; tokens in the provider-supplied hidden system content do not count toward this minimum, and that minimum is 1,024 tokens for GPT-5.6 and later, or 2,048 tokens for older models. There is no error when you fall short — prompts below the minimum are processed without caching, and no error is returned. A run that reports all zeros is usually a short prefix, not broken code.
A prefix must be byte-for-byte identical. A single character difference in the first 1,024 tokens results in a cache miss, characterized by a cached_tokens value of 0. A timestamp, a session ID, or a reordered JSON key in the stable region is enough to defeat caching entirely.
This is why our example policy is deliberately long. Anything shorter would produce zeros regardless of where we placed the breakpoint, and we would learn nothing from the comparison.
Isolate the Experiment from Other Traffic
There is a third rule that matters enormously for an experiment, and it is about scope. Prompt caches are isolated between organizations and processing regions — not between processes, machines, or individual developers. Any request from your organization that renders the same prefix can populate or match the same cache entry.
That is excellent in production and inconvenient in a measurement exercise. If a teammate, a background job, or another learner sharing the same organization has already sent our policy, our "first" request may report cached tokens before we have written anything. The experiment would then measure someone else's traffic rather than our own design decision.
The fix is to make each program run render a prefix that nobody else is sending. We generate one random identifier at startup and place it at the very beginning of the cached content.
Three properties make this work:
- The identifier is generated once per run, so all three requests inside a single run still share an identical prefix and can genuinely reuse it.
- The identifier sits at the start of the prefix, so an unrelated request cannot match it even partially.
- The implicit and explicit experiments use different namespaces, so the second experiment cannot accidentally read entries written by the first.
We will also pass a matching prompt_cache_key on each request. That parameter is a routing and matching hint that helps related requests reach the same machine; it is not a hard cache partition, so the unique prefix is what actually provides isolation. Both together give us a clean measurement.
One consequence to accept up front: because the prefix is unique per run, and because routing and expiration are not guaranteed, the exact token counts in this lesson will not reproduce exactly on your machine. The numbers below are a representative run. What must reproduce is the pattern: repeated writes with no reads in the implicit experiment, and one write followed by large reads in the explicit experiment.
Prepare a Usage Report for Caching
Before comparing caching strategies, we need an instrument panel. As before, provider-reported usage is our billing source of truth. The helpers below read the total input tokens and the two cache-related categories from response.usage.input_tokens_details.
cache_usage() does the accounting and print_cache_usage() displays one row and returns the same dictionary, so later code can total the categories without recomputing them.
In cache_usage(), cache_write_tokens shows the tokens assigned to a cache write, while cached_tokens shows the tokens retrieved from an existing cache entry. We read both with getattr and a default, exactly as in Unit 3, because some models and deployment types do not expose cache_write_tokens at all. The ordinary category uses the same clamped subtraction, so a surprising usage report cannot produce a negative count.
Observe Implicit Caching Behavior
Prompt caching is enabled by default for supported models. When prompt_cache_options.mode is implicit, OpenAI places a breakpoint at the end of the latest eligible message, and that implicit breakpoint creates a cache write through the latest eligible message. Our first experiment sends the policy and question as one string, so the changing question sits at the end of the input — and therefore inside the checkpoint.
A representative run produces:
Every request writes its entire input and reads nothing. The first request creates a cache entry whose checkpoint sits after its question. The second question changes that ending, so when request 2 works backward through eligible breakpoints, the only candidate it finds is request 1's full-input checkpoint — which it does not match. The third request has the same problem.
Notice that total_input stays near 5,779 each time: caching has not removed input from the request. It has only determined how the provider categorizes that input. This is the pattern to recognize in production, and the recommended response is well established: if you see high cache writes with few reads in implicit mode, consider switching to explicit mode by adding a breakpoint at the end of your static content so the cached prefix is deterministic. Under GPT-5.6 pricing this workload is actively worse than no caching, because every request pays the write premium and never collects the discount.
Place an Explicit Breakpoint Around the Stable Prefix
We can fix the boundary by representing the policy and question as separate input_text parts, then attaching the breakpoint to the policy part only. The breakpoint includes its own block and all prompt content before it in the reusable prefix, so placing it on the policy block checkpoints exactly the policy. The question remains part of the live request but falls outside the checkpoint.
We also select explicit mode, which disables provider-managed breakpoints so that only blocks marked with prompt_cache_breakpoint participate in caching. A separate namespace and cache key keep this experiment independent of the implicit one.
The important change is the location of prompt_cache_breakpoint. It appears on the policy block, not on the question block. The model still receives both parts and must answer each question, but the large stable portion now has a deliberate, reusable boundary.
Two structural constraints are worth noting while the code is in front of you. Breakpoints attach to content blocks, not to whole requests: the Responses API supports breakpoints on input_text, input_image, and input_file blocks. And a natural first instinct does not work — top-level instructions cannot contain an explicit breakpoint, so reusable developer instructions must be placed in an input_text block inside a developer message. That is precisely why our policy is a content block rather than an instructions argument.
Interpret Usage Counters
The second loop uses the explicit breakpoint and its separate namespace. Its representative output is:
The results show the effect of moving the boundary:
- Request 1 has no matching entry, so it writes the 5,765-token policy prefix and reads nothing. The remaining 14 ordinary tokens are its question — the question was not added to the write.
- Requests 2 and 3 read the cached policy and write nothing at all. Explicit mode removed the implicit breakpoint, so there is no changing suffix to checkpoint and no repeated write premium.
- Every request still reports about 5,779 total input tokens, because the model still receives the policy and a new question.
As established in Unit 3, the three categories are disjoint subsets of the reported total, so they always reconcile:
Ordinary input tokens = total input tokens − cached tokens − cache-write tokens
For request 2:
5779 - 5765 - 0 = 14
That is exactly the question. Reconciling these four numbers on every request is the habit worth keeping, because a silent regression shows up here first: if ordinary suddenly grows to the size of the whole policy, something in the stable region changed.
Calculate Billed Units
For GPT-5.6 and later, cache writes cost 1.25× the standard uncached input-token rate, and it is worth incurring that charge when a prefix will be reused, because subsequent reads cost only 0.1× that rate — writing a prefix once and fully reusing it once costs 1.35× its ordinary input cost, compared with 2× for processing it twice without caching.
Applying those multipliers across all three requests, in units of the ordinary input rate:
| Strategy | Writes × 1.25 | Reads × 0.10 | Ordinary × 1.00 | Total |
|---|---|---|---|---|
| Implicit | 17,338 → 21,672.50 | 0 → 0.00 | 0 | 21,672.50 |
| Explicit | 5,765 → 7,206.25 | 11,530 → 1,153.00 | 43 | 8,402.25 |
| No caching | — | — | 17,338 | 17,338.00 |
The implicit workload costs more than no caching at all, because it pays the write premium three times and never reads. The explicit workload costs roughly half of the uncached baseline, and the gap widens with every additional question, since each new question adds only a discounted read plus a handful of ordinary tokens. Output tokens are unchanged across all three strategies, so they are excluded here.
Explicit breakpoints are especially useful for repeated policies, schemas, examples, tool definitions, and reference material — content that is large, stable, and shared across many requests.
When Caching Silently Does Nothing
Caching failures rarely raise exceptions — they show up as zeros. Use this panel to match your symptom to its cause.
| Symptom | Likely cause | Fix |
|---|---|---|
| All zeros, every request | Prefix is shorter than the model's minimum (1,024 tokens for GPT-5.6+, 2,048 for older models) | Measure the rendered prefix through your breakpoint before assuming the code is broken |
| Zeros despite a long, stable-looking prefix | Something in the stable region changed — a timestamp, UUID, or a dict that serializes in a different order | Generate identifiers like RUN_ID once per run, not per request; keep the stable region byte-identical |
| Writes keep happening; reads never do | Out of write slots — each request allows up to 4 writes, and implicit mode reserves one for its own breakpoint | Use explicit mode and place breakpoints deliberately; earlier-turn breakpoints are read-only and don't consume a new slot |
| An expected hit shows up as a miss | The entry expired, or the request landed on a different machine | Set prompt_cache_key consistently — it's a routing hint, not a guarantee; warm the prefix before fanning out in parallel; rerun before concluding the code is wrong |
cache_write_tokens is missing entirely | The deployment predates breakpoints | The getattr defaults in cache_usage() prevent a crash; the run degrades to pricing with no write premium |
One deliberate use of explicit mode is worth knowing: setting prompt_cache_options.mode to explicit and adding no breakpoints at all means the request does not use prompt caching and incurs no cache-write charges. For a workload of genuinely unique prompts, that is the cheapest configuration — it opts out of a write premium that would never be recovered.
Recap: Breakpoint Placement and Cache Usage
Two ideas from the experiments are worth restating plainly, without diagrams.
Where the boundary sits. In the implicit experiment, the breakpoint fell after the changing question, because implicit mode checkpoints through the latest eligible content. In the explicit experiment, we moved the breakpoint to the end of the policy block, before the question. Same policy, same questions — the only difference was which content sat inside the checkpoint versus outside it.
What the counters showed. The implicit workload produced three writes and zero reads — every request paid to save a prefix that the next request's differing ending could never match. The explicit workload produced one write followed by two reads, each read covering the full 5,765-token policy at a fraction of its ordinary cost.
The pattern to carry forward: a stable prefix is valuable only when the cache boundary preserves that stability, and the usage counters reveal whether later requests are writing the prefix again or reading it from cache. The healthy signature is meaningful cache reads following each write — one write, then many reads.
Conclusion and Next Steps
Application response caching and provider prompt caching optimize different layers. An application cache can skip the provider call and return stored text. Provider prompt caching still makes the request, but it can reduce the cost of repeated input work. We used input_tokens_details to measure cache writes and reads, observed that implicit caching placed its boundary too late for this workload, and then placed an explicit breakpoint after the stable policy.
The key design habit is to separate stable content from changing content before choosing a cache breakpoint. Three companion habits make it reliable: confirm the prefix clears the minimum cacheable length, keep the stable region byte-identical, and reconcile the four usage categories on every request so that a silent regression is visible immediately. We also learned to scope an experiment deliberately with a per-run namespace, because caches are shared across an organization and unrelated traffic can otherwise contaminate the measurement. Finally, we measured the economics honestly — cache writes carry an upfront premium, cached reads are deeply discounted, and every live request still pays for fresh input and output work.
In the practice section, we will build the isolated prefix and usage report, run the implicit workload, move the breakpoint, and compare the totals. This is a cost detective challenge for Reducing LLM Work and Cost in Python: make the stable prefix stay stable, watch the counters change, and prove the savings yourself.
