Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbook~15 min readProductionworked math + runnable code
The Prompt Caching Handbook

Cache the
prefix.

Prompt caching can cut the cost and latency of a big system prompt to almost nothing — and the whole thing hinges on one brutal rule most people don't know: the cache matches on the exact prefix, and dies at the first differing token. Put a timestamp at the top of your prompt and you've silently disabled caching for every request. Put the fixed content first and the variable query last, and you get a giant cache hit every time. This handbook is about that rule and how to structure prompts around it — the mechanics, not the sticker price.

00

New to this? Start here

What a prompt is, for this purpose. Every time you call a model you send it the whole conversation again — there is no memory between calls. That text usually starts with the same large, unchanging block (your instructions, your tool definitions, a document), followed by the one short thing that actually changed: the user's question.

What "caching" means here. Before the model can answer, it has to read and internally process everything you sent. That processing is the expensive part, and for the unchanging block the answer is the same every time. Prompt caching lets the provider keep that work and reuse it, so you pay full price for the block once instead of on every request.

Why the rest of this page is about ORDER. The cache is matched on the text from the very beginning of the prompt up to the first character that differs. So it is not enough for the big block to be present — it has to come first, byte for byte identical, every time. One timestamp at the top and the match fails immediately. That single rule is what the rest of this handbook unpacks.

01

Reuse the computation

Every request re-sends the same big preamble: a long system prompt, tool definitions, a document you keep asking about. The model recomputes its internal representation of all that from scratch each time — wasted work you pay for on every call. Prompt caching stores that computation for a prefix, so later requests sharing it skip the recompute and pay only a small fraction of the input price for the cached part.

Mechanically it's a reuse of the model's KV cache for the shared prefix tokens: the keys and values were already computed once, so a matching request reads them instead of recomputing. That's why the savings are real — cached tokens skip the expensive attention math. But the reuse only works when the prefix matches, and "matches" here is unforgivingly literal. Understanding exactly what counts as a match is the whole skill.

The one-sentence version

Caches key on the exact prefix and break at the first differing token — so put fixed content first and variable content last, and every request shares one long cached prefix.

02

Exact-prefix keys

Here's the rule that governs everything: a prompt cache is keyed on the exact prefix. When a new request arrives, it's compared to a cached one token by token from the very start, and the cache applies only up to the point where they still agree. The instant a token differs, the cache stops — every token from that position onward is recomputed at full price, even if the rest would have matched.

The consequence is stark and non-obvious: caching is a property of prefixes, not of content. Two prompts that share 5,000 identical tokens get zero cache benefit if those tokens don't start at the same place — if a single differing byte sits in front of them, the shared block is past the break and recomputed. It doesn't matter how much the prompts have in common; it matters how much they share from the front, uninterrupted. That single fact turns prompt caching from a billing feature into a prompt-structure problem.

03

Order is everything

If caching is about the shared prefix, then the design rule writes itself: put everything fixed at the front and everything variable at the back. The system prompt, tool schemas, and any static documents go first — identical on every request, so they form a long shared prefix that caches. The user's message, the current timestamp, the request id, anything that changes go last, after the cached region.

Two orderings, wildly different hit rates
Fixed-first[system][docs][tools] … then [query] → long shared prefix caches.
Variable-first[query][system][docs] → prefix differs every call → cache useless.
One stray tokenA timestamp at the top breaks the cache for everything after it.
RuleFixed content first, variable content last — always.

Get this backwards — put the user query or a timestamp near the top — and the prefix differs on every single request, so nothing after it caches, no matter how much static content follows. This is the number-one prompt-caching bug, and it's invisible: everything works, you just quietly pay full price forever. The same discipline is why context engineering and caching go together: a stable, well-ordered context is both easier to reason about and far cheaper to serve.

04

The prefix math

The cache benefit is exactly the length of the shared prefix between the new prompt and a cached one. Compare token by token; the hit ends at the first difference:

cache hit tokens  =  | longest common prefix (cached, new) |   ⟹   cached fraction = hit / |new|

Only leading tokens that match uninterrupted count. A difference at position i caps the hit at i, regardless of what follows.

So ordering, not content overlap, sets the hit rate. With fixed content of length F first and a variable query last, every request shares the full F; with the variable part first, the shared prefix is essentially zero:

fixed-first: hit = F (the whole preamble)     variable-first: hit ≈ 0 (prefix differs immediately)

Same tokens, opposite outcomes — the only difference is where the variable content sits. The runnable version below computes the shared prefix and shows ordering flipping the hit rate from full to zero.

RUN IT YOURSELF

The prefix decides everything

A prompt cache serves tokens only as far as the new prompt shares a leading prefix with a cached one, breaking at the first differing token. So the cache hit is the longest common prefix — and ordering controls it. Put fixed content (system, docs) first and the variable query last, and two requests share the entire fixed prefix. Put anything variable at the front — a timestamp, the user message — and the prefix differs immediately, so nothing caches even if the rest is identical. Change the ordering or the tokens and watch the hit rate flip.

CPython · WebAssembly
05

TTL and breakpoints

Two more mechanics complete the picture. TTL (time to live) is how long a cached prefix survives before it expires — prompt caches are typically short-lived (often minutes), so caching helps most when the same prefix is reused frequently within that window: a busy chat session, a burst of requests sharing one system prompt. If reuse is sparse relative to the TTL, the prefix expires between uses and you're recomputing anyway.

MechanicWhat to know
Exact-prefix keyCache applies up to the first differing token — byte-for-byte match required.
Cache-aware orderFixed content first, variable last — the single biggest lever on hit rate.
TTLPrefixes expire (often minutes); reuse must be frequent enough to land within the window.
BreakpointsSome APIs let you mark where the cacheable prefix ends — cache the stable head explicitly.
Minimum lengthCaching often kicks in only above a token threshold — tiny prompts may not cache at all.

Some providers expose explicit cache breakpoints — you mark the boundary between the stable, cacheable head and the variable tail, so the system knows exactly what to store. Whether implicit or explicit, the mental model is the same: identify the longest stable prefix, keep it byte-for-byte identical across requests, and put everything that varies after it. The economics of when this pays off — the write premium versus the read discount — live in the cost handbook; here the job is just to make the hit rate high.

06

Pitfalls

The silent killers all change the prefix. A timestamp or unique id near the top — "Current time: 14:03:22" in the system prompt — differs every second and disables caching for everything below it; move it to the end or drop it. Non-deterministic serialization — a dict whose key order varies, a JSON blob re-encoded differently — produces a different prefix even when the content is "the same"; serialize the fixed part deterministically. And reordering or editing tool definitions between calls shifts the prefix; keep them stable and in a fixed order.

Two more. Assuming a cache hit without measuring: instrument the cached-token counts your provider returns and confirm the hit rate is what you expect — a broken cache looks identical to a working one except on the bill. And over-caching volatile content: if the "fixed" prefix actually changes often (a document that updates per user), caching it wastes the write premium for little reuse. The craft is simple to state and easy to get wrong: find your longest genuinely-stable prefix, keep it identical, put it first, and measure. Do that and a huge system prompt becomes nearly free to send again and again.

Worth knowing

The most common cache-breaker is invisible: a timestamp, request id, or non-deterministic serialization near the front of the prompt changes the prefix every call, silently disabling caching for everything after it. Keep the fixed head byte-for-byte identical and measure the cached-token count.

By the numbers

Worked example: 100 requests, three orderings

A support bot sends a 10,000-token fixed head (system prompt, tool schemas, a policy document) plus a 200-token question, 100 times inside one cache window. Count cost in token-units, where 1 unit is one uncached input token. Writes cost 1.25×, reads 0.1× (the shape of Anthropic’s 5-minute cache; other providers differ, so check yours).

StepCaseArithmeticToken-units
1No caching at all100 × (10,000 + 200)1,020,000
2Request 1, fixed-first (cold)10,000 × 1.25 + 20012,700
3Requests 2–100 (warm)99 × (10,000 × 0.1 + 200)118,800
4Fixed-first total12,700 + 118,800131,500 (12.9% of step 1)
5A 10-token seconds timestamp moved to the topevery request writes: 100 × (10,010 × 1.25 + 190)1,270,250 (124.5%)
6Fixed-first, but one request every 10 minutesevery request is cold: 100 × 12,7001,270,000 (124.5%)
7Break-even reuse1.25 + 0.1n < 1 + n, so n > 0.28the first reuse already pays

Step 4 is the payoff: the same 100 requests for about an eighth of the price, saving 888,500 units. Step 5 is the page’s timestamp bug, and it is worse than no caching: on an API with explicit breakpoints you pay the write premium 100 times and never read once. On a provider with automatic caching and no write premium, the same mistake just costs the full 1,020,000. Step 6 is the TTL rule: perfect ordering cannot help when the prefix expires before the next request arrives. Step 7 is why the decision is about reuse within the window, not reuse in general.

Trade-offs

Cost and trade-offs of each cache outcome

Here Time is the prefill work, which sets time to first token. Space is what you pay for, or what someone has to hold in memory.

CaseTimeSpaceWhy
Warm hitOnly the uncached tail is prefilled, so the first token arrives soonerCached tokens billed at a fraction (0.1× above)The prefix’s keys and values are read back, not recomputed.
Cold writeFull prefill, same as no cacheA write premium on explicit-breakpoint APIs (1.25× above); none on automatic cachingSomeone has to compute the prefix once before anyone can reuse it.
Partial hitPrefill restarts at the first differing tokenDiscount only up to the breakThe match never resumes after a difference, even if later blocks are identical.
Expired (past TTL)Full prefill againPays the write againReuse sparser than the TTL turns every request into a cold write (step 6).
Self-hosted prefix cacheSame prefill savingGPU memory: Llama 2 7B in fp16 holds 0.5 MiB of KV per token, so a 10,000-token prefix is about 4.9 GiB2 (K and V) × 32 layers × 4,096 dims × 2 bytes per token. Cached prefixes compete with live requests for that memory and get evicted under load.
Longer TTL, where offeredHits survive longer gapsA higher write price (Anthropic’s 1-hour cache writes at 2×)Worth it only when the gap between reuses is longer than the short window.

Every row reduces to the same two questions: how long is the stable prefix, and how often is it reused inside the window? Ordering fixes the first. Traffic shape decides the second, and no prompt edit can change it.

In the wild

Where this shows up in production and interviews

  • Anthropic API: explicit breakpoints

    You mark the end of the cacheable head with cache_control on a content block. Each response’s usage reports cache_creation_input_tokens and cache_read_input_tokens. Put both on a dashboard: a healthy service shows a few writes and many reads.

  • OpenAI API: automatic caching

    Prompts of 1,024 tokens or more are cached automatically, with no markup. The hit shows up as usage.prompt_tokens_details.cached_tokens. There is no breakpoint to place, so ordering is the only lever you have.

  • Self-hosted serving

    vLLM’s automatic prefix caching reuses KV blocks whose whole prefix matches. SGLang’s RadixAttention keeps a tree of shared prefixes. The rule is the same exact prefix, but the cache lives in your own GPU memory, so its size is your cost (see the self-hosted row above).

  • Agents, chat, and the interview version

    A conversation is append-only, so each turn’s prompt is the previous turn’s prompt plus new messages, and every turn hits the last turn’s cache. Compaction that rewrites the start of the history, or a tool list that changes mid-session, resets it. A favourite interview prompt: “the agent’s bill jumped after a small prompt change.” The answer is a prefix diff: find the first token that now varies.

Self-check

Check yourself

Your system prompt starts with "Today is 2026-10-28". Is caching broken?

Mostly not. The date changes once a day, so the prefix is stable all day and only the first request after midnight misses. A seconds timestamp is the killer, because it changes on every request. Still, moving the date to the end costs nothing and removes even the daily miss.

A RAG app retrieves different chunks for every question. Where do the chunks go?

After the fixed system prompt and tool schemas, and before the question. The fixed head still caches for every user. The chunks differ per query, so they sit in the uncached tail anyway. Putting them first would push the stable head past the break and nothing would cache.

Traffic is one request every 10 minutes and the cache lives 5 minutes. Should you mark a breakpoint?

No, not on an API that charges a write premium. Every request arrives after the prefix has expired, so each one is a cold write at 1.25× with no reads to pay it back, 124.5% of uncached in the worked example. Either batch the requests closer together, use a longer TTL if it is offered, or skip the breakpoint.

To save tokens, a chat app drops the oldest message once history passes a limit. What happens to caching?

It breaks on every turn after the limit. Dropping the first message changes the prefix right after the system prompt, so only the system prompt still hits. An append-only history hits the previous turn’s cache in full. If you must trim, trim rarely and in large steps, so most turns still share a prefix.

Frequently asked

Quick answers

How does prompt caching work?

It stores the model's computation for a prompt prefix and reuses it on later requests that share that exact prefix, charging a fraction for the cached part.

Why does ordering matter?

The cache matches the exact prefix, so only content before the first change is reusable — put fixed content first, variable last, for a big shared prefix.

What is TTL?

How long a cached prefix stays valid (often minutes); caching pays off when the same prefix is reused frequently within that window.

What breaks caching?

Anything that changes the prefix — a timestamp or id near the top, reordered tools, or non-deterministic serialization drops the cache from that point.

Finished this one? 0 / 209 Handbooks done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks