LLM API Cost Spiked 3x: Troubleshooting and Optimization

    This article examines a real case where LLM API costs more than tripled while token usage grew by only about 18%. It explains how to build a correct cost model, identifies six common root causes of sudden cost increases, and shows how to establish observability for per-request cost attribution. It also provides seven practical cost-reduction techniques, including prefix caching, context trimming, output limits, tiered routing, asynchronous batching, retry suppression, and cost regression testing.

    1. The Symptom: Token Usage Rose ~18%, but Cost More Than Tripled

    A developer compared two consecutive days on the usage dashboard of the same AI coding assistant. On day one, a lightweight model consumed about 631 million tokens (all reported as cache hits), with a cost of about RMB 23.93. On day two, the same model tier consumed about 748 million tokens (also labeled as cache hits), but the cost jumped to RMB 80.12. Token usage increased by about 18.5%, while cost increased by about 235% — and this happened during deliberately chosen off-peak hours.

    What makes this data worth attention is not the price increase itself, but a more common engineering problem it exposes: when billing rules change, most teams’ usage observability breaks down. We can see total token counts, but we cannot see how the cost was actually calculated.

    2. Build the Correct Cost Model First

    To troubleshoot abnormal costs, the first step is to decouple “token count” from “cost.” LLM billing in the industry typically includes the following dimensions; refer to the provider’s official documentation for specific unit prices and rules:

    • Separate pricing for input and output tokens: output-side unit prices are usually significantly higher than input-side prices.
    • Separate pricing for cache hits and misses: cached input tokens are cheaper; non-cached portions are billed at the standard rate.
    • Separate pricing for batch/async vs. real-time calls: asynchronous batch processing is often cheaper.
    • Time-of-day or resource-tier differences: some platforms offer discounts during low-load periods.
    • Model-tier differences: unit prices across lightweight, standard, and flagship tiers can differ by an order of magnitude.

    This yields an illustrative formula for quick estimation:

    1. Cost ≈ InputTokens × (HitRate × CachePrice + (1 - HitRate) × StandardPrice)
    2. + OutputTokens × OutputPrice
    3. + Add-ons (retrieval, vectorization, log retention, network egress, etc.)

    Plugging yesterday’s data into this model reveals the contradiction: if 631 million tokens were truly “all cache hits,” the cost calculated at cache prices should not differ from today’s by 3x. This suggests two possibilities. First, the dashboard’s definition of “cache hit” may not match the actual billing definition (for example, only a partial prefix was counted, or a short cache TTL caused cross-request invalidation). Second, the billing dimensions may have changed (for example, a higher output ratio, a model-tier switch, or the removal of an off-peak discount).

    3. Six Common Root Causes of Sudden Cost Spikes

    1. Billing rule or unit-price changes. This is the most direct external factor, usually accompanied by an announcement. Establish a fixed routine of “rule change → bill reconciliation.”
    2. A drop in the actual cache hit rate. Unstable prompt prefixes (timestamps, random IDs, or usernames placed at the front) invalidate prefix caching entirely; changing the system prompt invalidates the cache across the whole chain.
    3. A higher output-token ratio. Asking the model to “think before answering” or to “output complete code and explanations” significantly increases output-side costs, and output tokens are usually more expensive.
    4. Continuous context growth. Multi-turn conversations resend the full history, long documents are repeatedly passed as input, and retrieval results are not trimmed or reranked.
    5. Hidden consumption from retries and failures. Timeout retries, regeneration after a stream interruption, and tool-call loops all make actual consumption far exceed the number of successful business operations.
    6. Model-tier and call-path drift. A fallback switch fails, routing sends requests to a higher-tier model, or an asynchronous task is changed to a real-time call.

    4. Establish Observability: Get the Accounting Right First

    You must be able to attribute costs before optimizing. Collect at least the following dimensions, and feed them into your logging service and monitoring/alerting system:

    1. {
    2. "request_id": "r-8f2c",
    3. "scene": "code_completion",
    4. "model_tier": "light",
    5. "input_tokens": 8421,
    6. "cached_input_tokens": 7900,
    7. "output_tokens": 512,
    8. "latency_ms": 1830,
    9. "retry_count": 0,
    10. "estimated_cost": 0.0031
    11. }

    There are three key practices. First, tag by scene so that every business category can compute a unit cost (such as “cost per completion” or “cost per thousand lines of code”). Second, record both the hit rate and the miss volume to avoid being misled by a single “cache hit” label. Third, set budget guardrails for cost, with daily or per-project thresholds wired into alerts, and automatically fall back to a lightweight tier or queue to an asynchronous channel when anomalies occur.

    5. Seven Cost-Reduction Measures You Can Apply Immediately

    1. Stabilize the prefix structure: place the system prompt, tool definitions, and fixed examples at the front and keep them unchanged; move timestamps, random numbers, and user-state variables to the end to maximize prefix-cache reuse.
    2. Trim the context: summarize and compress historical messages, rerank and truncate retrieved snippets, and keep only the parts strongly relevant to the current question.
    3. Control output length: explicitly require “only key code snippets and necessary explanations,” and use structured output to constrain redundant phrasing.
    4. Tiered routing: run intent recognition first; send simple completions to the lightweight tier and escalate to the flagship tier only for complex reasoning.
    1. if task_complexity < threshold and context_length < L:
    2. route -> lightweight model (real-time)
    3. else if latency is tolerable:
    4. route -> standard model (async batch)
    5. else:
    6. route -> standard model (real-time) + strict output limit
    1. Asynchronous batching: route non-interactive tasks such as log analysis, batch refactoring, and document generation through the asynchronous channel.
    2. Suppress retry amplification: set a maximum retry count, exponential backoff, and idempotency keys; on a stream interruption, prefer resuming over full regeneration.
    3. Cost regression testing: add “average cost per scene” to the continuous integration dashboard, and block releases when a rule or prompt change causes cost drift beyond a threshold.

    6. Conclusion

    A single-day 3x cost jump appears to be a pricing issue, but it is really a gap in cost observability and budget governance. Only by breaking costs down by scene, tracking hit rates and miss volumes separately, and baking tiered routing and asynchronous strategies into the architecture — combined with budget guardrails and a cost regression dashboard — can you keep spending under control when billing rules change frequently. For more complete model-serving, monitoring/alerting, and log-analysis capabilities, you can compose offerings from Baidu AI Cloud’s general cloud product portfolio as needed to build your own cost-governance loop.