LLM API Cost Control and Context Caching: A Practical Guide

    This guide explains why a low per-token price does not guarantee a low bill, breaking down the four variables that drive LLM API costs: input size, output size, cache reuse rate, and high-speed routing. It includes a pure cost-estimation function, the prefix-matching rules that determine cache hits, guidance on choosing short versus long TTL cache writes, when to enable high-speed channels, and the observability metrics and checklist needed for ongoing cost governance.

    1. Why a Cheap Unit Price Does Not Mean a Cheap Bill

    When building LLM-powered coding assistants, knowledge base Q&A systems, or long-document analysis tools, teams most often make one mistake: looking only at the price table. The real bill is determined by four variables working together: input size, output size, cache reuse rate, and whether requests go through a high-speed channel. If the unit price drops one tier but the cache hit rate falls from 60% to 10%, total cost can actually rise. So the first step in cost governance is to make the billing model explicit rather than estimating it by intuition.

    The mainstream billing dimensions across the industry can usually be abstracted into the table below (values are illustrative, meant to show the order of magnitude; refer to the provider’s published pricing for actual figures):

    Billing item Standard channel High-speed channel
    Base input Base price (e.g., 13/MTok) Base price ×2
    Base output Base price (e.g., 68/MTok) Base price ×2
    Cache hit Base price ×0.1 Base price ×0.1
    Cache write (short TTL) Equal to base input price Equal to base input price
    Cache write (long TTL) Base input price ×2 Base input price ×2

    Three general rules can be drawn from this table, and none of them depend on any specific vendor:

    1. Output is far more expensive than input, usually by a factor of 4 to 6. Controlling output length is often more effective than compressing input.
    2. A cache hit is the strongest discount, generally around one-tenth of the base input price, making it the main cost-saving lever for long-context scenarios.
    3. Cache writes are not free. A short-lived write costs the same as base input, while a long-lived write doubles it; the write cost needs to be amortized over multiple subsequent hits.

    2. Express the Cost Model as Computable Code

    Do not calculate in your head. Consolidate the pricing rules into a pure function so that the cost of any request can be estimated beforehand:

    1. # Unit price: CNY per million tokens
    2. def estimate_cost(in_tok, out_tok, cache_hit_tok,
    3. cache_write_tok, ttl_hours, highspeed=False):
    4. base_in, base_out = 13.0, 68.0
    5. factor = 2.0 if highspeed else 1.0
    6. hit = cache_hit_tok * base_in * 0.1
    7. write = cache_write_tok * base_in * (2.0 if ttl_hours > 0.5 else 1.0)
    8. fresh = (in_tok - cache_hit_tok - cache_write_tok) * base_in * factor
    9. return (hit + write + fresh + out_tok * base_out * factor) / 1e6

    With this function, you can run a “unit price vs. hit rate” sensitivity analysis for each type of workload: sweep the hit rate from 0 to 0.9, plot the total cost curve, and find the minimum reuse rate you need to achieve. This curve becomes the acceptance criterion for all subsequent optimization.

    3. How Context Caching Works and When It Hits

    Context caching essentially persists the attention computation results of a long prefix, so that when the next request hits the same prefix, the repeated computation is skipped. It brings two benefits: a substantial drop in cost and lower time-to-first-token latency. But a hit requires strict prefix matching, which determines the direction of all optimization efforts.

    Typical reasons for a cache miss:

    • The prefix contains content that changes every time, such as timestamps, random IDs, or user nicknames;
    • The system prompt is assembled dynamically with an unstable order;
    • In multi-turn conversations, history messages are summarized or trimmed, breaking the prefix;
    • The cache has expired (short TTL is usually measured in minutes, long TTL in hours) or has been evicted.

    The corresponding engineering practice is “static content first, dynamic content last“: place unchanging long content (tool descriptions, domain specifications, code repository indexes, full document text) at the very front with a fixed serialization format; place volatile content (the current question, real-time retrieval snippets) at the end.

    1. [Stable prefix] System specs + tool definitions + reference docs (cacheable)
    2. [Semi-stable section] Conversation history (appended in a fixed order, no reordering, no summarizing)
    3. [Volatile tail] This turn's retrieval results + the user's current input

    When combined with structured output constraints, it is also recommended to put the schema definition in the stable prefix rather than regenerating it every turn. This both improves format compliance and raises the reuse rate.

    4. Choosing TTL and Write Strategy

    There are two typical cache write lifecycles: minute-level and hour-level, with the latter costing about twice as much as the former. The choice depends on the reuse interval:

    • For interactive completion and single-turn Q&A, where the reuse interval is within tens of seconds, choose a short TTL;
    • For multi-turn agent tasks, batch document processing, and cross-session knowledge bases, where the reuse interval may reach tens of minutes, a long TTL is more cost-effective.

    A simple decision rule: check whether the long-TTL write premium is covered by the savings of base input price × number of hits × 0.1. If the expected number of hits is fewer than about 5, a short TTL is usually more economical.

    5. Should You Enable the High-Speed Channel

    The high-speed channel doubles the unit price of both input and output in exchange for improved throughput and latency. It suits online interaction and real-time completion scenarios that are sensitive to time-to-first-token; for throughput-insensitive tasks such as offline batch processing, overnight batch jobs, and evaluation regressions, the standard channel should be enforced. In engineering terms, it is recommended to do routing on the client side: tag requests by type with a priority, and let the gateway split traffic, so that high-speed quota is not mistakenly consumed by background jobs.

    6. Observability and Continuous Governance

    Cost optimization must form a closed loop. It is recommended to collect at least four categories of metrics: cache hit rate, average reuse length, the input/output distribution per request, and cost per unit of business output (for example, “cost per thousand lines of code completion”). Set alert thresholds for hit rate and per-request cost. When the hit rate keeps dropping, first check whether the prefix has been polluted by dynamic content, rather than blindly switching models.

    7. Implementation Checklist

    • Is the prefix fully static with stable serialization?
    • Is all volatile content placed at the end?
    • Is the TTL chosen based on the reuse interval?
    • Is the high-speed channel limited to online request paths only?
    • Have you run a sensitivity analysis with a computable model?
    • Have you set an upper bound on output length?

    Checking these six items one by one can usually reduce the overall cost of long-context scenarios to a small fraction of the original, without changing model capability. This approach applies equally on top of the general capabilities offered by LLM platforms such as Baidu AI Cloud Qianfan; the core principle remains: make the billing rules computable, make the cache prefix reusable, and make channel selection routable.