Sub topic 14
Deciding when caching is worth it
Earlier chapters covered how caching works and how to raise hit rates. This chapter covers whether caching is worth turning on for a given workload. It assumes you can read short Python snippets, know what tokens and context windows are, and have read the chapters on cache lifetime, minimum length, and reading usage fields.
Caching is a trade. Some providers charge extra to write an entry, and every provider charges a reduced price to read one. You come out ahead only if enough requests read the entry before it expires. The decision comes down to four numbers: prefix size, request rate, price multipliers, and the share of your bill that the prefix represents.
The cost model
Let the base input price be p per token and the cacheable prefix be P tokens. Providers publish two multipliers relative to p:
wis the multiplier for a request that writes the entry. Some providers charge more than the base price for this, and others charge nothing extra, which makesw = 1.ris the multiplier for a request that reads the entry. It is below 1.
Without caching, every request costs P × p for the prefix. With caching, a request that writes costs P × p × w, and a request that reads costs P × p × r. If a fraction h of requests are reads, the expected multiplier is:
h × r + (1 − h) × wCaching saves money when this is below 1. Solving for h gives the break-even hit rate:
h > (w − 1) / (w − r)If w = 1, any hit rate above zero saves money. Writes are free, so the worst case is paying the normal price.
The multipliers below are examples of the shape of published pricing. Prices change, so always take the numbers from your provider's current pricing page.
| Scenario | w | r | Break-even hit rate |
|---|---|---|---|
| Short-lived entry, write surcharge of 25% | 1.25 | 0.10 | about 22% |
| Longer-lived entry, write surcharge of 100% | 2.00 | 0.10 | about 53% |
| Automatic caching, no write surcharge | 1.00 | 0.50 | above 0% |
The longer lifetime costs more to write, so it needs a higher hit rate to pay off. It earns that only when your traffic has gaps longer than the short lifetime, as the next sections show.
A calculator you can run
def breakeven_hit_rate(write_mult, read_mult):
"""Smallest hit rate at which caching costs less than not caching."""
if write_mult <= 1:
return 0.0
return (write_mult - 1) / (write_mult - read_mult)
def prefix_cost(prefix_tokens, price_per_mtok, hit_rate, write_mult, read_mult):
"""Expected input cost in dollars of the cacheable prefix for one request."""
per_token = price_per_mtok / 1_000_000
multiplier = hit_rate * read_mult + (1 - hit_rate) * write_mult
return prefix_tokens * per_token * multiplier
PREFIX = 20_000 # cacheable tokens
PRICE = 3.00 # example base price, dollars per million input tokens
uncached = prefix_cost(PREFIX, PRICE, 0.0, 1.0, 1.0)
print(f"no caching: ${uncached:.4f}")
for hit_rate in (0.1, 0.2, 0.5, 0.9):
cost = prefix_cost(PREFIX, PRICE, hit_rate, 1.25, 0.10)
verdict = "saves" if cost < uncached else "loses"
print(f"hit rate {hit_rate:>4.0%}: ${cost:.4f} ({verdict})")
print(f"break-even (w=1.25): {breakeven_hit_rate(1.25, 0.10):.1%}")
print(f"break-even (w=2.00): {breakeven_hit_rate(2.00, 0.10):.1%}")At a 10% hit rate the cost is higher than no caching. At 20% it is almost level. At 50% and above it is clearly cheaper. The prefix is cheap enough to ignore only when it is tiny or your hit rate is near zero.
Where the hit rate comes from
The model above treats h as given, but your traffic pattern determines it. Two inputs matter most.
- Gap between requests that share a prefix. Each read usually refreshes the entry's lifetime, as covered in the lifetime chapter. If the typical gap between matching requests is shorter than the lifetime, one write can serve a long run of reads. If the typical gap is longer than the lifetime, the entry has expired by the next request and every request pays the write price.
- Number of distinct prefixes. Traffic spread over many different prefixes behaves like many separate low-rate streams. A thousand users, each with their own prefix and one request an hour, produce a poor hit rate even if total traffic is high.
You can estimate h from logs instead of guessing. The hit ratio function from the measuring chapter gives you a measured number. Compare it against the break-even rate for your provider and lifetime option.
def breakeven_requests_per_lifetime(write_mult, read_mult):
"""How many requests within one lifetime make a single write worthwhile.
Cost with caching: write_mult + (n - 1) * read_mult
Cost without: n
"""
n = (write_mult - read_mult) / (1 - read_mult)
return int(n) + (0 if n == int(n) else 1)
print(breakeven_requests_per_lifetime(1.25, 0.10)) # 2
print(breakeven_requests_per_lifetime(2.00, 0.10)) # 3With a 25% surcharge, the second request in a lifetime already pays for the write. With a 100% surcharge you need a third.
Latency is a separate benefit
Cost and latency do not always move together. A cache hit skips most of the prefill work, so time to first token drops, and the drop grows with prefix length. For an interactive chat with a 30,000-token document, this can be the main reason to cache even when the dollar savings are small.
For a batch job, nobody waits on any single response, so only the dollars matter. For a chat product, a hit that saves two seconds may justify caching at a hit rate that would not justify it on cost alone.
Caching does not change output tokens. Output is billed separately, and generation speed after the first token is unchanged.
When the savings are too small to matter
Compute how much of your bill the prefix represents before optimizing for it.
- Short prefixes. Below the provider's minimum cacheable length, nothing is cached. You get no benefit but also no penalty, so there is nothing to decide.
- Output-heavy workloads. If each request generates thousands of tokens from a 2,000-token prompt, input is a minor part of the cost. A 90% discount on a small line item is a small saving.
- Mostly unique content. If the stable part of the prompt is a few hundred tokens and the rest differs per request, the cacheable share is too small.
- Rare traffic. A job that runs once a day against a prefix pays the write price each time. With a write surcharge, that is a net loss.
- Prefixes that keep changing. If the stable prefix changes more often than it is reused, for example a document edited between nearly every call, you pay writes without reads.
A quick check is the cacheable share of total cost per request:
def cacheable_share(prefix_tokens, other_input_tokens, output_tokens,
input_price, output_price):
"""Fraction of a request's cost that caching can possibly discount.
Prices are dollars per million tokens.
"""
prefix_cost = prefix_tokens * input_price
total = (
prefix_cost
+ other_input_tokens * input_price
+ output_tokens * output_price
)
return prefix_cost / total
# Example prices: $3 input, $15 output per million tokens.
print(f"{cacheable_share(20_000, 300, 400, 3.0, 15.0):.0%}") # about 91%
print(f"{cacheable_share(1_500, 300, 2_000, 3.0, 15.0):.0%}") # about 12%The first workload is dominated by a long reusable prefix, so caching is the largest lever. In the second, even a perfect cache cannot discount more than about 12% of the cost, and the discount applies only to a reused prefix.
A decision procedure
Follow the flow in order, because the cheap checks come first. If you are unsure of the hit rate, enable caching on a small share of traffic, log the three usage counters, and compare the measured cost against the model above.
Common mistakes in the decision
- Using the discount, not the net saving. A 90% read discount does not mean 90% savings. Savings depend on how many requests are reads and on what writes cost.
- Ignoring write surcharges. With a surcharge, a workload with low reuse can cost more than no caching.
- Choosing a longer lifetime by default. The longer option costs more per write. Pick it only if your gaps between matching requests regularly exceed the shorter lifetime.
- Forgetting traffic changes. A hit rate measured at peak may not hold overnight. Re-check after launches, prompt edits, and model changes, since any of these can change multipliers, minimum lengths, or prefix content.
- Deciding once. Prompt edits and new tools quietly change the prefix. Keep the hit ratio on a dashboard so a drop is visible.
Exercise
A prefix is 10,000 tokens. Your provider charges 1.25 times the base price to write a cache entry and 0.10 times to read one. In a test run, 100 requests produce 15 reads and 85 writes. Does caching save money, and what hit rate would you need?
Show answer
Break-even is (1.25 − 1) / (1.25 − 0.10) = 0.25 / 1.15, about 21.7%. The measured hit rate is 15%, which is below that, so caching costs more than not caching: the expected multiplier is 0.15 × 0.10 + 0.85 × 1.25 = 1.0775, about 8% more. You need at least 22 reads per 100 requests. Look first for why 85 requests wrote entries, for example gaps longer than the lifetime, a timestamp early in the prompt, or many distinct prefixes.
Exercise
A workload sends 1,000 tokens of prefix, 200 tokens of other input, and 1,500 output tokens per request. Input costs $3 and output costs $15 per million tokens. Is prompt caching a major cost lever here?
Show answer
No. The prefix costs 1,000 × 3 = 3,000 units, other input costs 200 × 3 = 600, and output costs 1,500 × 15 = 22,500. The prefix is 3,000 / 26,100, about 11.5% of the cost, so even a perfect cache removes only a fraction of that. The prefix may also be below the provider's minimum cacheable length. Reducing output length would save more.