Prompt Caching for LLMs: A Practical Guide to Cutting API Costs
This guide explains how prompt caching reduces LLM API costs by reusing stable request prefixes instead of paying for them on every call. It covers how prefix-based caching works, its TTL and write-premium constraints, a break-even cost model with a Python estimation example, observability metrics such as cache read and write tokens, engineering techniques for improving hit rates, and which workloads benefit or not. It also outlines how to build caching as an application-side capability on Baidu AI Cloud.
1. Why API Costs Get Out of Control
After integrating large language model capabilities into a business system, the cost structure often exceeds expectations faster than anticipated. The reason is straightforward: most application requests are not independent, one-off questions. They repeatedly call the model around the same relatively stable context—system prompts, tool and function definitions, long documents, code repository snippets, knowledge base summaries, and multi-turn conversation history. All of this content is billed again in every request, even though it barely changes.
The real bill can be abstracted as:
Total cost ≈ output cost per request + input cost per request × number of requestswhere input cost = stable context length + the incremental part that changes each time
When the stable context makes up a large share and the request volume is high, cost is almost proportional to “context length × QPS.” This is the mathematical root of runaway costs, and the core problem that prompt caching is designed to solve.
2. How Prompt Caching Works
The basic idea of prompt caching is to “write” the unchanged portion of a request prefix once, then read it back at a discounted price on subsequent hits, while billing only the new incremental portion at the standard rate.
The token structure of a typical call can be split into three segments:
[ Cacheable prefix: system prompt / tool definitions / long documents ] -> cache hit, discounted billing[ Incremental context: new content added this turn ] -> standard-rate billing[ Output content ] -> output-rate billing
There are three engineering constraints you must understand:
- Prefix matching is strictly sequential. The cache is keyed on the request prefix, and any change anywhere in the prefix invalidates everything after it. This makes placing volatile content (timestamps, random IDs, usernames) at the end of the prompt the first determining factor for hit rate.
- Caches have a time to live (TTL). A common industry practice is to offer two tiers: short-lived caching (minute-level) and longer-lived caching (hour-level). If a cache is not hit within its TTL, it expires automatically and must be written again.
- Writing usually carries a premium. Tokens used to create a cache are billed at a ratio higher than the standard input price (the 25% write premium mentioned in the original text is a common industry magnitude), while the read portion that hits is billed at a discount off the standard price (around 10% is a more aggressive and also fairly common tier).
3. Cost Model: When You Actually Save Money
Let the standard input unit price be 1, the write premium be w (e.g., 0.25), the hit discount be d (e.g., 0.1), and the total number of calls within the cache lifetime be N. Then:
Without caching: C0 = NWith caching: C1 = w + (N - 1) × dBreak-even point: N* = (1 - w) / (1 - d) ≈ 0.83
The conclusion is counterintuitive: when the discount is low enough, even reusing the cache just once within its lifetime is already close to break-even. Reusing it 5 times brings cost to about 0.65, and reusing it 10 times brings it to about 0.15—the “save 90%” magnitude mentioned in the original text. The real risk is not the unit price, but whether N is actually greater than 1. If the prefix differs on every request, caching not only fails to save money but also adds the write premium on top.
So you must estimate the hit rate before deployment:
# Illustration: estimate caching savings; parameters must follow the actual billing documentationdef estimate_cost(n_calls, std=1.0, write_premium=0.25, hit_discount=0.1):no_cache = n_calls * stdwith_cache = write_premium + (n_calls - 1) * hit_discountreturn {"no_cache": no_cache, "with_cache": with_cache,"saving": 1 - with_cache / no_cache}
4. Transparency: Observability Sets the Ceiling for Optimization
Approaches differ markedly in “whether they tell you what the cache is doing.” The more friendly approach returns two metrics directly in the response—the number of cache write tokens and the number of cache read tokens—making the bill attributable and verifiable through regression testing. Regardless of which approach you use, it is recommended to build your own observability layer:
- Collect the write tokens, read tokens, missed tokens, and total latency for each request;
- Compute hit rate = read tokens / (read tokens + write tokens + missed tokens);
- Monitor and alert on hit rate, cache invalidation counts, and end-to-end latency to surface anomalous prefix changes.
Without these metrics, cost reduction is just guesswork; with them, optimization has a closed loop.
5. Engineering Practice: Concrete Ways to Improve Hit Rate
- Layer your prompts. Split content into a “highly stable layer (role and rules)—moderately stable layer (tool definitions, knowledge snippets)—volatile layer (user input, timestamps).” The order cannot be reversed.
- Serialize stably. Standardize JSON key order, array order, whitespace, and line breaks to avoid prefix mismatches caused by serialization differences.
- Batch and merge requests. Aggregate scattered calls into batches to raise the reuse count within a unit of time, offsetting the expiration loss from minute-level TTLs.
- Align TTL with your business rhythm. High-frequency interactive scenarios can use a short TTL; offline batch processing and scheduled jobs are more cost-effective with a long TTL.
- Use gradual rollout and rollback. Caching is a “behavior-sensitive” optimization, so keep a switch to disable it and proactively invalidate it when the prefix template changes.
Request assembly pseudocodesystem_rules(stable) + tool_schema(stable) + retrieved_docs(moderately stable)↓ cache hit, discounted billing+ session_delta(volatile) + user_query(volatile)↓ standard-rate billing→ call → record write/read tokens → report to monitoring
6. Suitable and Unsuitable Scenarios
Suitable: customer service and assistants with long system prompts, function calling with a fixed tool set, code-completion-style intelligent programming tools, repeated Q&A over long documents, and multi-turn conversations with long history.
Unsuitable: extraction tasks where the context is completely different on every request, scenarios where the prefix contains random or time-based factors that cannot be moved to the end, one-off tasks with extremely low call frequency, and pipelines that are insensitive to cost but extremely sensitive to time-to-first-token and cannot accept the cache write overhead.
7. Practical Recommendations on Baidu AI Cloud
Within Baidu AI Cloud’s large model services and general cloud product portfolio, you can build prompt caching as an application-side capability: use cache hit rate and token structure metrics to feed into logging services and monitoring alerts, use object storage or file storage to hold stable context such as long documents, use a message queue to aggregate requests and raise the reuse count, and use a container platform to host a stateless prompt-assembly service. For specific billing ratios, TTL tiers, and response fields, refer to the official documentation, and do not reuse empirical numbers from elsewhere to build your budget directly.
8. Conclusion
Prompt caching is not about “switching to a cheaper model.” It removes the structural waste of being billed repeatedly for the same content. Its benefit is determined by hit rate rather than discount, and its risk is determined by prefix stability and TTL. First make prompt layering and serialization clean, then connect the write/read token metrics to monitoring, and finally use the break-even formula to work out your budget—follow this sequence, and a one-order-of-magnitude reduction in call costs for high-frequency, repeated-context scenarios is a reasonable expectation.
