LLM API Cost Accounting: Empirical Unit-Price Modeling and Tiered Scheduling
Estimating large language model (LLM) API costs from a published unit-price table almost never matches the real bill, because billing spans multiple dimensions—input, output, cache-hit input, reasoning tokens, long-context tiers, batch discounts, and retries. This article shows how to move from price-table guessing to a cost model grounded in your own call logs: a single weighted cost formula, least-squares regression (with scipy.optimize.nnls) to reverse-engineer real per-token prices, converting a quota into a usable token budget, and squeezing the most underestimated lever of all—prompt caching. It then covers tiered model routing that lets expensive models "think" and cheap models "do," along with production concerns such as observability, sliding-window budget guardrails, six common misconceptions, and a prioritized optimization checklist. All numbers are illustrative values for demonstrating the method, not any provider's official pricing.
1. Why estimating from a unit-price table is always off
Many teams find, after integrating several model providers, that the bill never matches what they calculated from the price table. The reason isn’t complicated: LLM call billing usually has more than one dimension. Input, output, cache-hit input, the reasoning/thinking phase, long-context tiers, batch discounts, and retry consumption all affect the final charge.
If you take a single “price per million tokens” and multiply it by an estimated token count, you tend to miss four problems:
- More than one billing dimension. Input, output, and cache hits are usually priced separately, and some services apply different rules for long context, reasoning phases, and batch requests.
- Distorted input/output ratio assumptions. One-off Q&A may produce long output, while agent multi-turn loops and long-document rewriting are dominated by input. A fixed ratio directly amplifies error into the budget conclusion.
- Caching is ignored. Cached-input pricing is usually far below normal input pricing. Not quantifying cache both overestimates current cost and hides an optimization lever.
- Context bloat and failure cost are underestimated. Multi-turn conversation history is billed repeatedly, and retries after timeouts, rate limiting, or validation failures push actual consumption above the paper estimate.
So the more reliable approach isn’t to trust the price table, but to start from your own real call logs and reverse-engineer the true unit cost.
2. Abstracting the billing model into a weighted cost formula
The common three-part input/output/cache pricing model can be written as a single formula:
C = (T_in − T_cache) × P_in+ T_cache × P_cache+ T_out × P_out
where:
C: amount spent (currency or credits);T_in: input token count;T_cache: cache-hit token count;T_out: output token count;P_in: normal input unit price;P_cache: cache-hit input unit price;P_out: output unit price.
In practice, it’s best to collapse cost estimation into an injectable, configurable estimator rather than scattering magic numbers across business code:
from dataclasses import dataclass@dataclass(frozen=True)class UnitPrice:"""Priced uniformly per million tokens, to align with the billing model."""input_per_mtok: floatcached_input_per_mtok: floatoutput_per_mtok: floatdef estimate_cost(usage: dict, price: UnitPrice, cache_ratio: float = 0.0) -> float:"""usage: {"prompt_tokens": int, "completion_tokens": int}cache_ratio: share of input tokens served from cache in this request, 0.0 ~ 1.0"""prompt = usage.get("prompt_tokens", 0)cached = prompt * cache_ratiouncached = prompt - cachedreturn (uncached * price.input_per_mtok+ cached * price.cached_input_per_mtok+ usage.get("completion_tokens", 0) * price.output_per_mtok) / 1_000_000
The value of this step is that cost becomes a function of observable quantities. As long as you can record token usage, cache hits, and output length, cost can be predicted, regressed, and optimized.
3. Using least squares to reverse-engineer real unit prices from logs
3.1 Data collection requirements
To fit a model, you first need structured logs. At minimum, record for every call:
- model identifier;
- input token count;
- cache-hit token count;
- output token count;
- reasoning or thinking-phase usage, if the server returns it separately;
- the corresponding actual charge for the same cycle.
The key constraint is that the charge must map one-to-one to a single call or a single batch. If billing is aggregated over 5 hours, daily, or weekly, aggregate by that window and treat the window’s usage and window charge as one sample.
3.2 The fitting process
Reverse-engineering unit prices is essentially a linear regression problem: the samples are past calls, the feature columns are the three token-usage counts, and the target is the charge. Since prices should not be negative, scipy.optimize.nnls (non-negative least squares) is recommended. Install numpy and scipy before use.
import numpy as npfrom scipy.optimize import nnlsdef fit_unit_price(rows: list[dict]) -> dict:"""rows: [{"prompt": int, "cached": int, "completion": int, "cost": float},...]"""X = np.array([[r["prompt"] - r["cached"], r["cached"], r["completion"]]for r in rows],dtype=float,) / 1_000_000y = np.array([r["cost"] for r in rows], dtype=float)# Non-negative least squares yields more sensible price estimatescoef, _ = nnls(X, y)pred = X @ coefss_res = float(((y - pred) ** 2).sum())ss_tot = float(((y - y.mean()) ** 2).sum())# If y is constant, ss_tot is near 0 and R² is undefinedr2 = 1.0 - ss_res / ss_tot if ss_tot > 1e-12 else float("nan")return {"price": dict(zip(["input", "cached", "output"], coef.tolist())),"r2": r2,"max_abs_residual": float(np.abs(y - pred).max()),"samples": len(rows),}
If you don’t want a scipy dependency yet, you can start with np.linalg.lstsq for exploratory fitting, but you should eventually add a non-negativity or linear-programming constraint—otherwise the fit may produce negative prices that can’t be explained.
3.3 Interpreting fit quality
Don’t just look at the fitted prices; also check three things:
- R² and residuals. R² near 1 and residuals near 0 indicate billing is approximately linear. Systematically large residuals may mean you’ve missed a dimension such as long-context tiers, reasoning usage, or rounding to a minimum billing unit.
- Whether features are collinear. If input and output always appear in a fixed proportion in your logs, the coefficients become hard to identify. Deliberately construct extreme samples: one very long input with short output, and one very short input with long output.
- Whether samples are isolated. Mixing multiple models makes different unit prices overlap, so you must fit per model group.
3.4 A de-identified empirical example
The following is a de-identified illustrative example to explain the “empirical modeling” process; it does not represent any provider’s official billing model:
- Sample size: 96 rows;
- Time window: 7 consecutive days, aggregated every 5 minutes;
- Sample composition: includes long-input/short-output, short-input/long-output, high-cache-hit, and low-cache-hit requests;
- Fitting method:
scipy.optimize.nnls; - Illustrative results: input price ≈ 0.21, cached-input price ≈ 0.02, output price ≈ 0.85, in units of “credit consumption per million tokens”;
- Fit quality: R² ≈ 0.996, max residual ≈ 0.006.
This example shows that when log fields are complete and samples cover enough cases, reverse-engineering unit prices can become the basis for budgeting and scheduling. In a real system, though, you should keep re-fitting against your own logs continuously.
4. Converting a quota into a “usable token budget”
Only after reverse-engineering unit prices can you answer “how long will my balance last.” The core is to compute a weighted unit price first, then divide:
weighted_price = input_share × effective_input_price + (1 − input_share) × output_priceusable_tokens = period_quota / weighted_price
where:
effective_input_price = (1 − cache_ratio) × P_in + cache_ratio × P_cache
def usable_tokens(quota: float,price: UnitPrice,input_share: float = 0.8,cache_ratio: float = 0.0,) -> float:in_eff = (price.input_per_mtok * (1 - cache_ratio)+ price.cached_input_per_mtok * cache_ratio)weighted = input_share * in_eff + (1 - input_share) * price.output_per_mtokreturn quota / weighted * 1_000_000
Here’s the critical caveat: quota and P_in / P_cache / P_out must be in the same currency or credit unit. If the quota is in dollars, the prices must also be converted to dollars; if the quota is in credits, the prices must be in credits too. Otherwise the division result is meaningless.
Usable token counts can differ substantially between model tiers, but these are only illustrative magnitudes that depend on input/output ratio, cache hit rate, model unit price, retry rate, and task type. For real selection decisions, don’t rely on unit price or a single case alone—combine offline evaluation, real traffic samples, and quality acceptance results.
Another common cognitive bias is that output cost often contributes no small share to total cost. Even if output tokens are only 20% of the total, when the output price is 4–5× the input price, output can still contribute around half of the total cost. So compressing output length, limiting verbose reasoning, and setting a maximum output token cap can sometimes be more cost-effective than compressing input.
5. Caching: the most underestimated lever in the cost structure
Cached-input pricing is usually far below normal input pricing. Assume a cache hit rate of r, then the input cost is:
input_cost = (1 − r) × P_in + r × P_cache
If the cache hit rate reaches 80%, the input cost is not simply cut to one-fifth, but rather:
input_cost = 20% × P_in + 80% × P_cache
If P_cache is 5% of P_in, input cost is about 24% of the original; if P_cache is 10% of P_in, it’s about 28%. In other words, at high cache hit rates, input cost can typically drop to roughly 20–30% of the original, depending on the cache price and hit-rate stability.
To capture the cache lever, the key is prefix stability:
- The prefix must be byte-for-byte stable. Put system prompts, tool definitions, few-shot examples, and domain knowledge snippets all up front; put user input, timestamps, session state, and random IDs at the back.
- Control the number of prefix versions. Don’t stuff “a completely different prompt template for every tenant” into a shared prefix, or the cache gets fragmented and diluted.
- Understand invalidation conditions and time-to-live. Caches usually have a lifetime, and long-interval requests from low-frequency calls get recomputed. High-frequency stable prefixes paired with periodic warm-up are needed to maintain hit rates.
- Group batch tasks by prefix. Requests that share a prefix are more likely to hit cache when submitted back-to-back than when interleaved at random.
- Treat cache hit rate as a first-class metric. Cache hit rate can swing sharply with prompt changes, so monitor it by model, business line, and template version.
- Don’t misuse the cache. Data across tenants or across permission boundaries must never enter a shared prefix. Cache hits touch data-retention boundaries—this is a compliance baseline, not just a performance issue.
6. Tiered scheduling: let high-cost models “think” and low-cost models “do”
Reverse-engineering unit prices and cache optimization address “unit cost”; tiered scheduling addresses “cost structure.” The basic idea is to assign model tiers by task value:
| Tier | Typical responsibilities | Selection criteria |
|---|---|---|
| Flagship reasoning | Requirement decomposition, solution design, architecture decisions, final review | A single decision affects many downstream calls; error cost is high |
| Mid-tier reasoning | Complex logic derivation, long-context understanding, difficult troubleshooting | Long input and deep chains, but results can be verified downstream |
| Workhorse execution | Code generation and refactoring, routine Q&A, document processing | High frequency, verifiable, single-context size controllable |
| Lightweight batch | Classification/extraction, format conversion, summarization/tagging, batch inspection | Short output, clear rules, suitable for large-scale concurrency |
Routing shouldn’t rely only on hand-wavy rules; you can adopt a structure of “rules + lightweight classifier + post-validation escalation”:
TIER_ORDER = ["lightweight", "workhorse", "mid_reasoning", "reasoning_flagship"]def route(task) -> str:# 1) Hard constraints first: high-risk or long-chain planning requests go straight upif task.risk == "high" or task.requires_planning:return "reasoning_flagship"# 2) Context length sets a floor on the tier, avoiding degradation on the lightweight tierif task.prompt_tokens > 100_000:return "mid_reasoning"# 3) Auto-verifiable and short output is the sweet spot for the lightweight tierif task.auto_verifiable and task.estimated_output_tokens < 2_000:return "lightweight"return "workhorse"
After a validation failure, you should retry at a higher tier rather than repeatedly burning tokens at the same tier. The escalation function should produce a sequence of consecutive tiers, avoiding running the same tier twice:
def with_escalation(base_tier: str, max_tries: int = 2):"""Starting from base_tier, try up to max_tries consecutive tiers.max_tries is the number of tiers to attempt, not extra escalations."""idx = TIER_ORDER.index(base_tier)end = min(len(TIER_ORDER), idx + max_tries)for tier in TIER_ORDER[idx:end]:yield tier
Usage example:
for tier in with_escalation(base_tier="workhorse", max_tries=2):result = call_model(tier, task)if is_valid(result):break
If an outer loop has already run a given tier separately, don’t put it back into the escalation sequence, or you’ll consume it twice. You can set base_tier to the next candidate tier, or have the scheduler uniformly iterate over with_escalation‘s output.
Two supporting mechanisms are also needed:
- Escalation: When output fails automated validation—for example, a compile failure, a failed unit test, an invalid schema, or a failed rule assertion—retry at the tier above.
- De-escalation: When quota or latency budget is tight, allow non-critical requests to move down a tier to keep the core path available. De-escalation must be an explicit configuration item, and the de-escalation rate must be recorded.
Tiered scheduling only holds if quality doesn’t regress. It’s best to build an offline evaluation set: fix a batch of real tasks, first run a baseline of “everything on flagship,” then run the “tiered routing” results, and compare pass rate, human acceptance rate, and failure rate. If the difference is within an acceptable range, tiering is pure gain; if the difference is significant, it means the routing features need to be supplemented, not that tiering should be abandoned.
7. Engineering implementation: observability and budget guardrails
Cost governance ultimately lands on the platform. A common setup is: use a model service for unified access and quota management, a logging service to hold call details, monitoring and alerting for anomaly detection, and object storage to hold offline evaluation sets and fitting samples.
Four categories of metrics must be established:
- Unit-cost metrics: cost per request, cost per task, cost per thousand successful calls.
- Usage-structure metrics: input/output ratio, cache hit rate, average context length, retry rate.
- Scheduling-effect metrics: call share by tier, escalation rate, de-escalation rate, failure rate.
- Anomaly metrics: sudden spikes in unit cost, abnormal quota consumption rate, rising error rate on a given tier.
For budget guardrails, use a real sliding window and account for concurrency safety. Below is a single-instance example; in a multi-instance production deployment, quota decisions should be centralized in a distributed quota service—for example, atomic deductions implemented with Redis Lua, a transactional database, or a unified quota platform.
import timefrom collections import dequefrom threading import Lockclass BudgetGuard:"""Single-instance sliding-window guard; production needs per-tenant/session/task bucketing and distributed concurrency handling."""def __init__(self, window_seconds: int, credit_budget: float):self.window = float(window_seconds)self.budget = float(credit_budget)self._events = deque() # (timestamp, estimated_cost)self._lock = Lock()def try_acquire(self, estimated_cost: float) -> bool:now = time.time()with self._lock:while self._events and self._events[0][0] <= now - self.window:self._events.popleft()used = sum(cost for _, cost in self._events)if used + estimated_cost > self.budget:return Falseself._events.append((now, estimated_cost))return True
Engineering notes:
- Set guardrails separately at three levels: tenant, session, and task.
- Estimated cost should try to include extra consumption from retries, timeouts, tool calls, context bloat, and validation failures.
- When over the limit, de-escalate tiers first, then queue, and finally reject explicitly.
- When a guardrail falsely rejects, don’t return only a generic “failed”—return an understandable budget error and keep a manual override or emergency quota-raise channel.
8. Six common misconceptions
- Comparing only unit price, not weighted cost. A model with a low unit price isn’t necessarily cheaper in practice if its output is long and it retries a lot.
- Ignoring reasoning or thinking-phase usage. Some tiers bill this consumption separately, so logs must record it completely.
- Ignoring the two-sided distortion caused by caching. Without quantifying cache, you both overestimate current cost and underestimate optimization room.
- Ignoring context bloat. History being billed repeatedly in multi-turn sessions is the top cause of cost spiraling out of control in long conversations.
- Ignoring failure cost. Retries after timeouts, rate limiting, and validation failures can push actual consumption well above the estimate.
- Looking only at direct fees. Rework from quality regressions, human intervention, and delivery delays are often more expensive than the token fees saved.
Framing this around common questions people search for:
- How do I choose a model? Look at weighted cost, output share, cache hit rate, retry rate, quality-validation pass rate, and human acceptance rate—not just unit price.
- How do I compute cache hit rate? Divide cache-hit input tokens by total input tokens, then aggregate by request, template version, model, and time window.
- What are the common mistakes? The most common aren’t failing to work out the formula, but missing log fields, samples that don’t cover extreme tasks, inconsistent budget units, and escalation retries not being counted into cost.
9. A directly executable optimization checklist
Doable within one week:
- Fill in input, cache-hit, output, retry, and failure-reason fields in the call logs;
- Run one unit-price fit grouped by model and record R², residuals, and sample count;
- Strip dynamic content out of the prefix and observe how cache hit rate changes;
- Compress output length for the highest-frequency prompt templates and set a maximum output token cap.
Doable within one month:
- Ship tiered routing with post-validation escalation;
- Build an offline evaluation set to quantify the quality difference tiering brings;
- Wire up budget guardrails and a dashboard of the four metric categories;
- Group and order batch tasks by prefix to raise cache hit rate.
Ongoing:
- Re-fit unit prices after every billing-rule or model-version change;
- Re-run the routing-strategy benefit assessment once per quarter;
- Make “cost per task” a core SLO metric alongside latency and success rate.
Note: The unit-price relationships, ratio assumptions, fitting example, and budget figures in this article are illustrative values used to demonstrate the calculation method, not any provider’s official billing model. Each provider’s billing dimensions, discount rules, and caching strategies may change, so when implementing for real, refer to the corresponding platform’s official documentation and keep re-fitting against your own logs continuously.
