## LLM API Cost Optimization: Why Identical Token Prices Still Produce Different Bills
LLM API providers can quote identical per-token prices, yet monthly bills for the same workload can differ by nearly twofold. The gap comes from billing rules rather than rates: the three-part input, output, and cache-hit pricing; batch discounts for offline jobs; token subscription plans; off-peak pricing; regional premiums; free quotas; and model migrations. This article explains how to design requests for prompt caching, provides a decision framework that maps workload characteristics (real-time versus offline, stable versus spiky volume, existing cloud usage) to a cost strategy, and gives a reusable Python cost estimation function. Follow the four-step approach, and cutting spend by 30–50% at the same volume becomes a predictable result.
1. Identical Unit Price, Different Bills: Where Does the Difference Come From?
Many teams compare LLM API costs by looking at a single number: the per-million-token rate. Yet when multiple providers quote exactly the same list price, the month-end bill can still differ by nearly twofold for the same business usage.
The reason is simple: the per-token rate is only the surface of the cost. What really determines the bill is the entire set of billing rules beyond the unit price, such as how caching is charged, whether offline jobs get a discount, whether capacity subscriptions are available, whether off-peak calls are cheaper, and whether there is a regional premium.
In short:
LLM API cost = billing structure × call pattern × selection strategy
Look at only the first factor, and you will never get an accurate bill. Let’s break it down layer by layer.
2. Understand the Billing Structure: Input, Output, and Cache Hits Are Three Different Prices
Mainstream LLM APIs generally bill by token, with the unit unified as “CNY per million tokens.” However, the price is never a single number but a triplet:
- Input (the part of the prompt that does not hit the cache)
- Output (the completion generated by the model)
- Cache hit (repeated prefixes served from the cache)
A few general rules are worth remembering:
- The output price is usually several times the input price. This means the impact of output length on cost is seriously underestimated. A change that asks the model to produce “a few hundred more words” may cost more than “adding a thousand more words of context.”
- The cache-hit price is usually only about one-tenth of the input price. This points to the most important lever for reducing LLM costs: prompt caching (prefix caching).
Designing cache-friendly requests
Prefix caching works like this: a stable prefix, such as a system prompt, fixed few-shot examples, or a long document, can be reused as long as its content stays unchanged. On a cache hit, you pay only the very low cache-hit rate. To make caching effective, how you structure your requests matters more than which model you choose:
def build_request(system_prompt: str, turns: list[dict]) -> dict:"""Place stable content first to maximize the prefix cache hit rate."""messages = [{"role": "system", "content": system_prompt}] # stable prefix -> easy to cachemessages.extend(turns) # dynamic content is appended only after the stable prefix, avoiding cache invalidationreturn {"model": "<your-model>", "messages": messages}
Three practical tips:
- Put the stable prefix first: Keep system prompts, tool definitions, and long-lived context at the very front and unchanged.
- Put dynamic content last: Do not mix timestamps, random IDs, or temporary user input into the prefix, or the prefix changes with every request and the cache is never hit.
- Watch the cache lifetime: Prefix caches typically have a TTL (time to live) and expire after a timeout or when the cache fills up. The “write” is often billed separately at a higher rate with its own TTL, and only subsequent “hits” are cheap. So high-frequency requests with a stable prefix deliver the biggest savings, while one-off requests see almost no benefit.
3. Five Hidden Rules That Decide Your Monthly Bill
Beyond the unit price, the following five categories of rules are where the real gap comes from.
1. Batch API: The Discounted Channel for Offline Jobs
For tasks that do not need real-time responses, such as data cleaning, offline summarization, batch labeling, and log analysis, most providers offer an asynchronous batch API. It charges a discount on the standard rate (commonly 50–60% of it), with the tradeoff of response times stretching to minutes or even hours.
The criterion is simple: as long as no user is waiting for the result, use batch processing. Running offline jobs on the real-time API is the most common waste.
2. Subscriptions / Token Plans: Trade Commitment for a Discount
Some providers offer token capacity packages purchased on a periodic basis, turning pay-as-you-go into a prepaid plan. Their value lies in the following:
- A lower unit price than pay-as-you-go, but overage is billed at a higher rate;
- Some plans also tie in off-peak rules, where only tokens consumed during low-traffic hours qualify for the plan discount.
These plans suit workloads with stable, predictable usage. Workloads with highly volatile usage may end up costing more because of the overage.
3. Off-Peak Pricing
Some providers offer discounts during low-traffic hours (often late night to early morning). If your workload allows non-real-time tasks to be queued for off-peak execution, costs can drop significantly. This works best combined with batch processing and a scheduling queue.
4. Regional Premiums
Prices often differ across a provider’s regions, with overseas regions typically priced higher than domestic ones. When deploying across multiple regions, remember to factor these unit price differences into your calculations.
5. Free Quotas and Model Migrations
- Free quotas: New model launches often come with free token quotas for a period of time, which suit early validation and load testing.
- Model retirement: Older models go through a “stop new registrations → gradual phase-out” process. Migrating to newer models not only ensures availability but often brings a lower unit cost as well. Part of cost optimization is proactively upgrading versions.
4. Selection Framework: Segment by Use Case First, Then Talk Savings
With all these rules in mind, you can decide along two axes:
| Use Case Characteristics | Recommended Strategy | Cost Impact |
|---|---|---|
| Real-time interaction, short output | Pay-as-you-go + caching optimization | Savings come mainly from cache hit rate |
| Real-time interaction, locked to a specific model | Pay-as-you-go, or a capacity subscription under stable volume | Subscriptions are cheaper under stable, high-frequency use |
| Offline, no real-time requirement | Batch API | Discounted pricing directly |
| Offline, some latency acceptable | Batch processing + off-peak scheduling | Discounts stack with off-peak pricing |
| Existing cloud workload | Connect to the same cloud’s LLM services nearby | Unit price is usually on par with the model’s original provider, with no cross-cloud transfer or ops costs |
The last row matters: if you already have workloads on a cloud (for example, data processing or application services on Baidu AI Cloud), connecting to that cloud’s LLM services nearby means the unit price is usually the same as the model’s original provider, while you save the hidden costs of cross-cloud data transfer, authentication, and operations. Network location is a cost item in its own right.
5. Calculate Your Bill: A Cost Estimation Function
Don’t make selection decisions on gut feeling. Use a reusable calculation tool instead. The function below brings together the triplet unit prices and the cached token count:
def estimate_cost(input_tokens: int,cached_tokens: int,output_tokens: int,unit_price: tuple[float, float, float]) -> float:"""unit_price: (input price, cache-hit price, output price), in CNY per million tokensReturns the cost of a single request in CNY."""price_in, price_cache, price_out = unit_pricemissed = input_tokens - cached_tokens # input tokens that did not hit the cacheassert missed >= 0, "cached tokens cannot exceed total input tokens"return (missed * price_in+ cached_tokens * price_cache+ output_tokens * price_out) / 1_000_000
Combined with offline batch processing, you can further estimate the savings from discounts:
def compare_batch(standard_cost: float, batch_discount: float = 0.5) -> float:"""Compare the cost of real-time pay-as-you-go vs. batch processing."""batch_cost = standard_cost * batch_discountreturn {"standard": round(standard_cost, 4), "batch": round(batch_cost, 4)}
With tools like these, you can quantify assumptions during the selection phase, such as how much to raise the cache hit rate, how many tasks to move to batch, and how much volume to put on a subscription, instead of regretting them only after the month-end bill arrives.
6. Common Pitfalls
- Looking only at unit price while ignoring output length: Output is the most expensive component, so compressing output saves more than compressing input.
- Running batch work on the real-time API: Offline jobs that skip batch processing mean giving up 50–60% off.
- Unstable cache prefix: Putting timestamps or random values into the prefix means the cache is never hit.
- Ignoring regional differences: Overseas deployment may see unit prices about 10% higher.
- Buying a subscription despite highly volatile volume: Overage charges can eat up the discount, making pay-as-you-go cheaper.
7. Summary
LLM API cost is never determined by the unit price alone. When unit prices are the same, nearly all of the difference in bills comes from billing rules: caching, batch processing, subscriptions, off-peak pricing, regions, free quotas, and version migrations.
The actionable path to lower costs comes down to four steps: compress output, optimize cache prefixes, move offline jobs to batch processing, and carefully choose subscriptions or nearby access based on how much your volume fluctuates. Bake this logic into your architecture design and cost estimation tools, and saving 30–50% at the same business volume is a predictable outcome.
