Time-Based Arbitrage for LLM Inference Costs: A Practical Guide

    This article explains how to reduce large language model inference costs through time-based scheduling instead of committing to a single vendor. It presents a cost model built around four levers—peak-hour factors, prefix cache discounts, quota status, and retry overhead—and a three-dimensional arbitrage framework covering time, billing, and compute tiers. A brand-agnostic routing layer, cache-friendly prefix design, stability guardrails, and governance practices are included to help teams apply the method sustainably across cloud environments.

    1. The Problem: Why “Which Provider Is Best?” Is the Wrong Question

    When teams evaluate LLM services, the first instinct is usually to compare vendors head to head and then commit to one for the long term. In real engineering environments, this approach often breaks down for three reasons:

    1. Capability dimensions are not comparable. Relative strengths in long-context understanding, code generation, structured output, and multi-turn tool calling are unstable and shift with every model release. Any benchmark conclusion has a very short shelf life.
    2. Cost structure varies far more than unit price. What actually drives the bill is not the price per million tokens, but the billing model (subscription quota, pay-as-you-go top-ups, credit systems), peak and off-peak discounts, cache hit policies, and the extra consumption caused by failed retries.
    3. Different users hold different assets. Annual plans already purchased, balances already topped up, and configured quota ceilings all differ. The optimal strategy is inherently a personalized “work with what you have” outcome, not one universal answer.

    The more rigorous question, therefore, is not “which vendor is strongest,” but: under a given set of asset constraints, how do you spend every unit of compute and every dollar at the point in time with the highest marginal return? That is the starting point for time-based scheduling arbitrage.

    2. Modeling the Cost: Build the Model Before Optimizing

    To optimize cost, you must first express it as something computable. For any single inference request, the actual cost can be abstracted as:

    1. Cost(request) = Base(input tokens, output tokens)
    2. × PeakFactor(time of request)
    3. × (1 - CacheDiscount(prefix hit rate))
    4. × QuotaFactor(current plan/credit balance state)
    5. + RetryOverhead(failed and timed-out retries)

    This expression reveals four levers you can act on:

    • PeakFactor (peak/off-peak coefficient): Resource pressure differs across time of day, and some billing schemes discount off-peak hours—effectively expanding your usable quota.
    • CacheDiscount (cache discount): When the request prefix (system prompt, tool definitions, long documents, code context) is highly repetitive, prefix caching can hit and input-side billing drops significantly.
    • QuotaFactor (quota state): Subscription quota has a near-zero marginal cost while it is valid, whereas pay-as-you-go balance costs the listed price when funds are sufficient. Their “shadow prices” are completely different.
    • RetryOverhead (retry overhead): Timeouts, rate limiting, and format validation failures all inflate real cost. This part is often overlooked, yet it is frequently the main cause of an abnormal bill.

    The essence of optimization is to land each request on the combination that minimizes Cost.

    3. A Three-Dimensional Arbitrage Framework: Time, Billing, and Compute

    3.1 Time: Shift Load to the Trough

    Divide the day into peak, secondary peak, and off-peak periods (the exact hours vary by platform and should follow the actual billing documentation; this article assumes no specific values). The core action is to move deferrable batch jobs into discounted windows: overnight bulk code refactoring, offline document summarization, log clustering, and test case generation are all latency-insensitive and can be queued for off-peak execution. Keep interactive tasks in daytime, served over a low-unit-price pay-as-you-go channel.

    3.2 Billing: Burn Prepaid Quota First

    Purchased plan quota is a sunk cost with the lowest marginal cost and should be consumed first; pay-as-you-go balance acts as an elastic buffer. A practical rule: priority = remaining quota / remaining validity period. The higher the ratio, the sooner it should be used, which avoids wasting quota at the end of the term.

    3.3 Compute: Route by Task Difficulty

    Not every request needs the strongest model. Classify tasks into three tiers: extraction/classification/formatting (light), routine Q&A and single-file code completion (medium), and cross-file refactoring and complex reasoning (heavy). Light tasks go to a fast, low-cost channel; only heavy tasks call the high-capability channel. In practice, light tasks make up a large share of production traffic, so the payoff from this routing layer is often the largest.

    4. Implementation: A Brand-Agnostic Routing Layer

    The key engineering constraint is that the routing layer must not hardcode any vendor identifier; it should be programmed purely against “capability tier + billing attribute.”

    1. from dataclasses import dataclass
    2. from enum import Enum
    3. class Tier(Enum):
    4. LIGHT = "light" # extraction, classification, formatting
    5. MEDIUM = "medium" # routine Q&A, single-file completion
    6. HEAVY = "heavy" # cross-file refactoring, complex reasoning
    7. @dataclass
    8. class Channel:
    9. name: str # logical channel name, no brand information
    10. tiers: set[Tier] # supported difficulty tiers
    11. billing: str # "quota" | "paygo"
    12. peak_sensitive: bool # whether peak/off-peak differences exist
    13. quota_left: float # normalized remaining quota
    14. expiry_days: int # remaining validity period
    15. def shadow_price(ch: Channel, hour: int) -> float:
    16. """Quota shadow price: the less left and the closer the expiry, the higher the priority."""
    17. if ch.billing == "quota":
    18. urgency = 1.0 / max(ch.expiry_days, 1)
    19. scarcity = 1.0 / max(ch.quota_left, 0.05)
    20. return 0.1 * urgency * scarcity
    21. peak = 1.0 if (ch.peak_sensitive and 9 <= hour < 21) else 0.6
    22. return 1.0 * peak
    23. def route(tier: Tier, hour: int, channels: list[Channel]) -> Channel:
    24. feasible = [c for c in channels if tier in c.tiers and c.quota_left > 0]
    25. if not feasible:
    26. raise RuntimeError("No available channel; degrade or queue")
    27. return min(feasible, key=lambda c: shadow_price(c, hour))

    The value of this implementation is that adding or replacing any backend service requires only registering a Channel, with zero changes to the scheduling logic—completely avoiding vendor lock-in.

    5. Cache Hit Rate: The Undervalued Cost Lever

    Whether a prefix cache hits depends on the request prefix being byte-for-byte stable. In engineering terms, you should:

    • Put the system prompt and tool definitions first in a fixed order, and never concatenate timestamps, random identifiers, or user nicknames into the prefix;
    • Keep long documents and code repository context in stable segments and ordering, avoiding reassembly on every request;
    • Place volatile content (user input, retrieval results) uniformly at the end;
    • Cluster batch jobs by “identical prefix” before sending, rather than interleaving them randomly.

    An illustrative stable prefix layout:

    1. [Fixed] System role definition + output format constraints + tool list (fixed order)
    2. [Semi-fixed] Repository structure summary / long document fragments (lexicographic order by path)
    3. [Volatile] Current user instruction + retrieved fragments + tail of conversation history

    Simply moving volatile fields to the end and clustering similar tasks can noticeably reduce input-side billing. This is the highest return-on-effort step available.

    6. Stability and Guardrails: Don’t Save on Unit Price and Lose on Retries

    A low-cost strategy must come with guardrails; otherwise rate limiting and timeouts will eat all the savings:

    • Exponential backoff with jitter for retries, with a maximum retry count and a total budget cap;
    • Circuit breaking and a degradation chain: when the high-capability channel is unavailable, automatically fall back to the medium tier and annotate the result’s confidence;
    • Idempotency keys to avoid duplicate billing and duplicate writes;
    • Timeout budgets differentiated by task tier—short timeouts for light tasks, longer for heavy ones;
    • Observability: track “cost per thousand successful tasks,” “cache hit rate,” “retry rate,” and “quota burn rate” as core metrics, connect them to logging and alerting, and build a daily cost dashboard.

    7. Governance and Compliance

    • Cost optimization must not circumvent any platform’s terms of use or quota limits; all scheduling must stay within authorized quota.
    • When sensitive data is involved, redact it before it enters the prefix to avoid cross-session information residue from caching.
    • Keep a human spot-check step on the output side to prevent quality from being sacrificed for cost.
    • If you use general cloud capabilities (object storage, message queues, container platforms, logging, alerting) to carry scheduling and queues, apply least privilege and key rotation.

    8. Conclusion

    “Which vendor is strongest” will keep being rewritten with each release, but cost engineering methods are stable: express cost as a formula, identify the four levers of peak hours, caching, quota, and retries, use a brand-decoupled routing layer to schedule by difficulty tier, and defend the quality baseline with guardrails and observability. This method can be implemented on the general product combinations of any cloud environment, such as Baidu AI Cloud. Its returns come from structure rather than a one-off promotion, making it sustainable, portable, and measurable.