LLM Inference Cost: A Practical Guide to Measuring Token Spend and Building Tiered Scheduling

    This article shows how to evaluate real large language model inference costs using your own usage records instead of published price lists, and how to turn those measurements into a tiered scheduling architecture. It covers fitting per-token consumption rates with least squares, why output tokens and cache misses dominate spend, a four-layer routing model that assigns flagship, mid-tier, and lightweight models to planning, reasoning, execution, and batch work, plus prefix caching, context governance, and capacity planning practices. The approach is provider-agnostic and applies to any token-metered model service, including platforms such as Baidu AI Cloud Qianfan.

    1. Background: Why “Cheap” Often Isn’t Cheap

    When teams build an AI coding assistant, a code review pipeline, or a multi-agent system, the most common problem is not model capability. It is a bill that spirals out of control. A pilot project that has been live for two weeks can burn through most of its monthly quota on a single full repository indexing run.

    Cost overruns usually trace back to three root causes:

    1. Pricing dimensions get ignored. Mainstream LLM services price input tokens and output tokens separately, and cached input tokens typically carry a significant discount. Comparing only the “price per million tokens” almost guarantees a wrong conclusion.
    2. Input/output structure gets ignored. Agent workloads consume far more input than output. Long contexts, tool return values, and conversation history are all counted as input again and again.
    3. Call structure gets ignored. For the same task, completing it with one expensive call versus twenty cheap calls can produce a cost difference of one to two orders of magnitude.

    So the right starting point for cost evaluation is not a price sheet. It is your own call distribution.

    2. Method: Deriving Unit Consumption Rates from Real Usage Records

    The method used here relies on no official pricing at all. It uses only two observable data sources: the credits consumed in each time window, and the token composition within that window.

    Let the credits consumed in a time window be $C$, input tokens be $I$, output tokens be $O$, and cache-hit tokens be $H$. Then:

    1. C = a * (I - H) + b * O + c * H

    Here a, b, and c are the credit consumption rates for uncached input, output, and cache-hit input respectively. Stack the records from multiple windows into a matrix and fit the parameters with least squares. Ideally the goodness of fit R² approaches 1 and the residuals approach 0, which indicates linear pricing and clean enough records.

    Sample implementation:

    1. import numpy as np
    2. # Each row: [uncached input, output, cache hit, measured credits]
    3. X = np.array([
    4. [820_000, 180_000, 0, ...],
    5. [1_500_000, 300_000, 900_000, ...],
    6. [400_000, 60_000, 2_100_000, ...],
    7. ])
    8. y = np.array([...])
    9. coef, *_ = np.linalg.lstsq(X, y, rcond=None)
    10. a, b, c = coef
    11. pred = X @ coef
    12. r2 = 1 - ((y - pred) ** 2).sum() / ((y - y.mean()) ** 2).sum()
    13. print(a, b, c, r2)

    Once the fit is done, organize the results into a “tier—consumption rate” reference table. You can then convert any workload into available capacity:

    1. Available tokens ≈ window credits / (a * input share + b * output share)

    Assuming 80% input, 20% output, and no cache for now, capacity under the same credit window can differ by tens of times across tiers. A flagship reasoning tier typically supports only hundreds of thousands of tokens, a mid-tier reasoning tier around a million, a high-throughput lightweight tier up to tens of millions, and an extreme lightweight tier into the tens of millions and beyond. That spread is the economic basis for tiered scheduling.

    One caveat: the above figures are reverse-engineered from personal measurements and will change as rules change. In engineering practice, the measurement script should be a repeatable scheduled job, not a one-time conclusion.

    3. Where the Cost Differences Really Come From

    Breaking the consumption rates apart, the differences concentrate in three places:

    • Output premium. The generation stage decodes token by token, which costs far more compute than the parallel prefill stage. The output rate is usually several times the input rate, and more than ten times at the flagship tier.
    • Parameter count and activation volume. Larger models reason better but also raise the compute cost per token. This is the direct expression of the capability premium.
    • Caching. Prefix caching turns repeated system prompts, repository context, and tool definitions into extremely cheap cache-hit input, with hit prices often as low as a few percent of the uncached price. For agent workloads, this lever has the largest effect.

    4. Tiered Scheduling Architecture

    The conclusion is simple: let expensive tiers do the “thinking” and cheap tiers do the “doing.”

    Layer Responsibility Recommended tier
    Planning Task decomposition, approach selection, final review Flagship reasoning
    Reasoning Complex logic, hard defect localization Mid-tier reasoning
    Execution Code completion, single-file edits, routine Q&A High-throughput lightweight
    Batch Bulk formatting, comment generation, simple classification Extreme lightweight

    In practice, put a unified gateway in front to hide the differences:

    1. def route(task):
    2. if task.risk == "high" or task.needs_review:
    3. return "flagship"
    4. if task.complexity >= 3:
    5. return "mid"
    6. if task.batch:
    7. return "lite"
    8. return "fast"
    9. def run(task, client):
    10. tier = route(task)
    11. r = client.chat(tier, messages=task.messages,
    12. extra_headers={"cache": "auto"})
    13. task.trace.update(tier=tier, usage=r.usage)
    14. return r.text

    Four engineering constraints matter: every call must record usage so the fit can be refreshed continuously; high-risk changes must go through flagship review; batch jobs must be physically isolated from online requests so they do not compete for quota; and each layer needs a credit budget and a circuit-breaker threshold.

    5. Caching and Context Governance

    • Keep the prefix stable. Put the system prompt, tool schema, and repository conventions first and never concatenate them dynamically. Timestamps and random IDs always go last.
    • Compress context. Summarize and deduplicate historical tool output, keeping only conclusions and key fragments.
    • Batch and merge. Combine N small requests into one batch with delimiters to amortize fixed overhead.
    • Monitor hit rate. Make cache hit rate and average input/output ratio core dashboard metrics. A falling hit rate usually means a prompt template was changed.

    6. Capacity Planning and Common Pitfalls

    Plan with measured consumption rates rather than nominal unit prices, and reserve 30% headroom for peaks. Three common mistakes: looking only at unit price while ignoring the input/output ratio; using the flagship tier for simple tasks that could be batched; and overlooking the hidden cost of failed retries. Retries should have a cap and fall back to a lower tier.

    7. Conclusion

    The essence of cost optimization is decoupling “capability” from “price” in scheduling. Measure first, then tier, and finally use caching and context governance to push unit cost as low as possible. This method is not tied to any specific service and transfers to any token-metered model service. On model platforms such as Baidu AI Cloud Qianfan, the same measurement and routing approach can be reused to build a sustainable, observable, and scalable cost governance system.