How to Calculate Cost per Token for LLM Inference: A Practical Unit Economics Guide

    This article explains how to calculate the true unit cost of large language model inference—measured in yuan (or dollars) per million tokens—and why this metric matters more than hardware price or raw peak throughput. It breaks down the cost model into four components (hardware, infrastructure, effective throughput, and caching), discusses the impact of separating prefill and decode phases, and provides a parameterized Python model for sensitivity analysis. Common estimation mistakes and a step-by-step rollout plan are also covered.

    Large language model (LLM) inference services are typically billed and internally accounted for in tokens. When comparing different deployment options, the most direct and meaningful metric is therefore the cost per unit token—that is, how much it costs to produce one million tokens. Comparing procurement prices or nominal compute capacity alone cannot answer the question of which option is more cost-effective. Two similarly priced systems can differ by a factor of two in effective throughput, which translates directly into a two-fold difference in unit cost.

    In practice, it is also essential to distinguish between two concepts:

    • Peak throughput is the highest processing speed measured under ideal conditions: fixed input length, fully saturated batching, and no queuing.
    • Effective throughput is the actual number of valid tokens a system produces over a full year under real production traffic.

    The gap between these two values is often significant, due to varying request lengths, traffic peaks and valleys, and batching constraints imposed by time-to-first-token (TTFT) targets. A cost model should use effective throughput as the denominator; peak throughput serves only as an upper-bound reference.

    Four Components of a Cost Model

    A complete unit cost model can be broken down into four parts: hardware, infrastructure, throughput, and caching.

    1. Hardware Procurement and Depreciation

    Hardware cost is annualized based on purchase price, useful life, and residual value. Purchase price is influenced by order volume, contract terms, and supply lead times. Large-scale procurement often qualifies for significant discounts, but the discount range varies widely; modeling should use a quoted price range rather than a single number. The depreciation period determines the annualized cost, with three to five years being a common range. The calculation is:

    Annualized hardware cost = (Total purchase price − Residual value) / Depreciation years

    2. Facility, Energy, and Operations

    Facility costs include electricity, rack or floor space rental, cooling, dedicated network links, and operations staff. Electricity can be estimated as power draw multiplied by runtime hours and the electricity rate. The power draw should be the average measured under load, not the nameplate rating. PUE (Power Usage Effectiveness) determines the overhead of cooling and power distribution: for the same IT load, lowering PUE from 1.5 to 1.2 reduces energy cost by roughly 20%.

    Annualized facility cost = Annual electricity consumption × Electricity rate × PUE + Site and operations annual cost

    3. Effective Throughput

    Throughput is the variable most often overestimated in cost models. It depends on model size, precision (e.g., FP8 or FP4 quantization), batch size, input-to-output length ratio, and TTFT targets. Lower precision typically improves throughput, but output quality must be verified against business requirements.

    Annual valid tokens = Peak throughput × Average utilization × Seconds per year × Business validity ratio

    Here, average utilization is the ratio of daily average load to peak load, typically in the 30–70% range for online services. The business validity ratio excludes compute consumed by timed-out, failed, and retried requests.

    4. Caching and Computation Reuse

    For multi-turn conversations, code completion, and long system prompts, many requests share identical prefixes. When a prefix cache hit occurs, the corresponding prefill computation can be skipped and the cached KV cache reused directly. Therefore, the cache hit rate directly affects the actual amount of computation.

    The effective prefill unit cost can be expressed as a weighted average:

    Effective prefill cost = Miss cost × (1 − Hit rate) + Hit cost × Hit rate

    Hit cost is usually far lower than miss cost, but the exact ratio depends on the cache read path and storage layer. It must be determined through load testing—it cannot be taken from an empirical rule of thumb.

    Separating Throughput by Phase: Prefill vs. Decode

    LLM inference proceeds in two phases. The prefill phase processes the input sequence in one pass and is compute-bound, limited primarily by compute capacity. The decode phase generates output tokens one at a time; each step reads a large amount of KV cache and is bound by memory bandwidth and access latency. The two phases have different hardware demands, and mixing them in the same batch can cause mutual interference.

    Impact of Input–Output Ratio

    On the same hardware, the input-to-output length ratio can lead to very different outcomes. For code analysis and document processing scenarios, input is typically much longer than output, so prefill occupies a higher fraction of compute time—making prefix caching and prefill efficiency the primary cost drivers. For conversational and generation scenarios with longer outputs, decode efficiency and batching capability matter more. When estimating costs, first collect the input–output length distribution from real traffic, then select representative operating points.

    Benefits and Trade-offs of PD Separation

    PD separation means deploying prefill and decode onto separate resource pools, each configured with its own node count and batching parameters. The benefit is that both phases can be optimized independently, avoiding resource contention, and TTFT and generation speed can be controlled more stably. The trade-offs are equally clear: KV caches produced on prefill nodes must be transferred to decode nodes, which demands considerable network bandwidth and low latency; the scheduler must manage two resource pools, adding complexity; and if the pool ratio is misconfigured, one side sits idle.

    Whether to adopt PD separation should be determined by load-test data. For light workloads or constrained network environments, co-located deployment may offer a lower unit cost.

    Example: A Parameterized Calculation Model

    The following Python functions illustrate the calculation method. All inputs are hypothetical values used to demonstrate the approach; they do not represent the performance of any specific device or service.

    1. SECONDS_PER_YEAR = 365 * 24 * 3600
    2. def cost_per_million_tokens(
    3. hardware_cost: float, # total hardware cost, in yuan
    4. years: int, # depreciation period in years
    5. annual_opex: float, # annual facility and operations cost, in yuan
    6. peak_tps: float, # peak throughput, in tokens/second
    7. utilization: float, # average utilization, 0 to 1
    8. ) -> float:
    9. """Return the cost per million tokens, in yuan."""
    10. annual_cost = hardware_cost / years + annual_opex
    11. annual_tokens = peak_tps * utilization * SECONDS_PER_YEAR
    12. return annual_cost / annual_tokens * 1e6
    13. def effective_prefill_cost(
    14. base_cost: float, # prefill unit cost when cache is missed
    15. hit_rate: float, # prefix cache hit rate, 0 to 1
    16. cached_cost_ratio: float, # cost ratio on hit vs. miss; must be load-tested
    17. ) -> float:
    18. """Return the weighted prefill unit cost after accounting for cache hits."""
    19. return base_cost * ((1 - hit_rate) + hit_rate * cached_cost_ratio)

    Sensitivity Under Hypothetical Inputs

    Assume a single node with a total hardware cost of ¥3,000,000, a depreciation period of 5 years, annual operations cost of ¥300,000, and peak throughput of 20,000 tokens per second. The table below shows the impact of varying average utilization.

    Average utilization Annual valid tokens (millions) Unit cost (yuan/million tokens)
    30% 189,216 4.76
    50% 315,360 2.85
    80% 504,576 1.78

    These results show that, under the stated assumptions, increasing utilization from 30% to 80% reduces unit cost by more than 60%. This indicates that utilization is often a higher-leverage optimization target than hardware unit price—including improving batching efficiency, smoothing traffic spikes, and properly allocating resources between prefill and decode pools.

    Common Pitfalls

    Pitfall 1: Using peak throughput directly in cost calculations. Results measured under peak conditions do not represent year-round averages; you must multiply by realistic utilization.

    Pitfall 2: Comparing unit prices only. A lower device price does not imply a lower cost per unit of throughput. Always compare using cost per unit of throughput.

    Pitfall 3: Comparing under inconsistent conditions. Any difference in model, precision, input/output length, concurrency, or TTFT limits makes measured throughput non-comparable. Test reports should state the full set of conditions.

    Pitfall 4: Ignoring networking and interconnect. Multi-node deployment, PD separation, and KV cache transfer all depend on inter-node bandwidth. Network bottlenecks can directly suppress effective throughput.

    Pitfall 5: Assuming a constant cache hit rate. Hit rate depends on business patterns, user base, and request distribution. As the cluster grows, requests become more concentrated and the hit rate typically increases, but this must be validated with production data—it cannot be extrapolated without evidence.

    Implementation Steps

    1. Collect production traffic data: input length, output length, concurrency, request time distribution, and cache hit rate.
    2. Run load tests with the same model and precision to obtain throughput and TTFT curves for different batch sizes.
    3. Choose an operating point based on service-level objectives (e.g., TTFT limit), and use the throughput at that point—not peak throughput—as the basis for calculation.
    4. Feed hardware quotes, electricity rates, PUE, and depreciation years into the model. Compute optimistic, neutral, and conservative scenarios.
    5. Perform sensitivity analysis on utilization, cache hit rate, and procurement price to identify the variables with the greatest impact.
    6. Backfill model parameters with production data quarterly to correct forecast drift.

    The unit cost obtained through these steps can be used not only for deployment option selection, but also as a basis for capacity planning and pricing estimation.