LLM Cost Optimization: Technical Selection and Practical Strategies for High-Volume API Usage
This article breaks down large language model (LLM) API costs into calculable variables and shows why cache hit pricing, not headline token rates, dominates the bill in long-context engineering workloads. It covers a four-part cost model, capacity estimation formulas, four dimensions for evaluating cost-performance, layered routing and context compression strategies, and a practical checklist for handling price increases. Engineers will learn how to profile their own request patterns, improve prefix cache hit rates, and build a predictable, quality-regressable cost architecture.
1. Reframing the Problem: From “Pick the Strongest Model” to “Pick a Sustainable Model Mix”
For the past two years, developers mostly chose LLMs based on capability leaderboards. Once call volume reached tens of millions of tokens per day, the metrics that actually determined the experience shifted to cost per token, cache hit rate, and rate-limit stability.
The core pattern in the original discussion: in a certain class of coding scenarios, a combination of a “lightweight model + code-specialized model” cost roughly tens of yuan per month while supporting billions of tokens. But once the cache hit price was raised several times over, the same budget supported only about one fifth of the usage.
The real lesson here is not the price of any particular plan, but a general rule: in engineering scenarios with long contexts and highly repetitive prefixes, the dominant variable in the bill is the cache hit price, not the model’s nominal unit price. Cost-performance evaluation must therefore be built on your own request profile, not on someone else’s recommendation.
2. Cost Model: Breaking the Bill into Calculable Variables
A single request’s billed volume typically consists of four parts: uncached input, cached input, output, and — on some platforms — separately billed thinking/reasoning tokens. It can be written as:
cost per request = Pin × Cin + Ph × Ch + Pout × Coutmonthly cost = QPS × 86400 × 30 × cost per request
Here Ch is mainly determined by “stable prefix length / total input length.” Common stable prefixes in practice include system prompts, tool definitions, repository skeletons, and long document bodies. If this portion exceeds 70%, doubling the cache price can raise the overall bill by more than 50% — which explains why phenomena like “usage shrank to one fifth after the price increase” cluster in AI coding tool scenarios, while chat Q&A scenarios barely notice.
Illustrative request structure (pseudocode):
SYSTEM_PROMPT = load_repo_rules() # stable, cacheableTOOL_SCHEMA = load_tool_schema() # stable, cacheabledef build_request(user_msg, ctx):# Put the stable prefix first to maximize cache hitsreturn [{"role": "system", "content": SYSTEM_PROMPT + TOOL_SCHEMA},{"role": "system", "content": ctx}, # variable part goes last{"role": "user", "content": user_msg},]
3. Four Dimensions for Evaluating Cost-Performance
- Effective cost, not list price: measure cost per “completed mergeable code change” rather than comparing price per million tokens.
- Cache friendliness: whether prefix caching is supported, the minimum length threshold for caching, and whether the invalidation policy matches how you organize context.
- Throughput and rate limits: low-price plans often trade off concurrency and requests per minute; confirm whether 429s and queuing occur.
- Operability: whether usage details, logging services, and monitoring alerts are available, and whether costs can be tagged and split by project or environment; enterprise scenarios also need to check whether invoicing and compliance processes meet finance requirements.
4. Capacity Estimation: Turning “How Many Tokens Can I Run” into a Formula
Given monthly budget B, output ratio r, average input length L, and cache hit rate h, the approximate number of supported requests is:
N ≈ B / ( L × (h·Ph + (1-h)·Pin) + r'·Pout )
Example: budget of 68 yuan, average input of 20k tokens, hit rate of 0.8, output ratio of 10%. When the cached input price is 0.02 yuan per million tokens, this supports roughly 6 to 7 billion tokens; if the cache price rises to 0.1 yuan per million tokens, the same budget drops to about 1.5 billion tokens. The conclusion is straightforward: do prefix governance first, then talk about model selection. The gain from raising the hit rate from 0.5 to 0.85 usually exceeds switching to a cheaper model.
5. Mix and Routing Strategies
- Layered routing: route intent recognition, formatting, and unit test generation to the lightweight model; route cross-file refactoring and complex defect localization to the code-specialized model. Rules or a small classification model can implement this, typically covering over 60% of requests.
- Context compression: replace full paste with retrieval-based context, combined with summary caching, to compress
Lto under 5k. - Streaming and batching: use streaming output on interactive paths to reduce perceived latency; send offline tasks (batch test backfilling, comment generation) through asynchronous batch processing to improve throughput per unit cost.
- Fallback chain: automatically switch to a backup model when the primary model is rate-limited or its price rises, and tag degraded results for quality traceability.
routing:- match: intent in ["format", "docstring", "unit_test"]model: light- match: files_changed > 3model: code_specializedfallback: [code_specialized, light]
6. A Checklist for Handling Price Increases
- Re-collect one week of real request profiling (input length distribution, hit rate, output ratio) and replace all estimates based on list prices.
- Deduplicate and templatize stable prefixes, make hit rate a core monitoring metric, and configure alerts.
- Design the budget in two layers — “base plan + elastic usage” — to avoid binding to a single option; also evaluate the break-even point between pay-as-you-go and annual/monthly commitments under the same load.
- Build a quality baseline regression set; run regression before any model or price change to prevent cost reductions from being accompanied by quality collapse.
- Confirm invoicing and settlement methods with finance in advance to avoid rework in technical selection due to process issues.
7. Conclusion
LLM cost-performance is not a static leaderboard, but a function of “request profile × cache strategy × routing design.” In an environment where price fluctuations have become the norm, engineering the cost model, capacity formulas, and fallback chains is what makes budgets predictable and quality regressable. For finer-grained usage attribution, elastic scaling, and cost dashboards, you can build your own observable system decoupled from the business by combining general capabilities such as container platforms, logging services, and monitoring alerts offered by Baidu AI Cloud.
