Sub topic 8
What Caching Changes in Cost and Latency
This chapter assumes you know how prefix matching works from earlier chapters and can read short Python. It covers which parts of a request caching makes cheaper or faster, how to calculate the break-even point, and which costs stay the same.
What gets cheaper and what does not
Caching changes how the provider handles the input side of a request. Each input token falls into one of three groups:
- Cache read tokens are prefix tokens served from a stored entry. They are billed at a discounted rate.
- Cache write tokens are prefix tokens stored for the first time. Some providers bill these at a premium over the normal input price. Others charge the normal price.
- Uncached tokens are everything after the last matched prefix: the new question, fresh tool results, the latest turn.
Output tokens are billed at the normal output price whether or not the input was cached. A request that sends 20,000 input tokens and generates 3,000 output tokens still pays full price for those 3,000. Caching helps most when the prompt is long and the answer is short.
The price model
Providers publish prices as multipliers on the base input price, or as separate per-million-token rates. The table below shows the shape of the pricing. The numbers are illustrative.
| Token group | Typical multiplier | Notes |
|---|---|---|
| Uncached input | 1.0x | The normal input price |
| Cache write | 1.0x to 2.0x | Explicit-breakpoint providers often charge more, and a longer lifetime may cost more |
| Cache read | 0.1x to 0.5x | The discount varies by provider and model |
| Output | Unchanged | Caching does not affect it |
Look up the current values for your model before you plan around them. Prices, discounts, and lifetimes change, and they differ between models from the same provider. Automatic-caching providers often have no write surcharge, so a miss costs the same as an uncached request. Explicit-breakpoint providers may charge extra for writes, so a write that is never read is a small loss.
Break-even: how many reads repay a write
Let w be the write multiplier and r the read multiplier. Suppose a prefix of P tokens is sent n times within its lifetime, with one write and n − 1 reads.
- Without caching, the prefix costs
n * Ptoken-units. - With caching, it costs
P * w + (n - 1) * P * r.
Caching wins when n > (w - r) / (1 - r). The prefix length P cancels out, so break-even depends only on the multipliers and the number of reuses.
import math
def min_requests_to_win(write_mult, read_mult):
"""Smallest number of requests (one write plus reads) where caching is cheaper."""
return math.floor((write_mult - read_mult) / (1 - read_mult)) + 1
def input_cost(read, written, uncached, base_per_million,
read_mult=0.1, write_mult=1.25):
"""Dollar cost of the input side of one request."""
units = uncached + written * write_mult + read * read_mult
return units * base_per_million / 1_000_000
print(min_requests_to_win(1.25, 0.1)) # 2
print(min_requests_to_win(2.0, 0.1)) # 3
print(min_requests_to_win(1.0, 0.5)) # 2With a 1.25x write price and a 0.1x read price, a single reuse is enough to come out ahead. With a 2.0x write price, you need at least two reuses.
A worked example
Suppose a support bot sends a 20,000-token policy prefix plus about 200 new tokens per question. The base input price is $3 per million tokens, and ten questions arrive within the cache lifetime.
BASE = 3.00 # dollars per million input tokens (illustrative)
PREFIX, NEW, N = 20_000, 200, 10
no_cache = N * input_cost(0, 0, PREFIX + NEW, BASE)
first = input_cost(0, PREFIX, NEW, BASE)
rest = (N - 1) * input_cost(PREFIX, 0, NEW, BASE)
with_cache = first + rest
print(f"no cache: ${no_cache:.4f}")
print(f"with cache: ${with_cache:.4f}")
print(f"saved: {1 - with_cache / no_cache:.0%}")The script prints:
no cache: $0.6060
with cache: $0.1350
saved: 78%The first request costs a little more than an uncached one, about $0.0756 against $0.0606. Each later request costs about $0.0066 against $0.0606. The saving comes almost entirely from the reads.
The saving depends on the hit ratio from the previous chapter. If only half of the later requests hit because of a changing timestamp or a lifetime that expired, the saving drops sharply. You can plug your measured read, write, and uncached counts into input_cost and compare the result with your invoice.
Latency: time to first token
Before the model can emit its first token, it must process the whole prompt (prefill). Prefill time grows with prompt length. When a prefix is cached, the provider loads the stored attention state and prefills only the uncached suffix.
Two things follow from this:
- Time to first token (TTFT) drops, and the drop grows with prefix length. A 500-token prefix saves almost nothing, while a 50,000-token prefix can save seconds.
- Generation speed is unchanged. The model still produces output one token at a time at the same rate. A response with a long answer takes about as long as before, so total request time falls less than TTFT does.
Measure TTFT yourself instead of relying on published figures, because the gain depends on model, load, and prefix size. This snippet streams a response and records the time until the first text arrives.
import time
import anthropic
client = anthropic.Anthropic()
POLICY = open("policy.md").read()
def time_to_first_token(question):
start = time.perf_counter()
with client.messages.stream(
model="YOUR_MODEL_NAME",
max_tokens=256,
system=[{"type": "text", "text": POLICY,
"cache_control": {"type": "ephemeral"}}],
messages=[{"role": "user", "content": question}],
) as stream:
for _ in stream.text_stream:
return time.perf_counter() - start
print("first call: ", time_to_first_token("Summarize the refund rules."))
print("second call:", time_to_first_token("What is the return window?"))Run each call several times and compare medians. A single pair of measurements is dominated by network and queue noise.
Edge cases that change the arithmetic
Writes that never get read
On a provider that charges a write premium, every miss that rewrites a large prefix costs extra. Traffic that sends a unique long prompt each time, such as one-off documents, pays the premium and never recovers it. Mark a breakpoint only on content you expect to reuse.
Lifetime and traffic gaps
Entries expire after a period without use, and each read usually refreshes the timer. A steady stream of requests keeps one entry alive for hours. Traffic that arrives in bursts separated by long gaps pays for a new write at the start of each burst. If your gaps are longer than the lifetime, compare the cost of a longer-lived entry, if the provider offers one, against rewriting.
Short prompts
Prompts below the provider's minimum cacheable length are not cached at all. You pay the normal price, and nothing is written. A short prompt also gains little latency, because prefill was already fast.
Output-heavy workloads
If a request has a 2,000-token prompt and generates 4,000 tokens, input is a small share of the bill. Caching the prompt saves a small fraction of the total. Estimate the share before investing in prompt restructuring:
def input_share(input_tokens, output_tokens, in_price, out_price):
inp = input_tokens * in_price
out = output_tokens * out_price
return inp / (inp + out)
print(f"{input_share(2_000, 4_000, 3.0, 15.0):.0%}") # 9%Output prices are usually several times the input price, which makes input share smaller still.
Rate limits and other discounts
Providers handle cached tokens differently for rate limits. Some exclude cache reads from input-token limits, and others count them in full. Batch discounts and cache discounts may or may not combine. Check the provider's documentation for both.
Summary of the decision
Caching pays off when four conditions hold:
- The prefix is above the minimum cacheable length and is large compared with the new tokens.
- The same prefix is reused enough times inside its lifetime to pass break-even.
- Input is a meaningful share of total cost.
- The measured hit ratio stays high.
If one of these fails, the savings shrink. If the write premium applies and reuse is rare, caching can cost slightly more than not caching.
Exercise
A provider charges 2.0x the base input price for cache writes and 0.1x for cache reads. A 10,000-token prefix will be reused within its lifetime. What is the minimum number of requests (one write plus reads) at which caching becomes cheaper than no caching, and why does the prefix length not matter?
Show answer
Use n > (w - r) / (1 - r) = (2.0 - 0.1) / (1 - 0.1) = 2.11, so the minimum is 3 requests. The prefix length P appears in both the cached and uncached costs and cancels out of the inequality, so only the multipliers and the number of requests matter.
Exercise
A service sends 1,000 requests a day, each with a 30,000-token prefix that is identical across requests. Requests arrive evenly, one every 86 seconds, and the cache lifetime is 5 minutes with a refresh on each read. Roughly how many cache writes happen per day, and what would change if requests arrived in bursts of 100 separated by 2-hour gaps?
Show answer
With even traffic, each read refreshes the entry before it expires, so about one write happens per day. With 2-hour gaps the entry expires between bursts, so about one write happens per burst, which is roughly 10 writes for 1,000 requests. Each write pays the write multiplier on 30,000 tokens, but the 99 reads per burst still dominate the savings.
Exercise
A request has a 1,500-token prompt, a 3,000-token output, an input price of $3 per million tokens and an output price of $15 per million tokens. Is prompt caching likely to cut the bill much, and what else might block caching here?
Show answer
Input is 1,500 x 3 = 4,500 units against 3,000 x 15 = 45,000 units for output, so input is about 9% of the cost and even a 90% discount on it saves under 9% of the bill. The prompt may also fall below the provider's minimum cacheable length, in which case nothing is cached.