LLM API Cost Engineering: Why Unchanged Token Prices Can Still Raise Your Bill
This article explains why stable per-token pricing does not guarantee a stable API bill, and how input/output price asymmetry, prompt caching, output token growth, and per-task cost differences affect total spending. It outlines practical cost optimization methods, including building an internal per-task cost baseline, controlling output length, maximizing prefix cache hits, using tiered routing, and setting budgets for long-running agent tasks, along with model selection and architecture recommendations.
1. The Core Issue: Unchanged Unit Prices Do Not Mean Unchanged Bills
The industry has recently seen a notable release pattern: new-generation large models show clear improvements in overall capability scores, while the official API token prices remain the same as those of the previous generation. For developers, the value of this information is not about which model is stronger. It reveals a long-overlooked fact: the API unit price is only one factor in the cost formula, not the cost itself.
A single task’s bill can usually be broken down as follows:
Cost per task ≈ (input tokens × input price)+ (output tokens × output price)+ (cache-missed input tokens × input price)+ (cache-hit input tokens × cache price)+ extra consumption from retries and failed requests
Three structural facts are worth extracting from the original information:
- The price of cached input tokens is usually only a small fraction of the regular input price, with discounts that can exceed 80%.
- The cost per task for models with similar intelligence levels may differ by about 20%.
- When completing the same task, a new-generation model may consume about 20% more output tokens than the previous generation.
Together, these facts lead to a counterintuitive conclusion: actual spending can still rise even when unit prices stay unchanged. Output tokens are often the most expensive part of the bill. A 20% increase in output volume has a much larger amplifying effect on the total bill than the same percentage change in input volume.
2. Four Key Variables and How They Interact
2.1 Input and Output Prices Are Asymmetric
Mainstream pricing systems generally charge more for output tokens because the computation and GPU memory usage during generation are much higher than during prefill. This means that any design that makes the model say more is priced at a higher marginal cost. The direct engineering implication is that controlling output length is usually more effective than compressing input.
2.2 Structural Discounts from Cache Hits
The billing logic of prompt caching is that the prefix portion identical to the previous request is charged at a very low price. It naturally fits call patterns with a fixed system prompt, fixed knowledge context, and changing user input. If the system prompt, tool descriptions, and examples are placed at the beginning and kept byte-for-byte stable, the cache hit rate will increase significantly. Conversely, any timestamp, random ID, or dynamic ordering will invalidate the prefix and reduce the discount to zero.
2.3 Cost per Task Is the Comparable Metric
Differences in output style across models make the “price per million tokens” metric lose comparability. A more reasonable industry metric is cost per task, meaning the total cost of completing a standardized task set. The roughly 20% difference in per-task cost between models at similar tiers shows that model selection must be based on end-to-end benchmarks rather than price lists.
2.4 Output Expansion and the Inherent Cost of Reasoning Models
New-generation models generally strengthen alignment and reasoning depth, tending to produce more complete thought processes and longer explanations. This brings capability benefits but also token expansion. Without constraints, part of the capability dividend will be consumed by the bill.
3. Practical Cost Optimization Methods
Method 1: Build Your Own Cost-per-Task Baseline
Do not rely on public leaderboards for decisions. Build an internal baseline set with real business samples. Usually, dozens to a few hundred records covering typical scenarios are sufficient:
# Example: skeleton for measuring cost per taskdef task_cost(record, price):cost = record["in_tokens"] * price["in"]cost += record["out_tokens"] * price["out"]cost += record["cache_hit_tokens"] * price["cache_in"]cost += record["cache_miss_tokens"] * price["in"]return cost / 1_000_000 # prices are per million tokensbaseline = {"avg_cost_per_task": sum(task_cost(r, price) for r in samples) / len(samples),"avg_out_tokens": sum(r["out_tokens"] for r in samples) / len(samples),"cache_hit_rate": sum(r["cache_hit_tokens"] for r in samples)/ sum(r["in_tokens"] for r in samples),}
There are three key metrics: average cost per task, average output tokens, and cache hit rate. Together, they explain the reasons behind bill changes.
Method 2: Treat Output Length as a First-Class Governance Concern
- Specify structure and length limits in prompts, for example, “no more than three sentences for the conclusion, followed by a bullet list.”
- Use constrained output formats for structured scenarios to prevent the model from freely elaborating.
- Set output limits and truncation policies at the application layer, and trigger a second round of summarization for overly long outputs.
- Separate explanatory content from machine-consumed content. Generate the former on demand and keep the latter minimal.
Method 3: Maximize Prefix Cache Benefits
[Fixed section] System role + tool definitions + output specifications + long-term knowledge snippets ← keep byte-stable[Semi-fixed section] Conversation summaries, retrieved documents (concatenated in a stable order)[Variable section] Current user input, time-related information
Engineering discipline includes: do not insert timestamps or random identifiers into the fixed section; make the ordering of retrieval results deterministic; evaluate cost fluctuations caused by cache invalidation when the fixed section changes.
Method 4: Use Tiered Routing to Allocate Compute by Difficulty
Classify requests by complexity. Send simple requests to lightweight models or rule-based logic, and escalate only complex requests to high-capability models. Combined with semantic caching, directly reuse historical answers for high-frequency repeated questions. This layer usually brings the most significant cost reduction without sacrificing the experience in critical scenarios.
Method 5: Budget Control for Long-Horizon Agent Tasks
The cost risk of agent tasks lies in amplification across multiple rounds of loops. It is recommended to introduce explicit budgets: set a maximum number of rounds, a maximum token quota, and a maximum wall-clock time for a single task; record incremental costs each round; apply a fallback strategy when the budget is exceeded rather than retrying indefinitely. Also include failed retries in cost accounting to avoid the hidden expense where “the success path is cheap and the failure path is expensive.”
4. Selection and Architecture Recommendations
When choosing between models at similar capability tiers, evaluate them in the following order: first measure cost per task with an internal baseline set, then check whether the output token distribution is controllable, then verify that the caching mechanism works reliably, and finally examine whether supporting capabilities such as rate limiting, quotas, logging, and monitoring alerts are complete. If an open-weight route is involved, also evaluate the compute depreciation and operational investment of self-hosted inference, and compare them with pay-as-you-go API billing over the full lifecycle.
Architecturally, keeping an abstraction layer for model access and consolidating prompt templates, routing policies, budget control, and metering instrumentation behind a unified gateway can make “switching models” a configuration change rather than a refactoring effort. Metering data should be connected to logging services and monitoring alerts to form a closed loop for cost observability.
5. Conclusion
“Unchanged unit prices and higher scores” is a signal from capability providers, but whether costs rise is determined by how you use them. What really determines the bill is output length, cache hit rate, task success rate, and routing strategy. The next stage of competition will shift from a pure capability contest to unit-cost efficiency at similar intelligence levels. For developers, building cost engineering into the architecture has more long-term value than chasing any single leaderboard.
