LLM Cost Fitting and Tiered Scheduling: Modeling Token-Level Billing and Routing Tasks Across Model Tiers
Once an LLM is wired into production, the bill is rarely as simple as "how many calls we made." Within a single task, prompts, tool returns, conversation history, model output, and cache hits are all metered under different accounting buckets. Looking only at total credits or total spend makes it impossible to tell whether the driver is an oversized context, an oversized generation, or a cache that barely fires. This article shows how to decompose each call into additive usage components, fit the unit cost of each component, and then decide which capability tier each task type deserves. It covers the log fields worth keeping, least-squares fitting with non-negative constraints, how to judge whether a fit is trustworthy, converting unit costs into a usable token budget for a given window, and a rule-based routing scheme with quotas and acceptance checks so cost control does not quietly consume quality.
Start by breaking spend into explainable components
Common text billing includes at least three quantities: input tokens, output tokens, and reusable prefix or cache-hit tokens. Input usually covers system instructions, the user question, retrieved passages, and prior conversation turns; output covers newly generated content; cache hits correspond to the discounted portion when a repeated prefix is reused. Some platforms also meter reasoning content and tool-call arguments separately. The log fields differ, but the principle is the same: first confirm which dimensions are actually priced independently in the billing rules, then decide which variables belong in the regression.
For logging, keep these fields per request: timestamp, task type, model tier, input tokens, output tokens, cache-hit tokens, whether it was a retry, and the credits or amount finally deducted. Retries and failed requests must be flagged separately; otherwise a timeout replay gets counted as normal consumption and skews the fit. For batch jobs, also record concurrency and truncation, because truncation changes the output-length distribution and therefore the per-task cost.
Use a linear relationship to back out unit costs
If billing is linear in usage, a single call can be written as:
consumption ≈ input unit price × input volume + output unit price × output volume + cache unit price × cache-hit volume + fixed term
The fixed term may be zero, or it may correspond to a per-call fee. Stack many requests together and you get a multivariate linear system. Fit it with least squares or a regression with non-negative constraints; the resulting coefficients are the unit costs of each component. Non-negativity is usually a reasonable assumption, since token prices should not be negative. If the fit produces a negative coefficient, suspect first that field definitions are inverted, that cache volume is being double-counted inside input, or that samples with different billing rules got mixed together.
The sketch below expresses only the algorithm and does not map to any specific platform API:
import numpy as np# X column order: input volume, output volume, cache-hit volume, constant term# y: credits or amount actually deducted for that requestcoef, *_ = np.linalg.lstsq(X, y, rcond=None)
Samples must span different lengths and different cache ratios. If nearly every request has the same input-to-output ratio, the input price and output price get entangled and the coefficients become unstable. You can deliberately construct three probe task types — short input with long output, long input with short output, and high cache hit — but probes must comply with usage and privacy policies and must not send real user data to unrelated environments.
How to tell whether the fit is credible
A high coefficient of determination only means the linear relationship explains the current sample well; it does not automatically extrapolate to another model tier or to rules that changed later. Look at the residuals too: residuals scattered randomly around zero suggest few missing terms, while residuals that grow systematically with output length hint at a per-call fee, a minimum billing unit, or rounding up. Replay grouped by day or by model tier; if one group is biased as a whole, split it out and refit rather than forcing one global unit price onto everything.
Logs themselves can be wrong. Token counts are sometimes approximated by characters and sometimes produced by the real tokenizer, and the two cannot be mixed. If cache hits record only “prefix length” instead of “tokens actually discounted,” the equation will overfit. After fitting, replay a held-out period: predict credits from the coefficients and compare against actual deductions. Only when the deviation stays within an acceptable range should the numbers be used for budgeting. After a rules change, the old coefficients are void.
State the conclusion as “an estimate under the current rules and the current log definitions,” not as an official price list. Public list prices, contract discounts, promotional credits, and actual deductions may disagree; continuous records from the account side take precedence.
Converting unit prices into usable scale within a time window
With unit costs in hand, you can answer “given a credit or dollar budget and a time window, roughly how many tokens can we run.” Let the input share be p and the output share be 1-p, ignoring cache for the moment, then the blended unit price is:
blended unit price = p × input unit price + (1-p) × output unit price
usable tokens in window ≈ window budget / blended unit price
Do not guess p. Derive it from real task statistics: conversational tasks tend to have longer inputs, while code generation and long-form writing have a higher output share. Cache hit rate must be estimated separately. Once a hit occurs, the portion of input covered by the cache should be priced at the cache unit price rather than the normal input price. The savings are approximately:
savings ratio ≈ hit rate × (1 - cache unit price / input unit price)
So stable prefixes, fixed system prompts, and repeated retrieval templates reduce cost more reliably than swapping models blindly. At the same time, avoid stuffing stale or irrelevant context into the prompt just to inflate cache hits; latency and error rates will rise.
Tier by task complexity instead of using one model for everything
Cost differences usually come from capability tiers, not from absolute judgments about “who is cheaper.” A more sensible split routes by failure cost and reasoning difficulty:
- Planning and final review: requirement decomposition, tradeoff decisions, result acceptance, review of high-risk changes. Failure is expensive, call volume should be low, and a higher unit-cost tier is acceptable.
- Complex reasoning: multi-constraint solving, cross-document synthesis, problems needing rigorous intermediate steps. Put these in the mid-to-high tiers and cap output length.
- Main execution: carrying out an already-confirmed plan — retrieval and organization, format conversion, routine code completion, draft generation. Optimize for throughput and stability, preferring lower unit cost.
- Batch simple tasks: classification, extraction, tagging, template filling, low-risk rewriting. Optimize for unit price and concurrency, combined with caching and short prompts.
Routing can use explicit rules; a heavy learning system is not required. For example: let a low-cost tier do intent classification first; escalate to the high-cost tier only when the task is marked as planning, review, or has failed validation twice in a row. Every escalation must record its reason, otherwise cost quietly drifts back to “everything goes to the top tier.”
Sketch of the flow:
request arrives → rule-based classification (simple / execution / reasoning / review)→ pick tier and length cap→ reusable prefixes go through cache→ execute and write logs→ if validation fails, escalate a limited number of times; if still failing, hand to a human or return an explicit error
The expensive tier is responsible for “thinking it through,” the cheap tier for “finishing as planned,” and the handoff between them uses checkable intermediate artifacts such as task lists, constraint lists, and acceptance criteria. Do not pass full long reasoning traces back and forth between tiers; that multiplies context cost.
Quality control must not be swallowed by cost targets
After tiering, guard against two failure modes. One is a low tier barely attempting a hard task: it looks like savings, but rework and human correction cost more. The countermeasure is to define acceptance criteria per task type — is the format complete, are key fields present, does the output conflict with the constraints. Escalate on acceptance failure and track the escalation rate. A steadily rising escalation rate means the classification rules or prompts are broken, not that you should simply buy a higher tier.
The other is the high tier being saturated by everyday traffic. The countermeasure is quotas: set caps on call count and input length for review tasks; requests beyond the cap either queue or are downgraded with the capability change clearly communicated. Output length is a cost lever, so require conclusions and key points first, expanding only when the caller needs it.
Engineering checklist
- Unify log definitions: token counts, cache hits, retries, tier, task type, and actual deduction in a single record.
- Fit per tier: estimate unit prices separately for each tier instead of merging different rules into one coefficient.
- Hold out a replay: validate residuals on a new period and re-estimate immediately after rules or discounts change.
- Use real input/output ratios and cache hit rates for budget conversion, and report a range rather than a single point.
- Keep routing rules explainable and auditable, with a limited number of escalations to avoid oscillation.
- Monitor at least: cost per task, cache hit rate, escalation rate, truncation rate, and failure rate. When one of them jumps, check log definitions and prompt changes first.
Object storage can hold desensitized usage details, a log service handles retrieval, and monitoring and alerting handle thresholds. These are general cloud capabilities used for cost accounting; there is no need to bind them to any one model vendor’s console.
Boundaries when using these estimates
Unit costs change with billing rules, context caching strategy, tokenization, and discounts. Even a fit with tiny residuals only shows that “deductions at that time were almost linearly explainable by these components.” It is not a permanently fixed price list, and it must not be used to compare services that were not measured under the same definitions. When reporting externally, include the sample range, field definitions, and items not accounted for, such as per-call fees, failed retries, and human review time.
Chain the logs, the linear estimate, the window budget, and tiered routing together and a team can answer three practical questions: is the money going mainly to input, output, or cache misses; how much scale can the current budget support; and which steps genuinely require a high-capability tier while others should go to a lower-unit-cost execution tier. That is more repeatable than comparing “which chat felt more expensive,” and it fits better into a system that runs continuously.
