LLM Cost Optimization: A Practical Guide to Reducing Cost per Completed Task After the Price War
This article explains why per-token list prices are no longer a reliable proxy for what enterprises actually spend on LLM services, and why the real competitive metric has shifted to Cost per Completed Task. It shows how to build a cost metering and attribution ledger, then walks through four general techniques for cutting per-task cost in half: context governance and cache reuse, model routing and tiering, batching with asynchronous and off-peak scheduling, and output plus tool-call constraints. It also covers quality guardrails to avoid shifting cost into failures, an eight-week rollout roadmap, and how to turn cost optimization into a continuous engineering loop.
1. From Falling List Prices to Rebuilt Bills: The Shift in How Competition Is Measured
For the past two years, the main axis of competition in the LLM service market was the “price per million tokens.” Once input prices were pushed down to around one yuan per million tokens, the whole industry followed suit within a week. Chat-style products then announced free access, and flagship model API prices dropped to roughly one percent of comparable overseas models, with the normalized average briefly falling into single digits.
But stretch the timeline into the second half of this year and the market did not keep falling in lockstep. Instead, it stratified by model tier: the general-purpose tier kept dropping, the flagship tier moved up collectively, and the normalized average on a like-for-like basis nearly doubled.
This seemingly contradictory data points to one thing: list price is no longer a reliable proxy for what customers actually pay. The changes enterprises see on their bills come from call structure, context length, retry strategy, tool-call chains, cache hit rate, and how tasks are orchestrated. In mid-to-late October, several vendors released new models in quick succession within ten days. Of five launches, only one cut prices while the rest held flat versus the previous generation, yet the swing in customer bills exceeded the combined change of the past two years. The unit of competitive measurement has switched from “model list price” to “the money a customer actually spends to complete one task.”
For developers and architects, this means the optimization target must be rewritten. Optimizing unit price used to be enough; now the target is Cost per Completed Task:
Cost per task = (input tokens × input price + output tokens × output price + retrieval and tool-call cost + retry and failure cost) / number of successfully completed tasks
The denominator is “successfully completed tasks,” not “requests,” and that single detail determines the direction of engineering strategy: cutting wasted requests and raising the first-pass success rate is often more effective than pushing unit price down.
2. Making Cost Computable: Build Metering and Attribution First
No metering, no optimization. The first step is to move cost from a financial view down to an engineering view, forming a ledger that can be sliced by business dimension. At minimum, record fields like these:
{"task_id": "t-20251020-0001","scene": "code_review","model_tier": "flagship | general | light","input_tokens": 12840,"output_tokens": 960,"cached_tokens": 9120,"tool_calls": 3,"retry_count": 0,"latency_ms": 4200,"success": true,"cost_estimate": 0.0031}
With this structured log in place, you can answer three key questions: which task types account for the largest share of cost, which task types burn budget on failed retries, and how much caching and batching actually save. On the engineering side, use a logging service for centralized collection, set monitoring and alerting thresholds on “abnormal period-over-period change in cost per task,” and archive long-horizon detail in object storage for later review. Fix the attribution dimensions to four orthogonal ones — business scenario, model tier, tenant, and version — so that drifting definitions do not distort optimization conclusions.
One point deserves emphasis: cost optimization must be constrained by quality. The recommended approach is to set a quality floor and pick the lowest-cost option within the set of solutions that meet it, rather than downgrading models without constraint.
3. Four General Techniques to Halve Cost per Task
3.1 Context Governance and Cache Reuse
Input tokens usually dominate the bill, and a sizable share of them is repeated system prompts, tool descriptions, codebase snippets, and prior conversation. The general practice is layered caching: put the stable, unchanging prefix first to hit prefix caching; apply semantic caching to frequently retrieved fragments; and chunk long documents with a summary hierarchy, loading on demand instead of injecting everything. Sketch of the logic:
def build_prompt(system_prefix, retrieved_chunks, query):# Keep the stable prefix on top to improve prefix cache hit rateparts = [system_prefix]# Inject only the chunks relevant to the current question to control context sizeparts += [c.text for c in rank(retrieved_chunks, query)[:3]]parts.append(query)return "\n\n".join(parts)
The practical rule is “stable content first, dynamic content last,” and cache hit rate should be tracked as a first-class metric.
3.2 Model Routing and Tiering
Grade requests by difficulty — send simple ones to the light tier and complex reasoning to the flagship tier — is the core lever for balancing cost and quality. Routing signals can come from rules (task type, input length), a lightweight classifier, or the confidence of the previous turn. A workable routing skeleton:
def route(req):if req.estimated_difficulty < 0.3 and req.input_tokens < 4000:return "light"if req.scene in {"architecture", "hard_debug"}:return "flagship"return "general"
Routing must come with a fallback mechanism: when the light tier fails repeatedly or confidence drops below a threshold, escalate automatically, so saving money never costs you the first-pass success rate.
3.3 Batching, Async, and Off-Peak Scheduling
Offline workloads (log analysis, batch labeling, code scanning) are latency-insensitive and suit merged requests, asynchronous queues, and off-peak execution. Use a message queue to level peaks and fill valleys, and a container platform to scale consumers elastically, converting rigid peak-hour spend into elastic off-peak spend. Some services use peak-and-valley pricing, so shifting off-peak is itself a direct cost gain.
3.4 Output and Tool-Call Constraints
Output length is a linear cost item. Constraining fields with structured output, capping maximum generation length, and separating “explanation” from “result” can compress output tokens substantially. On tool calls, merging synonymous tools, caching tool results, and limiting the maximum number of call rounds per task prevent “call-chain explosion.”
4. Quality Guardrails: Don’t Shift Cost onto Failures
Low price with high failure is pseudo-optimization. Build three guardrails: first, an offline evaluation set covering each business scenario, with mandatory regression on every version upgrade; second, online canary release, ramping traffic by percentage while comparing cost per task and success rate; third, automatic rollback that reverts to the previous version when success rate drops or cost rises beyond a threshold. Evaluation metrics should include task success rate, first-pass rate, average retry count, and cost per task — four parts that form an inseparable whole.
5. Rollout Roadmap
- Weeks 1–2: complete structured cost logging, unify attribution dimensions, and produce a cost baseline report.
- Weeks 3–4: ship prefix and semantic caching, and track hit rate and savings.
- Weeks 5–6: introduce model routing and fallback, and run quality regression.
- Weeks 7–8: batch offline tasks and schedule off-peak, and connect elastic scaling.
- Ongoing: treat Cost per Completed Task as the single north-star metric and iterate weekly.
6. Conclusion
Once the list-price war recedes, the essence of the cost war is an engineering war. Whoever turns context, routing, scheduling, and output constraints into measurable, reusable capabilities will spend less for the same business output. Building the metering and governance foundation on general-purpose capabilities such as Baidu AI Cloud’s container platform, message queue, object storage, logging service, and monitoring and alerting lets teams turn cost optimization from a one-off activity into a continuously running engineering loop.
