LLM API Cost Optimization: Why the Same Unit Price Can Produce Different Bills
This article explains why LLM API bills can differ even when unit prices match, and presents a practical method for modeling, estimating, and reducing costs. It covers billing dimensions, a cost formula and sample Python estimation, cache behavior, batch discounts, subscription and overage plans, migration costs, scenario-based selection, and implementation practices such as cache-friendly prompts, output limits, usage monitoring, and periodic price reviews.
1. Why Bills Differ When the Unit Price Is the Same
The per-token unit price for the same model is often identical across providers, because many providers follow the same public price list or industry conventions. Bill differences usually come from three areas.
First, billing dimensions are divided differently. Some providers price input, output, cache hits, and cache writes separately, while others only distinguish input and output. For the same request volume, a platform with finer billing dimensions may be significantly cheaper when the cache hit ratio is high.
Second, discount rules beyond the listed price differ. For example, whether offline batch tasks receive a discount, whether real-time calls have a quota limit, and whether new models offer free quota all directly change the final amount paid.
Third, subscription plans and overage billing are combined differently. A fixed subscription fee plus overage usage versus pure pay-as-you-go can produce very different results under different usage curves.
Therefore, comparing providers by looking only at the unit price table cannot lead to a conclusion. You need to build a cost model first, then plug in your own real usage for calculation.
2. Building a Cost Model
2.1 Split Billing Dimensions
LLM API costs usually consist of the following items:
- Uncached input tokens: billed at the standard input unit price.
- Cached input tokens: billed at a lower cache-hit unit price.
- Cache writes: some platforms charge separately for content first written to cache, and the cache lifetime affects the write price.
- Output tokens: usually the highest unit price and one of the main sources of cost.
The basic monthly cost formula is as follows:
Monthly cost = (uncached input volume × input unit price + cached input volume × cache-hit unit price + output volume × output unit price + cache write volume × write unit price) ÷ 1,000,000 + other additional fees
Unit prices are in “CNY per million tokens,” and usage is measured in tokens.
2.2 Estimate Monthly Cost with Code
The following example is for calculation only. All unit prices are hypothetical numbers, not the real prices of any provider.
def monthly_cost(uncached_input_m: float, # Uncached input volume, in millions of tokenscached_input_m: float, # Cached input volume, in millions of tokensoutput_m: float, # Output volume, in millions of tokensprice_input: float, # Input unit price, CNY per million tokensprice_cache_hit: float, # Cache-hit unit price, CNY per million tokensprice_output: float, # Output unit price, CNY per million tokensdiscount: float = 1.0, # Batch or subscription discount factor; 1.0 means no discount) -> float:base = (uncached_input_m * price_input+ cached_input_m * price_cache_hit+ output_m * price_output)return round(base * discount, 2)# Assumption: 20 million input tokens per month, 60% of which hit cache; 3 million output tokens per month# Assumed unit prices: input 10 CNY, cache hit 1 CNY, output 50 CNY (per million tokens)with_cache = monthly_cost(8, 12, 3, 10, 1, 50) # Result: 242 CNYno_cache = monthly_cost(20, 0, 3, 10, 1, 50) # Result: 350 CNYbatch = monthly_cost(8, 12, 3, 10, 1, 50, 0.6) # Assume 40% off for batch tasks; result: 145.2 CNYprint(with_cache, no_cache, batch)
As the example shows, when the cache hit ratio rises from 0 to 60%, the monthly cost drops by about 31%. If offline tasks can also receive a batch discount, the cost can fall to about 60% of the original. This shows that the combined effect of billing rules is often larger than unit price differences.
2.3 Calibrate the Model with Real Usage
Model parameters should come from logs, not estimates. It is advisable to collect at least two weeks of call data and measure the following:
- Average input length and output length per request;
- Proportion of repeated prefixes in requests, i.e., the part that can be cached;
- Share of real-time requests versus offline requests;
- Time distribution of requests during the day;
- Peak concurrency and average concurrency.
Only with this data can you judge which billing method is more cost-effective.
3. Billing Rules to Watch
3.1 Automatic Cache Enablement and Cache Lifetime
Some platforms automatically enable caching for repeated request prefixes. Developers do not need to declare it explicitly, but they need to understand two points.
First, caching depends on exact prefix consistency. If the system prompt, tool definitions, or the beginning of the conversation history changes slightly each time, the cache cannot hit. Therefore, stable content should be placed at the beginning of the request, and user input that changes each time should be placed at the end.
Second, cache lifetime is limited. If the interval between two requests exceeds the lifetime, the cache expires. Some platforms charge separately for cache writes and allow different lifetimes; longer lifetimes usually have higher write unit prices. Developers should choose an appropriate lifetime based on request intervals: high-frequency calls are suitable for short lifetimes, while low-frequency calls with long context may need longer lifetimes.
3.2 Batch Offline Discounts
Offline batch interfaces allow a batch of requests to be submitted and processed by the server within a certain time window, with results returned asynchronously. Providers usually reward this delay-tolerant workload with a lower unit price because it allows more even use of compute resources.
Tasks suitable for offline processing include batch document summarization, data labeling, historical corpus cleaning, and nightly report generation. Unsuitable tasks include online customer service and interactive applications that require immediate feedback.
Note that whether batch interface discounts apply to all models and what the completion time window is should be based on the provider’s official documentation.
3.3 Subscription Plans and Overage Billing
The core of a subscription plan is a fixed fee plus quota. When calculating, distinguish three things:
- Which models the plan covers, and whether it includes the target model;
- How the plan quota is measured: by request count, token count, or time period;
- How billing works after the quota is exceeded: whether it falls back to the standard pay-as-you-go unit price or uses a lower overage unit price.
For businesses with stable and relatively large call volumes, subscription plus overage may be cheaper. For businesses with volatile or uncertain usage, pure pay-as-you-go carries lower risk.
Some plans also have time-window rules, such as discounts for calls made during specific periods. If requests can be shifted, scheduling some tasks into discount periods can significantly reduce the bill. However, the time boundaries and scope of such rules must be verified item by item.
3.4 Free Quota and New Model Strategies
When a new model is first launched, providers often offer a certain amount of free quota. This quota is suitable for validating results and load testing, but it should not be used as the basis for long-term cost estimates, because the price returns to standard after the quota expires.
3.5 Migration Costs When Old Versions Are Retired
Providers usually set dates for stopping new user access and eventual retirement of old model versions. When migrating to a new version, costs come not only from unit price changes but also from:
- Prompts for the new version may need retuning, increasing labor costs;
- Output length may differ between old and new versions, affecting output billing;
- Caches need to be warmed up again, so initial costs may be higher.
Before migration, it is advisable to run an offline comparison on the same sample set, record quality metrics and cost metrics, and then decide when to switch.
4. Scenario-Based Selection
Different business scenarios suit different billing combinations. The following framework can be used as a reference.
Scenario 1: Offline batch tasks. Prefer interfaces that offer batch discounts. These tasks are not latency-sensitive, so the discount benefit is greatest.
Scenario 2: Real-time interactive tasks with stable usage. Compare the monthly bill of subscription plus overage against pure pay-as-you-go. First estimate the minimum monthly usage; if it exceeds the break-even point, a subscription is usually more cost-effective.
Scenario 3: Real-time interactive tasks with volatile usage. Pure pay-as-you-go is more flexible. At the same time, costs can be controlled through cache design, output length limits, and load shifting.
Scenario 4: Businesses with existing cloud infrastructure. If the business is already deployed in a cloud environment, connecting to an LLM service nearby can reduce cross-network latency and data transfer overhead. In this case, fees are usually consistent with the vendor’s price list, and the selection focus shifts to network and operational convenience.
If you use large model services provided by Baidu AI Cloud, the same method can be applied to estimate costs, subject to its official billing documentation.
5. Implementation Practices
5.1 Design Cache-Friendly Prompt Structure
The recommended request structure is: stable parts first, variable parts last.
[System instructions: role, rules, output format] ← stable, cacheable[Tool definitions or knowledge base snippets] ← relatively stable, cacheable[Conversation history summary] ← updated as needed[Current user input] ← changes each time
Avoid adding timestamps, request IDs, or other content that changes every time to system instructions, because that breaks prefix consistency.
5.2 Control Output Length
Output unit prices are usually higher than input prices, so controlling output length is the most direct way to reduce cost. You can specify a maximum answer length in instructions, use fixed fields for structured output, and reduce redundant explanations. At the same time, verify that length limits do not cause answers to be truncated and affect business results.
5.3 Establish Usage Monitoring and Budget Alerts
It is advisable to record the input volume, cache-hit volume, output volume, model used, and business unit for each request, and summarize costs daily. Set budget thresholds and trigger alerts when daily costs or cumulative monthly costs approach the threshold, preventing abnormal calls (such as looped requests or prompt bloat) from causing runaway bills.
Monitoring data can be integrated into common logging services and monitoring alert systems, displayed on dashboards, and reconciled with bills regularly.
5.4 Review Prices Periodically
LLM prices and rules change quickly. Teams should include price verification in routine processes, record the verification date and source page, and make unit prices configuration items in code rather than hard-coding them. This way, when rules change, you only need to update the configuration and re-estimate.
6. Notes
- All prices and rules are subject to the latest version on the provider’s official page. This article does not constitute a quotation.
- Discount factors, lifetimes, quotas, and time-window rules may all change and must be verified again before launch.
- Cost optimization must not come at the expense of quality. After each adjustment to caching, output length, or model version, quality evaluation should be performed.
- For businesses involving data privacy, provider selection also requires evaluating data processing and storage terms. Cost is only one selection factor.
In summary, LLM API costs depend on the combination of billing dimensions, discount rules, and usage patterns. Breaking down the cost model first, calibrating it with real logs, and then choosing a billing method based on the business scenario is more effective for controlling bills than simply comparing unit prices.
