LLM API Cost Optimization: A Practical Guide to Lowering Cost per Task
This guide explains why per-million-token pricing misleads LLM cost estimates and how to switch to cost per completed task. It presents a three-token cost model, a score-versus-cost evaluation method for tiered model selection, and four cost-control levers: input compression, prompt caching, routing, and retry reduction. An engineering checklist and common pitfalls are included.
1. The Starting Problem: Why “Price per Million Tokens” Misleads Decisions
When evaluating an LLM service, the first thing developers usually do is compare unit prices: how much per million input tokens, how much per million output tokens. Real bills often contradict intuition, for three reasons:
- Task structure differs. Summarization and rewriting tasks have long inputs and short outputs; code generation and structured extraction have a high output share. At the same unit price, task cost can differ by several times.
- Cache hit rates differ. Multi-turn conversations, repeated questions over a long document, and fixed system prompts all have a high share of repeated prefixes. Cached input pricing is usually significantly lower than regular input pricing.
- Retry and failure costs. Retries caused by timeouts, truncation, or non-compliant formatting multiply actual consumption, and this part is rarely included in estimates.
The more mature industry practice is to switch the evaluation basis from “unit price” to “cost per unit task,” meaning the total token consumption and cost required to complete one acceptance-ready task.
2. Writing the Cost Model Down: Three Token Types and One Formula
A single call is typically billed in three categories: regular input, cached input, and output. Let regular input unit price be p_in, cached input unit price be p_cache, and output unit price be p_out. The cost of one call is:
cost = (tokens_in - tokens_cached) * p_in+ tokens_cached * p_cache+ tokens_out * p_out
Cost per unit task is the sum over multiple calls, multiplied by a retry factor r (r >= 1):
task_cost = r * Σ cost_i
This formula reveals three general optimization paths: reduce total tokens, raise the cache hit rate, and lower the retry factor. None substitutes for another; all three must be pursued together.
3. Evaluation Method: Pick a Point on the Score-Cost Curve, Not the Most Expensive or the Cheapest
A common way to present evaluations is with cost per completed task on the horizontal axis and a quality score on the vertical axis, one point per model, forming a “score-cost” curve. Three points matter when using it:
- Look at the knee, not the endpoints. The far left of the curve (cheapest) often lacks quality; the far right (most expensive) has diminishing marginal returns. Real value for money appears near the knee where the slope clearly flattens.
- Pick points per task tier. High-tolerance tasks such as extraction, classification, and format conversion fall on the left; complex reasoning and long tool-call chains fall on the right. One business often needs both points at the same time.
- Quantify the quality score. Replace subjective impressions with automatically判定 metrics (field accuracy, unit test pass rate, human spot-check pass rate), otherwise the curve cannot be reproduced.
A schematic evaluation loop:
def evaluate(task_set, model, max_cost):scores, costs = [], []for t in task_set:out = call_model(model, t.prompt) # pseudocode: unified call wrapperif not validate(out, t.schema): # schema validation failure counts as a low scorescores.append(0.0)else:scores.append(score(out, t.gold))costs.append(usage_cost(out.usage))if costs[-1] > max_cost:breakreturn mean(scores), mean(costs)
4. Four Levers for Cost Governance
4.1 Input Side: Compression and Structure
- Layered prompts: put stable system instructions and tool descriptions first and dynamic content last, so the prefix can be reused.
- Context trimming: in retrieval-augmented scenarios, rerank and remove redundancy first, keeping only highly relevant fragments; for long documents, summarize in segments before entering the main chain.
- Output constraints: specify fields, length, and format clearly to reduce invalid generation and rework.
4.2 Cache Side: Turn Repeated Prefixes into a Discount
Cached input pricing is usually far below regular input pricing, so the hit rate is the most direct cost-reduction lever. Practical measures include: pinning prompt template versions, keeping the prefix byte-level stable (avoid timestamps and random IDs in the prefix), and restructuring conversation history as “summary + increments.”
[Stable prefix: system instructions + tool definitions + few-shot examples] <- cacheable[Semi-stable: conversation summary] <- refreshed periodically[Volatile: current question, retrieved fragments] <- not cached
4.3 Routing Side: Tiered Dispatch
Handle simple requests on a low-cost path first, then escalate to a high-capability path when confidence is insufficient or validation fails. “Confidence” here can be approximated with generic signals such as rule hits, schema validation pass rate, and agreement across multiple candidate outputs, avoiding dependence on any specific interface.
def route(req):if req.est_tokens < 800 and req.schema_simple:return cheap_tierif validate(prev_output, req.schema) is False:return strong_tierreturn standard_tier
4.4 Retry Side: Push r Close to 1
Set timeouts and a maximum number of rounds, validate structured output, degrade quickly on failure, use idempotency keys to prevent duplicate-billing replays, and turn frequently failing samples into a fixed regression set. Every 0.1 drop in the retry factor lowers overall cost proportionally.
5. Engineering Checklist
- Build a usage dashboard: break down the three token types and the cache hit rate by business line, scenario, and model, and configure budgets and alerts (generic cloud capabilities such as monitoring/alerting and logging services can be used).
- Build a regression evaluation set: fix the samples and the scoring script, and run a “score-cost” comparison after any prompt or routing strategy change.
- Capacity and elasticity: separate batch offline jobs from online interactions, use a queue to smooth peaks on the offline side, and scale containers on demand.
- Data and compliance: desensitize data before it enters the model chain, handle sensitive fields locally, and minimize retention.
6. Common Pitfalls
- Looking only at unit price and not task cost, which leads to bills exceeding expectations after launch.
- Trying to cover all traffic with the highest-capability model, where marginal returns are extremely low.
- Expecting cache hits with an unstable prefix, so the hit rate stays near zero over time.
- Ignoring failures and retries, leaving
rabove 1.3 for a long time. - Lacking automatic scoring, so evaluation conclusions cannot be reproduced and optimization turns into subjective debate.
7. Conclusion
The cost competitiveness of LLM applications comes from the combination of three things: the right evaluation basis, proper caching and routing, and controlled retries. Make cost per unit task the single north-star metric, use the “score-cost” curve for tiered point selection, and pair it with an observable usage dashboard and automated regression, and you can continuously push the bill into a reasonable range without sacrificing acceptance-ready quality.
