LLM Caching Practice: Cutting API Call Costs by Up to 90%

    This article explains why repeated context is the main driver of rising LLM API bills and how prompt caching reduces input costs. It breaks down common cache pricing rules, shows how to track cache write and read tokens for accurate cost accounting, and outlines architecture practices such as stable prefixes, content normalization, segmented caching, and lifecycle alignment. It also covers common pitfalls and a simplified formula for estimating real savings.

    1. Where the Cost Anxiety Really Comes From: Repeated Context Is Billed Again and Again

    In enterprise LLM applications, a growing bill is usually not the result of making too many model calls. It comes from paying for the same content over and over on every call. System prompts, tool definitions, product manuals, code repository indexes, and long-document summaries barely change during a session, yet they are re-encoded and re-billed with every request. When the input length of a single request grows from a few hundred tokens to tens of thousands, the cost of the repeated portion quickly becomes the bulk of total spending.

    To see where the savings are, split input cost into two categories. The first is the “incremental input” that changes on every turn, such as the user’s latest question. The second is the long-lived “shared prefix,” such as the role definition and background knowledge. The essence of cache optimization is to reuse the computed result of the shared prefix and run full computation only on the incremental part.

    2. Three General Rules of Cache Pricing

    Mainstream solutions differ in the details, but their pricing logic is highly consistent and can be reduced to three rules.

    First, cache hits receive a steep discount. Cached input is typically billed at only a small fraction of the original price, with discounts reaching around 90%. This is the main source of cost reduction.

    Second, writing carries a premium. When a cache is created for the first time, you pay a write surcharge on top of the normal input cost. A common industry ratio is about one quarter of the original price. In other words, a cache is an asset that requires upfront investment and is amortized over time; it pays off only when it is hit many times afterward.

    Third, the lifetime is limited. Cache entries are usually retained for only a few minutes and may be renewed when accessed. Once the survival window is exceeded, the next request has to pay the write premium again.

    Taken together, these rules define a clear applicability boundary. The benefit is greatest when the same long context is called repeatedly at high frequency over a short period. In scenarios with sparse requests or a context that changes every time, caching only adds overhead.

    3. Observability: Turning Cost from a Black Box into an Accountable Number

    You cannot optimize cost without quantifying it. Mature API designs return cache-related usage details in the response, usually with two fields: the number of tokens written to the cache in this call, and the number of tokens read from the cache in this call. With these two fields, you can build a cost dashboard on the application side:

    1. def estimate_cost(resp, price_in, write_premium=0.25, hit_discount=0.1):
    2. usage = resp["usage"]
    3. fresh = usage.get("input_tokens", 0) # Incremental input that missed the cache
    4. created = usage.get("cache_creation_tokens", 0) # Tokens written to the cache in this call
    5. read = usage.get("cache_read_tokens", 0) # Tokens read from the cache in this call
    6. cost = fresh * price_in \
    7. + created * price_in * (1 + write_premium) \
    8. + read * price_in * hit_discount
    9. return cost, {"fresh": fresh, "created": created, "read": read}

    With this table, a team can answer three key questions: what the cache hit rate is, how many times the write premium has been amortized, and which business flows should not use caching at all. As a rule of thumb, if the ratio of “read tokens / write tokens” for a flow stays below 3 to 5 over time, reuse is insufficient and the write premium has not been absorbed.

    4. Architecture Implementation: Tiered Caching and Stable Prefix Design

    Keeping the hit rate consistently high depends on how requests are constructed, not on calling tricks.

    1. Prioritize prefix stability. Put long-lived, unchanging content at the very front of the prompt and volatile content at the end. System settings, tool descriptions, and knowledge snippets come first; user input comes last. Any change anywhere in the prefix invalidates the subsequent cache.

    2. Normalize content. Do not concatenate timestamps, random IDs, request sequence numbers, or real-time retrieval results into the stable prefix. Use placeholders in the prompt instead and move dynamic values to the trailing fields.

    3. Use segmented caching. Split a very long context into several stable blocks and cache each block independently, so a local change does not trigger a full recalculation.

    4. Align the lifecycle. Match the cache survival window to the business rhythm: use centralized scheduling for batch jobs so the same context is consumed continuously within the window; for interactive scenarios, lightweight periodic requests can keep the cache warm, but check whether the maintenance cost is lower than the recalculation cost.

    5. Provide a fallback strategy. When the cache misses or has expired, automatically fall back to a normal call, prioritizing functional correctness over cost optimization.

    A sample call flow looks like this:

    1. def call(system_block, knowledge_block, user_query):
    2. prefix = normalize(system_block) + normalize(knowledge_block)
    3. resp = client.messages.create(
    4. model=MODEL,
    5. system=prefix, # Stable prefix, waiting for a cache hit
    6. messages=[{"role": "user", "content": user_query}],
    7. )
    8. log_usage(resp) # Log write/read tokens for cost accounting
    9. return resp

    5. Engineering Recommendations on Baidu AI Cloud

    If these capabilities run on the model services of Baidu AI Cloud, it is advisable to bring the caching strategy into a unified cost governance process: use the log service to retain cache usage details for every call, use monitoring and alerting to set thresholds for the hit rate and the write share, and use a message queue to smooth and centrally schedule batch jobs so the same context is fully reused within its survival window. The cache key construction rules, invalidation reasons, and hit trends should be treated as first-class metrics and observed over the long term, rather than added after launch.

    6. Common Pitfalls and ROI Calculation

    Pitfall 1: assuming caching is always cheaper. In low-frequency, long-context scenarios, the write premium can increase total cost.

    Pitfall 2: putting dynamic content in the prefix. This is the most common cause of a collapsing hit rate, and it is hard to notice; field-level monitoring is required to detect it.

    Pitfall 3: looking only at the discount ratio and not at the number of times it is amortized. A 90% discount translates into a real bill reduction only when the cache is hit repeatedly.

    A simplified rule is this: when the same context is reused n times and n is large enough, the input cost of the caching approach is approximately the original price multiplied by (the hit discount plus the write premium divided by n). When n reaches around ten and the hit discount is about 0.1, overall input cost can be compressed to roughly one tenth of the original price, which is exactly where “a 90% cost reduction” comes from. Conversely, if n is close to 1, cost actually rises by about one quarter.

    The conclusion is not complicated: caching is not a switch but a cost engineering practice that requires design and governance. When stable prefixes, observable usage, and lifecycle management matched to the business rhythm are all in place, the repeated overhead of LLM calls is genuinely eliminated.