Cost Engineering for LLM APIs: What to Do When Token Prices Stay Flat but Bills Keep Rising
A practical guide to LLM cost engineering when per-token API prices remain unchanged. Learn how to model cost per task, maximize context caching discounts, control output length, route requests across model tiers, and build observability dashboards to keep bills down as model capabilities converge.
1. The Problem: Flat Prices, Rising Bills
A common pattern is emerging in the industry: a new generation of general-purpose LLMs shows a clear jump in benchmark scores, landing in the same range as comparable competitors, while the official API token prices stay unchanged from the previous generation. On the surface, this looks like pure upside. In practice, the bill does not necessarily go down.
The reason is simple: the bill equals “unit price × usage.” When the unit price is frozen, usage can still rise because model behavior changes. For example, to improve success rates on complex tasks, the model tends to generate longer reasoning traces and more complete intermediate artifacts, increasing output tokens per task by roughly 20%.
This pushes a frequently overlooked engineering issue to the forefront: model selection cannot be based on the listed unit price alone; it must be based on cost per task. At the same intelligence tier, whoever consumes fewer tokens, hits more cache, and triggers fewer retries while completing the same batch of tasks ends up with the lower bill. This is the real focus of the next stage of competition: once capabilities converge, cost engineering becomes the dividing line.
2. A Computable Model of Cost
To optimize, you first need to measure. It helps to write the cost of a single task as:
cost_task = (in_tok * p_in + out_tok * p_out) * (1 - r_cache * d_cache) + n_retry * cost_task
Here, in_tok/out_tok are input and output tokens, p_in/p_out are the corresponding unit prices, r_cache is the cache hit rate, d_cache is the cache discount ratio, and n_retry is the average number of retries. This formula tells us three things:
- Output tokens usually cost several times more than input tokens, so compressing output yields far greater savings than compressing input;
- The discount from cache hits applies to the whole expression, so raising the hit rate from 20% to 60% is often more worthwhile than switching models;
- Retries are a hidden cost amplifier; a single failed retry can double the cost of that task.
In engineering terms, these three items should be turned into observable metrics: instrument the call path to record input/output tokens, whether the cache was hit, retry counts, and final success or failure for every request, then aggregate by business scenario to build a “unit cost dashboard per task type.” Without this dashboard, any optimization is guesswork.
3. Caching: The Most Underrated Discount
Major platforms generally offer context caching, where the cached portion is billed significantly lower than regular input (discounts commonly seen in the industry range from 30% to 10% off, roughly a 20% discount). To actually capture this discount, the key is to keep the request prefix stable:
- Put the system prompt, tool definitions, domain knowledge, and few-shot examples at the very front, in a fixed order;
- Move volatile content such as timestamps, random IDs, and user nicknames to the end of the prompt or a variable section;
- Avoid inserting dynamic content in the middle of a long prefix; one change invalidates everything after it;
- Set a reasonable cache time-to-live and align it with the batch window.
An illustrative structure:
[Stable prefix] System role + tool schema + domain rules + fixed examples[Semi-stable] Session summary (appended by paragraph, history unchanged)[Volatile] Current user input, timestamp, request ID
Combined with scheduling batch offline tasks within the same time window, the hit rate usually improves significantly. This gain shows up directly on the bill and costs nothing in quality.
4. Output Length Governance: Dealing with “More Verbose” Models
Capability gains in the new generation often come with longer outputs. The answer is not blunt truncation but layered constraints:
- State the deliverable format and length limit explicitly in the prompt, for example “conclusion first, then no more than five bullet points”;
- Prefer structured output, replacing free-form prose with fixed fields to cut redundant elaboration;
- Split long tasks into “plan—execute—summarize” stages, each emitting only the necessary intermediate results;
- Adopt a discardable policy for intermediate reasoning, keeping only the final conclusion for downstream use;
- Set
max_output_tokensand stop conditions, and trigger a single “compress and rewrite” pass for overlong outputs instead of a full rerun.
One point deserves emphasis: compressing output must not come at the expense of correctness. A sound approach is to run an A/B test on a small traffic slice while watching two curves, task success rate and average output length, to find the cost inflection point.
5. Routing and Fallback by Capability Tier
When multiple models are available at the same intelligence tier, routing is the main battlefield for cost optimization. Practical strategies include:
- Difficulty grading: use rules or a lightweight classifier to judge task difficulty, sending simple tasks to a low-cost small model and complex tasks to a high-scoring model;
- Cascading calls: start with the small model for a draft, escalate only when confidence is insufficient, balancing cost and quality;
- Failure fallback: automatically switch to a backup implementation when the primary model times out or is rate-limited, avoiding cost amplification from retries;
- Budget guardrails: set a daily budget and token cap per tenant or scenario, with automatic downgrade once exceeded.
def route(task):if task.difficulty <= 1 and task.risk == "low":return small_modelif task.type in ("code_review", "security_analysis"):return strong_model # prioritize capability for high-risk scenariosreturn mid_model
The value of routing is spending expensive intelligence only where it is truly needed, which typically brings a substantial overall cost reduction with little perceptible change in quality for users.
6. Capability Trends: Coding, Defensive Security, and Long-Horizon Agents
From public benchmark trends, the gains of the new generation concentrate in three areas: coding and code understanding, defensive cybersecurity analysis, and long-horizon agent tasks. Each affects cost differently:
- Coding tasks have long inputs (repository context) and medium outputs, so caching yields the greatest benefit;
- Security analysis is high-risk and low-tolerance, so the capability tier should be protected rather than downgraded too aggressively;
- Long-horizon agent tasks involve many calls and fast-accumulating state, so session summarization and externalized state (placing intermediate state in general storage or a cache service) are required to suppress context growth.
The engineering recommendation is to split these three scenarios into separate cost budget pools, each with its own optimization target, instead of using one set of parameters for everything.
7. Implementation Checklist
- Build a unit-cost-per-task dashboard with metrics for input/output tokens, cache hit rate, and retry rate;
- Restructure prompts into layers, prioritizing a stable prefix to earn a high cache hit rate;
- Impose format and length constraints on output, and validate with A/B tests that quality does not regress;
- Roll out difficulty routing and budget guardrails, reserving the high-capability tier for critical tasks;
- For long-horizon tasks, use externalized state plus summary compression to control linear context growth;
- On your own platform, combine monitoring and alerting, logging services, and message queues for asynchronous batch processing to smooth peaks and fill valleys, further lowering unit prices and failure costs.
The conclusion is clear: once different models reach the same intelligence range, competition shifts from “scores” to “cost per task.” Flat unit prices do not mean flat bills. The real dividend belongs to teams that turn caching, output length, routing, and observability into systematic capabilities.
