LLM API Cost Calculation: A Practical Guide to Workload-Weighted Effective Pricing
Comparing LLM API prices by a single per-million-token rate is misleading because real usage combines cached reads, uncached input, and output generation. This article explains how to build a workload-weighted effective price, how to derive the required ratios from telemetry, how to read a price tier list correctly, and which levers actually reduce cost. It also covers gateway-level implementation and common pitfalls such as relying on global averages or ignoring output length tails.
1. Why Per-Token Price Comparisons Break Down
When teams move LLM applications into production, cost is usually the first line item to be challenged and the hardest one to explain. Many teams start with a simple approach: list the per-million-token price of each model service in a table, sort it from low to high, and pick the cheapest option. That may be enough for a proof of concept, but once real traffic arrives, the bill often diverges sharply from expectations.
The reason is that real usage is not a single-dimensional consumption. It is made up of at least three billing categories:
- Cached read: when a request prefix closely matches previously seen content, the server can reuse the computed result. This is typically billed at a price well below normal input.
- Uncached input: the new context that genuinely has to be computed again. This is one of the main cost drivers.
- Output generation: content produced by the model segment by segment. This usually carries the highest unit price and the largest length variance.
Collapsing these three into one blended unit price for a side-by-side comparison hides the real structure of the workload. An extraction task with a high cache hit rate and very short outputs, and a generation task with almost no cache reuse and long outputs, can differ by several times in effective cost even on the same model. What is needed instead is a workload-weighted conversion method that maps all three categories onto the same comparable scale.
2. The Core Method: Workload-Weighted Effective Unit Price
The idea is straightforward: first determine the share of each of the three categories in the workload, then use those shares as weights and compute a weighted average of the three prices to obtain an “effective unit price.”
Let the cached read price be P_read, the uncached input price be P_in, and the output price be P_out; let the corresponding shares be r_read, r_in, and r_out, summing to 1. Then:
effective_price = r_read * P_read + r_in * P_in + r_out * P_out
This formula is useful for three reasons:
- Comparability: quotes from different models and vendors sit under the same weighting scheme, so ranking them becomes meaningful.
- Explainability: a cost change can be attributed either to a shift in ratios or to a change in price, which makes retrospectives easier.
- Actionability: ratios are a variable engineering teams can influence, while price usually is not, so the optimization focus becomes clear.
The ratios should not be guessed. They should come from telemetry on the real request path. It is advisable to collect them separately along at least two dimensions, “business scenario + model tier,” so that a global average does not mask local anomalies.
3. Deriving the Ratios: From Telemetry to a Baseline
The process breaks into four steps:
- Step 1, instrument the call path: in the request wrapper, record cached read volume, uncached input volume, and output volume for every request. Use one consistent unit of measurement and avoid mixing different conventions.
- Step 2, aggregate per scenario: aggregate separately by business scenario (for example retrieval QA, code completion, document summarization, multi-turn chat) to obtain each one’s
r_read / r_in / r_out. - Step 3, set a baseline: take the median over a stable period as the baseline ratio, excluding outliers from events such as promotional spikes and load tests.
- Step 4, recalibrate regularly: model upgrades, prompt restructuring, and cache strategy changes all shift the ratios. Recalibrate weekly or per release.
A simplified collection structure looks like this:
from dataclasses import dataclass@dataclassclass Usage:read_tokens: int # cached readinput_tokens: int # uncached inputoutput_tokens: int # outputdef ratios(u: Usage) -> dict:total = u.read_tokens + u.input_tokens + u.output_tokensif total == 0:return {"read": 0.0, "input": 0.0, "output": 0.0}return {"read": u.read_tokens / total,"input": u.input_tokens / total,"output": u.output_tokens / total,}
4. How to Read a Conversion Table Correctly
The source material includes a list of model tiers sorted by effective unit price, with values roughly ranging from 0.13 to 0.53 and covering a lightweight fast tier, a general balanced tier, and a code/reasoning-enhanced tier. The correct way to use such a list is not “pick the cheapest one,” but rather:
- Read the range, not the rank: gaps between adjacent ranks may be only a few thousandths, within measurement error, and should not drive a decision.
- Read the tier clustering: prices usually form clear steps. Models inside the same step can be treated as cost-equivalent, and the choice should then be made on quality and latency.
- Read the time-of-day differences: some services price normal hours and peak hours differently, so the conversion should use the price for the hours in which the workload actually runs.
- Read the context length constraints: long-context tiers are priced differently from standard tiers, so pick the tier that matches the actual input length distribution.
In other words, the purpose of a conversion table is to turn “expensive or cheap” into “expensive or cheap under a given workload structure.”
5. Four Levers for Cost Optimization
Since price is not controllable but ratios are, optimization should concentrate on the ratio side:
- Raise the cache hit rate: place stable system prompts, tool definitions, and long document prefixes at the very front of the request, keep the prefix byte-stable, and avoid inserting volatile content such as timestamps.
- Compress uncached input: reduce genuinely new context through retrieval pruning, structured summarization, deduplication, and templating.
- Control output length: define an upper bound on output structure, use segmented generation and early stopping, and avoid unconstrained free generation.
- Route across tiers: send simple requests to the lightweight tier and complex requests to the enhanced tier, using rules or a small model as the discriminator.
Illustrative routing logic:
def route(req) -> str:if req.estimated_output_len < 200 and req.hit_cache:return "light_tier"if req.task_type == "code":return "code_tier"return "general_tier"
6. Implementation Advice and Common Pitfalls
In practice, consolidate the conversion logic into a unified gateway layer. The gateway handles metering, conversion, aggregation, and alerting, while business code only deals with semantics. A cost dashboard can be built on general-purpose logging and monitoring/alerting capabilities, with a daily budget per scenario and a period-over-period fluctuation threshold, automatically falling back to a lower-cost tier when anomalies appear.
There are three common pitfalls. First, substituting a global average ratio for scenario-level ratios, which lets a severe local overspend hide inside the average. Second, ignoring the long tail of output length, where a small number of very long generations consume most of the budget. Third, treating cache hits as guaranteed, when in fact cache invalidation and prefix changes can make the hit rate drop sharply.
Overall, upgrading from “price ranking” to a “workload-weighted effective unit price” is a key step in moving from coarse cloud usage to fine-grained cost governance. It turns cost from a month-end bill into an engineering metric that is observable, actionable, and reviewable during development.
