LLM API Pricing and Context Caching: A Practical Guide to Cost Optimization

    This article explains how modern LLM API costs are calculated through base token pricing and context caching. It covers the asymmetry between input and output tokens, cache hit and cache write pricing, cache lifetime trade-offs, standard versus high-speed tiers, and practical ways to reduce cost through stable prefixes, cache settings, output length control, tiered routing, and monitoring.

    1. Why Understanding LLM API Pricing Matters

    In enterprise applications and day-to-day developer integration, LLM APIs have moved from “per-call” billing to fine-grained token-based measurement. Many teams find costs manageable during prototyping, but once an application enters production and request volume grows by tens of times, the bill can quickly spiral. The core problem is usually not “using too much,” but “not understanding where the money goes.”

    A mature LLM service generally has two billing dimensions: base token pricing and context caching pricing. These two dimensions combine to determine the actual cost of a single request. Only by understanding the rules of both can developers design a calling strategy that is both stable and cost-efficient.

    2. Base Token Pricing: Input and Output Are Not Priced the Same

    A token is the smallest unit used by LLMs to process and generate text. Almost all providers use a two-track pricing model: input tokens and output tokens. However, the prices are not identical. Output tokens usually cost significantly more than input tokens.

    This asymmetry is not arbitrary; it has clear engineering reasons:

    • Computational complexity differences: The input stage can be processed in parallel. A single forward pass can consume the entire context at once. The output stage, by contrast, is generated token by token in an autoregressive manner. Each new token requires a full model run, so compute grows roughly linearly with length.
    • Resource usage differences: Generation continuously occupies GPU memory and compute. It also requires maintaining the KV cache, making the per-unit-time cost higher.

    Therefore, if an application has a long-input, short-output profile, such as summarization or intent classification, cost is mostly determined by input. If it has a short-input, long-output profile, such as long-form writing or code generation, output pricing can dominate. Developers should evaluate the cost profile of their workload rather than simply assuming that “cheaper calls are always better.”

    3. Context Caching: The Key Factor That Separates Costs

    Beyond base pricing, context caching, also known as prompt or context caching, is a major way to reduce LLM service costs today. The idea is straightforward: when multiple requests share exactly the same prefix content, such as fixed system prompts, long documents, few-shot examples, or tool definitions, the service can cache the computation results for that portion. Subsequent requests can reuse the cached result instead of recomputing it.

    Caching usually introduces two billing dimensions:

    Dimension Description Relative cost
    Cache hit The request hits an already cached prefix Far lower than normal input
    Cache write One-time cost of writing the prefix into the cache Similar to, or slightly higher than, normal input

    Two details are easy for developers to overlook:

    1. Cache hit pricing can be much lower than base input pricing. When a prefix is served from cache, it does not need to be recomputed. As a result, its unit price is often only a fraction of normal input pricing. For scenarios with stable system prompts, repeated Q&A over long documents, or batch processing of similar tasks, caching can reduce costs by an order of magnitude.

    2. Cache entries have lifetime and lifecycle limits. Caches are not permanent. They are usually priced and retained by tier, such as short-term caching and long-term caching. The longer the retention period, the higher the write cost, but the longer the hit window. This creates a clear engineering tradeoff:

    • High-frequency, continuous calls: choose long-lived caching to amortize the write cost.
    • Low-frequency, sporadic calls: short-lived caching is usually enough, avoiding wasted write costs.

    4. Standard vs. High-Speed Tiers: An Explicit Tradeoff Between Performance and Cost

    Many LLM services offer two tiers: standard and high-speed. In terms of output quality, the two tiers are often equivalent. The difference lies in inference throughput and response latency. The high-speed tier provides faster generation by using more compute resources, and its price is usually a multiple of the standard tier.

    The choice should be based on how sensitive the workload is to latency:

    • Interactive scenarios, such as online chat or real-time completion, are sensitive to time-to-first-token and generation speed. The premium for the high-speed tier is often worth it.
    • Offline batch processing, such as data cleaning, bulk summarization, and asynchronous tasks, does not require real-time response. The standard tier is usually sufficient and more cost-effective.

    It is also important to avoid blindly selecting the high-speed tier, as this is a common source of wasted cost. A mature practice is to implement tiered routing at the gateway layer: route requests that need immediate feedback to the high-speed channel, and route requests that can tolerate delay to the standard channel.

    5. Practical Cost Optimization Steps

    Combining the above mechanisms gives a clear optimization path:

    1. Stabilize the prefix: Put fixed system prompts, tool definitions, and knowledge snippets at the very front of the request to maximize cache hit rate. Any change to the prefix can invalidate the cache, so avoid adding variable content at the beginning of the prompt, such as timestamps or random IDs.
    2. Set cache lifetime appropriately: Choose short-term or long-term caching based on call frequency, allowing the write cost to be fully amortized within the hit window.
    3. Separate input and output pressure: For scenarios with high output volume, control generation length, for example by setting a reasonable maximum token limit. For scenarios with high input volume, reduce redundant context.
    4. Use tiered routing: Route requests between standard and high-speed tiers based on latency requirements instead of always using the higher-tier option.
    5. Monitor quantitatively: Integrate logging and monitoring capabilities to track cache hit rate and input/output token distribution, then use data to drive tuning.

    6. A Simplified Cost Estimation Logic

    Before integration, you can use the following simplified logic to estimate the cost of a single call. This is illustrative and does not represent the rules of any specific provider.

    1. def estimate_cost(input_tokens, output_tokens,
    2. cache_hit_tokens=0, cache_write_tokens=0,
    3. p_in=1.0, p_out=3.0, # Unit price coefficients
    4. p_cache_hit=0.1, p_cache_write=1.0):
    5. # Inputs not covered by the cache are billed as normal input
    6. normal_input = input_tokens - cache_hit_tokens
    7. cost = (normal_input * p_in
    8. + output_tokens * p_out
    9. + cache_hit_tokens * p_cache_hit
    10. + cache_write_tokens * p_cache_write)
    11. return cost
    12. # Example: Input cost drops significantly when the cache is hit
    13. base = estimate_cost(input_tokens=8000, output_tokens=500)
    14. cached = estimate_cost(input_tokens=8000, output_tokens=500,
    15. cache_hit_tokens=7500, cache_write_tokens=500)
    16. print(f"Before optimization: {base:.1f} After optimization: {cached:.1f}")

    This example shows that when the request prefix is highly reusable and the cache is hit consistently, input-side cost can be reduced substantially. This is the core value of context caching in large-scale production environments.

    7. Summary

    The cost of LLM APIs is not a black box. It is determined mainly by two dimensions: base token pricing and context caching pricing, together with the choice between standard and high-speed tiers. Understanding the asymmetry of input and output pricing, as well as the tradeoff between cache hits and cache writes, is essential for cost control. On platforms such as Baidu AI Cloud, LLM services often follow this kind of billing model. If developers focus on five areas — prefix stabilization, cache lifetime selection, output length control, tiered routing, and quantitative monitoring — they can achieve significant cost reductions without changing quality. With this logic in place, cost optimization becomes an engineering practice that is calculable and reproducible, rather than guesswork.