Sub topic 9
Reading usage fields and computing a hit ratio
This chapter assumes you can call an LLM API from Python, know what tokens and context windows are, and have read the earlier chapters on prefix matching and breakpoints. Here you will learn to read the usage data that comes back with each response, turn it into a hit ratio, and use it to decide whether caching is working.
Why you must measure
A response looks identical whether the prompt came from the cache or not. The text, the status code and the stop reason do not change. The only evidence of a hit is in the usage data that the provider returns with the response.
If you do not read it, a broken cache stays invisible. You pay full price and wait the full latency. You find out when the invoice arrives. Treat usage fields as the test result for your prompt layout.
The three counters
Different providers name the fields differently, but they report the same three facts about the input tokens of one request:
- Tokens read from the cache. These matched a stored prefix and were reused. They are the hits.
- Tokens written to the cache. These were processed in full and stored so later requests can reuse them.
- Tokens neither read nor written. These were processed in full and were not stored.
With Anthropic's Messages API, the fields are on response.usage:
| Meaning | Anthropic field |
|---|---|
| Tokens read from cache | `cache_read_input_tokens` |
| Tokens written to cache | `cache_creation_input_tokens` |
| Tokens after the last breakpoint, not cached | `input_tokens` |
Note what input_tokens means here. It does not include the cached portions. The total input size is the sum of all three fields.
Some providers with automatic caching report differently. OpenAI's usage data, for example, reports a total prompt_tokens value and a nested prompt_tokens_details.cached_tokens value that is a subset of that total. In that shape you compute the uncached count by subtraction. Automatic caching has no explicit write counter, so the "written" figure is zero or absent. Always check your provider's current documentation for exact field names, because they change.
Reading the fields from one response
The following code makes one request with a breakpoint on the system block and prints the three counters. The model name is a placeholder, and the policy file must meet the model's minimum cacheable length.
import anthropic
client = anthropic.Anthropic()
POLICY = open("policy.md").read() # must meet the model's minimum cacheable length
response = client.messages.create(
model="YOUR_MODEL_NAME",
max_tokens=512,
system=[
{
"type": "text",
"text": POLICY,
"cache_control": {"type": "ephemeral"},
}
],
messages=[{"role": "user", "content": "Summarize the refund rules."}],
)
u = response.usage
print("written:", u.cache_creation_input_tokens)
print("read:", u.cache_read_input_tokens)
print("uncached input:", u.input_tokens)Run it twice within the cache lifetime. On the first run you expect a large "written" value and a small "uncached input" value. On the second run, "written" should drop to zero and "read" should equal the earlier written figure. If the second run still shows a write, the prefix changed or the entry expired.
Computing a hit ratio
A hit ratio condenses the three counters into one number you can chart. The most useful definition is the share of input tokens served from the cache:
hit ratio = read / (read + written + uncached)
def cache_hit_ratio(cache_read, cache_written, uncached):
total = cache_read + cache_written + uncached
return cache_read / total if total else 0.0
# First call: the prefix is written. Second call: the prefix is read.
print(cache_hit_ratio(0, 4000, 50)) # 0.0
print(cache_hit_ratio(4000, 0, 60)) # about 0.99The guard for total == 0 avoids a division by zero on empty or failed requests.
The first call has a ratio of 0.0 and that is correct. Someone has to pay to write the entry. A healthy system does not show a ratio of 1.0 on every request. It shows a few low-ratio requests, where entries are created, followed by many high-ratio requests that reuse them.
Per request and aggregate ratios
You can compute the ratio for each request, or for a group of requests. These answer different questions.
- The per-request ratio shows what happened to one call. Use it when debugging a specific bad prompt.
- The aggregate ratio sums the counters first, then divides. Use it for dashboards and cost estimates.
Do not average per-request ratios. A tiny request with a ratio of 0 counts as much as a huge request with a ratio of 0.99, and the average misrepresents the token volume. Sum the tokens, then divide.
from dataclasses import dataclass
@dataclass
class Totals:
read: int = 0
written: int = 0
uncached: int = 0
def add(self, usage):
self.read += usage.cache_read_input_tokens or 0
self.written += usage.cache_creation_input_tokens or 0
self.uncached += usage.input_tokens or 0
def ratio(self):
total = self.read + self.written + self.uncached
return self.read / total if total else 0.0The or 0 handles responses where a counter is None, which can happen when caching is not in use.
What a good number looks like
There is no universal target, because the ceiling depends on your prompt. A prompt with 4,000 stable tokens and 1,000 variable tokens cannot exceed a ratio of 0.8, even when caching works perfectly. Compare your measured ratio against that ceiling, not against 1.0.
You can compute the ceiling from your own layout:
ceiling = stable prefix tokens / total prompt tokens
If your measured ratio sits well below the ceiling, something is invalidating the prefix. If it matches the ceiling, the layout is working and the remaining gains come from moving more content into the stable prefix.
Reading the pattern over time
A single number hides the shape of the problem. Log the three counters with a timestamp and a label for the prompt type, then look at patterns.
| Pattern in the counters | Likely cause |
|---|---|
| Written is high on every request, read is zero | The prefix changes on every call, for example a timestamp near the top |
| Read is zero and written is zero | The prompt is below the minimum length, or no breakpoint is set |
| Read rises, then drops to zero after a pause | The entry expired during idle time |
| Read is high, then drops after a deploy | The system prompt or tool definitions changed |
| Read is lower than written from the first call | Parallel requests started before the first write finished |
The next chapters cover each cause in detail. For now, the point is that the counters let you tell them apart without guessing.
Logging in practice
Put the measurement in one place, a wrapper around your API call, so no code path skips it. Log the counters as structured fields, not as text in a message, so you can query them later.
import json
import time
def logged_call(client, label, **kwargs):
start = time.perf_counter()
response = client.messages.create(**kwargs)
elapsed = time.perf_counter() - start
u = response.usage
read = u.cache_read_input_tokens or 0
written = u.cache_creation_input_tokens or 0
uncached = u.input_tokens or 0
total = read + written + uncached
print(json.dumps({
"label": label,
"read": read,
"written": written,
"uncached": uncached,
"hit_ratio": round(read / total, 3) if total else 0.0,
"seconds": round(elapsed, 2),
}))
return responseLogging latency next to the counters lets you confirm the benefit directly. Requests with a high read count should usually finish their first token sooner than requests with a write. Total time also includes output generation, so compare requests with similar output lengths.
Edge cases
- Streaming responses. The usage data may arrive in the final events of the stream, not at the start. Read it after the stream ends.
- Failed requests. Errors return no usage data. Count them separately so they do not look like a zero ratio.
- Several breakpoints. The read and write counters are totals across all breakpoints. They do not tell you which breakpoint hit. To see that, test each layout separately.
- Partial hits. A read value smaller than your expected prefix means the match stopped partway. Something changed at that position, and the next chapters show how to find it.
- Different prompts under one label. Mixing prompt types in one aggregate hides problems. Keep a ratio per prompt type.
Exercise
A request reports 6,000 tokens read, 0 written and 1,500 uncached, using an API where uncached excludes cached tokens. What is the hit ratio, and what is the ceiling if the stable prefix is 6,000 tokens?
Show answer
The total is 6,000 + 0 + 1,500 = 7,500 tokens, so the hit ratio is 6,000 / 7,500 = 0.8. The ceiling is 6,000 / 7,500 = 0.8 as well. The cache is working perfectly for this layout, and more gain would need more stable content in the prefix.
Exercise
Over a day, requests show written values near 5,000 and read values of 0 on nearly every call, with the same prompt template. Name two likely causes and one way to confirm which applies.
Show answer
Likely causes are a value that changes on every call near the start of the prompt, such as a timestamp or request ID, and traffic so sparse that each entry expires before the next request. To tell them apart, log the gaps between requests and compare two consecutive prompts for the first differing position. A difference early in the prompt points to the first cause. Identical prompts with long gaps point to the second.