LLM Cost Optimization: Technical Selection and Practical Strategies for Reducing API Spending
This article explains why comparing per-token prices is not enough when LLM API costs change, and how to design a cost structure that serves more effective calls within the same budget. It presents a practical cost formula covering input/output token ratios, cache hit rates, context length, and retries, followed by four adjustable levers: improving prefix cache hit rates through prompt layering, controlling context length, governing the input-output ratio, and routing requests by difficulty with fallback limits. A reusable budget estimation and alerting workflow is included, along with two enterprise constraints around invoicing/compliance and observability. The conclusion emphasizes that while price changes are outside your control, cost structure is not.
1. Reframing the Problem: From “Which Model” to “How to Design the Cost Structure”
The core of the discussion is not the merits of a specific model, but a broader engineering problem: when upstream inference pricing and cache billing rules change, a setup that was once “cheap enough to call freely” can quickly stop working, and the monthly call volume it can support may shrink by several times. The real question therefore becomes: how can you serve more effective calls per unit of budget without sacrificing quality?
Start with one basic point: an LLM bill is not a single “price per thousand tokens.” It is determined by at least four variables:
- The ratio of input tokens to output tokens;
- The proportion of cache-hit versus cache-miss input;
- The average context length per request;
- Extra consumption from failed retries, rate-limit waiting, and overly long contexts.
Any selection based only on unit price will fail after real load testing.
2. Cost Model: Writing the Bill as a Computable Formula
A sufficiently engineering-oriented approximation is:
Cost per request =uncached input tokens × uncached unit price+ cached input tokens × cached unit price+ output tokens × output unit price+ retry count × cost per request
The monthly call volume a budget can support is then:
Supported calls ≈ monthly budget / cost per request
Substituting a several-fold increase in the cached unit price makes the conclusion clear: if the cached portion originally made up a large share, the overall cost per request is amplified to nearly several times, and the supported call volume drops proportionally. This matches the magnitude described in the original scenario, where capacity fell from a high level to roughly one fifth. The key takeaway is that the cache hit rate is a multiplier: its leverage on total cost is far greater than small fluctuations in unit price.
3. Four Adjustable Levers
3.1 Improve the Cache Hit Rate
Caching typically works by prefix matching, so the earlier parts of a prompt should stay as stable as possible. In practice, split content into three layers:
[Stable layer] System role, output format constraints, glossary, long-term knowledge snippets[Semi-stable layer] Project conventions, directory structure notes, common interface signatures[Volatile layer] Current user question, latest file content, timestamps, etc.
If volatile content such as timestamps, random IDs, or the current path is placed at the front, the entire prefix is invalidated and the hit rate approaches zero. This is the most common and most easily overlooked cause of cost overruns.
3.2 Control Context Length
Context length scales cost linearly. Engineering practice should do three things: rerank and truncate retrieval results, summarize and compress conversation history, and trim fields from tool return values. Illustrative logic:
def build_prompt(system, retrieved, history, query, budget=8000):fixed = system # Stable layer, kept firstctx = compress(history, ratio=0.3) # Summarize historyctx += rerank_and_truncate(retrieved, limit=budget - len(fixed) - len(query))return fixed + ctx + query # Volatile content goes last
3.3 Govern the Input-Output Ratio
Output tokens are usually significantly more expensive than input tokens. Asking the model to “think first and then produce long output” can multiply the bill. Practical measures: constrain the output structure, cap the maximum length, split long-form generation into incremental multi-turn output, and use a smaller model tier for non-critical scenarios.
3.4 Routing and Fallback
Layering requests by difficulty is the core of cost-efficiency design:
Intent classification / format conversion / field extraction -> small model or rules engineRoutine code completion and rewriting -> mid-tier general modelComplex reasoning and long-chain refactoring -> high-capability model
Also set timeouts, retry limits, and circuit breakers so that ineffective retries during rate limiting do not burn through the budget.
4. A Reusable Budget Estimation Workflow
- Sample one week of real traffic and measure the input/output token distribution and cache hit ratio;
- Plug the numbers into the cost formula to get the current cost per request and monthly supported volume;
- Run a sensitivity analysis, observing the result when the cached unit price and the output unit price each double;
- Set a budget red line and alert thresholds, and aggregate usage by project rather than by account;
- Review the routing strategy and prompt layering structure once a month.
The illustrative code below gives a minimal working cost estimate and alert check:
def estimate(uncached_in, cached_in, out, price, retries=0):unit = price["uncached_in"] * uncached_inunit += price["cached_in"] * cached_inunit += price["out"] * outreturn unit * (1 + retries)def guard(month_cost, budget, warn=0.8):return "ok" if month_cost < budget * warn else "throttle"
5. Two Additional Constraints in Enterprise Scenarios
The first is invoicing and compliance. Enterprise procurement requires corporate settlement and compliant invoices. This is a procurement process issue and should be confirmed during selection, not patched after the bill arrives. The second is observability. Without a usage view broken down by business line, no optimization can be validated. Collect at least five metrics: call count, token distribution, cache hit rate, failure rate, and cost per request, and connect them to a unified logging, monitoring, and alerting system.
6. Conclusion
Price changes themselves are out of your control; the cost structure is not. Layer prompts to stabilize cache hits, compress context, govern output length, and build tiered routing, then combine this with budget estimation and usage observability. That lets you quickly rebuild cost efficiency after upstream billing rules change. For integrated LLM development and application support, you can look at the general model services and engineering capabilities offered by the Baidu AI Cloud Qianfan model platform, but the sound selection path is to load-test against your own traffic characteristics before choosing a tier.
