Module 3 · Long-context ingestion
Prompt caching: architecture and savings
6 min read
When fifty questions concern the same 150,000-token contract, the model rereads the same contract fifty times, and you pay for it fifty times. Prompt caching avoids this waste: the start of the prompt, identical from one request to the next, is computed once and then reread from the cache, faster and far cheaper. This lesson shows the mechanism on the local model, then puts a number on the savings with the Claude API and gives the architecture rules that let you benefit from it.
The mechanism: the KV cache
To generate, a model computes for each prompt token attention keys and values (the "KV cache"). This computation, the prefill, is most of the cost of a long prompt. Yet a token's keys and values depend only on the tokens that precede it: if two prompts start with the same prefix, that prefix's KV cache is identical and can be reused.
Locally, we measure it directly: compute the prefix cache once, then process only the rest.
def measure(prefix: str, suffixes: list[str], model_name: str) -> CacheTiming:
_, tokenizer = local.load(model_name)
local.prefill_seconds(prefix[:2000], model_name) # échauffement (allocation, noyaux)
full = [local.prefill_seconds(prefix + s, model_name)[0] for s in suffixes]
_, prefix_cache = local.prefill_seconds(prefix, model_name)
cached = [local.prefill_seconds(s, model_name, past=copy.deepcopy(prefix_cache))[0] for s in suffixes]
return CacheTiming(len(tokenizer(prefix, add_special_tokens=False)["input_ids"]),
sum(full) / len(full), sum(cached) / len(cached))
| Shared prefix | Without cache (prefix + question) | With cache (question only) | Speed-up |
|---|---|---|---|
| 1,922 tokens | 2,479 ms | 87 ms | × 28 |
| 7,859 tokens | 11,239 ms | 138 ms | × 82 |
Averages over five questions, Qwen2.5-1.5B on the GTX 1060. Two observations:
- the gain grows with the prefix length: without cache, reading time grows with the prefix (and faster than it: 4 times more tokens, 4.5 times more time); with cache, only the question is read, whatever the document size;
- at 8,000 tokens, prefill dominates everything: 11 seconds before the first answer token, versus 0.14 seconds with the cache. That is the latency the user perceives.
With the Claude API
The Claude API does the same thing server-side. You mark the end of the prefix to cache with cache_control; everything before that point (tools, system prompt, messages) forms the prefix:
def ask_long_document(document: str, title: str, question: str, effort: str = "medium") -> tuple[str, dict]:
"""Document long EN TÊTE, mis en cache ; question À LA FIN. Renvoie la réponse et l'usage (jetons, cache)."""
response = client().messages.create(
model=config.CLAUDE_MODEL,
max_tokens=4000,
system="Tu réponds aux questions sur les documents fournis. Cite le passage qui justifie ta réponse.",
messages=[{"role": "user", "content": [
{"type": "text", "text": f"<document titre=\"{title}\">\n{document}\n</document>",
"cache_control": {"type": "ephemeral"}}, # le préfixe stable est relu depuis le cache
{"type": "text", "text": question}, # la partie variable, après le point de cache
]}],
output_config={"effort": effort}, # low | medium | high | xhigh | max
)
u = response.usage
usage = {"input": u.input_tokens, "cache_write": u.cache_creation_input_tokens or 0,
"cache_read": u.cache_read_input_tokens or 0, "output": u.output_tokens}
return text_of(response), usage
The response tells you what happened: cache_creation_input_tokens (tokens written to the cache, on the first request), cache_read_input_tokens (tokens reread from the cache), input_tokens (the rest, at normal price). Check these fields: a cache that never triggers produces no error, only an invoice.
The savings, in numbers
Pricing:
| Opus 5.5 | Sonnet 5.5 | |
|---|---|---|
| Normal input (per million tokens) | $4.00 | $2.00 |
| Cache write (5-minute lifetime) | 1.25 × input: $5.00 | $2.50 |
| Cache read | $0.20 | $0.20 |
The calculation for n requests sharing a prefix:
def api_cost(model: str, prefix_tokens: int, question_tokens: int, n_requests: int, cached: bool) -> float:
"""Coût d'entrée (USD) de n requêtes partageant le même préfixe, avec ou sans cache (TTL 5 minutes)."""
p = PRICES[model]
if not cached:
return n_requests * (prefix_tokens + question_tokens) * p["input"] / 1e6
write = prefix_tokens * p["input"] * WRITE_FACTOR / 1e6
reads = (n_requests - 1) * prefix_tokens * p["cache_read"] / 1e6
questions = n_requests * question_tokens * p["input"] / 1e6
return write + reads + questions
For 50 questions of 200 tokens over a 150,000-token contract:
| Model | Without cache | With cache | Savings |
|---|---|---|---|
| Opus 5.5 | $30.04 | $2.26 | −92% |
| Sonnet 5.5 | $15.02 | $1.86 | −88% |
Writing costs 25% more than a normal read: caching pays off from the second request on the same prefix. Prices change: check them in the documentation before building a budget.
The architecture of a "cacheable" prompt
The cache only works on an exact prefix: a single different character, and everything after it is recomputed. The prompt order therefore becomes an architecture decision:
| Order | Content | Stability |
|---|---|---|
| 1 | Tools (their definitions) | Rarely changes |
| 2 | System prompt: role, rules, format | Changes with each prompt version |
| 3 | Fixed examples (lesson 2.2) | Stable |
| 4 | Long documents | Stable during a question session |
| ← cache point | ||
| 5 | Recent history, question | Changes with each request |
The mistakes that silently break the cache:
- a date or timestamp in the system prompt ("Today is October 12, 2026, 4:21 pm"): the prefix changes every minute. Put it after the cache point;
- a request or user identifier at the top;
- dynamically chosen examples (lesson 2.2) before the documents;
- a setting that varies between requests: changing the model, the tools or the
effortlevel invalidates the cache; pin them per request type; - a non-deterministic order: tools or documents assembled from a
setor an unordered dictionary; - a prefix that is too short: below a minimum (512 tokens on current Claude models), nothing is cached, without error.
The cache has a lifetime (5 minutes by default, refreshed at each read; a 1-hour option costs 2 × input at write time). For interactive use, 5 minutes is often enough; for spaced-out jobs, the longer option avoids rewriting.
Key takeaways
- Prompt caching reuses the computation of an identical prefix: faster, and much cheaper.
- With Claude:
cache_controlmarks the end of the prefix; checkcache_read_input_tokensin the usage.- 50 questions over a 150,000-token contract: $30.04 without cache, $2.26 with it, on Opus 5.5.
- What is stable goes first (tools, system, examples, documents), what changes goes last.
- A date, an identifier or a random order at the top of the prompt breaks the cache without error.
Practice
- Run
examples/05_prompt_caching.pyand compare the time savings for 2,000 and 8,000 prefix tokens. - With
QUILL_FAKE=1, callclaude.ask_long_documenttwice on the same long document and checkcache_writethencache_read. - Reread the system prompt of one of your projects: what would prevent it from being cached?