Cost Optimization for LLM APIs Under Peak and Off-Peak Pricing

    This article explains how time-based (peak and off-peak) pricing for large model inference works and how engineering teams can cut costs without hurting user experience. It covers profiling your hourly traffic, classifying requests into interactive, near-real-time, and offline tiers, scheduling by deadline and cost weight, flattening peaks with queues and batch inference, reusing stable prefixes and semantic caches, routing between smaller and larger models, capping output length, and building observability dashboards with budget guardrails. A pre-launch verification checklist is included.

    1. Why Time-Based Pricing Is Inevitable for LLM Services

    The cost structure of large model inference closely resembles traditional cloud computing: compute supply is rigid in the short term, while request traffic shows clear daytime peaks and nighttime troughs. When concurrent requests concentrate in a given window, the provider must reserve enough accelerator cards and GPU memory to meet time-to-first-token and throughput targets; during off-peak hours, much of that capacity sits idle. Peak and off-peak pricing is essentially a price signal that makes resource scarcity explicit and nudges deferrable workloads toward the trough automatically.

    In practice, the common approach splits the day into a peak window and an idle window. For example, several hours in the morning and afternoon are marked as peak, and the rest of the day is idle, billed at half the peak rate. For developers, this means the bill is no longer determined only by how many tokens you call, but also by when you call them. Understanding this is the prerequisite for every optimization that follows.

    2. Profile Your Traffic First

    Before changing anything, quantify the time distribution of your own requests. Instrument the business side to log a timestamp, model tier, input and output token counts, and a business scenario tag for each call, then aggregate by hour:

    1. # Example: aggregate call volume and token usage by hour
    2. from collections import defaultdict
    3. buckets = defaultdict(lambda: {"calls": 0, "tokens": 0})
    4. def record(ts_hour: int, tokens: int):
    5. buckets[ts_hour]["calls"] += 1
    6. buckets[ts_hour]["tokens"] += tokens
    7. def peak_ratio(buckets, peak_hours=range(9, 12), peak_hours2=range(14, 18)):
    8. total = sum(v["tokens"] for v in buckets.values())
    9. peak = sum(v["tokens"] for h, v in buckets.items()
    10. if h in peak_hours or h in peak_hours2)
    11. return peak / total if total else 0.0

    If peak_ratio is close to 1, nearly all of your traffic is compressed into peak hours and the optimization headroom is largest. If the ratio is already low, shift your focus to caching and model tier selection.

    3. Task Tiering: Separate “Must Be Live” from “Can Wait”

    The point of cost optimization is not to squeeze every request, but to layer requests by latency sensitivity. Three tiers work well in practice:

    • Interactive: completion and query rewriting while a user is waiting. These must run in peak windows, preferably on smaller models or with thinking mode disabled.
    • Near-real-time: summarization, tagging, and ticket classification that tolerate minute-level latency. Buffer them in a queue and land them in idle windows where possible.
    • Offline: batch document parsing, code repository indexing, evaluation regressions, and data cleaning. These can be scheduled entirely overnight.

    Once tiering is in place, scheduling is no longer “dispatch as they arrive” but queue ordering by deadline and cost weight:

    1. priority = business weight / (estimated token cost × time-slot factor × inverse of remaining time)

    Use 0.5 as the time-slot factor in idle windows and 1.0 at peak. Offline tasks then naturally sink into the trough, while interactive tasks still get released first because their remaining time is tiny.

    4. Async and Batching: Flatten the Peak

    The most direct way to shave the peak is a message queue plus a consumer pool. Producers only write the request to the queue and return a task ID immediately; consumers adjust concurrency dynamically based on the current time slot:

    1. def concurrency_by_hour(hour: int, base: int = 4) -> int:
    2. # Scale concurrency up in idle windows to absorb cheap capacity
    3. if 9 <= hour < 12 or 14 <= hour < 18:
    4. return base
    5. return base * 3

    Pair this with a batch inference endpoint that merges multiple short requests into a single call, amortizing fixed scheduling and network overhead. Note that batching raises per-request latency, so it applies only to the offline and near-real-time tiers.

    5. Caching and Reuse: The Cheapest Call Is No Call

    In long-context and knowledge-base scenarios, prefixes repeat heavily. Context prefix caching, widely supported across the industry, computes fixed parts such as system prompts, tool definitions, and reference documents only once; later requests that hit the cache substantially reduce input-side billing and time-to-first-token. In engineering terms, put stable content first and volatile content last:

    1. [system instructions][tool schema][long-term knowledge snippets] -> stable prefix, cache-friendly
    2. [conversation history][current user input] -> volatile suffix

    Also build a semantic cache for deterministic Q&A: normalize the question into a vector, run a similarity lookup, and return the historical answer directly when the match clears the threshold. A practical pattern is layered expiry: short TTL for factual answers, long TTL for document answers, plus a manual invalidation switch.

    6. Model Tier and Output Length Governance

    A single business flow rarely needs the strongest model end to end. Route with “small model first, large model as fallback”: generate a draft and a confidence score with a lower tier, and escalate only on low confidence or high-risk cases. Governance on the output side matters too. Treat maximum output length as a budget rather than a default, and use structured output constraints and explicit length caps to keep the model from expanding without limit. Enable thinking mode per scenario; turning it off for simple classification lowers both latency and cost.

    7. Observability and Budget Guardrails

    Optimization must be measurable. Build three dashboards: cost distribution by time slot, cache hit rate, and token quota utilization per business line. Then add budget guardrails that trigger alerts and automatic degradation at thresholds:

    1. def guard(used: float, quota: float):
    2. if used / quota > 0.8:
    3. return "warn"
    4. if used / quota > 0.95:
    5. return "throttle" # switch to smaller model / extend cache TTL / pause offline tasks
    6. return "ok"

    The value of guardrails is turning cost from a surprise at month-end settlement into a control variable with runtime feedback.

    8. Pre-Launch Verification Checklist

    • Replay historical traffic and compare time-of-day bills and P95 latency before and after the change;
    • Validate queue backlog limits and task timeout policies so trough tasks do not pile up into peak hours;
    • Confirm cache keys include model version and prompt version to avoid returning stale results after an upgrade;
    • Give offline tasks an idempotency key so failed runs can be retried without double billing;
    • Roll out gradually: shift 10% of offline traffic first and observe one full peak-trough cycle.

    Conclusion

    Time-based pricing turns “time” into a tunable dimension. A mature solution is not about swapping in ever cheaper models, but about landing each class of request at the right time, on the right tier, at the right length. When task tiering, async peak shaving, prefix caching, and budget guardrails form a closed loop, cost reduction happens naturally and user experience stays intact.