LLM API Billing Explained: Token Pricing, Prompt Caching, and Practical Cost Optimization
Listed per-token prices often fail to match the real API bill, especially once output pricing, prompt caching, and subscription quota cycles enter the picture. This article breaks down how modern LLM APIs actually charge for usage—input, output, and cached tokens—and explains the hidden differences between pay-as-you-go APIs and subscription coding plans, including credit reset cycles and isolated quota pools. It then offers a practical checklist for lowering costs through prompt trimming, prefix caching, tiered model routing, batching, and result caching, along with guidance on building your own cost-accounting baseline and a portable model integration layer.
1. The Core Problem: Listed Unit Price ≠ Actual Bill
Many teams evaluate LLM call costs by directly comparing each vendor’s public “price per thousand tokens,” only to find that the actual bill deviates noticeably from expectations. When one model generation raises output prices severalfold over the previous one while input and cache-hit prices form a tiered structure, this “just look at the unit price” approach becomes misleading.
First, clarify a basic point: API pricing is essentially the vendor’s suggested retail price, designed for raw pay-as-you-go usage. But most developers actually encounter subscription coding plans or bundled credits—and these are entirely different billing models. The former meters tokens precisely; the latter amortizes against a “credit cycle.” When compute supply is tight, subscription plans often don’t grant generous credits the way raw APIs do, so in practice the perceived gap between a “more expensive newer model” and “the competitor it targets” is quickly erased.
Understanding cost therefore can’t stop at the unit-price level. You need a complete mental model covering “billing unit → billing tier → credit cycle → quota pool isolation.”
2. The Three-Layer Structure of Token Billing
Modern LLM APIs generally use token-based metering, and the cost of a single request is usually made up of three parts:
- Input tokens (Prompt): tokens consumed by the user and system prompts.
- Output tokens (Completion): tokens consumed by the model’s generated content, usually priced significantly higher than input.
- Cached input tokens: the portion of the input that hits the context cache, priced far below regular input.
The unit-price relationship among the three is generally output > input > cached. To illustrate with a set of indicative prices (for understanding only, not any real product quote):
Input tokens: 20 per 1M tokensOutput tokens: 100 per 1M tokensCached tokens: 1 per 1M token
These numbers reveal two key facts. First, output is roughly 5x more expensive than input, so a call that “generates long text” is far costlier than one that “sends a long prompt.” Second, the cache-hit price can be as low as about 5% of regular input, which means context caching is the core lever for cost optimization.
3. Cache Hits: The Underrated Cost Lever
The essence of the cache-hit mechanism is this: when multiple requests share the same prefix (for example, a fixed system prompt, few-shot examples, or long document context), the vendor caches the already-computed portion of the input, and subsequent cache hits are billed at an extremely low price.
To maximize cache hits, how you organize the prompt is crucial. The core principle is to keep the prefix stable and place variable content at the end. For example:
# Recommended structure: stable prefix + variable suffix[fixed system instructions] → [fixed few-shot examples] → [long, stable reference document] → [this turn's user input]
If you reverse the order and put the user input—which changes every time—at the very front, the entire prefix is invalidated, the cache can’t be hit, and costs soar accordingly.
From an engineering perspective, a practical cost-estimation function can be written like this:
def estimate_cost(input_tok, cached_tok, output_tok, prices):"""Estimate the cost of a single request.prices: dict containing the unit prices for input / cached / output (per million tokens)"""regular_input = input_tok - cached_tok # regular input that missed the cachecost = (regular_input * prices["input"] / 1e6+ cached_tok * prices["cached"] / 1e6+ output_tok * prices["output"] / 1e6)return round(cost, 6)
In real deployments, it’s advisable to extract each call’s prompt_tokens, cached_tokens, and completion_tokens from the response metadata and write them into a logging service and a monitoring/alerting system. Taking mainstream platforms such as Baidu AI Cloud as an example, they typically provide general capabilities like logging services and monitoring/alerting. Teams can feed token-usage and cost metrics into their own dashboards to achieve observability that “breaks cost down by business dimension.”
4. Hidden Differences Between Subscription Plans and Pay-As-You-Go
The cost complexity of subscription plans is far higher than that of a raw API, mainly due to three “hidden variables”:
1. Credit reset cycle
Subscription credits usually reset on a fixed cycle (for example, weekly or monthly). To cope with load fluctuations, vendors may dynamically adjust the reset frequency or temporarily add credits. As a result, the same subscription fee can support quite different actual call volumes across different time windows.
2. Multiple isolated quota pools
Many platforms split calls for different capabilities into independent quota pools. For instance, “general chat credits” and “code completion / coding credits” are calculated separately and are not interchangeable. If a developer looks only at the total and ignores the pool isolation rules, they can easily exhaust one pool early while another still has room, leading to a misjudgment of actual availability.
3. The mismatch between price and perceived value
When a subscription plan’s credit allocation is less generous than expected, users unconsciously add retries and repeated conversations, further consuming credits. Combined with competing vendors periodically resetting weekly credits, the comparable basis for a user’s actual “net consumption” becomes blurry—this is the root cause of the feeling that “it isn’t really much cheaper.”
So for subscription users, the metric that truly needs to be calculated is not “unit price per million tokens” but “how many successfully completed tasks each unit of subscription fee buys.”
5. A Practical Checklist for Cost Optimization
Building on the mechanisms above, you can systematically cut costs along these dimensions:
- Trim prompts: remove redundant instructions and duplicate examples; on the output side, avoid unconstrained “long replies” and use explicit length and format constraints to suppress ineffective output.
- Cache the prefix: place stable system prompts and knowledge context at the front and reuse them to maximize the cache-hit rate.
- Tiered routing: route simple tasks to a low-cost small model and escalate complex tasks to a high-capability model, avoiding a “one-size-fits-all” reliance on the most expensive model.
- Batching and asynchrony: use batch endpoints or asynchronous queues for tasks that can be processed offline (leveraging general capabilities such as message queues to smooth peaks), which both flattens load and lowers unit cost.
- Result caching: build an application-layer cache for idempotent Q&A or identical inputs to avoid repeatedly requesting the same content.
- Budget and alerting: set token and cost budget thresholds for each business line, connect them to monitoring/alerting, and intervene early as the limit is approached.
A simple tiered-routing example:
def route_model(task):# Select a model tier based on task complexityif task.is_simple: # classification, extraction, short Q&Areturn "small_model"elif task.is_reasoning: # complex reasoning, long-form generationreturn "large_model"return "medium_model"
6. Guidance on Model Selection and Budget Planning
When facing phenomena like a given model generation doubling in price, the rational approach is to go back to the cost model itself rather than being swayed by the listed unit price:
- Build your own cost-accounting baseline: base it on “the tokens and cost corresponding to a unit of business value,” not on a horizontal comparison of vendors’ listed prices.
- Clarify the billing tiers: sort out the three-tier input, output, and cache prices, and identify whether your business mainly consumes output or input.
- Account for credits and cycles: if you’re a subscription user, be sure to confirm the credit reset rules and the multi-pool isolation mechanism to avoid misjudging availability.
- Maintain portability: decouple prompts, model calls, and business logic, and wrap a unified model access layer so that model tiers can be switched, costs compared, and vendors replaced.
7. Conclusion
The essence of LLM call cost is an engineering problem of “metering and amortization,” not a simple matter of unit price. Understanding token-tiered billing, the cache-hit mechanism, subscription credit cycles, and multi-pool isolation is the key step from “looking at unit price” to “looking at the total account.” When a team builds observable usage data, an optimizable prompt structure, and a portable model access layer, cost transforms from a passively endured black box into an engineering variable that can be budgeted, governed, and continuously optimized.
