How to Measure the Real Cost of LLM APIs: Methods and Practice
Comparing per-million-token prices is the most common way to evaluate LLM API costs, but it often leads to wrong conclusions. This article explains why cost is a multi-variable function rather than a single price, and breaks down the three decisive variables: cache hit rate, input-to-output token ratio, and off-peak scheduling. It also provides a reusable Python script for scanning cost curves and locating cache hit rate crossover points, a method for converting subscription plan prices into equivalent API value based on quota utilization, and a practical evaluation workflow with common pitfalls to avoid.
1. Why “Unit Price Comparison” Almost Always Leads to the Wrong Conclusion
When evaluating the procurement cost of LLM APIs, the most common approach is to place the “price per million tokens” of two options side by side. The flaw in this approach is that it treats cost as a scalar that depends only on unit price, when in reality cost is a function determined by multiple variables.
A more engineering-realistic formulation is:
Cost per request = Σ(token usage per category × corresponding unit price)Monthly total cost = request volume × cost per request × (1 + retry and failure overhead rate)
The “token categories” typically include at least four types: input tokens that hit the cache, input tokens that miss the cache, output tokens, and reasoning tokens that are billed separately in some implementations. Any conclusion based on comparing only one of these unit prices lacks verifiability.
Therefore, the core argument of this article is: cost evaluation must first fix the “workload profile” and then compare unit prices. Unit price comparison detached from the workload profile has no decision-making value.
2. Three Decisive Variables
2.1 Cache Hit Rate: The First Inflection Point of the Cost Curve
The billing logic of prompt caching is: repeated context prefixes are charged at a price significantly lower than the regular input price. This introduces a key property—total cost is highly sensitive to the cache hit rate, and not in a linear way.
Let the regular input unit price be P_in, the cached input unit price be P_cache, the hit rate be h, the output unit price be P_out, and the input-to-output token ratio be r. The expected cost per unit token can be approximated as:
C(h) = (1 - h) × P_in + h × P_cache + r × P_out
Since P_cache is usually far lower than P_in, C(h) drops very rapidly as h approaches 1. This means two options may have a “crossover point” across different hit rate ranges: an option with a lower cache price but a higher regular input price is better in the high hit rate range, and vice versa. When making a selection, you must plug in your actual business hit rate rather than an ideal value.
Improving the hit rate is an engineering problem. Common techniques include: keeping system prompts, tool definitions, and few-shot examples fixed at the very front of the request and byte-level stable; avoiding injecting volatile content such as timestamps or random request IDs at the beginning of the context; and using incremental appending rather than full rewriting for multi-turn conversations.
2.2 Input-to-Output Ratio: An Underestimated Cost Amplifier
The unit price of output tokens is typically several times that of input tokens, so small changes in output proportion get amplified. Calculating with two profiles, “input:output = 99.5:0.5” and “90:10”, the output cost component of the latter may increase by an order of magnitude. Any scenario involving long-form generation, code completion, or structured data extraction should measure the output ratio separately rather than relying on a generic assumption.
2.3 Off-Peak Scheduling: Introducing the Time Dimension into the Cost Model
Some platforms apply different quotas or different pricing for “peak hours” and “off-peak hours.” In this case, the cost function needs an added time dimension:
Monthly cost = Σ_over_hours (request volume in that hour × unit price for that period)
The value of off-peak scheduling is reflected not only in unit price but also in quota availability: rate limiting during peak hours translates directly into retries, queuing, and timeouts, which in turn raises the effective cost. Scheduling batch tasks (offline evaluation, log analysis, batch summarization) to off-peak periods is one of the highest-ROI actions in cost optimization.
3. A Reusable Measurement Script
The following is sample code for horizontally comparing multiple options under a given workload profile and automatically finding the cache hit rate crossover point:
def unit_cost(p_in, p_cache, p_out, hit, out_ratio):"""Return the expected cost per million tokens (in the same currency unit)"""return (1 - hit) * p_in + hit * p_cache + out_ratio * p_outdef scan(hits, plans):return {name: [unit_cost(p_in, p_cache, p_out, h, out_ratio)for h in hits]for name, (p_in, p_cache, p_out, out_ratio) in plans.items()}plans = {"Plan A": (12.0, 1.15, 60.0, 0.005),"Plan B": (2.0, 0.5, 8.0, 0.005),}hits = [i / 100 for i in range(80, 100)]table = scan(hits, plans)# The crossover point is the hit value where the two plans have equal cost, which can be located using binary search
Usage recommendation: make both out_ratio and hit interval scans rather than single-point values, and output a cost curve chart. The decision basis should be “within our hit rate fluctuation range, which option has a lower expected cost and smaller variance,” rather than a win or loss at a single point.
4. How to Convert Subscription Plans
When a platform offers a monthly subscription coding assistant plan, you need to convert the “plan price” into “equivalent API value” to compare it with pay-as-you-go. The conversion steps are:
- Take the token quota available per cycle as stated by the plan (note the distinction between “weekly” and “monthly” terms);
- Using the unit cost model above, convert the quota into the equivalent amount under pay-as-you-go;
- Calculate the discount rate = plan price ÷ equivalent amount;
- Adjust with your own workload’s “quota utilization”: if you actually use only 40% of the quota, the real discount rate must be divided by 0.4.
Step 4 is the most easily overlooked. The economics of a plan are entirely premised on “the quota being fully used.” When utilization is insufficient, a nominal 50% off may become effectively full price or even more expensive. It is recommended to first collect one to two weeks of call logs to measure the actual token consumption distribution before deciding whether to purchase.
In addition, plans usually come with constraints such as non-accumulating quota cycles, peak-hour restrictions, and concurrency limits. These constraints should be converted into “effective quota,” meaning the portion of quota that is actually available during business peaks.
5. Implementation Workflow and Common Pitfalls
Recommended evaluation workflow:
- Step 1: Collect the real workload profile: hit rate, input-to-output ratio, peak/off-peak distribution, retry rate;
- Step 2: Build a unified unit cost model and do interval scans rather than single-point comparisons;
- Step 3: Convert rate limiting and queuing into effective cost and factor it into total cost of ownership;
- Step 4: Validate model output quality with a small-traffic canary to avoid introducing rework costs for the sake of saving money;
- Step 5: Set up a cost dashboard with alert thresholds for cache hit rate and output ratio.
Common pitfalls include: using theoretical hit rates instead of measured values; ignoring changes in output ratio; treating plan quotas as accumulable resources; comparing only unit prices while ignoring hidden costs caused by rate limiting; and overlooking downstream rework and manual review overhead caused by model quality differences.
6. Conclusion
Cost governance for LLM APIs is essentially restoring a seemingly simple multiplication problem to a multi-variable engineering problem. Cache hit rate, input-to-output ratio, and time-of-day structure together determine the shape of the cost curve; subscription plans need to be converted via quota utilization before they become comparable. Building your own measurement model and monitoring loop is more valuable in the long run than memorizing any specific set of prices. If you already use Baidu AI Cloud services, you can archive call logs directly via object storage and use monitoring and alerting capabilities to set thresholds on cost metrics, solidifying the above model into a routine cost operations process.
