Sub topic 12
Prompt caching
This chapter assumes you can read basic Python, have called an LLM through a chat or completion API, and know how per-million-token pricing works from the earlier chapters on pricing and history growth.
The problem caching solves
A chat that resends its history pays for the same opening tokens on every call. The system prompt, tool definitions, and early turns are identical from one request to the next. Prompt caching lets the provider reuse its work on that repeated opening instead of processing it again.
When a request starts with a prefix the provider has seen recently, it can serve that prefix from a cache. Cached input tokens are billed at a lower rate than normal input tokens. The output is unchanged. The model still reads the full prompt, and you still need it to fit the context window.
How it works
Caching matches on a prefix. The provider compares the start of your new prompt with recent prompts, and the match must be exact, token for token, from the first token onward. The first difference ends the match. Everything after that point is processed and billed at the normal rate.
Providers differ in the details, so check your provider's documentation:
- Some cache automatically once a prompt passes a minimum length. Others require you to mark where the cacheable prefix ends.
- Some charge a premium to write the cache and a discount to read it. Others charge nothing extra to write.
- Cache entries expire after a short time without use, often minutes. Each hit usually extends the lifetime.
- Models have a minimum prefix length below which nothing is cached.
Cost arithmetic
Suppose a prompt has a 2,000-token fixed prefix and a 100-token new part. Use placeholder prices: normal input is $3.00 per million tokens, cache reads are $0.30 per million, and cache writes are $3.75 per million.
def input_cost(prefix, new, hit,
normal=3.0, read=0.30, write=3.75):
prefix_price = read if hit else write
return (prefix * prefix_price + new * normal) / 1_000_000
first = input_cost(2000, 100, hit=False) # writes the cache
later = input_cost(2000, 100, hit=True) # reads the cache
uncached = (2100 * 3.0) / 1_000_000
print(f"first call: ${first:.5f}") # $0.00780
print(f"cached call: ${later:.5f}") # $0.00090
print(f"no caching: ${uncached:.5f}") # $0.00630The first call costs more than no caching, because of the write premium. Each later call costs about 86% less on input. Over ten calls, caching costs 0.00780 + 9 × 0.00090 = $0.01590, against $0.06300 without it.
Structuring prompts for hits
Because matching is by prefix, order matters. Put stable content first and changing content last.
- System prompt and instructions.
- Tool definitions and reference documents.
- Earlier conversation turns.
- The newest user message.
The common errors are all ways of breaking the prefix:
- Putting a timestamp, request ID, or user name at the top of the system prompt. It changes every call, so nothing after it can match.
- Reordering tool definitions or JSON keys between calls.
- Editing or trimming early messages. Trimming history, as in the context management chapter, moves the start of the conversation and invalidates the cache. Trim in occasional large steps, not one message per turn.
- Sending requests too far apart, so the entry expires before the next one.
Verifying that it works
Do not assume caching is active. Read the usage data in each response, as covered in the chapter on usage reporting. Providers report cache reads and writes in separate fields. Their names differ, so look them up for your provider. If cache reads stay at zero across repeated calls, the prefix is changing, is shorter than the minimum, or is expiring between requests.
Exercise
A chat app puts "Current time: <timestamp>" as the first line of its system prompt, followed by 3,000 tokens of fixed instructions. Cache reads are always zero. Why, and what is the fix?
Show answer
The timestamp changes on every call, so the prompts differ from the first line onward and the prefix never matches. Move the timestamp to the end of the prompt, for example into the latest user message, so the 3,000 fixed tokens stay at the start and can be served from cache.
Exercise
Using the placeholder prices above (normal $3.00, cache read $0.30, cache write $3.75 per million tokens), what does the input cost of a call with a 4,000-token cached prefix and 200 new tokens come to?
Show answer
(4,000 × 0.30 + 200 × 3.00) / 1,000,000 = (1,200 + 600) / 1,000,000 = $0.0018.