AI Coding Agents
How to debug a prompt cache miss with a prefix diff
To debug a prompt cache miss with a prefix diff, capture the provider-bound body that wrote the cache and the next body that should have read it. Compare the stable parts in prompt order and locate the first changed block at or before the intended breakpoint. Check that location against provider diagnostics or read and write counts, then replay the pair after correcting the change.
Confirm a miss where you expected a read
Start with two closely spaced requests from one session on the same provider and model. Identify which response should have established the cached boundary, then which response should have reused it. For a reproduction, let the first response finish and send the next request before the cache lifetime expires. The Anthropic docs say a cache entry becomes available only after the first response starts, so avoid sending both requests simultaneously.
As of November 30, 2026, Anthropic Messages reports reads in usage.cache_read_input_tokens and writes in usage.cache_creation_input_tokens. Its usage.input_tokens is ordinary input. OpenAI Responses reports reads in usage.input_tokens_details.cached_tokens and writes for GPT-5.6 and later in usage.input_tokens_details.cache_write_tokens. Its usage.input_tokens is total input. Pull the counters from the same response as the request under investigation. Missing usage calls for checking the capture path before classifying the request. Prompt cache metrics
Look for a drop in read tokens or a write much larger than the new turn’s content. A first-turn write on an eligible prefix is expected. Later turns can read older context and write a newly eligible suffix on the same request. When part of the prefix still hits, identify the last boundary you expected to reuse before attributing the entire conversation’s cost to a miss. Compare token counts with the scope of that boundary. Anthropic cache breakpoints
Capture the requests after client and gateway transformations
- Save the request that established the prefix. Use an SDK transport hook or a local logging proxy you control to capture the raw serialized JSON after the application assembles the request. If a gateway translates or enriches it, capture the provider-bound body at the gateway where available.
- Save the follow-up in the same way. Preserve object and array order in the original capture. Record model, endpoint, timing, cache usage, and any prompt-affecting headers separately. Keep track of which attempt produced the response if the client retried.
- Mark the expected boundary in both bodies. On Anthropic, walk
tools, thensystem, thenmessages. For an explicit breakpoint, identify the block carryingcache_control. Verify that the same prefix was previously written and still falls at a lookup boundary. On OpenAI, inspect the configured mode and the eligible message endings or explicit breakpoints. The server’s rendered prompt can include content beyond the request’s visible strings. - Keep the full captures local. Use synthetic prompts for a replay when possible. Save the raw bodies separately from any redacted copies used for sharing. A redaction that changes the same field you are investigating can hide the difference in the copy.
Keep captures at the same stage of the request path. Comparing application objects from one turn with gateway output from the next mixes normal transformation with the suspected regression. If you have both ingress and egress, compare the two turns at each stage. A change that first appears after adaptation narrows your search to that part of the path. Prompt caching through LLM gateways
Find the first changed block without reordering arrays
A structural diff is a useful first pass. Parse both JSON bodies and compare object keys in a consistent order while keeping arrays in their original sequence. Keep string values unchanged, including embedded newlines and spaces. This filters out indentation between JSON fields and still catches a change inside system text. Do a raw comparison afterward when object ordering or serialization is a candidate. Anthropic specifically calls out nondeterministic key order in tool_use content. Sorting keys for inspection can hide that difference. Deterministic prompt serialization
The illustrative Python script below uses only the standard library. Save it locally as prefix_diff.py and run python3 prefix_diff.py before.json after.json. It reports a path using JSON Pointer escaping. For Anthropic-shaped requests it prioritizes the prompt sections in documented order, then checks other body fields. Its traversal is a way to locate changed request data. Use the provider’s usage and cache controls to decide if a change falls inside an eligible prefix.
import json
import sys
PROMPT_ORDER = ("tools", "system", "messages", "input")
def first_difference(left, right, path=""):
if type(left) is not type(right):
return path
if isinstance(left, dict):
keys = left.keys() | right.keys()
priority = [key for key in PROMPT_ORDER if path == "" and key in keys]
ordered = priority + sorted(keys - set(priority))
for key in ordered:
escaped = key.replace("~", "~0").replace("/", "~1")
child = f"{path}/{escaped}"
if key not in left or key not in right:
return child
result = first_difference(left[key], right[key], child)
if result is not None:
return result
elif isinstance(left, list):
for index, (old, new) in enumerate(zip(left, right)):
result = first_difference(old, new, f"{path}/{index}")
if result is not None:
return result
if len(left) != len(right):
return f"{path}/{min(len(left), len(right))}"
elif left != right:
return path
return None
if len(sys.argv) != 3:
sys.exit("Usage: python3 prefix_diff.py before.json after.json")
with open(sys.argv[1], encoding="utf-8") as before:
with open(sys.argv[2], encoding="utf-8") as after:
difference = first_difference(json.load(before), json.load(after))
if difference is None:
print("No structural difference")
else:
print(difference or "(document root)")
For OpenAI Responses bodies, inspect top-level instructions separately. The script treats the field like any other body field outside its priority list. OpenAI says it cannot contain an explicit breakpoint. Starting with GPT-6.2, those instructions are appended after input and billed as ordinary input. A change there can leave reuse of the preceding prefix intact.
Consider an assumed Claude test with fixed tool definitions, two system blocks, and a breakpoint on the second block. The follow-up appends its user message as expected, but the app also inserts a fresh request identifier into the second system block. The script should report /system/1/text first. Inspect the two string values locally and compare their UTF-8 bytes if the edit is hard to see. A line-ending change or trailing whitespace inside a string can be easier to see as bytes. Move the variable identifier out of the cached prefix, then run the pair again. When the remaining divergence is at the first appended message after that breakpoint, the visible structural change is consistent with reuse.
A first reported path can also be an expected append, a moved marker, or an irrelevant setting. Always check it against the expected boundary. If a request uses server-side history, the saved body may contain only the new input. A matching pair of local bodies also leaves room for lifetime, eligibility, routing, or header differences. Keep those checks in the workflow even when the script returns no difference.
If the structural diff points to an expected append but reads still fall, compare the raw fragments around the tool and message blocks with a byte-oriented diff. Ignore indentation between fields for the structural investigation, but keep the exact key ordering visible in the original fragments. For example, two captures can have the same parsed tool arguments while emitting object keys in a different order. Keep the earlier tool block unchanged on a replay. If reads return under the same route and settings, you have an experiment that narrows the failure to how that block is serialized.
When the visible mismatch is a new request setting and a changed body block also exists, use one replay for each variable. First change only the setting from the known good request pair. In a separate replay, change only the prompt block from that same pair. Read and write counts from each replay show which conditions still allow reuse. Use separate fresh fixtures if an earlier replay could populate the cache for the next one. This is especially helpful when the failing turn arrived after a rollout that changed the prompt template and gateway settings together.
Map the divergence to a fix
| First divergence or observation | What to inspect | Corrective action |
|---|---|---|
/tools or a nested input_schema path | Added, removed, reordered, or reserialized tools. | Retain a stable ordered list and serialize schemas deterministically. |
/system | Timestamps, IDs, or environment details interpolated into otherwise stable instructions. | Move changing text after the intended breakpoint and keep stable instructions fixed. |
An earlier entry in /messages | Truncation, compaction, edited assistant content, or a reserialized tool_result. | Replay prior blocks unchanged when you intend to reuse them. Record intentional compaction as a rebuild. |
A cache_control block disappeared | The gateway may have flattened block-form content or applied an incompatible translation. | Inspect the upstream body and choose a supported boundary for that route. |
/model or no visible edit but a different endpoint | A model alias or fallback may have resolved differently between turns. | Keep the route fixed during the test and record the actual model. |
| OpenAI input extends a previously cached message in place | The previous endpoint may now be inside that message, outside implicit lookup boundaries. | Append a new message when appropriate or use a supported explicit breakpoint at the reusable block. |
| No structural difference and low reads | Check raw ordering, prompt-affecting settings, minimum prefix length, and expiration. | Hold settings constant and repeat a sequential pair at a qualifying boundary. |
Cross-check with Anthropic diagnostics or OpenAI usage
On the Claude API or Claude Models on Google Cloud (Anthropic managed), opt in on the first request with diagnostics.previous_message_id set to null. Send the first response’s id as diagnostics.previous_message_id on the next request. Both requests need to include the diagnostics object and be close enough for the earlier fingerprint to remain available. Use the same workspace. Inspect diagnostics.cache_miss_reason.type for the first reported divergence, such as system_changed, tools_changed, or messages_changed. The accompanying cache_missed_input_tokens is an estimate of scope. Use the usage counters for billing. Anthropic cache diagnostics guide
If diagnostics is null on a correctly linked comparison and reads are low, check for a cache entry that expired or a prefix too short to qualify. A result containing cache_miss_reason: null means the comparison was still pending. A previous_message_not_found result usually means the earlier request omitted the diagnostics object, ran in a different workspace, or is too old. An unavailable result can occur when model, system, and tools match but another prompt-affecting parameter differs. Compare tool_choice, thinking, context_management, output_config, output_format, and the set of active anthropic-beta headers in the two captures. Very long conversations can also put the first change beyond the comparison horizon. Check those conditions before editing the prompt again.
For OpenAI Responses on GPT-5.6 and later, watch cache_write_tokens alongside cached_tokens. Falling reads with increasing writes are consistent with a rebuilt prefix. The counters alone give no divergence path. An upgrade to a longer cache lifetime can also count as a write, so check the write lifetime breakdown when present. If you changed from implicit to explicit mode, confirm that an explicit marker points to the prior cached endpoint. A visible shared prefix needs a matching lookup boundary before it can produce a read.
Verify the fix on a fresh request pair
- Change the earliest unexpected difference that falls within the intended reusable prefix. Keep the model, route, and prompt settings fixed during the replay.
- Establish a fresh cache entry and run a completed follow-up. Compare reads, writes, and ordinary input with the failing pair.
- Confirm that the ordinary user or tool-result append still works and that the expected earlier prefix reads. Compare gateway ingress and egress if the update affects serialization.
- Keep the two request shapes and expected usage as a regression check. Use the same cache metrics on production traffic to see whether large rebuilds become less common.
Sources
- Prompt caching (Anthropic, accessed 2026-11-30)
- Cache diagnostics (Anthropic, accessed 2026-11-30)
- Prompt caching (OpenAI, accessed 2026-11-30)
- Prompt caching in Claude Code (Anthropic, accessed 2026-11-30)
Interactive report
- The Cache Breakers: The agent sends another ordinary-looking request. A timestamp, a shuffled tool list, or a model switch just changed what the API can reuse. See what each edit puts on the invoice.
How this note was produced
Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.
How to debug a prompt cache miss with a prefix diff. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/debug-prompt-cache-miss-prefix-diff/