LLM API Cost Optimization: A Practical Guide to Token Billing, Caching, and Model Routing
This guide breaks down how large language model API costs accumulate across input, output, cache reads, and storage fees, then walks through four proven ways to cut them: slimming context, reusing prefix caches, batching requests asynchronously, and routing tasks to different model tiers. It also shows how to calculate the real value of limited-time discounts, how to build a repeatable cost governance loop with instrumentation and budget alerts, and which common mistakes quietly inflate your bill. All prices are illustrative and vendor-neutral.
1. Where the Problem Starts: Why “Experience” Ends Up on the Bill
When teams evaluate a large language model, they usually look first at whether the answers are fluent and the reasoning is sound. But once an application goes live and call volume grows from a few dozen requests a day to a few thousand, the discussion almost inevitably turns to cost. The reason is simple: the per-call price difference looks negligible, yet once you multiply it by call frequency and context length, it goes from “the price of a meal” to an expense that needs formal budget approval.
So evaluating the real experience of a large language model should cover three dimensions: quality, latency, and unit cost. This article focuses on the third one and lays out a reusable method for estimating and optimizing cost. It mentions no specific vendors or products, and all prices are illustrative values used to demonstrate the calculation.
2. The Cost Ledger: Understand How Token Billing Adds Up
Billing for mainstream LLM APIs generally revolves around tokens. A mature cost model should break down into at least four items:
- Input cost: tokens consumed by the prompt and context, usually the largest share;
- Output cost: tokens generated by the model, typically priced significantly higher than input;
- Cache read cost: the fee for reading a repeated prefix (system prompt, long document, code index) that hits the cache, usually far below the original input price;
- Write/storage add-on fees: some platforms bill separately for writing to the cache or for long-term storage, which needs to be confirmed individually.
Putting these four items into a table is the first step of cost governance. Without a ledger, every optimization afterward is just a feeling.
3. Using Limited-Time Discounts Correctly: Calculate the Real Gain
A limited-time discount (for example, “50% off for two weeks”) is essentially a cost window. To decide whether it is worth adjusting your launch schedule for it, you need to calculate the per-call cost before and after the discount.
Assume a typical task: about 500K tokens of input context and about 20K tokens of output containing recommendations and code. Illustrative unit prices (CNY per million tokens):
- Before discount: input 0.8, output 2.8, cache read 0.23
- After discount: input 0.4, output 1.4, cache read 0.115
Cost per call before discount: 0.5 × 0.8 + 0.02 × 2.8 = 0.456
Cost per call after discount: 0.5 × 0.4 + 0.02 × 1.4 = 0.228
The conclusion is straightforward: the cost is halved. If monthly volume is in the hundreds to thousands of calls, the savings are substantial. But keep three points of rational judgment in mind:
- Discounts are temporary. Do not bake the discounted price into a long-term budget model, or you will face a budget gap once the window closes.
- If you compress the testing cycle to catch the discount, rework costs may far exceed what you saved.
- Discount windows suit “high-value batch tasks” such as scanning a legacy codebase for historical issues or structuring documents in bulk. These tasks are latency-insensitive and can be queued.
4. Four Cost-Reduction Levers That Actually Work
4.1 Slim Down the Context
Input tokens are the biggest cost driver, and most projects stuff their context with redundancy: repeated license headers, large blocks of commented-out legacy code, dependency lists nobody maintains. Clean up on the engineering side first, then talk about model-side optimization.
def build_context(files, budget=200_000):# 1) Deduplicate and filterfiles = [f for f in files if not f.is_generated and f.size > 0]# 2) Sort by relevance, keeping high-value files firstfiles.sort(key=lambda f: f.relevance, reverse=True)# 3) Greedily assemble within budgetctx, used = [], 0for f in files:if used + f.tokens > budget:continuectx.append(f.content)used += f.tokensreturn "\n".join(ctx), used
4.2 Reuse the Prefix Cache
Put stable system prompts, tool descriptions, and long documents at the very front of the request so the unchanged prefix hits the cache read price as often as possible. In practice, avoid inserting volatile content such as timestamps or random IDs at the start of the prompt, or the cache will never be valid.
4.3 Batching and Asynchronous Queues
For tasks that tolerate minute-level latency, an asynchronous batch interface usually buys a better unit price. Pairing it with a message queue to smooth out peaks both flattens the cost curve and avoids retry amplification caused by rate limiting during traffic spikes.
4.4 Tiered Model Routing
This is the highest-return move: use a lightweight model for simple tasks like classification, extraction, and formatting, and escalate to a large-parameter model only when complex reasoning is required.
def route(task):if task.kind in {"classify", "extract", "format"}:return "light-model"if task.risk == "high" or task.needs_reasoning:return "strong-model"return "standard-model"
In practice, if simple tasks make up more than 60% of traffic, overall cost often drops by more than half with almost no quality loss, provided you maintain a regression evaluation set to ensure the routing policy does not quietly degrade quality.
5. Make Cost Governance a Process
One-off optimization is meaningless; cost needs to be observed continuously. The recommended minimum loop has four steps:
- Instrument: log input, output, and cache-hit token counts plus task type for every call;
- Attribute: break cost down by business line, scenario, and model tier to find the top consumers;
- Cap: set budgets and alert thresholds per scenario, with automatic notifications on abnormal growth;
- Review: compare unit task cost trends weekly and evaluate the payoff of prompt and routing changes.
Pairing this with monitoring, alerting, and logging services lets you catch problems before cost spirals. Putting your evaluation sets and prompt versions under version control ensures optimization does not cause quality regressions.
6. Common Pitfalls
- Looking only at unit price, not structure: when the input/output ratio is unbalanced, a low unit price does not mean low total cost;
- Blindly lengthening context: longer context is not only more expensive but can also lower accuracy as key information gets diluted;
- Ignoring retry amplification: timeout and failure retries without backoff and caps will multiply the bill;
- Treating a discount as the norm: the budget model must be stress-tested at original prices.
7. Conclusion
Cost optimization for LLM calls is still fundamentally a classic performance engineering problem: measure first, locate the bottleneck, then optimize with tradeoffs. Build the token ledger, push the context down, put caching and batching to work, and roll out tiered model routing, and most teams can cut unit task cost to half or less without sacrificing quality. As for limited-time discounts, they are an accelerator, not a strategy.
