LLM API Cost Breakdown and Caching Billing: A Practical Guide
This guide breaks down large language model API pricing into three billing components—cache-hit input, cache-miss input, and output tokens—and explains why output length often drives total cost more than input optimization. It includes a cost formula you can apply to your own traffic, the prefix-stability requirements that make prompt caching work, engineering practices such as session stickiness and tiered model routing, common budgeting mistakes, and a rollout checklist for building cost visibility and alerts.
1. Why You Should Break API Costs into Three Parts
When teams first integrate LLM capabilities into a business system, they usually focus on a single number: the price per million tokens. Only after the bill arrives do they discover that actual spending is several times the estimate. The reason is straightforward. The cost of a single call is not one price multiplied by a token count, but the sum of three independently billed components: cache-hit input, cache-miss input, and model-generated output.
Take the public pricing structure of one cloud provider as an example. For a given model tier, cache-hit input costs about CNY 1.3 per million tokens, cache-miss input about CNY 13, and output about CNY 68. Reading these three numbers together reveals two key facts:
- There is roughly a 10x price gap on the input side, so whether a cache hit occurs directly determines the cost magnitude of long-context workloads.
- Output is priced far above input (in this example, about 5x the cache-miss input and more than 50x the cache-hit input). Making the model say less often reduces cost faster than making the model read less.
Note that the specific numbers vary widely across providers and model tiers. The figures cited here only illustrate the billing structure; when choosing a platform, rely on the prices published by that platform at the time.
2. Why Billing Is Split into Three Parts
2.1 Cache-Miss Input: The Full Prefill Cost
When the context carried by a request has no reusable intermediate state on the inference side, the system must run a full prefill over those tokens to build the key-value cache required for attention. This computation scales roughly linearly with input length. The unit price is the lowest of the three, but with long documents and long conversation histories it accumulates quickly into the dominant cost.
2.2 Cache-Hit Input: The Price of Reuse
If the prefix of the current request is identical to a recent one, the inference side can reuse the already-built intermediate state and compute only the newly added portion incrementally. What is saved is repeated compute; what is paid for is cache storage and lifecycle management. Hence the significantly lower price compared with cache-miss input. Economically, this gap is an incentive for keeping request prefixes stable.
2.3 Output: Token-by-Token Autoregressive Generation
The output stage decodes autoregressively, one token at a time, and every step must read the full history of states. It cannot be parallelized as fully as prefill. Low compute utilization and latency sensitivity make it the most expensive of the three. This is also why, for the same million tokens, the output portion often accounts for the majority of total spending.
3. Cost Estimation: Applying the Formula to Your Own Workload
Let (H) be the number of cache-hit input tokens, (M) the number of cache-miss input tokens, and (O) the number of output tokens, with unit prices (p_h, p_m, p_o) (CNY per million tokens). The cost of a single call is:
Cost = (H * p_h + M * p_m + O * p_o) / 1_000_000
Substituting the example prices above gives a simplified formula that is easy to estimate with:
Cost ≈ (1.3 * H + 13 * M + 68 * O) / 1_000_000
One intuitive conclusion: for a call with 1,000 input tokens and 1,000 output tokens, the cost is about CNY 0.081 if all input misses the cache, and about CNY 0.0693 if all of it hits. When output grows to 4,000 tokens, the cost jumps to about CNY 0.285. The marginal impact of output length is far larger than the room available from input-side cache optimization.
Teams are advised to hard-code this formula into load-testing scripts and replace average-value estimates with real traffic distributions (input length percentiles, output length percentiles, prefix repetition rate). Error typically converges from several times over to within 20%.
4. Prefix Stability Is the Prerequisite for Cache Hits
Cache reuse generally requires the request prefix to match token by token. This means any dynamic content placed early in the context degrades everything after it to a cache miss. Common high-frequency mistakes include:
- Putting timestamps, request IDs, or random numbers at the beginning of the system prompt;
- Prepending the user’s current input ahead of a long document;
- Frequently rewording prompts or changing spaces and line breaks;
- In multi-tenant scenarios, interleaving different users’ data within the same prefix.
The recommended context order is: stable system instructions → stable domain knowledge or reference documents → conversation history → the current user input. A schematic structure:
[fixed] Role and output specification[fixed] Reference knowledge block (version-controlled, replaced as a whole when changed)[semi-fixed] Conversation history (append-only growth)[variable] Current user question
Combined with a knowledge-block versioning strategy, this lets the vast majority of requests share the same long prefix and keeps the hit rate high.
5. Supporting Engineering Practices
- Session stickiness: route the same session to the same inference instance so the cache is not evicted by other traffic;
- Tighter output constraints: use explicit word, field, and format requirements to compress output length, and post-process structured results when necessary instead of letting the model narrate at length;
- Tiered model routing: send intent recognition, classification, and extraction tasks to lighter tiers, and escalate to higher-capability tiers only for complex reasoning;
- End-to-end metering: log the three token counts for every call at the gateway layer, build cost dashboards by business line and by endpoint, and configure budget alerts;
- Capacity and rate limiting: use monitoring and alerts to queue and degrade sudden traffic spikes, preventing runaway costs.
6. Common Pitfalls
- Looking at unit price but not structure: a model with cheap input can end up more expensive overall if its output is verbose.
- Treating the cache as a correctness mechanism you can rely on: caching affects only cost and latency, not business semantics; results must be consistent whether or not a hit occurs.
- Budgeting with average token counts: the contribution of long-tail requests to the bill often far exceeds what the average suggests.
- Ignoring retry amplification: failed retries are billed repeatedly, so backoff and idempotency controls are needed.
7. Implementation Checklist
- Map out context layering and move all dynamic fields to the end of the context;
- Establish the three-part cost formula and load-testing scripts, fed with a real traffic profile;
- Instrument the gateway to collect hit, miss, and output token counts, then build cost dashboards and alerts;
- Define output length standards and a tiered routing strategy;
- Review prices and hit rates quarterly and update the budget model on a rolling basis.
Following this approach, teams can typically bring the per-call cost of long-context applications into a predictable range without changing business logic, while capacity planning rests on solid data. For more complete managed inference, logging, and monitoring capabilities, the metering and alerting setup can be built on the relevant general-purpose cloud products from Baidu AI Cloud.
