A Practical Guide to LLM API Cost Optimization
Learn how LLM API pricing structures affect your bill and how to reduce costs through prefix caching, context compression, output length control, and model routing.
1. Where the Problem Starts: Model Upgrades Change the Cost Structure, Not Just the Price
During a typical generational model update, providers often adjust two things at once: the capability ceiling and the billing unit price. Take a recent general-purpose LLM series as an example. Its high-capability tier saw input and output unit prices drop by roughly 20% compared with the previous generation, while the cached-input price fell by as much as 60%. The three prices land in the ranges of $8, $0.1, and $40 per million tokens. The lightweight tier, meanwhile, keeps the previous generation’s pricing: $2 for input, $0.1 for cached input, and $10 for output per million tokens.
For developers, what matters is not “how much did the price drop” but three structural facts:
- The output token price is usually several times the input price (about 5x in the example above), which means generation length is the dominant variable on the bill.
- Cached input is priced separately and significantly lower, which turns “repeated context” from waste into an optimization target.
- There is roughly a 4x unit price gap between the high-capability and lightweight tiers, which gives routing and tiered calls clear economic value.
2. Get the Billing Model Right First: The Boundaries of the Three Token Types
Most platforms’ billing can be abstracted into three categories:
- Regular input tokens: context that newly appears in this request and does not hit the cache;
- Cached input tokens: the portion of context that hits the prefix cache and is reused;
- Output tokens: the content generated by the model.
This yields an approximation that is handy for engineering estimates:
cost per call ≈ input price × uncached input volume+ cache price × cached input volume+ output price × generation length
This formula explains a common counterintuitive phenomenon: stuffing an entire long document into the prompt at once can still cost more per call than a “retrieve first, then feed snippets” approach, even with a high hit rate, because the output side and the uncached portion still add up. The first principle of cost optimization is therefore: do not optimize the unit price first; optimize where the tokens flow.
3. Four Actionable Optimization Levers
1. Stabilize the prefix to improve cache hits
Cache reuse generally depends on an exact prefix match. Moving volatile content such as timestamps, random IDs, and user nicknames out of the system prompt and placing it at the end of the conversation or in structured fields can significantly improve the hit rate.
# Bad example: the prefix changes every time, so the cache can hardly ever hitSystem prompt: current time 2026-08-12 03:21:07, user ID u_88213 ...# Recommended: static prefix + dynamic tailSystem prompt: <stable role setup, rules, output format>Dynamic section: {"ts": "...", "uid": "..."}
2. Compress context and move retrieval forward
Replace “stuff everything in” with “retrieved snippets + summary + structured citations.” In engineering, you can use a fixed budget to control context length, for example reserving no more than 40% of the total budget for retrieved snippets and leaving the rest for instructions and output. This both reduces the uncached input volume and cuts quality fluctuations caused by attention dilution.
3. Govern output length
Since the output unit price is the highest, generation length should be constrained explicitly: limit structured output fields, set a maximum token cap, and split “explanatory long text” into “conclusion + on-demand follow-up.” A practical rule of thumb: if the median output length for a certain task type exceeds the input length, prioritize compression on that task rather than negotiating the unit price.
4. Tiered routing
Group requests by difficulty: simple classification, extraction, and format conversion go to the lightweight tier, while complex reasoning and long-chain planning go to the high-capability tier. The routing signals can be very simple:
def route(task):if task.kind in {"classify", "extract", "format"}:return "light" # lightweight tier, unit price about 1/4 of the high-capability tierif task.chain_steps > 3 or task.requires_reasoning:return "pro" # high-capability tierreturn "light"
4. Turn Cost into an Observable Metric
Without measurement there is no optimization. It is advisable to collect at least four dimensions: cost per business action (per ticket/per article), cache hit rate, average output length, and the call share of each tier. You can build a dashboard with monitoring, alerting, and logging services, and set a threshold alert for the cache hit rate—a sudden drop in the hit rate often means the prefix was changed unexpectedly, not that traffic rose.
Architecturally, you can use a message queue to smooth peaks, object storage to archive long texts and call details, and a container platform to host the routing and caching layers, making cost governance a platform capability rather than a script patch.
5. Common Pitfalls
- Looking only at unit price and not at structure: a 20% price drop can still raise the bill if output length doubles;
- Treating the cache as a default capability: cache hits depend on strict prefix consistency and platform-side policies, and need to be verified in practice;
- Switching everything to the high-capability tier: the 4x unit price gap gets amplified into a major cost item under heavy traffic;
- Ignoring failed retries: retries amplify both input and output costs, so backoff and caps should be set.
6. Conclusion
The real dividend of a generational update comes from the optimization space opened up together by “cheaper caching + tier separation.” If you get the four things right—token flow, output length, routing strategy, and observable metrics—there is usually still considerable room to reduce the cost per business action. If you need to support multiple model types and multiple billing tiers in a unified way, you can build the routing, caching, and monitoring system on top of the general cloud product capabilities of Baidu AI Cloud, turning cost control into a sustainable engineering practice.
