LLM API Pricing and Cost Optimization: A Practical Guide to Token Billing, Caching, and Routing
Over-budget LLM bills are usually driven by request structure rather than raw call volume. This article breaks down the three layers of modern inference pricing—separate input and output token rates, context caching with asymmetric hit and write costs, and tiered service channels—and turns them into a single cost formula you can instrument. It also provides a cost attribution code sample, a ranked list of optimization levers, a vendor evaluation checklist, and common mistakes to avoid.
1. The Starting Point: Why Pay-as-You-Go Does Not Mean Cost Control
In enterprise LLM applications, bills that exceed budget are rarely caused by runaway call volume. More often, the billing dimensions themselves are underestimated. Mainstream inference services meter usage by token, price input and output separately, and add context caching plus tiered service channels on top. Understanding how these dimensions multiply against each other is the first step toward cost governance.
A common misconception is treating a lower unit price as a lower total bill. If context length grows, cache misses increase, or the output share stays high, a unit price cut gets cancelled out by amplified usage. Cost evaluation therefore has to start from the structure of a single request, not from a per-million-token sticker price.
2. The Three Layers of the Billing Model
2.1 Base Tokens: Input and Output Priced Separately
Input is usually priced well below output, sometimes by a factor of several times. The reason is that the output phase generates tokens autoregressively one by one, which consumes far more compute and GPU memory than the parallel encoding of an existing sequence. The engineering implication is straightforward: controlling output length—especially redundant fields in structured generation—saves more money than compressing input.
2.2 Context Caching: The Asymmetry Between Hits and Writes
Caching separates a reusable prefix from repeated computation. Its billing has three characteristics:
- The cache hit rate is the lowest of all, typically a small fraction of the base input price;
- Cache writes cost extra and are tiered by retention duration—the longer you keep them, the more you pay;
- The write price is often on par with the base input price or a multiple of it, making it a one-time sunk cost.
This yields the core inequality: caching only pays off when reuse count × hit savings > write cost.
2.3 Tiered Channels: The Premium for Low Latency
The same model is often offered through a standard channel and a high-speed channel, with the latter costing roughly twice as much while the cache hit price stays the same. The premium buys throughput and time to first token, not a lower marginal compute cost. For offline batch jobs, paying that premium usually yields nothing.
3. Cost Modeling: Breaking the Bill Into Optimizable Variables
The cost of a single request can be abstracted as:
Cost = Lin*P_in + Lout*P_out+ H*(Lpre*P_cache_hit)+ (1-H)*Lpre*P_in+ W*P_write
Here H is the prefix hit ratio, Lpre is the cacheable prefix length, and W is the number of tokens written in this call. In practice, this formula should be wired into your observability stack: log input and output length, cache hit status, and channel type for every call in your logging service, then use monitoring alerts with thresholds for signals such as “cache hit ratio drops sharply” and “output length P99 spikes.”
An illustrative cost attribution implementation:
def estimate_cost(req, price, cache_hit_ratio):base_in = req.input_tokens * price.inputbase_out = req.output_tokens * price.outputcache = req.prefix_tokens * cache_hit_ratio * price.cache_hitmiss = req.prefix_tokens * (1 - cache_hit_ratio) * price.inputwrite = req.write_tokens * price.writereturn base_in + base_out + cache + miss + write
4. Optimization Levers: A Practice Checklist Ranked by Payoff
- Stabilize the prefix to raise the hit ratio. Put system prompts, tool definitions, and few-shot examples first in a fixed order, and keep timestamps and random IDs out of the prefix. Once the prefix changes, every subsequent token degrades to a miss.
- Reuse instead of rewriting. When multi-turn conversations or batch jobs share the same prefix, a single write followed by many hits delivers the highest payoff; one-off tasks should disable cache writes.
- Compress output. Cap the maximum generation length, trim fields in structured output, and stop the model from restating the input.
- Route in tiers. Split requests by difficulty across model sizes so simple tasks do not occupy high-spec compute.
- Choose channels on demand. Use the high-speed channel for interactive scenarios to buy experience, and the standard channel for offline batch work to buy cost savings.
- Match retention to your business rhythm. Short-lived sessions do not need a long retention tier—avoid paying for duration you will never use.
5. A Decision Framework for Selection
When evaluating a given inference service, check the following in order: whether the price structure separates input and output, whether prefix caching is supported and how hits and writes are priced, whether tiered channels are available, and whether usage details and budget alerts are provided. Put these dimensions into a comparison table, then run a weighted estimate against your actual request profile—average input and output length, prefix reuse rate, latency requirements. The conclusion will be far more reliable than comparing unit prices alone.
6. Common Pitfalls
- Looking only at the input price while ignoring scenarios with a high output share;
- Keeping cache writes on while the hit ratio stays persistently low;
- Running batch jobs on the high-speed channel;
- Setting no budget alerts, so problems only surface in the month-end bill;
- Continuously concatenating more context under the mistaken belief that “memory is free.”
7. Conclusion
The essence of LLM inference cost is the product of token structure and billing dimensions. Break a request into five variables—input, output, cache hit, cache write, and channel premium—set an optimization target for each, and bring them into your observability stack. Cost then turns from an uncontrollable black box into an engineering metric you can tune continuously. In related work at Baidu AI Cloud, this approach applies equally well to cost governance across general-purpose inference services.
