How to Calculate the True Cost of LLM API Caching

    LLM API pricing typically divides token consumption into cached input, uncached input, and generated output, each with vastly different unit prices. Evaluating only a single unit price can lead to inaccurate cost estimates. This article introduces a weighted cost formula to calculate the true cost of large language model APIs, demonstrates how cache hit rates affect the final bill, and provides a reusable Python script for cost estimation. It also compares pay-as-you-go and subscription models to help you optimize your LLM expenses.

    1. Unit Price Does Not Equal True Cost

    Large language model (LLM) APIs typically split token consumption into three billing categories: cached input, uncached input, and model-generated output. The unit prices for these three categories vary significantly. Cached input prices are often only about one-tenth of regular input prices, while output prices are usually several times higher than input prices.

    Therefore, comparing only one unit price can lead to distorted conclusions. For instance, if Plan A has a higher cache unit price and Plan B has a lower one, looking solely at the cache price would lead you to choose Plan B. However, the actual bill is determined by all three token types, and the cache hit rate can change the relative cost-effectiveness of the two plans.

    The unit prices used in this article are for demonstration purposes only and do not represent quotes from any specific vendor. Vendor prices fluctuate based on region, time, contract, and other factors. Always refer to the official documentation for current pricing before making actual calculations.

    2. Weighted Cost Formula

    Let us standardize the metrics first. Assume the total number of tokens over a certain period is N, where:

    • h: The proportion of cache hit tokens to the total tokens
    • r_in: The proportion of uncached input tokens to the total tokens
    • r_out: The proportion of output tokens to the total tokens

    These three are expressed as decimals, and h + r_in + r_out = 1. If using percentages, 98% must be written as 0.98, not 98, otherwise the result will be magnified a hundredfold.

    Let the three unit prices be P_cache, P_input, and P_output, all in CNY per million tokens. The weighted cost per million tokens is:

    cost_per_m = h × P_cache + r_in × P_input + r_out × P_output

    The cost per 100 million tokens is 100 × cost_per_m, measured in CNY.

    3. Calculations for Two Plans

    The demo unit prices are as follows (CNY/million tokens):

    Plan Cache Hit Input Output
    Plan A 0.115 1.0 4.0
    Plan B 0.05 2.5 6.0

    To observe the impact of hit rate changes, assume the uncached portion is split into input and output at a 3:1 ratio, meaning r_in = 0.75 × (1 − h) and r_out = 0.25 × (1 − h). At a 98% hit rate, input accounts for 1.5% and output for 0.5%.

    98% Hit Rate

    • Plan A: 0.98 × 0.115 + 0.015 × 1.0 + 0.005 × 4.0 = 0.1477, or approximately 14.77 CNY/100M tokens
    • Plan B: 0.98 × 0.05 + 0.015 × 2.5 + 0.005 × 6.0 = 0.1165, or approximately 11.65 CNY/100M tokens

    At this rate, Plan B is cheaper.

    95% Hit Rate, input accounts for 3.75%, output for 1.25%

    • Plan A: 0.95 × 0.115 + 0.0375 × 1.0 + 0.0125 × 4.0 = 0.19675, or approximately 19.68 CNY/100M tokens
    • Plan B: 0.95 × 0.05 + 0.0375 × 2.5 + 0.0125 × 6.0 = 0.21625, or approximately 21.63 CNY/100M tokens

    At this rate, Plan A is cheaper.

    The full comparison is as follows (values rounded to two decimal places):

    Hit Rate Input Ratio Output Ratio Plan A (CNY/100M tokens) Plan B (CNY/100M tokens) Cheaper Plan
    90% 7.5% 2.5% 27.85 38.25 A
    95% 3.75% 1.25% 19.68 21.63 A
    98% 1.5% 0.5% 14.77 11.65 B

    Under these unit prices and the 3:1 split, the hit rate at which the costs of both plans are equal is approximately 96.2%. The cost per million tokens for Plan A can be written as 1.75 − 1.635h, and for Plan B as 3.375 − 3.325h. Setting the two equations equal yields the break-even point.

    The conclusion is clear: a difference of just a few percentage points in the hit rate can reverse the ranking of the plans. You must estimate your business’s actual hit rate before conducting cost calculations.

    4. How to Estimate the Hit Rate

    The hit rate depends on the degree of prefix reuse in requests, primarily determined by the following four factors:

    1. System prompt length: Longer and fixed prompts allow for more cacheable prefixes.
    2. Context window strategy: Whether multi-turn conversations carry the full history. Long-context continuations typically have higher hit rates.
    3. Request time distribution: Caches have a time-to-live (TTL). The more concentrated the requests, the higher the hit probability.
    4. Request templating degree: When RAG retrieval results are appended to the end of the prompt, the prefix can still be reused.

    It is recommended to collect real data during a canary or testing phase rather than directly assuming ideal values. You typically need to log three fields:

    • cache_hit_tokens: Number of cache hit tokens
    • non_cache_input_tokens: Number of uncached input tokens
    • output_tokens: Number of output tokens

    Then h = cache_hit_tokens ÷ total_tokens, and similarly for r_in and r_out, where the total tokens equal the sum of these three. Before tracking, verify the vendor’s usage field definitions. Some vendors include the cached portion within the input field; adding them directly would result in double-counting.

    5. A Reusable Calculation Script

    1. def cost_per_100m(h, r_in, r_out, p_cache, p_input, p_output):
    2. """
    3. h, r_in, r_out: proportion of total tokens, as decimals (0.98 means 98%), sum must be 1
    4. p_cache, p_input, p_output: unit prices in CNY per million tokens
    5. Returns the cost per 100 million tokens in CNY
    6. """
    7. if abs(h + r_in + r_out - 1) > 1e-9:
    8. raise ValueError("h + r_in + r_out must equal 1")
    9. cost_per_m = h * p_cache + r_in * p_input + r_out * p_output
    10. return 100 * cost_per_m
    11. # Demo unit prices, not real quotes
    12. PLAN_A = dict(p_cache=0.115, p_input=1.0, p_output=4.0)
    13. PLAN_B = dict(p_cache=0.05, p_input=2.5, p_output=6.0)
    14. # The remaining part is split 3:1 between input and output
    15. for h in (0.90, 0.95, 0.98):
    16. rest = 1 - h
    17. r_in, r_out = rest * 0.75, rest * 0.25
    18. a = cost_per_100m(h, r_in, r_out, **PLAN_A)
    19. b = cost_per_100m(h, r_in, r_out, **PLAN_B)
    20. print(f"Hit rate {h:.0%}: A={a:.2f} CNY/100M, B={b:.2f} CNY/100M")

    The trailing digits of the results may differ slightly from the table above due to floating-point rounding. By integrating this script into your usage monitoring data, you can continuously track your true unit cost.

    6. Pay-As-You-Go vs. Subscription Plans

    The monthly cost for pay-as-you-go (PAYG) billing can be calculated as: average monthly usage (100M tokens) multiplied by the cost per 100M tokens derived in the previous section. If a subscription plan’s monthly fee is F, the PAYG monthly cost is C, and the plan’s quota can cover the team’s peak usage within a week, then when C is greater than F, the subscription is usually more cost-effective.

    Consider a hypothetical example. A team’s monthly PAYG cost is about 700 CNY. A certain subscription plan costs 600 CNY/month, and its quota is equivalent to about 1000 CNY at PAYG prices. Even if the team only uses 70% of the quota, the plan still saves 100 CNY compared to PAYG. This example is solely to illustrate the calculation method. Always refer to the official documentation for actual plan quotas and pricing.

    Before choosing a subscription plan, you also need to verify the following:

    Check Item What to Confirm Why It Matters
    Quota Period Rolling weekly or monthly, whether it can accumulate across periods Determines if it can handle peak weeks
    Peak Hours Definition and duration of peak hours, whether it covers the team’s actual working hours Peak restrictions directly impact user experience
    Overage Handling Rate limiting, queuing, or fallback to PAYG Determines service stability and budget limits
    Quota Conversion How the vendor converts quota to tokens, whether the calculation matches API pricing If the metrics don’t match, comparisons are unreliable

    7. Conclusion

    The key to reducing LLM costs is to first accurately measure your business’s cache hit rate and input/output structure. By plugging these into the weighted formula to calculate the true cost, you can then choose between pay-as-you-go and subscription models based on usage stability. Since a difference of just a few percentage points in the hit rate can reverse plan rankings, it is recommended to review your calculation model with real logs every quarter.