LLM API Cost Breakdown and Throughput Optimization Guide

    A practical guide to understanding why cheap per-token pricing does not guarantee a cheap bill. Learn how input/output ratios, prompt caching hit rates, and peak versus off-peak scheduling shape real costs, how to turn a blended average into structural cost data with usage logging, and how to monitor TTFT and streaming throughput. Includes a cost optimization checklist, client-side heartbeat pattern, and capacity planning strategies for peak-hour degradation.

    1. Introduction: Why a Low Unit Price Doesn’t Mean a Low Bill

    When integrating large language model capabilities into a production system, developers often make the same mistake: comparing the advertised price per million tokens across providers and concluding that one is “more cost-effective.” In reality, the final bill is determined by four variables working together: input token volume, output token volume, cache hit ratio, and whether calls happen during off-peak or peak hours. A shift in any single variable can change the total cost by several times.

    Using a real usage log spanning a weekend into the workweek as a thread, this article abstracts a reusable method for cost accounting and performance observation. All numbers here are illustrative statistical measures used to explain the methodology; they do not represent the pricing of any specific service.

    2. The Four Variables of the Cost Model

    2.1 Input-to-Output Ratio

    Conversational and generative tasks typically have a low output share. For workloads centered on understanding, classification, extraction, and rewriting, the output share may be only a few thousandths; for long-form generation and code completion, it rises significantly. Because output-side unit prices are generally higher than input-side prices, the output share acts as an amplifier on the bill.

    2.2 Cache Hit Rate

    When multi-turn conversations or batch tasks share the same prefix (system prompts, knowledge base snippets, code context), the server can reuse already-computed intermediate results, and the cached portion is billed significantly lower than the uncached portion. The hit rate depends on the stability of the request prefix: any timestamp, random ID, or dynamic ordering will invalidate the prefix.

    2.3 Off-Peak vs. Peak Hours

    Many platforms offer off-peak discounts, where the off-peak unit price may be roughly half the peak price. For offline batch processing, overnight data cleaning, and non-real-time report generation, scheduling tasks into off-peak windows is a zero-cost optimization.

    2.4 Billing Transparency

    If the billing page does not show cache hit rates or an input/output breakdown, developers can only derive a blended average from “total cost ÷ total tokens.” This average masks structural problems, which makes building your own usage instrumentation a necessary step.

    3. Decomposing the Blended Average into Structural Cost

    Let total cost be C and total tokens be T, so the blended average is P = C / T. As an example from one log: roughly 180 million tokens cost about 31 RMB, giving a blended average of about 0.17 RMB per million tokens; extrapolated to the 1 billion token scale, that is about 170 RMB. This number looks extremely low, but it blends cache hits with misses, and input with output.

    To recover the structure, you need to log the usage fields of every call yourself:

    1. # Illustrative: wrap the call layer uniformly and persist the usage structure of each request
    2. record = {
    3. "ts": time.time(),
    4. "model": cfg.model,
    5. "prompt_tokens": resp.usage.prompt_tokens,
    6. "completion_tokens": resp.usage.completion_tokens,
    7. "cached_tokens": getattr(resp.usage, "prompt_tokens_details", None),
    8. "latency_ms": (t1 - t0) * 1000,
    9. "stream": True,
    10. }
    11. db.insert(record)

    With this table, you can compute the cache hit rate, output share, and time-of-day average price, and then determine whether the issue is unit price or structure. In most cases, improving the hit rate and compressing output delivers more benefit than switching providers.

    4. Throughput and Time to First Token: More Impactful Than Unit Price

    A second observation carries more engineering value: the same service held steady at 50 to 55 tokens/s on the weekend, but during the weekday morning peak, the reasoning-chain phase dropped to 4 to 9 tokens/s and the main output dropped to 12 to 25 tokens/s.

    This exposes a common reality: inference runs on a shared resource pool, and peak-hour queuing and batch scheduling can reduce the effective throughput of a single request by an order of magnitude. For developers, this means:

    • Time to first token (TTFT) and streaming token rate must be monitored separately, not just total elapsed time;
    • When the reasoning-chain phase rate is extremely low, users may perceive it as a “disconnect,” so the product layer needs explicit heartbeats and phase indicators;
    • Timeout thresholds cannot be set from off-peak data, or peak hours will trigger large-scale failures and retries, further worsening congestion.

    A practical client-side skeleton:

    1. async def stream_with_heartbeat(client, messages, idle_s=8.0):
    2. q, hb = asyncio.Queue(), time.time()
    3. async def pump():
    4. async for chunk in await client.chat(messages, stream=True):
    5. await q.put(chunk); hb = time.time()
    6. task = asyncio.create_task(pump())
    7. while True:
    8. try:
    9. yield await asyncio.wait_for(q.get(), timeout=idle_s)
    10. except asyncio.TimeoutError:
    11. yield {"type": "heartbeat", "idle": time.time() - hb}
    12. if task.done():
    13. break

    5. Cost Optimization Checklist

    1. Stabilize the prefix: keep system prompts, tool definitions, and knowledge snippets fixed at the very front of the request, and place dynamic content afterward to improve cache hit rates.
    2. Compress output: use structured constraints to limit redundant explanations, and post-process or trim output when necessary.
    3. Schedule off-peak: move offline tasks into off-peak windows while reserving peak-hour budget for real-time paths.
    4. Tiered routing: send simple tasks to lightweight models and complex reasoning to stronger models, using rules or a small classifier as a front-end decision step.
    5. Budget guardrails: set token quotas and circuit breakers per tenant and per endpoint to prevent runaway loops from burning through budget.
    6. Observability: feed usage, latency, and error rates into logging services and monitoring alerts to build a cost dashboard.

    6. Stability and Capacity Planning

    Peak-hour throughput degradation is the norm, so engineering teams should prepare three types of fallback plans: first, degradation, such as disabling the reasoning chain or shortening context; second, queuing and backpressure, using a message queue to buffer burst traffic; third, elastic scaling across multiple availability zones and backends, relying on container platforms and load balancing to distribute pressure. Also change retries to exponential backoff with jitter to avoid retry storms.

    7. Conclusion

    To evaluate a model service, look at three things at once: the structured real cost, the phase-by-phase throughput behavior, and the peak-hour degradation capability. Build usage instrumentation, caching strategy, off-peak scheduling, and an observability system first, then talk about model selection. Only then can an intelligent application strike a stable balance between budget and experience. If you are already using Baidu AI Cloud capabilities, you can apply the same accounting and observation framework to compare different backends under your own business workloads.