LLM API Cost Calculation and Cache Billing: A Practical Guide

    This guide explains why list prices alone cannot guide LLM API selection and how to build a workload-aware cost model. It covers the three billing dimensions (uncached input, cache reads, and output), a blended unit price formula with example code, a three-tier ranking based on normalized pricing, and the structural impact of cache read discounts. It also details practical levers for reducing cost: maximizing cache hit rates through stable prefixes, shifting batch workloads to off-peak windows, handling long-context pricing tiers, and instrumenting usage for cost attribution and budget alerts. The recommended workflow is to profile your traffic first, calculate blended prices, optimize structure, and only then compare models.

    1. Why the Price Sheet Cannot Guide Model Selection

    When building coding assistants, knowledge base Q&A systems, or long-document processing applications, teams often run into a counterintuitive result: the model with the lowest listed price does not always produce the lowest bill, while a model priced several times higher can be more cost-effective under a specific workload.

    The reason is that a price sheet simply lists three independent dimensions: the uncached input price, the output price, and the cache read price. Real workloads consume these three in different proportions, so looking at any single number leads to a conclusion that can be far off.

    A more reliable engineering approach is to first characterize your workload structure, then compress the multi-dimensional pricing into a single comparable scalar metric, and only then move on to selection and optimization.

    2. Cost Model: Three Billing Dimensions and Blended Unit Price

    The tokens in a single request typically fall into three buckets:

    • Uncached input: the part of the prompt that is not reused from cache, billed at the input price;
    • Cache hit read: the part that exactly matches an already cached prefix, billed at a read price significantly lower than the input price;
    • Output: the content generated by the model, usually the most expensive bucket.

    Let h be the cache hit ratio and r the ratio of output tokens to input tokens. The cost of a single request is:

    1. cost = (1 - h) * P_in + h * P_read + r * P_out

    With a fixed workload profile of h = 0.8, r = 0.1, and an uncached input share of 0.1, you get the blended unit price:

    1. P_blend = 0.8 * P_read + 0.1 * P_in + 0.1 * P_out

    The unit is currency per million tokens. The value of this formula is not absolute precision, but turning selection from “comparing prices” into “comparing structures”: any model becomes meaningfully rankable once you plug in the same set of weights.

    Example implementation:

    1. def blended_price(p_in, p_out, p_read, hit=0.8, out_ratio=0.1):
    2. return hit * p_read + (1 - hit - out_ratio) * p_in + out_ratio * p_out
    3. candidates = [
    4. ("model-a", 0.30, 3.10, 0.03),
    5. ("model-b", 1.20, 6.00, 0.12),
    6. ]
    7. for name, pi, po, pr in candidates:
    8. print(name, round(blended_price(pi, po, pr), 4))

    3. Reading the Ranking: Three Tiers and Structural Differences

    Normalizing a cloud provider’s published price list with the weights above reveals a clear three-segment distribution.

    The first tier (blended unit price roughly 0.3 to 1.4 per million tokens) consists of lightweight models focused on cost efficiency, time-of-day priced “flash” models, and mid-range workhorse models. Their shared trait is a cache read price pushed below one tenth of the input price, so their advantage is amplified further under high-hit workloads.

    The second tier (roughly 1.9 to 5.5) is dominated by pro-tier models, some lightweight multimodal models, and open-source-style models, with median input and output prices and a typical cache discount.

    The third tier (roughly 6.7 to 47.6) covers flagship and ultra-long-context models, whose output price often reaches 3 to 5 times the input price and whose cache discount is limited. They only become cost-effective in complex reasoning and very long document scenarios.

    One key structural finding: some models that rank in the middle by “listed input price” move sharply forward in the blended ranking, precisely because their cache read price is extremely low. Conversely, models with cheap input but a weak cache discount drop noticeably. This is why decisions must be based on a workload profile rather than the listed price.

    For entries where the full three-dimensional pricing (any of input, output, or read missing) cannot be verified, exclude them from the ranking outright rather than filling gaps with zero or an average, which would introduce systematic bias.

    4. Cache Hit Rate: The First Lever on Cost

    The core premise of cache billing is a “stable prefix.” Hit determination is usually based on token-by-token consistency of the request prefix, so:

    • Put the system prompt, tool definitions, and few-shot examples at the very front and freeze them;
    • Place variable content (timestamps, user input, retrieved snippets) at the end;
    • Avoid inserting random IDs or rotating copy into the stable prefix;
    • Control the history increment in multi-turn conversations so it only appends and never rewrites.
    1. [Stable prefix: system instructions + tool schema + examples] <- target hit rate > 0.9
    2. [Semi-stable section: conversation summary, appended per turn]
    3. [Volatile section: this turn's retrieval results + user question]

    Raising the hit rate from 0.5 to 0.9 can cut costs several-fold on high-hit-weight models, and this lever usually takes priority over switching models.

    5. Time-of-Day Billing and Load Shifting

    Some models offer two price sets, peak and standard, for the same capability, with a difference of up to double. The engineering implication is that offline batch jobs (log summarization, code base indexing, bulk labeling) should be scheduled into standard windows, while online interactions stay in peak windows. In practice, you only need to add time-window constraints and retry backoff to the task queue to obtain the discount at zero cost.

    6. Long-Context Thresholds and Tier Jumps

    When context length has billing tiers (for example, a boundary at 256K), the cost function is piecewise rather than linear. Crossing a threshold causes a unit price jump, so the number of retrieved chunks in RAG, chunk size, and summary levels all become cost parameters. Practical advice: set an upper bound on the context budget, and when it is exceeded, apply hierarchical summarization before feeding the model rather than simply enlarging the window.

    7. Observability and Governance: Making the Bill Attributable

    Without measurement there is no optimization. The minimum viable instrumentation should include: request ID, model identifier, input/output/cache read token counts, hit flag, time-window label, and business line ownership. With these fields you can recompute the blended unit price offline and build a team-level dashboard with budget alerts.

    1. {
    2. "req_id": "b1f...",
    3. "model": "model-a",
    4. "tokens": {"in": 1200, "cache_read": 9800, "out": 300},
    5. "hit_ratio": 0.89,
    6. "window": "off-peak",
    7. "owner": "kb-search"
    8. }

    8. Implementation Workflow and Conclusion

    1. Sample one week of real traffic and measure the distribution of h and r, rather than taking a single-point average;
    2. Compute and rank the blended unit price of candidate models with unified weights;
    3. Do prefix restructuring and load shifting first, then evaluate switching models;
    4. Build a cost dashboard attributed by business line with threshold alerts;
    5. Review the price list and tier changes every quarter and recompute the ranking.

    The conclusion is straightforward: the correct order for model selection is “profile the workload first, calculate the blended unit price second, compare prices last.” Cache hit rate and output share are the two highest-weight variables in the cost structure; engineer them well and the bill naturally converges into a predictable range.