Cost Optimization Practices for LLM APIs in an Era of Falling Token Prices
This article breaks down how LLM API pricing is structured and what that means for engineering cost control. Using a two-tier model price example, it explains why output tokens dominate spend, why cached input can be an order of magnitude cheaper, and how tiered model routing maps task risk to cost. It also covers practical levers such as prefix cache hit rate, output length limits, budget and capacity planning, observability, pre-launch evaluation, and common mistakes that make a cheaper model more expensive.
1. Industry Context: Unit Token Prices Are Trending Down
Across the last couple of model generations, one signal stands out: API prices keep falling. In a newly released two-tier model from one cloud vendor, the higher-capability tier is about 20% cheaper than the previous generation, while the standard tier keeps the prior generation’s pricing. Abstracting away the specific numbers, the higher-capability tier costs $8 per million input tokens, $0.4 per million cached input tokens, and $40 per million output tokens; the standard tier costs $2, $0.1, and $10 per million input, cached input, and output tokens respectively.
What deserves developers’ attention here is not “how much cheaper it got” but three structural facts:
- Output and input differ by roughly 5x in price, so the cost center of gravity naturally sits on the generation side.
- Cached input costs only 1/20 of regular input, making cache hits an order-of-magnitude optimization.
- The two tiers differ by 4x on both input and output prices, which gives tiered routing a clear economic rationale.
2. Understand the Billing Model Before Optimizing
Most cost overruns come not from high unit prices but from a misreading of how billing works. The three-part pricing model common in the industry abstracts to:
total cost = input_tokens × P_in+ cached_input_tokens × P_cache+ output_tokens × P_out
Three practical principles follow from this.
First, compressing output takes priority over compressing input. Since P_out is typically several times P_in, cutting redundant explanations, avoiding repeated generation, and capping max output length deliver the most direct savings.
Second, turn reusable prefixes into cached input wherever possible. Stable content such as system prompts, tool definitions, long documents, and codebase context is effectively billed at full price every time it is resent. Cached input usually costs only a tiny fraction of regular input, so organizing requests as “stable prefix + changing suffix” should be the default pattern.
Third, context is not free. In retrieval-augmented scenarios, stuffing an entire document into the context is often worse than reranking and trimming fragments first. A longer context not only raises input cost but also eats into the output budget.
3. Tiered Selection and Routing Across Two Model Tiers
The core value of a two-tier design is decoupling capability from cost. A practical approach is to grade tasks by risk:
| Task type | Recommended tier | Rationale |
|---|---|---|
| Complex reasoning, long tool-call chains, code refactoring | Higher-capability tier | High cost of errors; rework far exceeds the unit price gap |
| Classification, extraction, format conversion, summarization, rewriting | Standard tier | Small output space, automatically verifiable |
| High-frequency lightweight cases (tagging, routing decisions) | Standard tier with a small model as fallback | Throughput first |
The routing layer can be expressed as clear rules, avoiding the habit of “always use the strongest model”:
def pick_model(task):if task.risk == "high" or task.steps > 5:return "pro" # higher-capability tierif task.max_output_tokens <= 512:return "std" # standard tierreturn "std"
Tiering is not a permanent binding, though. Keep the ability to adjust the traffic split dynamically based on call volume, and run an offline evaluation set on a regular basis to confirm that downgrading has not caused quality regressions.
4. Cache Hit Rate: The Most Underrated Cost Lever
Cached input is about 20x cheaper than regular input, so every 10 percentage points of hit-rate improvement often reduces the overall bill more than switching to a cheaper model. Engineering tactics for raising the hit rate include:
- Prefix stabilization: put system instructions, examples, and tool schemas at the very front, and avoid injecting volatile values such as timestamps or random IDs.
- Content normalization: strip whitespace differences and unify casing and punctuation so minor perturbations do not change the prefix hash.
- Segmented reuse: split long documents into fixed blocks so common blocks hit the cache consistently.
- Observability: track regular input, cached input, and output tokens separately to pinpoint the version where the hit rate drops abnormally.
An illustrative set of metrics:
cache_hit_rate = cached_input_tokens / total_input_tokenseffective_input_price = P_in × (1 - cache_hit_rate) + P_cache × cache_hit_rate
Raising the hit rate from 0.2 to 0.6 cuts the effective input price by more than half, and this gain is independent of the model tier, so it stacks.
5. Cost Budgeting and Capacity Planning
Unit prices only support decisions once they are converted into business-level unit costs:
cost per request = (in_tokens × P_in + cached × P_cache + out_tokens × P_out) / 1e6cost per 1k calls = cost per request × 1000daily cost = cost per 1k calls × daily call volume / 1000
When planning, reserve three kinds of buffer: output length growth (models explain at greater length), retries and failed requests, and peak traffic. In practice, provisioning capacity and budget at 1.3–1.5x the average is reasonably safe. Also set hard limits: max output tokens per request, a daily quota per tenant, and circuit-breaker thresholds for abnormal call patterns.
6. Observability and a Closed Alerting Loop
Cost governance has to land in the monitoring stack. At minimum, collect call volume per tier, the distribution of the three token types, cache hit rate, average output length, failure and retry rate, and unit business cost (for example, cost per thousand Q&A turns). Use the log service and monitoring alerting capabilities to configure threshold alerts, and drill down into the root cause of any cost spike: is the prompt getting longer, are retrieval fragments bloating, or has the routing split drifted?
7. Evaluation and Load Testing Before Launch
A price cut does not mean you can scale traffic immediately. The standard process is: build an offline evaluation set covering typical tasks and compare the two tiers on accuracy, format compliance, and latency; then run a small-percentage canary with shadow traffic and watch the real cost and quality curves; then ramp up gradually. Load testing should cover three extreme scenarios — long context, high concurrency, and cold cache — to avoid a sudden hit-rate collapse and a bill spike after launch.
8. Common Pitfalls
- Looking only at unit price and ignoring output length, which makes the “cheaper model” more expensive.
- Stuffing everything into the context to chase quality, ignoring that input cost grows linearly.
- Mixing dynamic content into the cached prefix, driving the hit rate toward zero over time.
- Lacking per-token-type statistics, which makes cost sources impossible to locate.
- Switching models all at once, with no regression or rollback plan.
9. Conclusion
Falling prices are a long-term trend, but the cost advantage belongs only to teams that fully understand the billing structure. With the four-part toolkit of tiered selection, prefix caching, output constraints, and end-to-end observability, you can push unit call cost into a reasonable range without degrading capability. If your workloads already run on Baidu AI Cloud capabilities, these practices map directly onto general product categories such as model services, log services, and monitoring and alerting, forming a cost governance mechanism that can keep iterating.
