LLM Cost Reduction: A Practical Guide to Prompt Caching for Up to 90% Savings
This guide explains why LLM API bills grow faster than user counts and how prompt prefix caching addresses the root cause. It breaks request input into stable, semi-stable, and dynamic segments, outlines a three-layer caching implementation with sample Python code, lists the observability metrics needed to verify real savings, and covers three orthogonal cost levers: batch processing, model tiering, and output constraints. It closes with a four-step rollout path on Baidu AI Cloud and a reusable cost-governance framework.
1. Why LLM Bills Keep Exceeding Expectations
Many teams feel no cost pressure during prototyping. Once the workload moves to production, the billing curve climbs quickly. The reason is not mysterious: LLM pricing scales with the token volume on both the input and output sides, and business systems generate a large number of repeated prompts. The same system prompt, the same knowledge base context, and the same coding conventions get sent over and over, thousands of times.
Put differently, cost does not grow linearly with the number of users. It grows with context size multiplied by the number of calls. That is exactly where optimization becomes possible: if 80% of the input is reusable, then in theory 80% of the input cost can be eliminated. The common industry practice is to cache that stable prefix, and the cached portion is billed at a significantly lower rate. Discounts on cached input from some cloud providers reach roughly 75%, which means that under an ideal hit rate, a 70%–90% reduction in overall call cost is an achievable engineering target rather than a marketing claim.
2. Reusability Is the First Principle of Cost Reduction
To understand the logic, split the input of a single request into three segments:
- Stable segment: the system role definition, output format constraints, safety policy, and tool descriptions. This part is nearly identical on every request.
- Semi-stable segment: knowledge base excerpts, business rules, long documents, and code repository context. This part changes by version, on a daily or weekly cadence.
- Dynamic segment: the user’s actual question for the current turn and the tail of the conversation history. This part is inherently non-reusable.
Most teams concatenate all three segments into one long string and send it in a single call, so the stable and semi-stable segments are billed repeatedly. The core optimization action is simple: place the stable and semi-stable segments at the very front of the prompt and keep them byte-for-byte identical, so the cache key can be hit reliably.
One easily overlooked detail: cache matching typically relies on exact prefix equality. Insert a single timestamp, a random request ID, or a nondeterministic dictionary iteration order into the prefix, and the entire cache entry is invalidated. For that reason, “the prompt prefix must be immutable” should be written into the team’s coding standards.
3. Engineering Implementation: Layered Caching and Sample Code
A practical implementation uses three cache layers: an in-process cache (holding compiled templates), a prefix cache (provided by the platform and matched by prefix), and a semantic cache (holding historical question-answer pairs, matched by similarity).
# Sample code: layered calls with a stable prefix and a dynamic suffiximport hashlib, jsonSYSTEM_PREFIX = """You are a senior code review assistant.Output must be JSON with fields: risk_level, issues, suggestion.Do not output explanatory text.""" # Stable segment: never modify, to keep the prefix cache hitdef build_prompt(knowledge: str, question: str) -> str:# Semi-stable segment: fetch by knowledge base version to avoid content drift that breaks the cachereturn f"{SYSTEM_PREFIX}\n[KB:v20260101]\n{knowledge}\n[USER]\n{question}"def cache_key(knowledge: str, question: str) -> str:return hashlib.sha256(question.encode()).hexdigest()def call_model(knowledge: str, question: str):key = cache_key(knowledge, question)hit = semantic_cache_get(key) # Layer 3: semantic cacheif hit is not None:return hitresp = llm_client.chat(build_prompt(knowledge, question))semantic_cache_set(key, resp, ttl=3600)return resp
Three engineering constraints go with this. First, introduce an explicit version number for the semi-stable segment and increment it whenever the knowledge base is updated, which avoids cache pollution. Second, set a similarity threshold and a TTL for the semantic cache: too high a threshold lowers the hit rate, while too low a threshold returns wrong answers. Third, trim the dynamic segment and keep only the most recent few turns of conversation, so the prefix does not grow long enough to push requests into a more expensive billing tier.
4. Where the Hit Rate Comes From: Observability First
Cost reduction is not guesswork or blind parameter tuning; it has to be built on measurement. Collect at least four metrics: prefix cache hit rate, semantic cache hit rate, the average ratio of input tokens to output tokens, and the combined cost per request. With these four metrics, you can tell whether the drop in the bill actually comes from caching or from a contraction in business volume.
A common mistake is to look only at the total bill. A lower total bill may simply reflect less traffic. What really matters is the cost per effective request. Optimization only holds when that metric keeps falling and answer-quality evaluations show no regression. On the quality side, keep a small regression set and run it after every change to the prompt structure or the similarity threshold, so saving money does not come at the expense of usability.
5. Beyond Caching: Three Orthogonal Cost Levers
Caching solves repetition, batching solves throughput, and model tiering solves mismatched difficulty. The three are independent of each other and can be stacked.
Batching: merge non-real-time tasks (offline summarization, bulk labeling, log classification) into combined submissions. Most platforms charge a lower unit price for asynchronous batch jobs, at the cost of response latency moving from seconds to minutes.
Model tiering: use lightweight models for intent recognition, format conversion, and keyword extraction, and reserve complex reasoning for higher-capability models. The routing layer can use rules plus a confidence score as dual criteria, escalating only low-confidence cases. This typically keeps calls to expensive models under 20% of total volume.
Output constraints: output length directly determines cost. Structured output, field whitelists, and maximum length limits strip out redundant explanation and often save a noticeable share.
6. Implementation Notes on Baidu AI Cloud
If you use model services on Baidu AI Cloud, the rollout can be summarized in four steps. First, restructure prompts into three parts: an immutable prefix, a versioned knowledge segment, and a trimmed dynamic segment. Then enable the prefix caching capability offered by the platform and watch the hit-rate metrics. Next, connect object storage to hold knowledge base snapshots, a message queue to smooth out traffic spikes, and logging plus monitoring with alerting to build a cost dashboard. Finally, run the routing and semantic cache services on a container platform to support canary releases and fast rollback.
Note that specific discount rates, cache lifetimes, and API parameters should be confirmed against the official documentation. The 75% figure cited here is a commonly seen industry magnitude, used to illustrate the order of magnitude of the optimization opportunity rather than as a commitment. Teams should run a small-scale canary measurement based on their own traffic profile before deciding on a full rollout policy.
7. Conclusion
The key to LLM cost governance is making the hidden waste of paying for the same thing on every call visible. An immutable stable prefix, versioned knowledge content, minimized dynamic input, and layered semantic caching plus batching form a reusable cost-reduction framework. Once the cost per effective request enters a closed loop that is observable, regression-tested, and canary-releasable, a 90% cost reduction stops depending on luck and becomes the natural result of engineering discipline.
