LLM API Pricing Logic and Cost Optimization Practices
This article explains how LLM API billing works and how to design for cost control from the start. It breaks down token-based pricing, including why tokens differ from characters and why output tokens usually cost more than input tokens. It then covers cache read and write billing, showing when caching repeated context pays off and when it does not. The article closes with a practical optimization checklist, common mistakes to avoid, and a vendor-neutral approach to building a predictable cost model.
1. Why the Billing Model Shapes Architecture
In enterprise LLM applications, cost is no longer a financial concern that appears after launch. It is a core constraint that must be considered during architecture design. Most mainstream model services expose their capabilities through APIs, and their pricing typically revolves around two dimensions: token usage and cache read/write operations. Understanding how each dimension is measured and how they interact is the prerequisite for making the right technical choices and controlling costs.
It is worth noting that cloud providers differ in unit prices, cache implementation details, and free quotas. This article only discusses the general billing logic widely accepted in the industry and does not cover any vendor-specific rules. In engineering practice, it is recommended to build your own cost model around “measurement basis + optimization techniques.” General-purpose product categories from cloud platforms such as Baidu AI Cloud (for example, object storage, message queues, container platforms, log services, and monitoring/alerting) can serve as the underlying infrastructure for this model.
2. Token Usage Billing: Measurement Basis and Cost Structure
2.1 A Token Is Not a Character
A token is the smallest semantic unit the model processes, and it does not correspond linearly to character count. In English, there is a rough rule of thumb that one token equals several characters. In Chinese, token consumption for the same number of characters is often higher because of different tokenization granularity. Therefore, estimating cost by character count introduces systematic bias, and actual tokenization results must be used instead.
2.2 Input, Output, and the Inference Stage
A complete API call is usually split into input tokens and output tokens, which are measured separately. The input side includes the system prompt, conversation history, retrieved document fragments added through retrieval augmentation, and the user’s current question. The output side is the content generated by the model. Because generation requires token-by-token autoregressive decoding, the compute cost on the output side is typically much higher than on the input side. This is the fundamental reason most billing schemes assign a higher unit price to output tokens.
2.3 Cost Formula and Sensitivity Analysis
The cost of a single call can be abstracted as:
Cost per call = Input tokens × Input unit price+ Output tokens × Output unit price+ Cache-related fees (hits and writes calculated separately)
What really matters in engineering is sensitivity. When the input length is far greater than the output length (typical cases include long-document Q&A and code base understanding), cost is almost entirely determined by the input side, and optimization should focus on context compression and reuse. When the output is long (such as report generation or code completion), the priority should be controlling generation length and retry counts.
3. Cache Read/Write Billing: Turning Repeated Context into an Asset
3.1 The Problem Caching Solves
In conversational and agent-style applications, the system prompt, tool definitions, and knowledge base fragments often remain completely unchanged across consecutive calls. If they are recomputed as brand-new input every time, compute is wasted and time-to-first-token increases. The value of caching is to persist stable prefix context so that subsequent requests can skip repeated computation when they hit the cache.
3.2 Two Directions: Write and Read
Caching is not free. The common industry practice is to split caching into two billing directions: write and read. The first write incurs an additional cost, while a cache hit read is usually cheaper than the original input unit price. This means the economics of caching depend entirely on the number of reuses. Only when the same context is used repeatedly can the upfront write cost be amortized.
3.3 The Math Behind Hit Rate
Let the write cost be W, the savings per read be S, and the number of reuses be N. The net benefit is approximately N × S - W. When N is small, caching can actually be more expensive. Therefore, when evaluating a caching strategy, estimate the real reuse scale first and then decide whether to enable it, rather than turning it on by default.
4. An Actionable Optimization Checklist
- Prefix stability: Keep invariant content (system instructions, tool schemas, domain descriptions) fixed at the very front of the request and place variable content afterward to improve cache hit probability.
- Context slimming: Rerank and truncate retrieved fragments, remove redundant templates and duplicate examples, and replace raw text stacking with structured summaries.
- Output constraints: Suppress meaningless generation through explicit format and length requirements to reduce output tokens.
- Batching and asynchrony: Merge non-real-time tasks into scheduled batches and use message queues to smooth peaks, improving compute utilization per unit.
- Retry governance: Set limits and backoff strategies for timeouts and failures to avoid cost amplification from exceptions.
- Observability: Use log services and monitoring/alerting to build dashboards for token consumption, cache hit rate, and cost per request, and set budget threshold alerts.
Example call wrapper:
def call_model(system_prompt, stable_context, user_query, cache=True):# Keep stable_context stable to improve cache hitsprefix = system_prompt + stable_contextreturn {"input": prefix + user_query,"cache_control": {"enabled": cache, "scope": "prefix"},"max_output_tokens": 800,}
5. Common Mistakes
- Looking only at unit price while ignoring hit rate, causing the caching strategy to spin without benefit;
- Estimating budget by character count, leading to significant deviation from the actual bill;
- Concatenating all conversation history indiscriminately, causing input tokens to grow linearly with each turn;
- Lacking a cost dashboard, so problems often surface only when the month-end bill arrives.
6. Conclusion
Billing across two dimensions—token usage and cache read/write—is essentially guiding users to treat “context” as a manageable resource. By turning stable prefixes into cached assets, compressing redundant context, and feeding cost metrics into a monitoring system, you can achieve a predictable cost curve without sacrificing quality. This methodology is vendor-neutral and applies to any general technical solution that provides model services through APIs.
