Discuss your project

Guide

Prompt caching: how a deployment holds a 98% hit rate

Prompt caching holds a 98% hit rate by structure, not a setting. The four rules that produce it, the four events that break it, and SQL to measure your own.

By · Updated · 7 min read

Prompt caching is the largest cost lever in a long-running AI agent. It is also almost never a setting you turn on.

A high hit rate falls out of how the prompt is built: a large, byte-stable prefix that gets re-sent every turn, and a small delta on top of it. Get the structure right and the hit rate sits at 96 to 99 percent by construction. Get it wrong and it collapses toward zero without any error being raised.

This page documents the mechanics, the measured result on a production deployment, the four rules that produce it, and the queries to measure your own.

Discuss your project

The measured result

On a production Hermes Agent deployment, over a two-day window:

ModelCache hit rate
deepseek-flash98.70%
deepseek-v4-pro96.81%
All traffic98.67%

The distribution is the useful part, because an average hides the failures.

PercentileHit rate
Median session98.63%
10th percentile97.29%
90th percentile99.24%
Worst session60.24%

Every session in the bottom tail is short: one to three API calls. A session that ends early never amortizes the prefix it paid for. That is the whole story of the misses.

Why 98% is structural, not tuned

The miss tokens come out at almost exactly one cold prefix per session.

miss tokens per session        = one prefix (about 47,000 tokens here)
miss share of all tokens sent  = 1.33%
cache read per API call        = about 103,000 tokens

Read the last line again. Every turn ships a prefix of roughly 100,000 tokens, and the provider charges the cached rate for about 98,700 of them. The cost driver is prefix volume, not per-token price, and the prefix is nearly free.

That is why "write shorter prompts" is the wrong first move. The prefix is supposed to be large. It is the part that does not change, and it is the part caching makes cheap.

How prefix caching works

The provider stores the processed state of a prompt prefix and reuses it when the same prefix appears again. The lookup is a prefix match: the request is compared from the beginning, and the cached portion ends at the first byte that differs.

Three consequences follow.

  1. Order matters. Stable content goes first. Volatile content goes last.
  2. One changed byte invalidates everything after it. A timestamp near the top of the system prompt does not cost one token. It costs the whole prefix.
  3. A cache is per model. Switching models mid-session moves the request to a different cache namespace, and the prefix has to be rebuilt.

The four structural rules

1. Keep a large byte-stable prefix

System prompt, skills, memory, tool schemas, and repository context belong in the prefix, and that block must not change between turns. In the deployment measured here, the block is roughly 45,000 to 47,000 tokens and is identical call to call.

Put volatile content at the end: timestamps, run IDs, the current user message, the result of the last tool call. A single datetime.now() interpolation in the system prompt guarantees a permanent zero percent hit rate.

2. Run long sessions and amortize the cold start

A cold start costs one full prefix prefill. Spread over 100 turns it is noise. Spread over two turns it is the entire session cost.

For repetitive background work, prefer a deterministic script over an agent session. A script costs zero tokens and pays no cold prefix. Use an agent when the task needs judgment, not when it needs a loop.

3. Never mutate the prefix mid-session

Four actions rewrite the cached prefix and turn into a miss spike:

  • Switching model mid-session, which uses a different cache namespace.
  • Reloading configuration, which rebuilds the system block.
  • Adding a skill or tool after turn one, which changes the tool schema region.
  • Context compression, which rewrites history.

One compression event per long session is free. Five in one session is a miss pump. If a session must load extra skills, load them in the first turn so the prefix stabilizes once.

4. Respect the cache TTL on idle gaps

Caches expire. Anthropic's short-lived tier is around five minutes by default and can be extended. DeepSeek's automatic prefix cache tolerates longer idle gaps but is not permanent.

An agent that thinks for 20 minutes, takes one call, then thinks again re-prefills on every call. Batch work into continuous bursts when latency allows.

The pricing gap that makes this worth doing

DeepSeek V4.1 bills cache hits at a small fraction of misses. Off-peak Flash pricing is $0.003 per million cached input tokens against $0.15 per million uncached, a 50x gap. Pro charges $0.022 cached against $0.66 uncached, a 30x ratio and a wider dollar spread.

Anthropic's prompt caching shows the same shape at different numbers: cache reads bill at roughly 10% of base input, and cache writes carry a small premium, so the crossover comes after a couple of turns rather than immediately.

Applied to a window where the cache covered 98.7 percent of input, the bill lands at roughly 3 to 4 percent of what the same traffic would cost uncached. That is what the hit rate buys. It is not a discount on the plan. It is the price of sending the same prefix once instead of a hundred times.

Measuring your own hit rate

Hermes records per-session, per-model usage in the profile's state.db. Nothing here requires an API key or a dashboard.

-- Overall hit rate by model
select model,
       sum(api_call_count) as calls,
       sum(input_tokens) as miss_tokens,
       sum(cache_read_tokens) as hit_tokens,
       round(100.0 * sum(cache_read_tokens)
             / (sum(cache_read_tokens) + sum(input_tokens)), 2) as hit_pct
from session_model_usage
group by model
order by sum(cache_read_tokens) desc;
-- Sessions where the hit rate is worst
select session_id, model, api_call_count, input_tokens, cache_read_tokens,
       round(100.0 * cache_read_tokens
             / (cache_read_tokens + input_tokens), 1) as hit_pct
from session_model_usage
where input_tokens + cache_read_tokens > 5000
order by hit_pct asc
limit 10;
sqlite3 -readonly ~/.hermes/profiles/<profile>/state.db \
  "select model, sum(api_call_count), sum(input_tokens), sum(cache_read_tokens) \
   from session_model_usage group by model;"

Three readings matter:

  1. Miss tokens divided by session count. If that number is close to your prefix size, the caching is healthy and every miss is a legitimate cold start.
  2. The bottom 10 percent of sessions. Confirm they are short. If they are long, something is mutating the prefix and needs finding.
  3. Cache read per call. A rising value means the prefix is growing, which is fine until it approaches the context limit.

A diagnostic tree for a low hit rate

Is the hit rate near zero? Look for a dynamic value in the system prompt. A timestamp is the usual cause.

Is it low but not zero? Look for a model switch or a configuration reload mid-session.

Is it high on long sessions and low on short ones? That is expected. The cold start dominates a short session.

Did it drop after a change? Check whether the change added a tool, a skill, or a memory block. Any of those changes the prefix.

Is the prefix growing every turn? Check whether tool output is being appended to the system block instead of the message tail.

What caching does not fix

A model that is too expensive for the task. Caching reduces the price of the prefix, not the price of the output.

A workflow that runs the wrong task. A fast, cheap wrong answer is still wrong.

A retry loop. Three retries cost three times, cached or not.

A context that is too long. Caching makes the prefix cheap to resend, but it still has to fit.

What to do next

If you run an agent in production, measure the hit rate this week. If it is below 90 percent, find the mutation before changing anything else. If it is above 96 percent, the caching is working and your cost problem is somewhere else: output volume, tool payloads, or a model that is stronger than the task.

Read how to reduce token costs without losing quality

Sources and what they change

These are the documents behind the numbers, if you want to check the mechanics yourself.

  • Anthropic prompt caching. Cache reads are billed at a reduced rate, writes carry a premium, and the default lifetime is five minutes, refreshed free on use. The crossover comes after a couple of turns.
  • DeepSeek context caching. Automatic, on by default, and strict about full prefix-unit matches. It also documents common-prefix detection and fixed-interval persistence, which explain why some turns hit and others do not.
  • OpenAI prompt caching. Cached input is discounted up to 95%, caching is on by default for supported models, and a session alone does not guarantee a hit. Same structural rule: stable prefix first.

Questions owners ask

It is a provider capability, but the hit rate is produced by prompt structure. You can enable it and still get zero if the prefix changes every call.

No. It reuses the processed prefix. The model still generates the output from the same context.

Short sessions pay the cold prefix and never amortize it. That is expected. The question is whether your long sessions hit.

It depends on the provider and the cache scope. A shared system prefix can be reused across users if the provider scopes the cache that way. Per-user prefixes may not be shareable. Check the provider's documentation rather than assuming.

Weekly, and after every model, prompt, or tool change. A single new tool can change the schema region and drop the rate.

Start with the process that costs you the most time

Tell me which process you want to improve. A name, an email, and a short description of the process are enough to start a useful conversation.

Discuss your project