LLM API Pricing and Inference Cost Optimization: Why Unit Price Is Not the Same as Cost
This article breaks down how token-based LLM pricing actually translates into spend. It covers the four billed token categories (input, output, cache hit, cache write), a minimal cost model you can compute with, task-level cost and effective cost per result (ECR), how to convert subscription plans into a leverage ratio and break-even usage, prefix-cache hit-rate mechanics and how to structure prompts around them, context reduction techniques, difficulty-based model routing, and the observability metrics and budget guardrails needed to keep inference spend under control. Included are working Python snippets for cost estimation and cache savings, a prompt-layout template, a routing configuration example, and an end-to-end vendor evaluation checklist that does not rely on list prices.
Introduction: A Higher Unit Price Is Not a Higher Bill
Discussions about new-generation model pricing usually start with a direct comparison of sticker prices. A new model lists output at 100 RMB per million tokens, input at 20 RMB, and cache hits at 1 RMB — roughly five times the previous generation — so the conclusion is “it got more expensive.”
That conclusion isn’t wrong, but it answers only half the question. Sticker price defines the cost curve per unit token. What businesses actually care about is how much it costs to complete the same batch of work. Between the two sits a whole set of variables: the input-to-output ratio, cache hit rate, the context length each task consumes, the usage leverage of subscription plans, and the hidden amplification from retries and failures.
A more engineering-grounded observation: models priced one to two orders of magnitude below the leading overseas offerings can end up costing roughly the same per completed task, because they consume longer contexts and more reasoning steps per task on average. Conversely, top overseas products that amplify usage to more than twenty times the amount actually paid through subscription plans can beat a nominally cheaper competitor whose leverage is only six to fourteen times. Even with a lower sticker price, cost per unit of effective output ends up higher.
This article takes that reasoning chain and turns it into engineering metrics you can compute, observe, and optimize.
1. The Four Dimensions of Token-Based Pricing
Most mainstream model services meter usage at token granularity, but a bill typically has more than one line item:
- Input tokens: prompts, system instructions, conversation history, tool and function definitions, and retrieved content, added together.
- Output tokens: everything the model generates, including reasoning traces when a thinking mode is enabled. Output is usually priced well above input — commonly three to five times higher — because autoregressive decoding can’t be parallelized effectively, which raises the serving cost per unit of compute.
- Cache hit tokens: when a request’s prefix matches cached content exactly, those tokens are billed at a discounted rate, typically 5% to 10% of the input price.
- Cache write tokens: some implementations charge a slightly higher rate than standard input for tokens written into the cache for the first time, to cover storage overhead.
Understanding how these four interact is the prerequisite for everything that follows. One immediate implication: when the output share is high and cache hit rate is low, sticker price almost linearly determines cost; when the input share is high and cache hit rate is high, the effect of unit price is diluted substantially. The combination of 20 RMB input and 1 RMB cache hits is, in effect, an incentive for long-context reuse patterns.
2. From Unit Price to Task-Level Effective Cost
2.1 A Single-Request Cost Model
Writing the billing items as a function is the first step toward cost governance:
# cost_model.py — a minimal, usable model for estimating inference costfrom dataclasses import dataclass@dataclassclass Price:input_per_mtok: float # input token price (per million tokens)output_per_mtok: float # output token pricecache_hit_per_mtok: float # cache-hit token pricedef estimate(price: Price, in_tok: int, out_tok: int,cached: int) -> float:"""Price the three token classes separately and return request cost."""fresh = max(in_tok - cached, 0) # tokens billed at full input ratereturn (fresh * price.input_per_mtok+ cached * price.cache_hit_per_mtok+ out_tok * price.output_per_mtok) / 1_000_000
2.2 Task Cost and Effective Cost per Result
In real workloads, one “task” usually maps to several requests: planning, retrieval, code generation, validation, repair, summarization. So define two more metrics:
- Task cost,
C_task: the sum of billed requests along that task’s chain. - Effective Cost per Result (ECR):
C_task / pass_rate, where pass rate comes from your internal evaluation set (tests passing, schema validation passing, human spot-check approval, and so on).
ECR is the correct denominator for cross-vendor comparison. Two services with a fivefold sticker-price gap collapse to less than a twofold real gap if one of them raises task pass rate from 70% to 90%. If the higher pass rate also reduces rework and human intervention, the conclusion can even invert. This is also why “benchmark ranking” and “cost-effectiveness” are two different things: capability rankings influence pass rate and the depth of reasoning you need to burn, while cost-effectiveness depends on the product of the two.
2.3 Subscription Leverage: Converting Plans into Real Pay-As-You-Go Value
The most useful insight in this analysis is quantifying the “leverage ratio” of subscription plans. Define:
Leverage ratio L = pay-as-you-go value of included quota / price actually paid
At the magnitudes reported for these offerings: a new-generation domestic model’s entry plan costs about 199 RMB and includes quota worth roughly 1,200–2,800 RMB at pay-as-you-go rates, giving L ≈ 6–14. A leading overseas product’s $20 tier includes quota worth $400–800 at list rates, giving L ≈ 20–40, with the $200 tier reaching up to 50x.
This ratio drives a key conclusion: when leverage differs by several times, a lower sticker price does not automatically translate into lower total cost. Suppose two options can both complete the same workload. Option A has a lower list price with L=8; Option B costs five times more per token but has L=30. The ratio of actual spend is (1/8) : (5/30) = 0.125 : 0.167 — only a 33% gap remains, and once cache hits and model routing are introduced, the ranking can change again.
So rather than judging a plan by its headline price, compute its break-even usage: the plan only delivers a genuine cost advantage once your usage, converted to pay-as-you-go terms, reaches price paid × L_target. Below that threshold, pay-as-you-go is the cheaper choice.
3. Cache Hit Rate: The Highest-Leverage Optimization
3.1 How Prefix Caching Works
Prefix caching, whether automatic or explicit, hits only when the token sequence of the request prefix is completely identical. The moment anything changes at a given position, everything after that position degrades to a cache miss. That yields a counterintuitive but critical engineering constraint: dynamic content must go at the end of the prompt.
A recommended layout:
┌─ Stable prefix (target: 100% hit rate) ────────────────┐│ System instructions + output format constraints ││ Domain knowledge and specification documents ││ Few-shot examples ││ Tool / function schema definitions │├─ Semi-stable section (infrequent changes) ─────────────┤│ Conversation history summary │├─ Volatile section (differs on every call) ─────────────┤│ Current user input ││ Timestamps, random IDs, per-request metadata │└────────────────────────────────────────────────────────┘
Common cache-hit killers: injecting the current timestamp or a random trace ID into the system prompt; concatenating user input ahead of the knowledge base; unstable field ordering during JSON serialization; and re-sampling few-shot examples on every request.
3.2 Measuring Hit Rate and Estimating the Payoff
def cache_hit_rate(total_input: int, cached_input: int) -> float:return cached_input / total_input if total_input else 0.0# Fraction saved on the input line item thanks to cachingdef input_saving(price: Price, hit_rate: float) -> float:# hits bill at cache_hit rate, misses at the full input rateeffective = hit_rate * price.cache_hit_per_mtok + \(1 - hit_rate) * price.input_per_mtokreturn 1 - effective / price.input_per_mtok
Plugging in the 20 RMB input / 1 RMB cache-hit case, the input line alone saves 95% of its cost multiplied by the hit rate. If input tokens account for 80% of total billed tokens on a coding task, moving the hit rate from 0 to 60% cuts overall request cost by roughly 45%. This is the best return-on-effort optimization available, and it costs almost nothing in output quality.
4. Context Governance: Attacking Total Input Volume
Caching solves repetition. Context governance solves volume. The cost of long contexts is routinely underestimated: a single call carrying 100,000 tokens of context can still be dominated by the uncached portion of the bill even at a decent hit rate. General-purpose techniques:
- Retrieval instead of dumping everything in: replace whole documents with top-K fragments from vector or keyword retrieval. This typically compresses input by an order of magnitude while maintaining or improving answer relevance.
- Layered summarization with a sliding window: roll older conversation content into a structured summary (decisions, constraints, open items) while keeping recent turns verbatim.
- Structural pruning: inject only the subset of tool schemas relevant to the current step. Filter at the field level rather than pasting whole blocks.
- Output constraints: cap format and length explicitly. Since output tokens are expensive, cutting redundant explanation and repeated code pays off immediately.
- Control reasoning depth: enable deep-thinking mode only for genuinely complex tasks. Turning it off for simple extraction, classification, and formatting workloads measurably reduces output-side spend.
5. Model Routing: Dispatch by Difficulty
Routing all traffic to a single model is one of the main causes of runaway cost. Building a tiering policy around capability and difficulty detection lets only the requests that truly need it reach the top tier:
routing:- name: deep-reasoningmatch: { task: [code_generation, complex_analysis], min_difficulty: 0.7 }model: tier-a # high-capability tiermax_tokens: 8000fallback: tier-b- name: routinematch: { task: [summarize, classify, extract, rewrite] }model: tier-b # lightweight tiermax_tokens: 1500
Difficulty detection can rely on rules (task type, input length, whether multi-step reasoning is involved), scoring from a small classifier, or a cascade approach: try a lightweight model first, then escalate when a confidence check fails. In practice cascades are often the most economical option — most requests close out on the lightweight tier, and only a minority pay the premium price. Pair this with a quality safety net: track escalation rate and post-escalation pass rate so the router doesn’t silently degrade into “always use the most expensive model.”
6. Cost Observability and Budget Governance
You can’t optimize what you don’t measure. Bring these metrics into monitoring and alerting:
| Dimension | Key metrics |
|---|---|
| Usage | Input / output / cache hit / cache write token counts, request volume, peak concurrency |
| Unit cost | Cost per request, task cost C_task, average cost per 1K tokens |
| Quality-linked | Task pass rate, effective cost ECR, rework rate |
| Stability | Time to first token, failure rate, retry rate, rate-limit hits |
| Budget | Daily quota consumption and forecast overspend, sliced by tenant / business line / environment |
An often-overlooked hidden cost is retry and timeout amplification: thresholds set too tight, combined with non-idempotent request handling, can make a single failure burn three to five times the intended tokens. Related problems include resending full conversation history on every turn, batch jobs that don’t deduplicate, and debugging environments pointed at production-grade models.
Cloud platforms such as Baidu AI Cloud offer general-purpose capabilities — a unified model-calling gateway, log services, monitoring and alerting, and quota management — that can be used to build this observability loop: land call logs in a log service for structured attribution, wire unit-cost metrics into monitoring and alerting for threshold and trend warnings, and enforce hard budget limits through quotas and rate limiting. These are industry-standard engineering practices; specific allowances and billing rules should always be confirmed against actual commercial terms and the official documentation.
7. An Actionable Process for Evaluating Options
Bringing the dimensions above together, here is an evaluation flow that doesn’t depend on sticker price:
- Build an internal evaluation set: sample from historical real requests, covering typical task types and difficulty distribution, and define pass criteria that a machine can judge.
- Collect a full usage profile: measure the input/output token distribution and cache-hit potential of each model on the evaluation set, not just call counts.
- Compute task-level cost: calculate
C_taskand ECR for each candidate rather than comparing price per million tokens. - Convert subscription plans: use
Land break-even usage to decide whether a plan is worth buying. If monthly usage falls below the threshold, choose pay-as-you-go. - Layer in optimized costs: estimate the reduction from improved cache hit rate, context compression ratio, and routing split, producing an “optimized ECR.”
- Close the governance loop: review metrics monthly after launch, and adjust routing thresholds, caching strategy, and budget quotas accordingly.
Conclusion
“A new-generation model raised prices fivefold” is an accurate observation, but it is a conclusion about price, not about cost. Once you fold in the input-output mix, cache hit rate, the reasoning depth each task demands, subscription leverage, and pass rate, the ranking implied by sticker prices frequently gets rewritten. For developers and enterprises, the real capability isn’t picking the service with the lowest list price — it’s building a cost model you can measure: every call attributable, every context reusable, and every hard problem paid for only when it genuinely needs to be. In a cycle where model capabilities iterate quickly and pricing strategies shift often, that is the only durable source of cost advantage.
