LLM Inference Cost Optimization: An Engineering Approach That Cut Token Usage by 85% on the Same Task
This article explains why two LLM runs can produce equally valid output while consuming very different amounts of compute, and breaks down the four main sources of that gap: inference path length, context redundancy, output redundancy, and repeated computation. It then walks through a five-step governance method with code samples: task tiering and routing, input/output budget hard limits, structured output contracts, prefix caching with retrieval instead of long context, and an evaluation loop that combines a quality gate with a cost dashboard. A sample benchmark design and a list of common anti-patterns are included, along with an acceptance checklist. The conclusion is that cost is driven mainly by execution path and constraint strength rather than task difficulty, and that treating cost as an engineering discipline turns occasional savings into a repeatable capability.
1. The Phenomenon: Same Quality, Different Bill
In a table-generation task, several LLMs fully satisfied the field, format, and content constraints in both “auto mode” and an explicitly specified mode. Every output passed. This means the task itself was not beyond the capability boundary of any of the models involved; the real difference showed up in how much compute each one consumed to complete the same job.
For an engineering team, the value of this observation is not “which model is stronger.” It reveals a fact that is easy to overlook: as long as output quality meets the bar, cost can still differ by an order of magnitude. Cost governance therefore should not start with “switch to a stronger model.” It should start with stating the task clearly, putting a budget in place, and running evaluations.
2. Four Sources of Cost Differences
- Inference path length: An explicitly specified execution path is usually shorter than an auto-decided one, eliminating one extra round of planning and selection overhead.
- Context redundancy: Repeatedly pasting specs, prior conversation, and unrelated material scales input-side consumption linearly.
- Output redundancy: Without format and length constraints, models tend to produce long explanatory text, and output-side consumption grows several times over.
- Repeated computation: Multiple requests sharing the same prefix do not reuse intermediate results, creating a steady, recurring expense.
3. A Five-Step Method You Can Actually Deploy
3.1 Task Tiering and Routing
Tag the task first, then decide “which path, and how much budget.” Example:
def route(task):if task["schema_strict"] and task["steps_known"]:return {"mode": "explicit", "budget": 0.6} # Path is known, keep the budget lowif task["ambiguity"] > 0.5:return {"mode": "auto", "budget": 1.0} # Explore first, converge laterreturn {"mode": "explicit", "budget": 0.8}
Key point: treat “does the model need to plan on its own?” as a first-class decision instead of defaulting to auto mode.
3.2 Token Budgets and Hard Limits
Set both an input and an output ceiling for each task category, and validate before the request goes out. If a request exceeds budget, downgrade or split it immediately, rather than “run it first and look at the bill later.”
{"max_input_tokens": 4000,"max_output_tokens": 1200,"on_exceed": "split_and_retry"}
3.3 Output Contracts
Replace natural-language descriptions with a structured contract, turning “please be as concise as possible” into a machine-verifiable constraint:
{"type": "object","required": ["rows", "columns"],"properties": {"rows": {"type": "array", "maxItems": 50},"columns": {"type": "array", "maxItems": 12}},"additionalProperties": false}
Paired with an instruction that forbids explanatory text and allows only the target structure, this usually produces the most noticeable drop on the output side.
3.4 Prefix Caching and Retrieval Instead of Long Context
Keep stable system specs and the field dictionary in the request prefix, byte-for-byte identical, so intermediate computation results can be reused. Move bulky material out of the context and inject retrieved fragments on demand instead. Example:
PREFIX = "You are a table generator. Output JSON only, no explanations.\nField dictionary v3:\n" # Keep this stabledef build_prompt(user_input, retrieved):return PREFIX + "\nReference:" + retrieved + "\nTask:" + user_input
3.5 Evaluation Loop: Quality Gate Plus Cost Dashboard
Every optimization must pass the quality gate; otherwise the tokens you saved come back as rework. Record quality scores and resource consumption together, and track them as a dual-line dashboard:
def accept(result, cost):return result["schema_ok"] and result["accuracy"] >= 0.99 and cost["total"] <= cost["budget"]
4. Sample Benchmark Design
Design principle: same task, same input, same acceptance script; change only the execution path and the strength of constraints.
| Group | Execution path | Output constraint | Quality | Relative consumption |
|---|---|---|---|---|
| A | Auto | None | Pass | Baseline |
| B | Explicit | Structured contract | Pass | Significant drop |
| C | Explicit | Structured + caching | Pass | Further drop |
The conclusion should be stated with restraint: when quality is “pass” in every group, resource consumption in groups B and C drops substantially relative to the baseline, which indicates that cost is determined mainly by path and constraints, not by task difficulty.
5. Common Anti-Patterns
- Repeating “be concise” in a longer prompt instead of supplying a structured contract.
- Monitoring call counts only, and not the input/output distribution.
- Stuffing all material into the context to “guarantee accuracy,” ignoring the cost-effectiveness of retrieval.
- Skipping regression evaluation after optimizing, which lets quality degrade silently.
6. Acceptance Checklist
- Is the task labeled as “path known / path unknown”?
- Are both input and output ceilings set, with validation done up front?
- Is the output a verifiable contract?
- Does the stable prefix stay byte-identical so the cache can be reused?
- Are there two metrics in place: a quality gate and a cost dashboard?
- Is there a switch to roll back to the higher-spec path in one step?
7. Closing
“Spending more than 80% fewer tokens on the same work” does not depend on one lucky choice. It is the result of engineering governance: state the task clearly, make the budget a hard constraint, turn output into a contract, eliminate repeated computation, and put quality and cost on the same dashboard. Once this loop is running, cost optimization stops being an occasional piece of experience and becomes a sustainable, reproducible engineering capability. It can also be combined with general-purpose capabilities such as container platforms, log services, and monitoring and alerting on Baidu AI Cloud to form a stable curve of declining cost per task.
