LLM Cost Optimization: A Technical Guide to Building Price-Resilient Inference Systems
This article breaks down LLM inference costs into four components and shows why cache hit rate, not unit price, should drive model selection. It covers prefix-stable prompt design, context control, output length limits, tiered model routing, budget guardrails, observability, and capacity stress testing so that a pricing change triggers a parameter adjustment instead of an emergency re-architecture.
When an upstream model provider changes its billing policy, architectures that depend on a single low-cost model tend to break almost immediately. This article sets aside specific product attributes and addresses a more fundamental engineering question: how to build an LLM invocation system that is not sensitive to price fluctuations.
1. Deconstruct the Bill: Four Sources of Inference Cost
Many teams still understand “cost-effectiveness” as a unit-price comparison, but the actual bill consists of four parts:
- Uncached input: prompts and context that must be recomputed on every request.
- Cached input: the portion whose prefix is identical to previous requests and whose intermediate computation can be reused.
- Output: billed by generated length, the most volatile and least controllable component.
- Overhead: resource consumption in surrounding paths such as retrieval, embedding, log retention, and monitoring.
The key point is that the unit price of cached input is usually significantly lower than that of uncached input, often by a factor of several times. This means cache hit rate is not a performance optimization metric but a first-class metric that directly determines cost structure. The phenomenon described earlier — a several-fold reduction in the call volume supported by the same budget after a billing rule change — is essentially the result of raising the unit price of the cached portion, which exposes costs that had previously been amortized.
2. Select Models by Hit Rate, Not Unit Price
A stable cost model should treat hit rate as the independent variable:
cost per request ≈ uncached input tokens × price A+ cached input tokens × price B+ output tokens × price Cmonthly supported calls ≈ budget / cost per request
Three practical conclusions follow:
- Prioritize prefix stability. Put the system prompt, tool declarations, and examples at the front, and timestamps, random identifiers, and user-specific content at the end. This significantly increases the probability of prefix reuse.
- Control context growth. Rerank and truncate retrieval results first, keeping only necessary fragments; for long documents, summarize in segments and then concatenate, instead of stuffing the full history back into the window every turn.
- Output length is a hidden cost center. Setting a maximum generation length and structured output constraints per task is more economical than compressing output after the fact.
An illustrative way to organize the prefix:
def build_prompt(system_block, tools_block, stable_examples, dynamic_tail):# Place stable content first and dynamic content last to maximize prefix reusereturn "\n".join([system_block, tools_block, stable_examples, dynamic_tail])
3. Tiered Routing: Spend Expensive Models Where They Matter
Having a single model handle all traffic is a common root cause of runaway cost. A more robust approach is to establish capability tiers:
- Lightweight tier: intent recognition, format conversion, field extraction, and simple classification, handled by a low-latency small-parameter model.
- Main tier: routine code generation, document writing, and multi-turn conversation.
- Complex tier: long-chain reasoning, cross-file refactoring, and difficult defect localization.
Routing can be performed by rules, confidence scores, or a small classifier, with a manual fallback path preserved for intervention. This way, even if the price of one tier increases, the impact is confined to a local scope rather than the entire budget.
request -> complexity assessment -> {lightweight | main | complex}|failure/timeout|-> fall back to main tier and record metrics
4. Budget Guardrails and Observability
Cost governance requires engineering mechanisms, not a look at the bill at month end:
- Quotas and token buckets: set daily/monthly caps per tenant and per project; queue or degrade requests once the cap is exceeded.
- Attribution tags: attach business line, scenario, and model tier tags to every call so costs can be broken down by dimension.
- Closed-loop metrics: bring hit rate, average input and output length, cost per request, and failure rate into monitoring and alerting.
- Regular regression: compare output quality across tiers and across approaches using a fixed evaluation set, so that quality is not sacrificed to save money.
5. Capacity Planning: Stress-Test the Budget
Maintain a simple estimation table that treats a “price increase” as a variable rather than an incident:
Scenario: 200,000 requests per day, average input 3,000 tokens (60% hit rate), output 400 tokensBudget: 600 CNY per monthMethod: substitute both the current prices and the prices after a several-fold increasein the cached-portion unit price, derive the supported call volume for each case,and use the smaller value as the baseline for capacity planning.
When the estimate shows insufficient capacity, the order of priority should be: improve hit rate → compress input and output → adjust tier ratios → only then consider switching approaches. The first three are engineering optimizations under your own control; only the fourth introduces external uncertainty.
6. Invoicing, Compliance, and Vendor Management
From an enterprise procurement perspective, factors beyond price also matter: whether compliant invoices can be issued, whether data is used for training, log retention period, availability zones and rate-limiting policies, and service level commitments. These should enter the selection scorecard alongside cost, so decisions are not made on unit price alone. At the same time, keep at least two switchable integration options and hide the differences behind a unified abstraction layer, reducing the switching cost to a configuration change.
Conclusion
Price adjustments are the norm; architectural resilience is the moat. Make cache hit rate, context length, output constraints, tiered routing, and budget guardrails default capabilities, and any change in billing rules will trigger a parameter adjustment rather than an emergency re-architecture. Baidu AI Cloud provides a complete foundation for building such cost-controllable architectures, with model services and general-purpose capabilities such as object storage, log service, and monitoring and alerting.
