Prompt Caching for LLMs: A Practical Guide to Cutting Inference Costs
This guide explains why multi-turn LLM applications can rack up costs quickly and how prompt caching reduces them. It covers how cache hits work, the engineering conditions required for them, a common failure pattern where requests succeed but billing shows no discount, and a four-layer verification approach. You will also find practical steps for stabilizing prefixes, passing cache markers through gateways and proxies, validating hits via usage statistics, and estimating cost savings.
1. The Problem: Why Your Balance Drops After Only a Few Turns
A common source of confusion in LLM application development is watching your account balance fall rapidly even though no single request seems large. The typical case is a long-context coding assistant: the system prompt, project files, and conversation history are carried into every turn, and the context quickly grows to the scale of hundreds of thousands of tokens. If billing is based on the full input, the cost of each turn scales linearly with context length.
To understand this, start with a basic fact: input and output tokens are usually priced very differently, with output often costing several times more per token than input. As a result, the bill for long-context, multi-turn applications is driven mainly by the input side, and the largest share of that input is usually the “prefix” that is nearly identical from turn to turn.
This points to the core opportunity: if that repeated prefix does not have to be billed at full price every time, overall costs can drop by an order of magnitude.
2. How Prompt Caching Works: What a Cache Hit Actually Saves
Prompt caching is a widely used inference-side optimization. When the prompt prefix of a request (typically made up of system instructions, tool definitions, long documents, and conversation history) is exactly the same as that of a recent request, the inference service can reuse the already-computed intermediate state (the KV cache) and skip recomputing the prefix.
The benefits come in two layers:
- Compute savings: the prefix does not need to be recomputed, so time to first token drops noticeably.
- Billing savings: cached input tokens are charged at a fraction of the normal rate, and only the uncached portion is billed at the standard input price.
Importantly, cache hits are not an always-on switch. They depend on several engineering conditions:
- The prefix must be byte-for-byte stable. Any change (a timestamp, a random ID, the order of retrieval results, the order of the tool list) changes the prefix hash and invalidates the cache.
- Caches have a minimum length threshold and a time-to-live (TTL). Prefixes that are too short are usually not cached, and a cache is reclaimed after being idle beyond its TTL.
- The request must explicitly express caching intent. Some APIs mark cacheable content with a structured field; others enable it through a specific request header or parameter.
- When requests pass through an intermediate routing layer, those markers and headers must be forwarded. Otherwise, caching support is silently dropped along the chain.
Point 4 is the focus of this article and the failure cause most often overlooked in practice.
3. A Typical Failure Pattern: The Chain Works, but Caching Does Not
A representative symptom: you call a closed-source model through an aggregation gateway. Connectivity is fine, the model responds normally, and everything works, yet billing is always based on the full input with no sign of any caching discount. Checking the request logs line by line shows that the input token count of each turn matches the context length exactly, and the cost equals “input price × full input + output price × output.”
It is easy to head in the wrong direction here and focus on the gateway’s “routing strategy,” for example changing the provider preference in your account settings from the default to “prefer lowest price.” That kind of setting affects backend provider selection and queuing, and has nothing to do with forwarding cache markers, so the bill does not change at all. This is a classic case of misreading what a configuration option actually controls: it looks cost-related but acts on a completely different dimension.
The correct troubleshooting order is bottom-up, verifying one layer at a time:
Layer 1: Does the model side support prompt caching? (capability check)Layer 2: Do the request body/headers carry the cache markers correctly? (construction check)Layer 3: Does the intermediate gateway forward those markers? (chain check)Layer 4: Does the response return cache hit statistics? (result check)
Only when Layer 4 shows “cache read tokens greater than 0” can you prove the chain is actually working. If any of the first three layers is broken, the symptom is always the same: everything functions, but the cost does not go down.
4. The General Solution: Getting Cache Markers Through the Entire Call Chain
Staying neutral and not tied to any specific product, the reusable approach has four steps.
4.1 Standardize the Protocol to Avoid Losing Information
Aggregation gateways usually support multiple protocol styles at once (the OpenAI-style chat/completions structure and various vendors’ native Messages structures). These protocols express “cacheable content” differently: native structures generally declare cache breakpoints with an explicit marker on a content block, while OpenAI-style structures rely more on request headers or extension parameters.
The practical recommendation is to use the protocol that aligns most closely with the model’s native capabilities, so extension fields are not lost during protocol conversion. If you must use a compatibility protocol, confirm that the gateway’s conversion implementation covers the cache-related fields.
An illustrative request structure (pseudocode that only conveys the semantics of “marking a cache breakpoint”):
{"model": "<model identifier>","messages": [{"role": "system","content": [{"type": "text","text": "<stable system instructions and long-document prefix>","cache_control": { "type": "ephemeral" }}]},{ "role": "user", "content": "<the new question for this turn>" }]}
4.2 Keep the Prefix Strictly Stable
This is the highest-value step, and it costs nothing. In engineering terms:
- Place system instructions, tool/function definitions, and knowledge base snippets at the very front of the request, in a deterministic order.
- Never inject volatile fields such as timestamps, random IDs, or usernames into the prefix.
- In retrieval-augmented scenarios, sort retrieved results deterministically and control where they sit.
- Always place volatile content (the current question, temporary variables) after the prefix.
A simple self-check: send two requests in a row that share the same prefix but have different suffixes, and compare whether the serialized strings are identical in the prefix portion.
4.3 Make the Middle Layer Forward Extension Fields
If you use an aggregation gateway or a self-built proxy, check whether it uses “whitelist forwarding” or “drop by default” for extension fields in the request body and for custom request headers. Dropping by default is a frequent cause of cache misses. For a self-built proxy, a minimal implementation at the forwarding layer looks like this:
CACHE_HEADERS = ("anthropic-beta", "x-cache-policy")def forward(req):body = req.json() # keep the request body as-is, do not strip fieldsheaders = {k: v for k, v in req.headers.items()if k.lower() in CACHE_HEADERS}return upstream.post("/v1/messages", json=body, headers=headers)
The key point: do not “normalize” the request body structure, because that usually wipes out non-standard fields such as cache_control.
4.4 Verify with Data, Not Gut Feeling
The only reliable way to confirm a hit is the usage statistics in the response. Most cache-aware APIs return the number of cache creation and cache read tokens in usage:
"usage": {"input_tokens": 120,"output_tokens": 340,"cache_creation_input_tokens": 18000,"cache_read_input_tokens": 17900}
When cache_read_input_tokens is consistently greater than 0 and that portion is billed at a discounted rate, the chain is complete. If the field is missing or 0, go back through 4.1–4.3 to locate the broken layer.
5. Quantifying the Cost Benefit
Before you have real measurements, a simple model is enough to make a decision:
cost per turn ≈ input price × (uncached input + cached input × discount factor) + output price × output volume
For long-context, multi-turn scenarios, the cached share is usually close to “context length / (context length + new content this turn).” So the more turns and the longer the context, the more obvious the benefit. Conversely, short conversations and low-repetition tasks (such as one-off summarization or single-shot translation) see limited gains and do not justify reworking the call chain.
One caveat: caching adds a very small write overhead and comes with TTL constraints. If the interval between calls is consistently longer than the cache lifetime, the hit rate approaches zero. Batch offline jobs should therefore aggregate requests and send same-prefix requests together.
6. Implementation Checklist and Common Pitfalls
Checklist:
- Confirm whether the model and protocol support caching.
- Fix and front-load the stable prefix, and remove volatile fields.
- Check whether the gateway/proxy forwards cache markers and headers.
- Use the cache read volume in usage as the sole acceptance criterion.
- Build a daily/per-session cost dashboard to track cache hit rate and average cost per turn.
Common pitfalls:
- Treating a routing preference as a caching switch (it affects provider selection, not caching).
- Assuming that “supporting a protocol” means “supporting cache marker forwarding.”
- Looking only at total cost in the logs instead of the token breakdown, which makes the problem impossible to locate.
- Mixing dynamic content into the prefix, so the cache repeatedly misses without you noticing.
- Inferring the benefit for long-context scenarios from the feel of short conversations.
7. Conclusion
The essence of a prompt cache hit is removing “repeated computation” from your cost. Whether it works depends on four things holding at the same time: capability, construction, forwarding, and verification, and the forwarding step is the one most often overlooked. For developers, building the habit of “trusting usage statistics as the source of truth” is more valuable than chasing any single configuration option. In the practice of model services on platforms such as Baidu AI Cloud, the same advice applies: verify the chain with general engineering methods first, then evaluate a specific product’s billing and capability details, so that inference costs stay within a predictable range.
