LLM Prompt Cache Misses: Find the Changes That Break Prefix Reuse
Your agent sends almost the same instructions and tools on every turn. Yet the provider reports few cached input tokens, and each conversation costs more than expected. The missing piece may be a timestamp near the top o
Your agent sends almost the same instructions and tools on every turn. Yet the provider reports few cached input tokens, and each conversation costs more than expected. The missing piece may be a timestamp near the top of the promptβor a tool list assembled in a different order on each request.
This guide shows how to investigate LLM prompt cache misses with a small, privacy-aware diagnostic. You will compare request structure, distinguish changed prefixes from normal cache expiry, and measure whether a fix actually saves money. The examples are vendor-neutral; always check the current rules and usage fields for your provider and model.
First, identify which cache is missing
Several caches can sit in one AI application. They solve different problems:
| Layer | Reuses | What a hit means |
|---|---|---|
| Prompt prefix | Computation for an earlier, identical prefix | The model still generates a fresh answer |
| Response | A previously generated answer | The model may not run at all |
| Retrieval | Documents or search results | Your retrieval system skips some work |
This article covers the first layer. An answer-cache freshness rule cannot tell you why a provider recomputed an unchanged system prompt. Likewise, a prompt-prefix hit does not prove that a retrieved document is current or that an answer is correct.
In many implementations, reuse depends on a matching prefix. An early change can reduce how much later content is reusable. But cache boundaries, routing, minimum lengths, expiration and billing differ between providers and even between models. Consult the OpenAI prompt caching guide or your provider's equivalent before turning any assumption into an alert.
Start with a controlled pair of requests
Pick a representative workflow, such as a support assistant that calls one read-only ticket tool. Capture two locally constructed request objects before sending them. They should have the same model, tool definitions, instructions and request options. Change only the final user message.
- Send the first request to warm the relevant prefix.
- Send the second shortly afterward using the same provider endpoint and configuration.
- Record the provider's reported input and cache usage for both calls.
- Repeat a few pairs; a single miss is not proof of a defect.
- Compare those figures with a cold run and with the expected reusable portion.
Do this in a non-production workspace with synthetic content. Keep the exact request body local and short-lived; logs do not need customer messages or secrets. A cold first request is expected. A second request can miss because the prefix is too short, the cache expired, a request was routed elsewhere, a model or endpoint changed, or the provider did not cache that shape. Do not label a miss as an application bug until you have ruled out these alternatives.
A subtle point: a growing conversation naturally contains new, uncached tokens. A 100% cache-hit rate across the entire request is not a reasonable target. Ask whether the expected stable part was reused, not whether every token was cached.
Find the first changed request block
Inspect the assembled request in the order relevant to your provider. Typical blocks include tool definitions, system instructions, examples, conversation messages and the new input. Their actual rendering order is provider-specific; the JSON key order alone does not reveal the provider's internal token order.
Start with simple fingerprints of each block, not a dump of the text. The following Python example is a local diagnostic, not a reproduction of a provider's tokenizer or cache key:
import hashlib
import hmac
import json
import os
KEY = os.environ["DIAGNOSTIC_HMAC_KEY"].encode()
def fingerprint(value):
data = json.dumps(
value, sort_keys=True, separators=(",", ":"),
ensure_ascii=False,
).encode("utf-8")
return hmac.new(KEY, data, hashlib.sha256).hexdigest()[:16]
def request_report(req):
blocks = [("tools", req.get("tools", []))]
blocks += [(f"message[{i}]", m)
for i, m in enumerate(req.get("messages", []))]
return [(name, fingerprint(block)) for name, block in blocks]
for name, digest in request_report(request_a):
print(name, digest)
Run it separately on request_a and request_b, using the same diagnostic key. Compare matching block names and locate the first difference. An HMAC makes offline guessing harder than a plain hash, but fingerprints are still sensitive operational data: restrict access, rotate the key and set a retention limit. A key rotation means old and new fingerprints cannot be compared.
The example sorts object keys for a stable diagnostic representation. It deliberately preserves array order. It does not prove that the actual payload or provider serialization matches: inspect the SDK's outgoing request safely in a local test when byte-level ordering matters. Never log the key itself. Do not normalize timestamps or IDs before comparing the raw fingerprints, because doing so could hide the very difference you are looking for.
The timestamp at the front
A system instruction such as Current time: 10:01:03 changes on every call. If it appears before a long set of otherwise stable instructions, it can make the later prefix unavailable for reuse.
First ask whether the model needs the exact time. If it does, put the current time in the changing user or task context where your provider's request design permits. If it needs only today's date, use the dateβbut only when that loss of precision is acceptable for the task. Never freeze time merely to improve a cache metric: stale time can make a correct workflow wrong.
Tool definitions arrive in a different order
A tool registry assembled from a set, concurrent discovery or filesystem enumeration may yield [search, ticket] on one call and [ticket, search] on the next. The tools mean the same thing to a human, but their sequence differs. The Qwen Code design note describes stable sorting as a practical response to this class of issue.
If your application controls the registry, sort tools by a unique, stable identifier before sending them. Keep schema generation deterministic too. Do not blindly sort every array inside a schema: some arrays have meaningful order, and changing descriptions or defaults can change behavior. Test the rendered request and evaluate the agent's task success after the change.
def stable_tools(tools):
names = [tool["name"] for tool in tools]
if len(names) != len(set(names)):
raise ValueError("tool names must be unique")
return sorted(tools, key=lambda tool: tool["name"])
Adapt the field path to your SDK. This is a construction rule, not a universal instruction to override a framework's expected order.
Old conversation turns get rewritten
An agent might summarize or clean an earlier tool result before the next request. That can be a sensible context-management decision, but it changes the prior prefix. The same applies to silently editing old messages, adding source markers after the fact or regenerating a tool response with different whitespace.
For a controlled experiment, retain the exact earlier messages and append new turns. Then test a separate compaction strategy. Compare total cost and task quality across the whole conversation, not just the next call: shorter context can save tokens while a rewritten prefix can reduce reuse. A recent research paper on context changes under prefix caching illustrates why those trade-offs depend on the workload and pricing assumptions.
Separate a changed prefix from a cold cache
A useful incident note records observations separately from hypotheses:
| Observation | Plausible explanation | Next check |
|---|---|---|
| Stable block fingerprint changed | Request construction changed | Compare synthetic payloads locally |
| Fingerprints match, cache read is zero | Expiry, routing, minimum size, configuration or provider behavior | Repeat promptly; check model and provider rules |
| Cached tokens rise but total also rises | New conversation tail is growing | Compare reused tokens with expected stable tokens |
| Hit rate rises but cost does not fall | Write charges, output tokens or request mix changed | Compute actual cost per successful task |
| Only one tenant misses | Per-tenant instructions or tool set differ | Compare authorized configuration versions, not private text |
A fingerprint cannot reveal provider eviction, internal token boundaries or routing. Unless the provider exposes that reason, label those explanations as hypotheses. Also check that usage parsing matches the provider: a field may mean cache reads, cache writes, total input or a subset of input. Summing overlapping fields produces misleading dashboards.
Measure savings without hiding quality problems
Instrument each request with a trace ID, provider, model, prompt version, tool-set version, input and output token counts, cache reads and writes when available, latency, status and a task outcome. Use your provider's documented accounting to calculate cost. Include cache-write charges where they apply, retries, output tokens and any extra calls introduced by the change.
A simple comparison uses:
cost per successful task = total measured workflow cost / successful tasks
Define success before the test. For a support assistant, it might require selecting the right ticket and returning a useful, authorized response. Count failed and retried attempts in the numerator. Report the sample size and use comparable traffic, time windows and model versions. A cache hit does not compensate for a tool that stopped being available to the agent.
Imagine two deployments each process 100 comparable tasks. The first costs $12 and completes 90; the second costs $10 and completes 80. Their costs per success are about $0.13 and $0.125 respectively, but the second has a much worse completion rate. Those are illustrative numbers, not a benchmark. Review both cost and quality before adopting the second configuration.
Do not infer a cause from a dashboard alone. Run a controlled before-and-after experiment, then inspect cost, latency and task outcomes together. Provider pricing can change, so use the prices and billing fields applicable to the actual requests rather than embedding permanent assumptions in code.
Add a regression check to your build
You can catch accidental request drift without calling a model in every test. Construct two requests with fixed synthetic inputs and assert that the stable blocks match. Also assert that changing a tool schema intentionally changes its fingerprint; otherwise the test may be hiding meaningful edits.
def test_stable_tool_order():
first = [{"name": "search"}, {"name": "ticket"}]
second = list(reversed(first))
assert stable_tools(first) == stable_tools(second)
def test_real_schema_change_is_visible():
before = [{"name": "search", "description": "Find tickets"}]
after = [{"name": "search", "description": "Find users"}]
assert fingerprint(before) != fingerprint(after)
These tests assume the helper functions above are imported and the diagnostic key is set in the test environment. They verify application construction, not cache behavior at the provider. Add a scheduled integration test using synthetic data if your budget allows. Make its result informational unless you can tolerate normal provider and network variability; an occasional cold cache should not block every release.
Protect useful changes. If a security policy, tool permission or customer instruction must change, ship the correct change and accept the cache miss. Caching is an optimization, never an authorization mechanism. Do not share tenant-specific prompts, documents or diagnostic records across customers merely to improve reuse. Check your provider's retention and isolation terms before enabling any caching feature.
A practical rollout checklist
- Choose one high-volume workflow and document its expected stable prefix.
- Confirm provider and model support, minimum sizes, retention and usage semantics.
- Use synthetic paired requests to observe a warm comparison.
- Compare block fingerprints and inspect any differences locally.
- Move truly volatile data later only when doing so preserves task meaning.
- Stabilize tool ordering where your application owns it; keep permissions unchanged.
- Run task-quality evaluations and measure cost per successful task.
- Ship with dashboards for cache usage, latency, error rate and completion rate.
- Recheck after SDK, model, prompt or tool-registry changes.
For related engineering decisions, see the earlier guide on source-aware cache invalidation: it addresses answer freshness, a separate concern from prefix-computation reuse. Also revisit your agent evaluation and latency budget when deciding whether a cache optimization improves the whole workflow.
FAQ
Why is my prompt cache hit rate zero?
Start with provider support, request size, configuration and the actual usage field. Then compare two synthetic requests for early changes in instructions, tools or previous messages. Cache expiration and routing can also cause misses even when your application constructs identical blocks.
Does prompt caching return an old answer?
Prefix caching typically reuses computation for matching input and still generates a new response. A separate response cache can return an old answer. Check the specific cache layer and provider documentation before drawing conclusions.
Will sorting tools always improve cache hits?
No. It helps only when nondeterministic ordering changes a cache-relevant prefix. Your provider may use different boundaries, and sorting may change behavior in some systems. Verify task quality and actual usage before and after.
Should I remove timestamps from every prompt?
No. Some tasks require current time. Remove a timestamp only if it is unnecessary; otherwise place it in the changing part of the request where supported. Never trade correct time-sensitive behavior for cache efficiency.
Can a stable fingerprint prove the provider had a cache hit?
No. It shows that your chosen local representation of a block did not change. Provider usage metrics are needed to observe a hit, and routing, expiry or hidden serialization can still affect reuse.
How much money will prompt caching save?
It depends on repeated prefix length, request frequency, provider prices, write charges, cache lifetime and task success. Measure the full workflow with representative traffic; there is no reliable universal savings percentage.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.