Cost Optimization for LLM API Peak/Off-Peak Pricing: How Teams Can Cut Inference Spending

    This article explains how teams can reduce LLM API inference costs under peak/off-peak pricing. It covers understanding the pricing model, profiling traffic to identify flexible workloads, implementing deferral scheduling, caching, asynchronous batch processing, token control, and setting up cost governance and monitoring with a unified gateway. Practical Python code and key metrics are included.

    Understanding Peak/Off-Peak Pricing

    According to official announcements, the API service will adopt peak/off-peak pricing starting from a specified date. Daily peak windows are 09:00–12:00 and 14:00–18:00; all other hours are off-peak, with unit pricing at 50% of the peak rate. Exact rules depend on official announcements and the pricing page. Model types, input/output token prices may be listed separately, so check each item carefully.

    This mechanism uses price as a lever to encourage users to shift flexible calls to off-peak hours, rather than imposing hard rate limits. The same concept applies to electricity peak/off-peak tariffs. LLM call volumes also follow a tidal pattern, typically concentrated during weekday mornings and afternoons, with a clear dip at night.

    A team’s daily cost can be estimated as:

    Daily cost = (peak tokens × peak unit price) + (off-peak tokens × off-peak unit price)

    Since off-peak pricing is half the peak rate, shifting the same token volume to off-peak reduces cost. The actual savings depend on how many calls can be moved.

    Profiling Your Traffic: Determine Which Calls Can Shift

    Before making changes, understand your own call structure. Recommend a three-step approach:

    1. Collect token consumption by hour over the past 30 days to identify your true daily peaks.
    2. Categorize calls: real-time interactive (e.g., online Q&A) vs. offline batch processing (e.g., document summarization, data labeling).
    3. Calculate the share of consumption during peak windows, then estimate what fraction of those calls can be deferred.

    Some claim that offline tasks typically account for more than 40% of total call volume, but this number lacks public sample data and statistical methodology, so do not rely on it. Teams should base decisions on their own statistics. If offline task ratio is low, peak-shifting benefits will be limited.

    Technical Implementation Strategies

    1. Task Tiers and Deferred Scheduling

    Divide tasks by SLA: real-time tasks execute immediately; latency-tolerant tasks enter a queue and run during off-peak hours. The example below uses an in-memory queue for clarity.

    1. from collections import deque
    2. from dataclasses import dataclass
    3. from datetime import datetime, time
    4. from zoneinfo import ZoneInfo
    5. TZ = ZoneInfo("Asia/Shanghai")
    6. PEAK_WINDOWS = [(time(9, 0), time(12, 0)), (time(14, 0), time(18, 0))]
    7. @dataclass
    8. class Task:
    9. task_id: str
    10. payload: dict
    11. realtime: bool
    12. defer_queue: deque[tuple[datetime, Task]] = deque()
    13. def is_peak(now: datetime) -> bool:
    14. t = now.astimezone(TZ).time()
    15. return any(start <= t < end for start, end in PEAK_WINDOWS)
    16. def next_offpeak_start(now: datetime) -> datetime:
    17. """Return the end of the current peak window, i.e., the start of the next off-peak period. Only call during peak hours."""
    18. local = now.astimezone(TZ)
    19. t = local.time()
    20. for start, end in PEAK_WINDOWS:
    21. if start <= t < end:
    22. return local.replace(hour=end.hour, minute=end.minute, second=0, microsecond=0)
    23. return local
    24. def execute_now(task: Task) -> None:
    25. # Placeholder: call the model API. Use task_id for deduplication to ensure safe retries.
    26. raise NotImplementedError
    27. def route_task(task: Task, now: datetime) -> None:
    28. if task.realtime or not is_peak(now):
    29. execute_now(task)
    30. else:
    31. defer_queue.append((next_offpeak_start(now), task))
    32. def drain_deferred(now: datetime, max_batch: int = 20) -> None:
    33. """Called by a timer every minute. Queue is FIFO; run_at values are non-decreasing, so peek from front."""
    34. if is_peak(now):
    35. return
    36. local_now = now.astimezone(TZ)
    37. done = 0
    38. while defer_queue and done < max_batch:
    39. run_at, task = defer_queue[0]
    40. if run_at > local_now:
    41. break
    42. defer_queue.popleft()
    43. execute_now(task)
    44. done += 1

    The time windows in the code use Beijing time. The announcement defines fixed daily periods, so holidays do not affect the logic. If the provider adds holiday rules, follow official announcements.

    Key considerations before deploying deferred scheduling:

    • SLA: Set a maximum wait for deferred tasks. For example, tasks queued from 09:00–12:00 wait at most 3 hours; those from 14:00–18:00 wait at most 4 hours. Tasks nearing their deadline should be executed immediately.
    • Data freshness: Downstream reports or recommendations that depend on offline results will be produced later than before.
    • Persistence: The in-memory queue above loses tasks after a process restart. Use Redis, RabbitMQ, Kafka, or a database table in production.
    • Retry and idempotency: Failed retries can cause duplicate calls and duplicate billing. Each task needs a unique ID; check whether the task has already been completed before re-execution.
    • Privacy compliance: Prompt data in the queue may contain personal information. Encrypt at rest, set a retention period, and verify the service agreement allows such data handling.

    2. Caching and Result Reuse

    Many calls are duplicates or near-duplicates: identical prompts, fixed system messages, or precomputed intermediate results. Build two levels of cache: exact prompt-level caching for identical requests, and semantic-level caching for semantically similar requests. A cache hit avoids model invocation entirely, regardless of time period.

    Semantic caching requires a similarity threshold. If the threshold is too low, different questions may be misclassified as identical and return wrong answers. Tune the threshold through manual spot checks. Set a time-to-live (TTL) for cached entries. When prompt templates or underlying data change, invalidate relevant cache entries to avoid stale results.

    How to measure cache hit rate? In the gateway logs, record for each request whether it was a hit, the token count, and the corresponding unit price. Estimate savings as:

    Savings ≈ (sum of tokens for all hit requests) × (corresponding unit price)

    This is the cost those hit requests would have incurred. A 10-percentage-point increase in hit rate does not equal a 10% reduction in total cost. That approximation holds only if the average cost of hit requests equals the overall average cost. Requests with longer prompts or longer outputs typically account for a larger cost share; their hit status matters more and should be traced separately.

    3. Asynchronous Processing and Batch Submission

    Convert synchronous calls into an asynchronous pipeline. Requests enter a queue, worker processes consume them in batches, and concurrency and rate limits are controlled. Batching can also amortize per-request overhead. For non-interactive scenarios, this change usually requires adding a consumer component with minimal code intrusion.

    Concurrency and rate limits should be set below the provider’s quotas, such as requests per minute and tokens per minute. Determine limits via load testing; don‘t copy fixed numbers. If the provider offers a batch endpoint, verify its unit price—do not assume it is cheaper.

    4. Prompt and Max Tokens Control

    Both input and output tokens are billed. Compressing prompts, removing redundant context, and structuring instructions can immediately reduce input costs. For long documents, summarize before reasoning—but summarization loses information, so spot-check quality.

    Output length is often the hidden cost driver. Set a max_tokens limit for each task type. After setting it, run a regression: sample a set of outputs and compare correctness and completeness against the previous version, plus manual review pass rate. If truncation occurs because the limit is too low, raise it until regression metrics pass.

    Cost Governance and Monitoring

    Peak/off-peak pricing changes the cost structure, and existing budget models may be inaccurate. Adopt the following:

    • Time-segmented cost dashboard: Split daily expenditure into peak and off-peak dimensions, using the formula from the first section.
    • Budget alerts: Notify the owner when daily token consumption exceeds 1.5× the 7-day moving average. This threshold is an example; adjust based on your traffic volatility.
    • Task-level attribution: Tag every call with business, task type, and project labels. Identify the highest-cost tasks and optimize them first.
    • Scheduling hit rate: Proportion of offline requests executed during off-peak hours, calculated as:

    Hit rate = (offline requests executed in off-peak) / (total offline requests)

    Review monthly, targeting above 80%. For tasks with strict latency requirements, do not force a high hit rate—SLA comes first.

    Treat cost as a development efficiency metric. For instance, track unit business cost (e.g., average cost per summarization) alongside response time, success rate, and other technical indicators.

    Minimal Interface for a Unified Gateway

    Wrap all model calls behind a unified gateway to centralize routing, caching, rate limiting, and retries. When billing rules change later, only the gateway needs modification. Minimal interfaces include:

    • Routing: Distinguish real-time vs. offline tasks; check whether the current time is peak or off-peak.
    • Cache: Exact and semantic two-level caching with TTL and version numbers.
    • Rate limiting: Control requests per minute, tokens per minute, and concurrency.
    • Retry: Use exponential backoff, maximum retry count, and an idempotency key.
    • Budget metering: Deduct quotas per project or department; reject requests or downgrade to a cheaper model when exceeded.
    • Audit tags: Record business, task type, token count, and cost for attribution and tracing.

    Conclusion

    Whether peak/off-peak pricing cuts costs depends on two factors: how high the share of offline traffic is, and how reliable the scheduling becomes. Teams with both can reduce inference spending through deferred scheduling, cache reuse, asynchronous batching, and cost governance. The amount of savings should be measured using the token structure and peak/off-peak ratio from the last 30 days—results vary significantly across businesses.