LLM Prompt Caching: A Practical Guide to Cutting API Costs by 90%
This article explains how prompt caching reduces LLM inference costs in enterprise applications, where repeated long prefixes—system instructions, tool definitions, few-shot examples, and knowledge base documents—are billed on every request. It covers three caching patterns (automatic, explicit, and hybrid), why strict prefix matching makes content ordering critical, how to verify savings using token usage fields, and how to manage cache lifecycles with TTL renewal and fallback strategies. Readers will find a cost estimation example, a deployment checklist, and guidance on building cache observability.
1. Why API Costs Become a Bottleneck
In enterprise LLM applications, the cost structure often has a counterintuitive feature: the expensive part is not generation, but repeated input. Scenarios such as customer service bots, coding assistants, document Q&A, and structured extraction send large, highly similar prefixes with every request—system instructions, tool definitions, few-shot examples, knowledge base fragments, and long document bodies. These tokens are billed again on every call, while the model’s “re-reading” of them produces no new information gain.
This points to a clear optimization direction: if a piece of input is identical across multiple requests, its computation result can be reused. This is exactly what prompt caching solves, and it is now widely supported by mainstream LLM services. Understanding how it works can typically compress input costs for long-prefix scenarios to one-tenth or one-fifth of the original, so a 90% reduction in the overall bill is not an exaggeration.
2. Three Types of Caching
1. Automatic Caching: Zero Changes, but Bound by Lifecycle
Some platforms enable prefix caching by default for specific models, so developers do not need to pass any parameters. The hit condition is usually that the very first part of the request (the token sequence) exactly matches a recent request.
- Advantage: zero integration cost; existing code needs no changes.
- Discount: the input cost for the cached portion is typically half to one-quarter of the original price.
- Pitfall: cache entries live for a very short time, usually only a few minutes to a dozen or so minutes. Low-frequency scenarios where users “use it once and leave” can hardly hit the cache.
2. Explicit Caching: Largest Discount, Requires Active Management
Another type of platform requires you to explicitly create a cache object and then reference it when making inference requests.
- Discount: the cached portion can cost as little as 10% of the original price, the strongest of all options.
- Cost: the initial write usually carries an extra premium (commonly around 1.25x the base input price), and the default survival window is short (often on the order of 5 minutes), so it must be rewritten after expiry.
- Suitable for: online services with stable prefixes, dense calls, and high QPS.
3. Hybrid Strategy: Tiering by Traffic
The optimal production solution is often not a binary choice, but tiering requests by “prefix reuse intensity”: high-frequency fixed prefixes go through explicit caching, long-tail requests go through automatic caching, and scenarios where the prefix changes frequently should actively shrink the cacheable prefix.
3. Hit Determination: Why “Prefix” Is the Keyword
Cache matching is strict prefix matching, not semantic similarity matching. This means that starting from the first token, any single difference will cause everything after it to miss. The most common “invisible failures” in engineering include:
- Concatenating the current timestamp, a random ID, or a username into the system prompt;
- Placing retrieved documents before the system instructions;
- Unstable ordering of the tool definition array;
- Inserting historical messages ahead of the long document in multi-turn conversations.
The correct ordering design is: stable content first, volatile content last.
[System instructions] → [Tool/parameter definitions] → [few-shot examples] → [Knowledge base long document] → [Current user input]Stable Volatile
4. Observability: Verify Real Savings with Token Fields
Do not estimate from the bill; verify against the usage fields in the response. Common field semantics usually include:
cache_creation_input_tokens: the number of tokens consumed writing to the cache this time;cached_tokens/cache_read_input_tokens: the number of tokens read from a cache hit this time.
It is recommended to log these two fields together with the request ID and prefix version number into a logging service, forming a “cache hit rate” dashboard. If the hit rate stays below expectations over time, investigate prefix drift first rather than doubting the platform’s capability.
def log_usage(resp, prefix_version):u = resp.usagecreated = getattr(u, "cache_creation_input_tokens", 0)hit = getattr(u, "cached_tokens", 0)total = u.prompt_tokenslogger.info({"prefix_version": prefix_version,"hit_rate": round(hit / max(total, 1), 3),"created": created,"total": total,})
5. Lifecycle Management: TTL and Renewal
The survival window of explicit caching is limited and needs active maintenance:
- Scheduled refresh: send a minimal request at a fixed interval within the TTL to “keep the entry alive”;
- Versioned prefixes: increment the version number when prefix content changes, avoiding a large number of invalid writes caused by mixing old and new;
- Hot-cold separation: write stable prefixes to object storage with a content hash, so the cache can be rebuilt quickly on cold start;
- Fallback path: automatically fall back to normal calls when the cache is unavailable, prioritizing availability.
6. How to Estimate Costs Correctly
Suppose the long prefix is 8,000 tokens, with 100,000 requests per day, the cached portion billed at 10% of the original price, and a 25% write premium. Under stable cache hits, input costs can drop by about 85%–90%. The key is that the number of “writes” must be far smaller than the number of “reads”, so the metric to evaluate should be the cache reuse ratio (reads / writes), not the single-call discount.
7. Deployment Checklist
- Has the prefix been reordered by “stable → volatile”?
- Have timestamps and random values been removed from the system prompt?
- Is usage field collection and hit rate alerting enabled?
- Are renewal and expiry fallback set for the cache?
- Is prefix isolation implemented for multi-tenant scenarios to avoid data cross-use risk?
8. Conclusion
Caching is not a marketing feature of a particular platform, but a general engineering capability of LLM inference services. Design it as a “storage layer”—with versioning, TTL, hit rate monitoring, and a fallback plan—and cost reduction turns from a one-time parameter tweak into sustainable cost governance. If an enterprise wants to implement a similar solution on Baidu AI Cloud, it can combine a general logging service with monitoring and alerting to build a complete cache observability system.
