Cross-Cloud LLM API Billing Compared: Four Rules to Halve Your API Costs
When the same model at the same version carries identical per-token prices across most major clouds, monthly API bills can still differ by nearly 2x. This article reframes an LLM inference bill as usage × rules rather than usage × unit price, then breaks down four cost drivers—batch async processing, subscription/resource packs with off-peak scheduling, prefix caching, and regional/nearest access—explaining how much each can save, when it applies, and at what cost. It also provides a ready-to-run Python cost model and an implementation guide covering usage instrumentation, monitoring, retries, and output governance, so you can turn billing rules into measurable, day-by-day cost control.
Cross-Cloud LLM API Billing Compared: Four Rules to Halve Your API Costs
1. The Phenomenon and the Misconception: Identical Unit Prices, Yet Bills Differ by 2x
As LLM applications move into large-scale production, token-based pricing for cloud vendors’ model APIs has become a major cost line. Many teams do the same thing: they list the per-million-token input price, cache-hit price, and output price of a third-party model platform (the general-purpose models behind AI coding tools, open-source model hosting services, etc.) across different clouds into a table to see which platform is cheaper.
The conclusion is often surprising: for the same model at the same version, the published pay-as-you-go unit prices are identical across most mainstream clouds’ model services. Only some platforms fail to list the cache price for a given model tier on their pricing pages, requiring you to check the pricing notes to confirm. If the unit price is the same, the monthly bill should be the same. Yet when you plug the same usage into two platforms, the results can differ by nearly half.
The reason is simple: the unit price is only one multiplier of the bill. The real bill is determined by a set of rules working together:
- Billing mode: real-time pay-as-you-go, batch async, or subscription/resource pack;
- Time window: peak vs. off-peak (some platforms offer off-peak discounts);
- Caching: whether the prefix hits, and when it hits;
- Region and access location: regional differences and cross-region traffic;
- Version tier: flagship vs. lightweight.
Identical unit prices mean all teams start from the same line, and price comparison contributes almost nothing to cost. What really drives the gap apart is the rules behind these four variables. This article tries to answer three questions:
- Which rules make up the bill;
- How much each rule can save, under what conditions it applies, and at what cost;
- How to hardcode these rules into your system with engineering means.
For clarity, the discussion below refers to cloud platforms that provide third-party model hosting and invocation as “model service platforms” (abbreviated as “platform” in some scenarios), and to cloud platforms that provide model services as “cloud platforms.” Each platform’s specific rates, discounts, and specs change over time, so actual decisions should be based on the official pricing documentation and your usage bills. All numbers in this article are illustrative examples of the calculation logic.
2. Start with a Model: Bill = Usage × Rules, Not Usage × Unit Price
2.1 The Billing Formula
Breaking the bill apart, the monthly LLM inference bill can be written as:
Monthly bill = Σ (per task type: uncached input × input price + cached input × cache price + output × output price)× (1 - schedulable share × corresponding discount)× (1 - off-peak share of the schedulable portion × time-window discount)- subscription/resource pack credit
(The exact scope of each discount follows the platform’s billing documentation; this is a simplified illustration.)
This formula hides three often-overlooked conclusions:
- The input side has a “triple discount”: the uncached portion is billed at full price, the cached portion at the cache price, and the offline/off-peak portion further at the channel discount.
- The output side has only a “double discount”: output has no cache, so it can only rely on batch and off-peak discounts.
- Subscription credit is subtraction: it changes the baseline, not the unit price.
2.2 Six Variables Determine the Bill
| Variable | Typical range | Direction of impact |
|---|---|---|
| Input tokens | Related to knowledge base size, conversation history, number of retrieved snippets | Input price × cache-miss rate |
| Output tokens | Related to generation length, reasoning process, structured formatting | Output price (usually much higher than input) |
| Prefix hit rate | Can be high with long system prompts, stable tool definitions, multi-turn conversations | Directly determines the real effect of the cache discount |
| Schedulable share | Offline batch, log summarization, data cleaning, etc. | Determines coverage of batch and off-peak discounts |
| Billing mode | Pay-as-you-go / subscription / resource pack | With high enough utilization, subscription amortizes the unit price |
| Region and access | Regional price differences, network latency, and traffic fees | Affects both unit price and latency |
When budget is tight, compress the first two first; as engineering matures, do the third and fourth in turn; once the business is stable and usage is predictable, use the fifth to lock in the unit price; finally, use the sixth to cover latency and compliance requirements.
2.3 Premise 1: Output Tokens Are Usually the Biggest Cost
Published pricing generally follows one rule: the output unit price is clearly higher than the input unit price, ranging from several times to more than ten times. Let the input price be I, the output price be O, and the input/output tokens be Nin and Nout. Let the share of output in the total cost be r = Nout·O / (Nin·I + Nout·O), and we can derive the leverage factor:
L = (O / I) × (Nin / Nout) × (1 - r)
L means: reducing one output token saves roughly L “input-token-equivalent costs.”
Using the example I = 4, O = 12, Nin = 1000, Nout = 200, we get L ≈ 18, meaning reducing one output token is roughly equivalent to reducing 18 input tokens. This gives three optimization mainlines:
- Compress output: cap maximum generation length, use structured output instead of lengthy explanations, don’t make the model “write essays,” and hand complex logic to code;
- Compress input: summarize history, trim retrieved snippets, control the context window;
- Make input cheaper: prefix caching, cheaper model tiers, batch async, off-peak scheduling.
2.4 Premise 2: Unify Units, Discount Scope, and Version Baseline
- Units: “yuan per million tokens” and “yuan per thousand tokens” are easily confused, differing by a factor of 1000; input, cache, and output are usually three independent rates.
- Discount scope: some discounts apply to the whole request, some only to input, and some require creating the task in advance and respecting min/max length limits; you can’t mix them when calculating.
- Cache threshold: the cache usually covers only the stable prefix of the input, with a minimum length threshold and a validity period; the uncached portion is billed at full price and output is unaffected.
- Version baseline: a model generation often has multiple tiers such as flagship, lightweight, and coding-specific, with unit prices that can differ by several times; comparisons must lock onto the same version. Older versions have deprecation plans, and migration itself is a cost.
- Free quota: the free quota offered to new users or at a new model’s launch is a one-time trial offer and shouldn’t be factored into long-term cost forecasts.
3. Rule 1: Batch Async—Trade Acceptable Latency for a Unit-Price Discount
3.1 The Essence of the Rule
The supply of inference compute fluctuates, while real-time calls are extremely sensitive to latency, so platforms must reserve resources for peak demand. Batch async tasks don’t require instant returns, so the platform can:
- Queue tasks and process them in bulk when compute is idle;
- Improve GPU utilization and amortize idle costs;
- Pass part of the savings back to developers.
This is the fundamental reason batch prices are lower than real-time prices, consistent with the logic of offline data center economies of scale.
3.2 Applicable Scenarios and Boundaries
| Good fit for batch async | Poor fit for batch async |
|---|---|
| Summarizing, tagging, and archiving historical documents | Online customer service, instant Q&A |
| Sentiment and intent classification of reviews/tickets | Agent tasks requiring real-time user interaction |
| Offline data cleaning, content-moderation preprocessing | Callbacks tightly coupled with online pipelines |
| Training-data construction, evaluation regression | API services requiring sub-second response |
| Scheduled reports, nightly batch jobs | High-frequency short requests (high overhead ratio) |
There is only one decision criterion: can the user perceive the latency? Anything users can perceive goes through the real-time pipeline; anything that only flows in the background should prefer the batch pipeline.
3.3 Engineering Implementation Points
- Unified entry + priority routing: all calls pass through the same entry, which decides real-time vs. batch based on task labels;
- Idempotency and deduplication: use a business primary key or content hash as the idempotency key to avoid duplicate billing from failed retries;
- Write results to object storage: batch results are written to object storage, and the business side consumes them via callback or polling;
- Queue-based peak shaving: use a message queue to buffer traffic and shift peak-hour calls to off-peak;
- Timeout and fallback: set a maximum wait time, and tasks that time out fall back to the real-time pipeline or a degraded path.
3.4 Quantifying the Savings
Let the share of batch-eligible calls be p and the batch discount be d; then the maximum savings is p × d. For example, with p = 0.6 and d = 0.4, you can save 24%. Note:
- This ratio depends on business structure, not platform choice;
- The difference between incremental and existing business is large. Existing business has plenty of historical data to process in batch, leaving large room for savings; a brand-new business that is mainly online interaction has limited room;
- Batch is usually still billed on the full input and output, so the “compress output” principle still applies.
4. Rule 2: Subscription/Resource Packs and Off-Peak—Prepay to Lock Unit Price, Discount Again at Off-Peak
4.1 The Economics of Subscription/Resource Packs
The essence of a subscription/resource pack is prepay-for-discount: you pay a fee upfront to get a call quota for a period, and usage beyond that is billed at the standard or overage price.
Let the pay-as-you-go unit price be p, the pack price be F, and the quota be Q, so the in-pack unit cost is c = F / Q. Then:
- When actual usage N ≤ Q, the cost is F, and the average monthly unit price is F / N;
- When N > Q, the cost is F + (N − Q) × p.
This is the point of the “subscription + pay-as-you-go overage” hybrid: the subscription locks in a low price for stable, predictable baseline traffic, while the overage portion doesn’t make you pay for quota you won’t use. For highly volatile business, this is safer than buying one large quota upfront.
The minimum monthly usage N* at which subscription pays off is:
N* = F / (p − c) = Q × p / (p − c)
With p = 4 and c = 3, N = 4Q. In other words, *subscription only starts saving money when actual usage reaches 4× the quota. When usage is only 1.5× the quota, the subscription’s average unit price is 3.67, already close to the pay-as-you-go price of 4, and once you add the overage portion, there’s almost no benefit. If usage stays between 1× and 2× the quota long-term, subscription may actually be more expensive.
You can compute the break-even point directly in code:
def pack_monthly_cost(N, Q, F, p):"""N: monthly usage; Q: pack quota; F: pack price; p: pay-as-you-go unit price (same unit)"""return F + max(0.0, N - Q) * pdef pack_breakeven(Q, F, p):"""Return the minimum monthly usage at which subscription beats pay-as-you-go"""return Q * p / (p - F / Q) # requires F/Q < pfor N in (500, 1500, 3000, 5000, 8000):print(N, round(pack_monthly_cost(N, 1000, 3000, 4)))print(pack_breakeven(1000, 3000, 4)) # 4000.0
The output is:
500 30001500 50003000 90005000 170008000 290004000.0
You can see that at 1500 usage, subscription (5000) is cheaper than pay-as-you-go (6000), but the gap between the subscription’s unit price of 3.33 and the pay-as-you-go price of 4 has been eaten up by the overage. Only at 5000 usage does the subscription’s amortization effect fully show.
If a certain period really needs a large amount of temporary compute, you can also evaluate building your own inference cluster or renting GPU instances. But you must factor in the hidden costs: idle instance uptime, VRAM fragmentation, batch throughput tuning, model upgrades and canary releases. In general, self-hosting has a cost advantage only when baseline usage is stable and high enough.
4.2 Off-Peak Discounts: Scheduling Tasks to the Trough
Some platforms give discounts to requests in specific time windows, with logic similar to peak/valley electricity pricing. Suppose peak and off-peak each account for half of the call volume, and the off-peak discount is d = 0.5; then moving half of the calls to off-peak saves roughly d / 2 = 25% overall. If you stack “batch + off-peak,” some platforms may take the better of the two discounts.
Implementation can leverage common cloud capabilities such as function compute, scheduled tasks, and message-queue delayed messages:
- Tag deferrable tasks and specify an “earliest executable time” when enqueuing;
- Have the scheduler consume them in bulk during the off-peak window;
- The real-time pipeline is completely unaffected.
4.3 The Common Constraint of Both Rules
Both subscription and off-peak depend on one premise: usage is predictable.
- With large usage fluctuations, you easily over-buy on subscriptions;
- With fast business growth, you easily exceed the quota.
The recommended rollout order is:
- First ship usage instrumentation and accumulate at least one or two full business cycles of data;
- Use two lines—average monthly usage and peak (e.g., P95)—to decide the subscription quota and safety margin respectively;
- Review monthly and adjust gradually.
5. Rule 3: Prefix Caching—Stable First, Variable Last
5.1 The Principle: KV Cache Reuse
During Transformer inference, the model must compute Key/Value vectors (the KV cache) for each token in the input. The idea of prefix caching is: if multiple requests share an exactly identical prefix, the KV cache for that prefix can be reused without recomputation, and only the uncached portion is billed at full price.
The platform-side KV cache lives for seconds to minutes and can’t be retained across requests. A prefix caching service separates this cache and hosts it independently, usually with a validity period (TTL) and possibly a separate charge for writes.
This leads to the following practice principles:
- Hits are at the “prefix” level: it counts as a hit only if the consecutive tokens from the very beginning are exactly identical. Changes later in the sequence only affect the parts after them; changes earlier invalidate everything after;
- Writes have a cost and a threshold: the first write is billed, and there may be a minimum length threshold. A cache is only meaningful when hit repeatedly;
- Hits only affect input: output is always billed at the output price, and caching cannot replace output compression;
- It has a lifecycle: after a cache expires it must be rewritten, so low-frequency or long-interval tasks should evaluate the ratio of writes to hits.
5.2 Engineering Practices to Improve Hit Rate
- Stable first, variable last: put fixed content such as the system prompt, tool definitions, and output specs at the front; put variable content such as user input, retrieved snippets, and timestamps at the back;
- Append-only history, no rewriting: in multi-turn conversations, append each turn’s Q&A to the end rather than going back to rewrite earlier text;
- Remove noise: don’t embed user IDs, request IDs, or the current time into the prefix;
- Stable fingerprint: changes to tool names, parameter structures, or template versions invalidate the prefix, so pin versions and manage them centrally;
- Bucketed batching: for batch tasks sharing the same template, group by template and submit serially or in shards so that requests with the same template consistently hit the same cache;
- Monitor hit rate: compute the hit rate from the cached-token count in call logs, as the core metric for cache optimization;
- Combine with RAG: in retrieval-augmented generation (RAG) scenarios, retrieved results are dynamic content and should go after the stable instructions; if you want to cache retrieved results, let similar questions retrieve the same set of snippets, then submit them together.
The example code below simulates the above layout with a request class:
class CachedRequest:"""Stable prefix + variable suffix to maximize prefix cache hits"""def __init__(self, system: str, tools: str):self.system = system.strip() # stable: system instructionsself.tools = tools # stable: tool definitions (with fingerprint)def build(self, *dynamic_parts: str) -> list[str]:"""Dynamic parts go last, appended only, never rewritten"""return [self.system, self.tools, *dynamic_parts]
5.3 Quantifying the Savings
Let the input be Nin, the cache hit rate be h, and the cache price be C; then the input-side savings from caching is Nin × h × (I − C). Using the example I = 4, C = 0.4, Nin = 1000:
| Hit rate h | Savings | Savings as % of input cost |
|---|---|---|
| 0 | 0 | 0% |
| 30% | 1080 | 27% |
| 60% | 2160 | 54% |
| 90% | 3240 | 81% |
Caching is one of the few optimizations that loses no quality at all: the request content is unchanged, only the compute path changes. But its impact on results depends heavily on the call pattern, so validate the hit rate with real-traffic sampling before going live.
6. Rule 4: Region and Access—Place Requests Closest to Users
6.1 Regional Differences
The same model may be priced differently in different regions; cross-border regions are often more expensive, and also carry cross-border network latency and potential data-egress compliance requirements. For latency-insensitive tasks (such as offline batch processing), you can choose a region with lower prices and more abundant resources; for latency-sensitive online pipelines, prefer the region nearest to your users.
6.2 Nearest Access
If your business is already deployed on a cloud, directly calling that cloud’s model service in the same region usually lets you:
- Go over the internal network, reducing network latency;
- Avoid public-network traffic fees.
This is the source of the conclusion that “business already on a platform, accessed nearby, costs the same as the original vendor”: cross-cloud doesn’t automatically save money—same-cloud internal networking does.
6.2.1 Nearest Access Also Requires Total Cost of Ownership
Migrating your whole business to the cloud where the model lives isn’t always worthwhile. Consider the following costs in your comparison:
| Cost item | Description |
|---|---|
| Migration effort | Data migration, interface adaptation, joint testing, canary release |
| Traffic and bandwidth | Fees from cross-cloud calls and cross-region replication |
| Latency and experience | Impact of extra network hops on P99 latency |
| Compliance and data residency | Data egress and industry regulatory requirements |
| Ops and staffing | Complexity of monitoring, permissions, and cost allocation across multiple clouds |
A practical decision rule: migration is justified only when “monthly inference savings + quantifiable latency gains” is greater than “one-time migration cost ÷ payback period.”
6.2.2 The Boundary of Private or Self-Hosted Deployment
For data-sensitive scenarios with stable, high-volume calls, you can consider private deployment or self-hosted inference. You need to evaluate:
- VRAM and concurrency limits;
- Batch throughput optimization;
- Model upgrades and rollbacks.
The hidden cost of such solutions is mainly in staffing, not the hardware bill.
6.2.3 Multi-Cloud and Disaster Recovery
Multi-cloud is not an end but a means: when one platform fails or rate-limits, traffic can switch to a backup platform, but only on the premise that each platform’s billing basis is consistent; otherwise switching brings unpredictable costs.
7. Turning Rules into Code: A Unified Monthly Cost Model
Write the earlier rules into an executable model, used for pre-launch evaluation, post-launch monthly accounting, and A/B comparison before changes:
from dataclasses import dataclass@dataclassclass Rate:"""Unified rate basis: yuan / million tokens"""input_price: float # inputcache_price: float = 0.0 # cached input; approximate with input price if unknownoutput_price: float = 0.0 # outputdef input_cost(self, n_in: float, cache_hit: float) -> float:"""Cached portion at cache price, uncached at input price"""hit = min(max(cache_hit, 0.0), n_in)return ((n_in - hit) * self.input_price+ hit * self.cache_price) / 1e6def total(self, n_in: float, n_out: float, cache_hit: float = 0.0) -> float:return (self.input_cost(n_in, cache_hit)+ n_out * self.output_price / 1e6)@dataclassclass Rules:batch_ratio: float = 1.0 # batch discount factoroffpeak_ratio: float = 1.0 # off-peak discount factoroffpeak_window: tuple = (0, 0) # off-peak window [start, end)pack_price: float = 0.0 # subscription/resource pack monthly feepack_quota: float = 0.0 # subscription/resource pack quota (tokens)def in_window(ts_hour: float, window: tuple) -> bool:start, end = windowif start <= end:return start <= ts_hour < endreturn ts_hour >= start or ts_hour < end # window crossing midnightdef month_bill(records, rate: Rate, rules: Rules) -> float:"""records: iterable, each with n_in / n_out / cache_hit / batch / hour"""bill, used = 0.0, 0.0for r in records:cost = rate.total(r.n_in, r.n_out, r.cache_hit)ratio = 1.0if r.batch:ratio = min(ratio, rules.batch_ratio)if in_window(r.hour, rules.offpeak_window):ratio = min(ratio, rules.offpeak_ratio)bill += cost * ratioused += r.n_in + r.n_out# The resource pack credit offsets costs already incurred; overage is billed as usualreturn bill - min(rules.pack_price, bill) if used <= rules.pack_quota else bill
Validate with a summarized usage (using the example rates input = 4, output = 12):
@dataclassclass Usage:n_in: floatn_out: floatcache_hit: float = 0.0batch: bool = Falsehour: int = 12RATE = Rate(input_price=4, cache_price=0.4, output_price=12)r = Usage(500_000, 100_000, cache_hit=300_000, batch=True, hour=23)RULES = Rules(batch_ratio=0.6, offpeak_ratio=0.5,offpeak_window=(22, 8))print(RATE.total(r.n_in, r.n_out, r.cache_hit)) # 3400.0print(month_bill([r], RATE, RULES)) # 2040.0
| Scenario | Calculation | Cost (yuan) |
|---|---|---|
| Pure pay-as-you-go, no cache | 0.5×4 + 0.1×12 | 3200 |
| Cache hit 60% | 0.2×4 + 0.3×0.4 + 0.1×12 | 2120 |
| Add batch at 60% | (1320+1200)×0.6 | 1512 |
| Add night off-peak at 50% | (1320+1200)×0.5 | 1260 |
1260 ÷ 3200 ≈ 0.39, meaning that under the example assumptions, just stacking the three rules of “cache + batch + off-peak” can bring the bill down to about 40% of the original. Adding a well-designed subscription plan can push it further down.
Note: batch tasks also consume output, and output has no cache to fall back on, so output compression remains the most fundamental and universal optimization.
8. Implementation: Observable, Schedulable, Regression-Testable
8.1 Usage Instrumentation
For each call, record: timestamp, task label (online/batch), input/output/cached-token counts, whether it was a retry, and an estimated per-call cost. This information is the data source for the cost model and the first means of discovering “cache misses” and “batch not taking effect.”
8.2 Monitoring and Alerting
- Daily/monthly cumulative cost threshold alerts;
- Three structural metrics: cache hit rate, batch share, and off-peak share;
- Per-request cost P99, to catch excessively long outputs and abnormal context.
8.3 Retries and Backoff
Failed retries are the most easily overlooked cost amplifier. Recommendations:
- Exponential backoff + jitter;
- Set a maximum retry count;
- Use an idempotency key to avoid duplicate billing;
- For over-limit requests, truncate locally rather than blindly retrying.
8.4 Output Governance
Set a maximum output token count; apply structured constraints to output (such as a JSON Schema); strip deterministic logic out of the model output and hand it to code.
8.5 Regular Regression
Each month, run the cost model once with real usage data, compare different options, and calibrate parameters. On the cloud side, using common capabilities such as Baidu AI Cloud’s log service, monitoring/alerting, object storage, and message queue, you can build a closed loop of “collect—schedule—account,” turning cost from “only known at month-end” into “visible every day.”
9. Conclusion and Action Checklist
Identical unit prices don’t mean there’s no room for optimization—quite the opposite: when everyone faces the same price list, the cost gap depends only on how you use the rules. In priority order, do these seven things:
- Unify the baseline: lock the model version, unify the rate basis, and clarify whether a discount applies to input, output, or the whole;
- Tier: use the flagship version for complex tasks and the lightweight version for simple tasks like classification and rewriting;
- Compress output: this is the highest-ROI step;
- Prefix caching: stable first, variable last, and monitor the hit rate;
- Batch async: trade user-imperceptible latency for a discount;
- Off-peak scheduling: schedule deferrable tasks to off-peak;
- Subscription as a fallback: when usage is stable and predictable, use subscription + pay-as-you-go overage to lock in baseline cost.
One last reminder: billing rules change. Model deprecation, price adjustments, and promotional campaigns all change the optimal strategy. Cost optimization is not a one-time project but a long-term practice embedded in the R&D workflow.
