How to Calculate the Real Cost of LLM APIs: A Practical Cost Model

    Comparing per-million-token list prices is a common but unreliable way to choose an LLM API. This article introduces a three-part cost model based on cache-hit rate, input/output mix, and time-of-day pricing, explains why cache hit rate is the most sensitive variable, and shows how to measure it through prompt design and observability. It also covers peak-hour routing, how to convert subscription plans into an equivalent pay-as-you-go baseline, and a reusable Python script for cost estimation. The goal is to compare real bills under your own traffic structure rather than advertised prices.

    1. Why Comparing Unit Prices Leads to Wrong Decisions

    When evaluating the cost of an LLM API, the most common approach is to put two vendors’ “price per million tokens” side by side and pick the smaller number. In engineering practice, this almost always leads to a wrong conclusion, for three reasons:

    1. Billing is not one-dimensional. Mainstream offerings split a request into cached input, uncached input, and output. These three rates can differ by an order of magnitude.
    2. Price is a function of time. Many platforms charge different rates during peak and off-peak hours, so the same request path costs different amounts depending on when it runs.
    3. The bill is a function of structure. Real cost depends on the token composition of your workload, not on the number on the price board.

    The right sequence is therefore: build a cost model first, plug in the real distribution of your own workload, and only then ask which option is cheaper.

    2. The Cost Model: Breaking the Bill into Three Parts

    Let T be the total tokens in a measurement period, h the cache hit rate, a the input share, and b the output share (a + b = 1), with unit prices p_cache, p_in, and p_out:

    1. Cost = T * [ h * a * p_cache + (1 - h) * a * p_in + b * p_out ]

    One easily overlooked detail: caching applies only to the input side. Output is always billed at the output rate, and it is the uncached portion of the input that really determines whether a plan is expensive.

    Using illustrative numbers (in CNY per million tokens, for demonstration only, not real quotes):

    1. Option A: p_cache=0.115, p_in=12.0, p_out=36.0
    2. Option B: p_cache=0.05, p_in=10.0, p_out=30.0

    At h=98%, a=98.5%, b=0.5%, the cost per 100 million tokens is roughly 12.6 for A and 9.4 for B. When h drops to 95%, the result flips: A ≈ 14.9 and B ≈ 18.3.

    The conclusion is clear: the option with the cheaper cache rate wins at a high hit rate, but once the hit rate declines, the uncached input rate and the output rate start to dominate the bill and the ranking reverses. The cache hit rate is the most sensitive variable in this model, and small changes in it are amplified into the total.

    3. Where the Hit Rate Comes From: Controllable Engineering Factors

    Hit rate is not luck; it is an architectural outcome. Practical ways to improve it include:

    • Stable prefix: Put the system prompt, tool descriptions, and few-shot examples at the very front and keep them byte-stable. Avoid volatile content such as timestamps or random IDs polluting the prefix.
    • Content-addressed reuse: Use the hash of the normalized prefix as the cache key so that an identical prefix always maps to the same cache entry.
    • Segment placement: Group high-frequency invariant content into blocks and place user input at the tail, maximizing the reusable prefix length.
    • Invalidation governance: Set sensible expiration and eviction policies so long-tail requests do not push hot data out.
    • Observability: Instrument logs, services, and alerting to track h, with dashboards broken down by business line, model version, and time window.

    Illustrative implementation (pseudocode):

    1. def build_prompt(system_block, history, user_msg):
    2. # system_block must stay stable: no timestamps, session IDs, or other volatile fields
    3. prefix = normalize(system_block) + render(history)
    4. key = sha256(prefix)
    5. return {"cache_key": key, "prefix": prefix, "suffix": user_msg}

    Note that platforms differ in cache granularity, minimum cacheable length, validity period, and billing definitions. Always follow the official documentation of the target platform before integration rather than reusing rules of thumb from elsewhere.

    4. Time-of-Day Structure: The Real Impact of Peak Windows

    Beyond caching, the second frequent misjudgment comes from time windows. Suppose a service defines peak as 4 hours per weekday (for example, a continuous afternoon block) and charges off-peak rates at all other times:

    • The peak window is about 20 hours per week, roughly 12% of the 168 hours in a week.
    • For schedulable workloads such as offline batch jobs, code-completion warmups, and bulk summarization, moving tasks out of the peak window yields a meaningful discount.
    • For online interactive paths, design for peak degradation: rate limiting during peak hours, shorter context, and reduced output length to keep uncontrollable cost minimal.

    A unified cost routing layer is recommended, consolidating model selection, time-window policy, and context trimming in one place instead of scattering them across business code:

    1. request -> cost_router
    2. |- peak? -> shorten context / downgrade model
    3. |- batch? -> queue to off-peak window
    4. `- cache? -> reuse prefix

    5. Subscriptions vs. Pay-as-You-Go: Converting to a Common Baseline

    Monthly subscription plans (such as coding plans) cannot be compared directly with pay-as-you-go pricing. They must be converted into an “equivalent list-price API credit”:

    1. Equivalent credit = plan token allowance * the three unit rates (weighted by your real h, a, b)
    2. Plan discount rate = plan price / equivalent credit

    Using publicly stated figures as an illustration: one tier costs 118 CNY per month with an official claim of about 317 million tokens per week available off-peak; a 538 CNY tier corresponds to about 1.9 billion tokens per week; the top tier at 1,078 CNY corresponds to about 4.433 billion tokens per week. Converting under a high-hit-rate assumption, the equivalent list-price credits are roughly 160, 955, and 2,229 CNY, meaning plan unit prices land at roughly 50%–70% of list price.

    This yields three selection heuristics:

    1. A plan is essentially “trading commitment for a discount.” It suits teams with stable, predictable workloads; with highly variable load, overage charges after the allowance is exhausted can eat up the discount.
    2. The discount rate moves with the hit rate. A high hit rate makes the plan more attractive; as the hit rate falls, the allowance is consumed quickly by uncached input and the effective usable volume shrinks.
    3. Recompute using “weekly allowance × your real structure” rather than trusting the advertised token count.

    6. A Reusable Estimation Script

    1. def cost_per_100m(h, a, b, p_cache, p_in, p_out):
    2. assert abs(a + b - 1) < 1e-9
    3. per_token = h*a*p_cache + (1-h)*a*p_in + b*p_out
    4. return per_token * 1e6 / 1e8 * 100 # cost per 100 million tokens
    5. for h in (0.90, 0.95, 0.98, 0.995):
    6. print(h, cost_per_100m(h, 0.985, 0.015, 0.115, 12, 36),
    7. cost_per_100m(h, 0.985, 0.015, 0.05, 10, 30))

    Plotting the output as a curve over h reveals the crossover point as the decision boundary: to the right of it, choose the option with the cheaper cache rate; to the left, choose the one with the cheaper uncached input rate.

    7. Implementation Recommendations

    • Measure before deciding: Replay a week of real traffic and collect h, a, b, and the time distribution as the only inputs.
    • Establish a single cost baseline: Convert all candidates (pay-as-you-go, subscriptions, self-hosted inference) into two metrics: cost per 100 million tokens and cost per request.
    • Make cost an observable metric: Put it on the same dashboard as latency and error rate, with budget alerts.
    • Preserve replaceability: Abstract model calls behind a unified gateway to avoid tightly coupling business logic to a single billing model.
    • Pay attention to compliance and data boundaries: For sensitive data, prefer cloud platforms with mature data protection capabilities, and handle masking and isolation at the architecture level.

    In related practice at Baidu AI Cloud, cost governance is typically driven by a unified access layer, full-chain observability, and accounting based on business structure. The core methodology matches the above: do not compare list prices; compare the real bill under your own workload structure.