A Practical Guide to Calculating the Real Cost of LLM Inference

    Comparing per-million-token list prices across vendors is misleading, because a real bill is a weighted sum of cached input, uncached input, and output tokens. This guide presents a blended cost formula, explains why prefix cache hit rate is the primary controllable variable, covers off-peak pricing windows, shows how to convert subscription coding plans into an effective discount rate, and outlines a repeatable measurement workflow for ongoing cost optimization.

    1. Why “Price-per-Token Comparisons” Almost Always Get the Math Wrong

    In cost assessments for LLM applications, the most common mistake is putting different vendors’ “price per million tokens” side by side and declaring a winner. This ignores a basic fact: the bill for a real request is a weighted sum of several billing items, and the weights can differ by an order of magnitude depending on the workload.

    Once a request enters the inference service, it is typically split into three token classes: the part that hits the prefix cache, the input part that misses the cache, and the output generated by the model. Their unit prices often differ dramatically — cached tokens are the cheapest, output tokens are the most expensive, and uncached input sits in between. So two services can quote nearly the same price on a single line item, yet the final bill can flip as soon as their cache billing policies or output pricing differ.

    The conclusion is straightforward: cost assessment must use the blended cost per effective token as the unit of measure, not the quote for any single line item.

    2. The Cost Model: Writing the Bill as a Formula

    Let the cache hit rate be h, the input share be α, and the output share be β (α+β=1), with cached unit price p_c, uncached input unit price p_i, and output unit price p_o. The blended cost per million tokens is:

    1. def blended_cost(p_c, p_i, p_o, hit_rate, input_ratio):
    2. """Return the blended cost per million tokens (same unit as the unit prices)"""
    3. cached = hit_rate * input_ratio * p_c
    4. missed = (1 - hit_rate) * input_ratio * p_i
    5. output = (1 - input_ratio) * p_o
    6. return cached + missed + output

    This formula explains two seemingly contradictory phenomena.

    The first is the high-hit scenario. When h approaches 0.98, input is only 1.5%, and output is 0.5%, the bill is almost entirely determined by the cache unit price. The service with the lower cache quote wins, and the gap is roughly proportional to the ratio of the two cache prices.

    The second is the medium-hit scenario. When h drops to around 0.95, the missed portion of the input is billed at full price, and its cost contribution is amplified quickly. If the two services differ in their full input price, the ranking can flip — the one with the higher cache quote may actually be cheaper.

    The takeaway: a low cache price does not mean a low total cost. It only becomes the dominant term when the hit rate is high enough. Any cost comparison must state its hit rate assumption first; otherwise the conclusion is meaningless.

    3. Hit Rate Is the First-Order Variable

    Hit rate is not a server-side property; it is a product of how the caller’s code is structured. In practice, it can be improved in four directions:

    • Stable prefix: put the system prompt, tool declarations, and examples at the very front of the request, and do not insert volatile content such as timestamps or random IDs in the middle.
    • Converged branches: reduce conditional concatenation in prompt templates so that the same business intent lands on the same prefix.
    • Batched homogeneity: group similar requests into batches so the prefix is not repeatedly flushed by different requests.
    • Monitoring first: use a logging service or monitoring alerts to track prefix reuse rate, and treat hit rate as a first-class metric rather than a black box.

    An illustrative structural comparison:

    1. High-hit structure (recommended) Low-hit structure (avoid)
    2. [Fixed system prompt] [Timestamp][Random session ID]
    3. [Fixed tool declarations] [Fixed system prompt]
    4. [Stable few-shot examples] [Dynamically concatenated template fragments]
    5. [User question] [User question]

    It is worth stressing that a cache hit means this part of the context is reused. When sensitive data is involved, desensitize and minimize it first, then consider the caching strategy — security and cost need to be evaluated together.

    4. Peak and Off-Peak Pricing: The Underrated Second Variable

    Beyond caching, many inference services use time-based pricing: standard rates during peak hours and discounts during off-peak hours. The real trap is that vendors do not define “peak” the same way — some split by calendar day and cover multiple windows, while others carve out only a very short window on weekdays. The narrower the window, the more feasible it is to schedule jobs into off-peak periods.

    So the scheduling side should do three things: move latency-insensitive work such as offline batch processing, code completion warm-up, and bulk summarization into off-peak windows; keep capacity available at any hour for interactive online paths; and manage time-window policies through a configuration center instead of hard-coding the windows into business code.

    5. How to Convert Subscription Coding Plans

    When usage is predictable and continuous, a subscription is often more economical than pay-as-you-go. Evaluating a plan means more than looking at the monthly fee; you have to convert it into an “equivalent full-price API quota” and then compute the discount rate:

    1. Discount rate = Monthly plan fee / (Weekly token quota × 4.33 × Full-price blended unit cost)

    If a plan tier provides hundreds of millions of tokens per week outside peak hours, converting at the full-price blended unit cost usually yields an equivalent quota of one to two times the monthly fee — meaning the plan’s unit price is roughly 50% to 70% of the pay-as-you-go full price. A lower discount rate is better, but it holds only under three conditions: your real usage consumes most of the quota, the workload can be scheduled into off-peak windows, and the quota resets weekly with no carry-over, so idle capacity is wasted.

    A common mistake is buying a plan based on peak-week usage and then consuming only about 30% of the quota long term, which makes the effective unit price higher than pay-as-you-go. The right approach is to run a percentile estimate on the real call volume of the past 4 to 8 weeks and pick the tier around P70.

    6. A Reusable Measurement Workflow

    1. Sample: instrument requests to record the three token classes, the time window, and whether the prefix was reused.
    2. Aggregate: compute h, α, and β per business scenario separately; do not let global averages hide long-tail scenarios.
    3. Substitute: plug the numbers into the formula above to get the blended unit price for each option.
    4. Convert: translate subscription plans into a discount rate and compare them side by side with pay-as-you-go results.
    5. Recheck: recompute monthly, because changes to business prompts directly change the hit rate.

    7. Conclusion

    Real cost = cache hit rate × cache unit price + uncached input × full input price + output × output unit price, plus a discount factor from peak and off-peak windows. The unit price is only one parameter; hit rate and scheduling strategy are the levers you actually control. Making these three items part of routine monitoring and a monthly review is what gives cost optimization a sustainable basis. For scenarios that need both elasticity and stability, general cloud capabilities from platforms such as Baidu AI Cloud (for example, logging, monitoring alerts, and container platforms) can carry the scheduling and observability paths.