Sub topic 2
How Long a Cache Entry Lives and What Refreshes It
Assume you know how to call an LLM API, what tokens are, and how to read basic Python. Cache behavior differs by provider and model, so verify the current API documentation before relying on a specific TTL or price.
Cache lifetime and refresh
A cache entry usually has a time-to-live (TTL), which is the period before the provider removes it. Some providers use a fixed lifetime. Others refresh the entry when a later request reads or writes the same prefix.
A cache hit does not always mean permanent storage. If traffic stops for longer than the TTL, the next request may need to process and write the prefix again.
A provider may refresh a cache on use, but this is not universal. Treat the TTL, refresh rule, and cache scope as provider-specific settings.
Minimum prompt length
Caching is useful only when the cacheable prefix is long enough to offset the provider’s storage and lookup overhead. Providers often enforce a minimum token length. A short system message may therefore be ignored even when you mark it for caching.
The minimum can vary by model, region, or cache duration. Count the tokens in the exact prefix that the provider evaluates, not the characters in your source file.
Cost and latency effects
A cache hit usually lowers input-token cost and prefill latency. The output cost normally remains unchanged. A cache miss pays the normal input price and may also write the prefix at a separate rate.
| Request type | Input work | Typical effect |
|---|---|---|
| Cache write | Processes and stores the prefix | Higher first-request cost |
| Cache read | Reuses stored prefix state | Lower cost and latency |
| No eligible cache | Processes the full prefix | Normal cost and latency |
Compare the provider’s published read, write, and uncached prices. Caching may not pay off when requests are rare, prefixes are short, or entries expire before reuse.
Measure cache hits
Providers commonly return separate usage fields for tokens read from cache, written to cache, and left uncached. A simple token-weighted hit ratio is:
def cache_hit_ratio(cache_read, cache_written, uncached):
total = cache_read + cache_written + uncached
return cache_read / total if total else 0.0
print(cache_hit_ratio(0, 4000, 50)) # 0.0
print(cache_hit_ratio(4000, 0, 60)) # about 0.99Log these fields per request. A falling ratio can indicate expiration, an ineligible prefix, or a changed prompt layout.
Exercise
A request reports 3,000 cache-read tokens, 500 cache-written tokens, and 100 uncached tokens. What is the token-weighted cache hit ratio?
Show answer
3,000 / (3,000 + 500 + 100) = about 0.833, or 83.3%.