Cost-Aware Routing and Time-of-Use Pricing for LLM APIs

    As LLM API prices rise and diverge across capability tiers and time windows, model selection becomes a financial decision. This article explains how time-of-use pricing works, why hard-coding a single model is risky, and how to build a unified adapter layer plus cost-aware routing — including task tiering, off-peak scheduling, failover, and sample Python code — to keep inference costs predictable.

    1. Background: Rising Model Prices, Falling Inference Costs

    Over the past two years, the LLM service market went through a round of aggressive price competition. In the second half of 2026, several providers adjusted their pricing, and some raised API unit prices multiple times within a year, with cumulative increases approaching 80 percent. Over the same period, industry statistics showed that the average cost for enterprises to complete an equivalent inference task dropped sharply — a decline of more than 80 percent compared with a few years earlier.

    These two trends move in opposite directions but point to the same conclusion: models are now priced in tiers based on capability, and price gaps between tiers and time windows are widening. For consumers of these services, which model you call, when you call it, and how often you call it all directly affect margins and budgets. Model selection has shifted from a technical detail to a financial decision.

    2. How Time-of-Use Pricing Works and What It Changes

    Time-of-use pricing means the same model is billed at different rates depending on when it is called. Common patterns include:

    • Peak vs. off-peak pricing, where off-peak rates are typically lower;
    • Weekends or holidays billed entirely at off-peak rates;
    • Input tokens split into cache-hit and cache-miss, with cache hits billed at a noticeably lower rate;
    • Output tokens generally priced higher than input tokens, so long-form generation often dominates total cost.

    Time-of-use pricing changes how costs are calculated. The same request submitted during peak hours versus off-peak hours can differ in cost by more than a factor of two. Cost estimation must therefore include a time dimension — multiplying a flat unit price by token count is no longer sufficient.

    This pricing model also imposes requirements on task scheduling:

    1. Real-time interactive tasks, such as online Q&A and customer-service chat, are constrained by latency and cannot be deferred arbitrarily. Costs can only be reduced through model tiering.
    2. Near-real-time tasks, such as content moderation queues or ticket summarization, tolerate delays of a few minutes to tens of minutes and can be processed in batches during certain windows.
    3. Offline tasks, such as bulk data cleaning, overnight report generation, and offline evaluation, are insensitive to completion time and are best scheduled in off-peak windows.

    3. Why You Should Not Hard-Code a Single Model

    Binding business logic directly to one specific model from one provider hands control of cost and availability to the supplier. This carries three categories of risk.

    Price risk. When the provider raises prices, budgets go out of control immediately. If model names and request formats are scattered throughout business code, migrating to another provider requires changes everywhere, which is slow and expensive to test.

    Availability risk. Any service can experience rate limiting, timeouts, or brief outages. A single point of dependency means failures propagate directly to the business side, and users experience the feature as unavailable.

    Capability mismatch risk. Different tasks have very different capability requirements. Using an expensive model for simple tasks like classification or extraction wastes budget; using a cheap model for complex reasoning can compromise quality. A single model rarely balances quality and cost well.

    A more reasonable approach is to treat models as replaceable resources rather than fixed dependencies.

    4. The Unified Adapter Layer: Containing Differences in One Place

    The unified adapter layer sits between business code and the various model providers. The business layer only expresses “which capability tier is needed,” and the adapter layer translates requests into each provider’s specific format. It typically handles the following responsibilities:

    • Protocol conversion: unify request fields, authentication, and response structures, and map each provider’s error codes to a single exception type.
    • Capability tier mapping: the business layer uses tier names such as light, standard, and heavy, never model names directly. Switching models only requires a configuration change; business code stays untouched.
    • Metering and logging: consistently record input/output token counts, latency, the billing window, and actual cost, providing the data foundation for cost analysis.
    • Externalized configuration: endpoints, prices, and time windows live in config files or a configuration center. Keys are read from environment variables or a secrets management service — never written into code or logs.

    The value of the adapter layer is isolation. When a provider changes pricing, adds models, or modifies its API, the impact is contained within the adapter.

    5. Cost-Aware Routing

    The core flow of cost-aware routing has three steps: task tiering, candidate ranking, and failover.

    5.1 Task Tiering

    Tiering is based on task type, input length, and quality sensitivity. A common division:

    • Light tier: classification, information extraction, format conversion, simple Q&A. Quality criteria are well-defined, making these tasks suitable for low-priced models.
    • Standard tier: general text generation, summarization, multi-turn dialogue. A balance between quality and cost.
    • Heavy tier: complex reasoning, long-document analysis, code generation. Quality comes first, and higher-priced models are acceptable.

    Tiering rules should not rely on intuition alone. A more reliable approach is to use a fixed evaluation set, compare the pass rates of each tier’s models on each task type, and set the mapping accordingly.

    5.2 Off-Peak Scheduling

    Non-real-time tasks can be placed in a queue and consumed during off-peak windows. The approach:

    • Record priority and deadline when a task is submitted;
    • The consumer pauses pulling during peak windows and executes in batches during off-peak windows;
    • If a deadline approaches while it is still peak time, execute anyway to avoid missing the deadline.

    Window calculation must use the billing provider’s time zone. For cross-time-zone deployments, always use time-zone-aware datetime objects to avoid misalignment between local time and billing time.

    5.3 Candidate Ranking and Failover

    Within a tier, candidate models are sorted by estimated cost in ascending order. Calls are attempted in sequence, and recoverable errors trigger a switch to the next candidate. Two points require attention during failover:

    • A failed endpoint should be temporarily marked unavailable and automatically recover after a cooldown period, to avoid repeatedly hitting a service that is already failing;
    • If all candidates fail, return a clear error and trigger an alert instead of silently degrading.

    5.4 Sample Code

    The following code demonstrates the structure above. The prices are example parameters used to illustrate the data structure and do not represent any real pricing.

    1. from dataclasses import dataclass, field
    2. from datetime import datetime, timedelta, timezone
    3. CST = timezone(timedelta(hours=8)) # billing provider's time zone
    4. class ProviderError(Exception):
    5. """Unified error raised by adapters on network, rate-limit, or server-side failures."""
    6. @dataclass
    7. class Endpoint:
    8. provider: str # provider identifier, used to look up the adapter
    9. model: str # model name, used only inside the adapter layer
    10. tier: str # capability tier: light / standard / heavy
    11. in_peak: float # peak input price per million tokens
    12. out_peak: float # peak output price per million tokens
    13. in_off: float # off-peak input price per million tokens
    14. out_off: float # off-peak output price per million tokens
    15. peak_hours: list = field(default_factory=lambda: [(9, 12), (14, 18)])
    16. healthy: bool = True
    17. def is_peak(self, now: datetime) -> bool:
    18. local = now.astimezone(CST)
    19. hour = local.hour + local.minute / 60
    20. return any(start <= hour < end for start, end in self.peak_hours)
    21. def estimate_cost(self, in_tokens: int, out_tokens: int, now: datetime) -> float:
    22. if self.is_peak(now):
    23. p_in, p_out = self.in_peak, self.out_peak
    24. else:
    25. p_in, p_out = self.in_off, self.out_off
    26. return (in_tokens * p_in + out_tokens * p_out) / 1_000_000
    27. # Example parameters for demonstrating the structure only
    28. ENDPOINTS = [
    29. Endpoint("provider_a", "model-a-large", "heavy", 9.0, 27.0, 4.5, 13.5),
    30. Endpoint("provider_a", "model-a-small", "light", 3.0, 9.0, 1.5, 4.5),
    31. Endpoint("provider_b", "model-b-large", "heavy", 8.0, 24.0, 4.0, 12.0),
    32. Endpoint("provider_b", "model-b-small", "light", 2.5, 8.0, 1.2, 4.0),
    33. ]
    34. class Adapter:
    35. """Each provider implements the same signature, handling auth,
    36. field mapping, and error conversion internally."""
    37. def chat(self, model: str, messages: list[dict]) -> str:
    38. raise NotImplementedError
    39. # Registered at startup, e.g. ADAPTERS["provider_a"] = SomeAdapter(...)
    40. ADAPTERS: dict[str, Adapter] = {}
    41. def pick_candidates(tier: str, in_tokens: int, out_tokens: int, now: datetime) -> list[Endpoint]:
    42. pool = [e for e in ENDPOINTS if e.tier == tier and e.healthy]
    43. return sorted(pool, key=lambda e: e.estimate_cost(in_tokens, out_tokens, now))
    44. def chat_with_routing(tier: str, messages: list[dict],
    45. in_tokens: int = 1000, out_tokens: int = 500) -> str:
    46. now = datetime.now(timezone.utc)
    47. last_error = None
    48. for ep in pick_candidates(tier, in_tokens, out_tokens, now):
    49. try:
    50. return ADAPTERS[ep.provider].chat(ep.model, messages)
    51. except ProviderError as exc:
    52. # Simplified: production should add a cooldown with automatic recovery
    53. ep.healthy = False
    54. last_error = exc
    55. raise RuntimeError(f"All candidates in tier {tier} are unavailable") from last_error

    The key points: the business side only passes a tier name; candidate order is determined by the current time and estimated cost; failures trigger automatic failover; and every switch can be logged and monitored.

    6. Practical Considerations

    Quality regression testing. Before switching models, compare old and new outputs on a fixed evaluation set and record the differences. Looking only at price reductions without validating quality easily leads to a degraded user experience after launch.

    Cost accounting. Track spend by time window, task type, and business line. Only at this granularity can you see the actual benefit of the routing strategy and spot tasks with abnormal consumption.

    Caching and prompt stability. Keep system prompts and fixed context prefixes stable to improve cache hit rates. Frequent prompt changes reduce hit rates and indirectly raise input costs.

    Budgets and alerts. Set daily or monthly budget thresholds. When approaching a threshold, automatically downgrade non-critical tasks to the light tier or pause offline tasks to keep spending within expectations.

    Billing rule changes. When a provider adjusts time windows or unit prices, update the configuration promptly, and reconcile costs before and after the change to confirm the new configuration is in effect and matches the bill.

    Data compliance. Providers may differ in data processing terms and regional requirements. Tasks involving sensitive data should be routed only to compliant endpoints, with this constraint encoded in the routing rules rather than left to manual judgment.

    7. Conclusion

    Model prices will continue to fluctuate, and simply hunting for “the cheapest model” only solves today’s problem. A more reliable approach is to build a mechanism that adapts as prices and availability change. The unified adapter layer ensures models are replaceable; cost-aware routing ensures every call lands at the right price and tier. Together, they let a team keep costs predictable even through a cycle of price increases.