LLM Token Accounting and Cache Billing: How Input, Output, and Cached Tokens Drive Your API Bill
This article breaks down how conversational AI usage is measured and billed, separating each request into input tokens, output tokens, and cached input tokens. It explains why cache hits lower marginal cost in long sessions, how prefix caching works and where it breaks, how time-based pricing shifts peak load, and how quotas and cost attribution fields make spending analyzable. Readers will find a practical cost-optimization checklist and the metering-first sequence behind moving from free to paid tiers.
What a Single Greeting Costs: From Chat to Bill
In free conversational AI services, users rarely sense that they are consuming anything. The picture changes once a platform shows token usage, cache hit ratio, and the converted amount under each response: chat behavior is translated into readable numbers for the first time. At typical off-peak rates, a short greeting costs only tens to a few hundred tokens for input and output combined, often less than a fraction of a cent. In a long session that has already accumulated hundreds of turns, however, the same sentence can cost something entirely different.
The difference does not come from the model “getting more expensive.” It comes from a finer billing breakdown. The mainstream approach in the industry splits the usage of one call into three parts: input (cache hit), input (cache miss), and output. Understanding these three is the key to understanding why a bill fluctuates.
Three Measurement Categories: Input, Output, and Cache Hits
- Input tokens: what the user sends in the current turn, plus the conversation history, system prompt, and tool results that are passed to the model to keep the context coherent.
- Output tokens: what the model generates. The unit price is usually much higher than for input, because generation requires a forward pass for every token.
- Cached input: the historical prefix has already been computed, so the intermediate results can be reused in this turn, which earns a substantial discount.
The key point: the longer the context, the smaller the uncached portion and the larger the cached portion, so the marginal cost may actually go down. This is also why a long session does not necessarily become more and more expensive.
Why Caching Saves Money
An autoregressive model processes the full context on every turn, but in a conversation the history is often unchanged word for word. If the computation results for this stable prefix (intermediate states such as attention keys and values) are stored, the next request that hits the same prefix can skip the repeated computation and process only the new part.
The billing logic can be sketched as:
def estimate_cost(input_tokens, cached_tokens, output_tokens,in_price, cache_price, out_price, peak_factor=1.0):miss = max(input_tokens - cached_tokens, 0)return peak_factor * (miss * in_price + cached_tokens * cache_price + output_tokens * out_price) / 1_000_000
Three engineering caveats apply. First, a cache hit requires the prefix to match exactly; changing the system prompt or inserting content into the history makes everything after it a cache miss. Second, caches have a lifetime, and once an idle entry expires it must be recomputed. Third, cache capacity is limited under high concurrency, so the hit rate fluctuates with load.
Time-Based Pricing and Peak Scheduling
Binding price to time slots is essentially using a price signal to shift compute load. Off-peak discounts and peak-hour multipliers can make the same conversation cost several times more depending on when it runs. For developers, this offers a clear optimization lever: latency-insensitive workloads such as batch jobs, offline summarization, and log analysis should be scheduled off-peak, while interactive paths need budget reserved for peak hours.
Limits, Quotas, and Cost Attribution
When call volume grows and compute supply tightens, free tiers inevitably move toward limits. The mature approach is three layers of quota: a daily or monthly token cap per account, a request cap per concurrency level, and a context length cap per session. When a limit is triggered, returning a clear error code with a suggested backoff time is friendlier than failing silently.
Cost attribution requires usage to land on analyzable dimensions. Typical fields look like this:
{"request_id": "r-8f2c","scene": "chat","input_tokens": 1840,"cached_tokens": 1760,"output_tokens": 210,"tier": "off_peak","latency_ms": 1260}
With these fields, you can answer which scene burns the most money, whether caching is actually working, and whether the context should be compressed.
A Practical Cost-Optimization Checklist
- Stable prefix: put the system prompt and tool descriptions first and never change them, to maximize cache hits.
- Trim history: replace full concatenation with rolling summaries to keep uncached input small.
- Control output: set explicit length limits and use structured output. Output has the highest unit price, so compressing it pays off most directly.
- Schedule off-peak: pool offline and real-time tasks separately and match each to a different price tier.
- Close the observation loop: build a usage dashboard with logging and monitoring alerts, and set budget threshold alarms.
The Path from Free to Paid
Early on, a large base of consumer users had unclear commercial value and was treated as pure cost. As call volume rose and compute tightened, these highly sticky users turned out to be the most willing to pay. Billing first and charging later became the natural path: let users see the cost structure before discussing quotas and plans. The lesson for developers is that metering capability should be built before billing capability. Without fine-grained usage data, any pricing or quota strategy lacks a basis. The general practice at Baidu AI Cloud around model services and observability likewise emphasizes the order of metering first, attribution second, and optimization last.
Conclusion
Splitting a chat into three measurable categories, input, output, and cache hits, and then applying a time-based factor, yields a bill that is explainable and optimizable. Understanding this logic helps you avoid hidden waste in long sessions and make the right architectural trade-offs when quotas are constrained.
