Measuring LLM Token Costs and Building a Tiered Routing Strategy

    When multiple LLMs of different tiers are mixed in production, token costs become hard to track—especially under credit-based pricing where input tokens, output tokens, cache hits, and model tiers all convert differently. This article presents a reproducible engineering method: fit per-tier cost coefficients from invocation logs, derive capacity estimates from a credit budget, design a four-layer routing strategy based on task value, reduce repeated input costs with caching and batching, and keep the coefficients trustworthy through continuous monitoring and governance. A platform-agnostic pseudocode example shows how to implement cost-aware routing with budget validation and graceful degradation.

    Measuring LLM Token Costs and Building a Tiered Routing Strategy

    1. Background: Why Costs Are Hard to See When Mixing Multiple Models

    Once LLM applications move into the engineering phase, a single model rarely satisfies quality, latency, and cost requirements at the same time. A common practice is to mix models of different tiers by task type: high-capability models handle planning, review, and complex reasoning, while low-cost models handle batch execution, classification, summarization, formatting, and other simple tasks. But once this is put into practice, teams quickly run into a core problem: token costs across models are not transparent. With credit-based token plans in particular, the conversion relationships among input tokens, output tokens, cache hits, and different model tiers are often impossible to read directly from the business side.

    Choosing models based on gut feeling leads to two typical problems. First, expensive models get used heavily for low-value tasks, and the budget drains quickly. Second, cheap models take on tasks beyond their capability, driving up rework, retries, and manual verification costs. What is needed is a reproducible method that turns invocation logs into cost coefficients, and then into routing policies and a budget model.

    It is important to stress that any coefficients inferred from historical call records are internal estimates—not an official price list, and not a substitute for the platform’s formal billing rules. Their value lies in helping the team build cost awareness and recalibrate quickly when rules change.

    2. Reverse-Engineering Costs: Approximating Credit Consumption as a Linear Function

    For most token-billed invocation patterns, the credit consumption of a single request can be approximated as:

    1. Total cost ≈ input tokens × input unit price + output tokens × output unit price + cached tokens × cache unit price

    The input, output, and cache unit prices can be fitted from historical records. The specific steps are:

    1. Collect invocation logs: record each request’s model tier, input tokens, output tokens, cached tokens, actual credit consumption, retry count, and similar fields.
    2. Clean anomalous samples: remove failed retries, truncated over-long contexts, billing delays, manual adjustments, and other abnormal records.
    3. Build a linear model: use input tokens, output tokens, and cached tokens as independent variables and credit consumption as the dependent variable to fit the cost coefficients for each model tier.
    4. Validate fit quality: check whether the goodness of fit is close to 1 and residuals are close to 0; if errors are large, look for hidden billing items or missing log fields.
    5. Version the coefficients: manage coefficients by platform rules, model version, and time window to avoid relying on stale values.

    In practice, if the goodness of fit is close to 1 and residuals are close to 0, credit consumption within that statistical window is well explained linearly by input/output tokens. At that point you have a cost coefficient matrix for budgeting and routing decisions.

    An illustrative coefficient structure is shown below, where the letters are parameters to be fitted and do not represent any platform’s actual prices:

    1. Cost coefficient matrix (unit: credits per million tokens)
    2. Tier A: input a_in, output a_out, cache a_cache
    3. Tier B: input b_in, output b_out, cache b_cache
    4. Tier C: input c_in, output c_out, cache c_cache
    5. Tier D: input d_in, output d_out, cache d_cache

    From general experience, a high-capability model’s output unit price can be significantly higher than a lightweight model’s—output costs reaching a hundredfold magnitude are not uncommon—and cache hits can reduce the cost of repeated context to a few percent of normal input cost. These observations should be treated only as methodological examples; concrete numbers must come from fitting your own logs.

    3. Capacity Estimation: Deriving Sustainable Token Volume from a Credit Budget

    With cost coefficients in hand, capacity estimation becomes possible. Suppose a plan provides a fixed credit budget within a given time window, the business-side input/output ratio is roughly stable, and cache hits are temporarily ignored. The sustainable token volume can then be approximated as:

    1. Sustainable tokens ≈ total credit budget / (input share × input unit price + output share × output unit price)

    For example, if the input share is 80% and the output share is 20%, the denominator is:

    1. 0.8 × input unit price + 0.2 × output unit price

    Substituting the coefficients of each tier yields the relative carrying capacity of each tier under the same budget. A clear stratification usually emerges: high-capability models sustain a small token volume and suit low-frequency, high-value tasks; mid-tier models suit complex reasoning; low-cost models suit mainline execution; and lightweight models suit batch simple tasks.

    The point of this step is not absolute precision but establishing relative relationships. As long as the coefficients remain stable within the same statistical window, the team can judge how much cost drops when a task migrates from a high tier to a lower one, and how much the budget grows if quality requires falling back to a higher tier. Capacity estimates should also reserve headroom for retries, tool calls, context growth, and traffic spikes.

    4. Tiered Routing: Expensive Models Think, Cheap Models Execute

    Based on cost coefficients and task characteristics, a four-layer routing strategy can be designed:

    4.1 Planning and Final Review Layer

    This layer uses high-capability models for requirement decomposition, solution planning, key decisions, final quality review, and risk identification. It is characterized by low call frequency, high per-call value, and low tolerance for errors. Input context should be limited—avoid feeding large volumes of raw logs directly. A cheap model can first produce summaries and candidate outputs, which the expensive model then reviews.

    4.2 Complex Reasoning Layer

    This layer uses mid-to-high-capability models for multi-step reasoning, complex logic in code generation, structured analysis, and hard problem diagnosis. Routing conditions can include a task difficulty score, historical failure rate, context length, and whether multi-round tool calls are needed.

    4.3 Mainline Execution Layer

    This layer uses low-cost models for the majority of routine generation, rewriting, extraction, classification, format conversion, and tool-call orchestration. It is the throughput workhorse, so cache hits, batching, rate limiting, and retry policies deserve the most attention here.

    4.4 Batch Simple Task Layer

    This layer uses very lightweight models for high-volume, low-risk, sample-checkable tasks such as tag cleaning, simple summarization, template filling, and keyword extraction. It should be paired with sampling-based quality checks and a failure fallback mechanism to prevent errors from silently propagating.

    The routing principle can be summarized as: expensive models “think” and “review,” cheap models “execute” and “batch.” But routing must consider failure cost, not just price. In high-risk domains such as finance, healthcare, and legal work, even seemingly simple tasks should retain manual review or spot checks by a high-tier model.

    5. Caching and Batching: Reducing Repeated Input-Side Costs

    Repeated input is common in multi-turn conversations, long system prompts, fixed knowledge-base Q&A, and agent tool calls. Cache hits can significantly reduce the cost of repeated context. Engineering efforts should focus on:

    1. Stable prefix design: place system prompts, tool descriptions, and fixed rules at the front to minimize the impact of dynamic content on caching.
    2. Cache hit monitoring: record cached tokens, hit rate, and credits saved, broken down by model tier.
    3. Invalidation and consistency: proactively invalidate related caches when rules, knowledge bases, or tool descriptions change, so stale context does not pollute results.
    4. Privacy and isolation: cache keys should include tenant, task type, and permission scope to prevent cross-tenant reuse.
    5. Batching: for offline tasks, use asynchronous queues, batch submission, and backoff retries to lower peak credit consumption and API pressure.

    Caching is not unconditionally better. For highly time-sensitive, highly personalized, or sensitive contexts, enable caching cautiously and keep auditable records in the logs.

    6. Engineering Implementation: Cost-Aware Routing Pseudocode

    The following pseudocode is platform-agnostic. The cost coefficients are fitted from historical logs; fill in the estimated values for the current window in actual use.

    1. # Cost coefficients: credits per million tokens, fitted from logs
    2. COST = {
    3. "plan_review": {"in": a_in, "out": a_out, "cache": a_cache},
    4. "complex": {"in": b_in, "out": b_out, "cache": b_cache},
    5. "execute": {"in": c_in, "out": c_out, "cache": c_cache},
    6. "batch": {"in": d_in, "out": d_out, "cache": d_cache},
    7. }
    8. def estimate_cost(tier, in_tokens, out_tokens, cache_hit_tokens):
    9. c = COST[tier]
    10. normal_in = max(0, in_tokens - cache_hit_tokens)
    11. return (
    12. normal_in * c["in"]
    13. + cache_hit_tokens * c["cache"]
    14. + out_tokens * c["out"]
    15. ) / 1_000_000
    16. def choose_tier(task):
    17. if task.needs_planning or task.needs_final_review:
    18. return "plan_review"
    19. if task.reasoning_depth >= HIGH_THRESHOLD or task.history_failure_rate > FAIL_THRESHOLD:
    20. return "complex"
    21. if task.is_batch and task.risk_level == "low":
    22. return "batch"
    23. return "execute"
    24. def route_with_budget(task, window_budget):
    25. tier = choose_tier(task)
    26. estimated = estimate_cost(tier, task.in_tokens, task.out_tokens, task.cache_hit_tokens)
    27. if estimated > window_budget.remaining:
    28. if tier == "plan_review":
    29. raise BudgetExceeded("High-value task requires manual confirmation or budget adjustment")
    30. tier = "execute" if tier == "complex" else "batch"
    31. estimated = estimate_cost(tier, task.in_tokens, task.out_tokens, task.cache_hit_tokens)
    32. if estimated > window_budget.remaining:
    33. raise BudgetExceeded("Insufficient budget; entering delayed queue")
    34. window_budget.consume(estimated)
    35. return tier

    The pseudocode embodies three principles: select the tier by task value first, then validate against the budget, and finally degrade or enter a delayed queue when the budget is insufficient. Production systems should also add rate limiting, circuit breaking, retry backoff, idempotency, and audit logging.

    7. Monitoring and Governance: Keeping Cost Coefficients Trustworthy

    Cost routing is not a one-time configuration but an ongoing governance process. Recommended metrics include:

    • Credit consumption rate and per-task cost for each tier;
    • Changes in the input/output token ratio;
    • Cache hit rate and credits saved by caching;
    • Routing mismatch rate: the proportion of high-value tasks handled by low-tier models;
    • Quality regression: sampling pass rate, manual rework rate, and failure retry rate;
    • Budget deviation: the gap between actual and estimated credit consumption.

    For governance: version the coefficients, roll out routing rules gradually, replay anomalous samples, and refit periodically. When platform billing rules, model versions, or business traffic patterns change, collect fresh logs and update the coefficients. For high-value tasks, keep a “high-tier model review” switch available so quality is not sacrificed purely for cost.

    8. Risk Boundaries and Conclusion

    It must be clear that cost coefficients inferred from logs have boundaries: they depend on the statistical window and can be affected by retries, caching, context truncation, and hidden billing items; they are not an official price list and cannot guarantee that future rules stay unchanged. Teams should position the inferred results as an internal budgeting and routing reference, not an external commitment.

    Overall, cost optimization for multi-model mixing can be summarized as one engineering path: fit cost coefficients from invocation logs, use the coefficients for capacity estimation, design tiered routing by task value, reduce repeated costs with caching and batching, and ensure long-term trustworthiness through monitoring and governance. High-priced models handle planning and review, mid-priced models handle complex reasoning, low-priced models handle mainline execution, and very lightweight models handle batch simple tasks. Only by putting cost, quality, and observability into the same framework does model mixing become an operable technical solution rather than a simple stack of models.