Prompt Caching in Practice: Stop Paying Twice for the Same System Prompt, Token Costs Drop 80%
Prompt Caching in Practice: Stop Paying Twice for the Same System Prompt, Token Costs Drop 80%
Last week I helped a friend investigate a customer service agent's bill: after seven days online, input tokens had spent 3 times the budget. Pulling the logs, the problem was simple — every request carried a 3000+ character system prompt and 20 tool definitions, and none of that content had changed a single character, yet it was billed at full price every round.
After enabling Prompt Caching, we got a 92% hit rate, input costs dropped to about 20% of the original, and time-to-first-token fell from 1.8 seconds to 0.9 seconds. This article breaks down the whole process: what exactly gets cached, which coding patterns will make it never hit, and a set of working Python observation code you can copy directly.
1. What exactly does a cache hit mean?
When a large model does inference, it computes a Key/Value vector for each token and stores it — this is the well-known KV Cache. If the same prefix was computed recently, the inference framework can reuse those KV blocks in GPU memory, skip the repeated computation entirely, and only run a forward pass on the new content.
In engineering, mainstream frameworks split the prompt into chunks and compute a prefix hash for each chunk. If the hash matches, they reuse it. So the rule is brutally simple:
Only a prefix that is byte-for-byte identical from the very first token can hit.
It's not "roughly the same meaning" that hits, nor "contains this text." One extra space or one timestamp invalidates everything after the point of difference.
Each provider differs in billing and mechanics, but the direction is consistent:
- OpenAI: auto-caches prefixes over 1024 tokens, cached input is billed at 50%.
- Anthropic: explicit cache breakpoints via cache_control; writes cost 1.25x, reads cost 0.1x, default 5-minute expiry.
- DeepSeek: automatic context caching, hit price is about one-quarter of miss price, automatically cleared after idle.
Exact rates change with versions; check the current price list before you start. The key takeaway: caching is "prefix reuse," not "content deduplication."
A quick reminder: caching usually only covers the input side; output tokens are still billed at full price. So its role is to "cut down repeated fixed overhead," not to bring your bill to zero.
2. Three habits that kill the cache
I've seen many failure cases, and they all fall into three categories.
1. Timestamp placed at the first line of the system prompt
"Current time: 2026-11-27 10:32:11" — every request differs, the first block of the prefix changes, and the subsequent 3000 characters all miss. The correct approach is to put the time at the end of the user message, or give the model a time-lookup tool so it can call on demand.
2. Dynamic few-shot random sampling
Each time randomly picking 3 examples from a question bank and splicing them into the system prompt looks like "enhancing effectiveness," but in reality it's "changing the prefix every round." Switch to fixed examples and put dynamically retrieved content after the prefix.
3. JSON serialization without sorting
Tool definitions and parameter dictionaries directly use json.dumps, and key order depends on insertion order, so the strings produced by different requests don't match, and the hash naturally fails. Adding sort_keys=True fixes it.
One-sentence principle: stable content first, volatile content last. Recommended order: system prompt → tool definitions → fixed examples → session history → current user input.
3. Runnable code: cache-friendly constructor + hit-rate monitoring
The code below relies on no third-party libraries; run the logic locally first; when connecting to a real API, only replace FakeLLM.
import hashlib
import json
from dataclasses import dataclass
# ---------- 1. Cache-friendly prompt construction ----------
SYSTEM_PROMPT = """You are an e-commerce customer service assistant.
Rules: only answer order, logistics, and return/exchange questions;
if uncertain, must call tools to query, never fabricate;
keep responses within 3 sentences."""
TOOLS = [
{"name": "query_order", "desc": "query status by order id", "args": ["order_id"]},
{"name": "query_logistics", "desc": "query logistics tracking", "args": ["order_id"]},
]
def build_stable_prefix() -> str:
# Key: stable part built separately, JSON serialization fixed order
tools = json.dumps(TOOLS, ensure_ascii=False,
sort_keys=True, separators=(",", ":"))
return f"<system>\n{SYSTEM_PROMPT}\n</system>\n<tools>\n{tools}\n</tools>"
def build_request(user_input: str, history: list[dict]) -> list[dict]:
msgs = [{"role": "system", "content": build_stable_prefix()}]
msgs += history[-6:] # history only appended at the tail, doesn't pollute prefix
msgs.append({"role": "user", "content": user_input})
return msgs
# ---------- 2. Hit rate and cost observation ----------
@dataclass
class Meter:
hit_tokens: int = 0
miss_tokens: int = 0
requests: int = 0
def record(self, hit: int, miss: int) -> None:
self.hit_tokens += hit
self.miss_tokens += miss
self.requests += 1
@property
def hit_rate(self) -> float:
total = self.hit_tokens + self.miss_tokens
return self.hit_tokens / total if total else 0.0
def cost(self, miss_price=2.0, hit_price=0.5, unit=1_000_000) -> float:
return (self.miss_tokens * miss_price + self.hit_tokens * hit_price) / unit
# ---------- 3. Local prefix cache simulation ----------
class FakeLLM:
"""Simulate prefix cache with a hash: same prefix seen before counts as a hit"""
def __init__(self) -> None:
self.seen: set[str] = set()
def chat(self, msgs: list[dict]) -> dict:
prefix = msgs[0]["content"]
block = hashlib.sha256(prefix.encode()).hexdigest()
hit = len(prefix) if block in self.seen else 0
self.seen.add(block)
miss = len(prefix) - hit + sum(len(m["content"]) for m in msgs[1:])
return {"hit_tokens": hit, "miss_tokens": miss}
if __name__ == "__main__":
llm, meter = FakeLLM(), Meter()
for i in range(1000):
usage = llm.chat(build_request(f"Where is my order? #{i}", []))
meter.record(usage["hit_tokens"], usage["miss_tokens"])
print(f"Requests={meter.requests}")
print(f"Hit rate={meter.hit_rate:.1%}")
print(f"Estimated input cost={meter.cost():.2f} CNY")
Running it prints request count, hit rate, and estimated cost. You can first change SYSTEM_PROMPT to only one or two sentences and compare — the shorter the prefix, the less obvious the caching benefit, which is why the checklist requires "at least 1024 tokens."
When connecting to a real service, replace the Meter inputs with the response's cache fields:
- DeepSeek:
usage.prompt_cache_hit_tokens/usage.prompt_cache_miss_tokens - OpenAI:
usage.prompt_tokens_details.cached_tokens - Anthropic:
usage.cache_read_input_tokens/usage.cache_creation_input_tokens
Then put the hit rate on a dashboard daily. If hit rate stays below 70% for a long time, the prefix is almost certainly polluted.
4. Real test data
Same prompt, 1000 requests, step-by-step comparison after refactoring (cost estimated at hit price = miss price × 0.25):
| Approach | Hit rate | Input cost | Time-to-first-token |
|---|---|---|---|
| Original: timestamp in first line + random few-shot | 0% | 100% | 1.8s |
| Only remove timestamp | 61% | 42% | 1.2s |
| Stable prefix + fixed examples + sort_keys | 92% | 21% | 0.9s |
Numbers will fluctuate with model, load, and prefix length, but the trend is stable: the higher the hit rate, the lower the cost, and the lower the time-to-first-token — because the few thousand tokens of prefix don't need to be recomputed.
The measurement method is also simple: take the same batch of 1000 real requests, send them to the pre-refactor and post-refactor services, only count input-side tokens, ignore output side, and compare P50 latency. Don't use "feels faster" as a conclusion.
5. Landing checklist
- Stable prefix at least 1024 tokens, too short yields no benefit;
- No time, UUID, random numbers, or auto-increment IDs in the prefix;
- All JSON serialization uses
sort_keys=True; - Session history only appended after the prefix, with window truncation;
- Instrument to record hit tokens / miss tokens, track trend daily;
- Watch TTL: low-frequency scenarios will expire the cache, don't expect overnight hits.
Summary
Prompt Caching is not a switch; it's a cache-friendly Prompt design problem. What really determines cost isn't the model unit price, but whether your prefix is stable enough.
I drew three conclusions from this: first, structurally separating "stable" from "volatile" yields far more benefit than nitpicking wording in the prompt; second, hit rate must be an observable metric, optimization without instrumentation is guessing; third, you save not just money but also time-to-first-token — which for agent experience often matters more than cost reduction.
Next time you see an abnormal bill, don't rush to switch models. Go check whether your prefix is hiding that timestamp that changes every second.