How to Cut LLM API Costs by 90% with Caching Practices

    This article explains why LLM bills often grow faster than call volume, and how prefix caching, explicit caching, and semantic caching address the repeated input-token consumption behind that gap. It covers how to measure whether caching fits your traffic, a break-even model for paid cache writes, four engineering details that determine hit rate, how caching works alongside RAG and context compression, and a checklist of pitfalls to avoid.

    1. Why Cost Structure Determines Where to Optimize

    After integrating large language model capabilities into a business system, the bill often grows faster than expected: call volume doubles, but cost grows fivefold. The cause is usually not the unit price, but repeated consumption on the input side (prompt tokens).

    A typical enterprise Q&A or coding assistant sends roughly the same content with every request: the system role definition, tool and output-format constraints, safety policies, and long business documents or code repository context. All of it is recomputed in full on each request, making up the largest share of the bill while contributing almost no new information.

    So the first principle of cost reduction is: measure first, optimize second. Start by instrumenting three metrics: average input tokens per request, the share of the fixed prefix in total input, and how densely requests cluster in time. If the fixed prefix accounts for more than 50% of input and requests are clustered in time, caching typically delivers a several-fold cost improvement. If requests are highly scattered and the context differs every time, caching gains will be limited, and you should prioritize context trimming and retrieval precision instead.

    2. An Abstract Model of Three Caching Approaches

    Setting aside vendor-specific differences, LLM caching capabilities fall into three categories. They differ along two dimensions: who decides what gets cached, and how the cache key is defined.

    2.1 Automatic Prefix Caching: Zero Code Changes, Full Benefit from Traffic Density

    The first category is handled automatically on the platform side, with no code changes required. Its decision logic is essentially longest common prefix matching: if the beginning of the current request (system prompt + fixed documents + fixed examples) is identical to a recent request, that portion is not recomputed and the intermediate state is reused directly.

    The advantage is that it is completely non-intrusive, and a hit usually comes with a significant discount on input cost (commonly 50% to 75% off across the industry; check each platform’s pricing page for specifics). The real trap is lifetime: automatic caches typically survive only minutes to tens of minutes, which makes them a “hot cache.” This rewards high-concurrency, continuous traffic. If users show up, leave, and come back half an hour later, the cache is long gone and the bill does not change.

    The engineering response is to manufacture request density: convert scattered calls into batch windows, keep the cache warm with a small number of real requests during traffic troughs, and concentrate non-real-time work (offline summarization, batch labeling, regression evaluation) into the same time window.

    2.2 Explicit Caching: Controllable Lifetime, but You Pay a Write Premium

    The second category lets developers actively declare “cache this content” and specify a lifetime. It extends the lifetime from minutes to hours or longer, which suits slowly changing knowledge bases: product manuals, policy terms, and retrieved snippets from large code repositories.

    There are two costs. First, creating a cache usually requires paying a write premium (commonly cited as roughly 25% above the baseline input price). Second, cache entries have count and capacity limits, so you must manage eviction yourself. A simple rule of thumb tells you whether it pays off:

    1. # Rough break-even estimate
    2. write_premium = 0.25 # Extra cost ratio for creating the cache
    3. discount = 0.50 # Discount ratio on a hit (0.5 means half price)
    4. ttl_seconds = 3600 # Cache lifetime
    5. def break_even(qps, prefix_tokens, price_per_token):
    6. hits = qps * ttl_seconds # Expected hits within the lifetime
    7. write_cost = prefix_tokens * price_per_token * (1 + write_premium)
    8. save_per_hit = prefix_tokens * price_per_token * (1 - discount)
    9. return hits * save_per_hit > write_cost

    The conclusion is straightforward: the write premium has to be amortized over enough hits. Do not create explicit caches for low-frequency, niche knowledge; only high-frequency fixed prefixes are worth it.

    2.3 Semantic Caching: Reusing Complete Answers Across Requests

    The third category ignores prefixes and looks at semantic similarity: when the vector representation of a new question is close enough to a historical one, the historical answer is returned directly without calling the model at all. This turns cost reduction from a “discount” into “zero,” but carries the highest risk—too loose a threshold returns wrong answers, while too tight a threshold yields a very low hit rate.

    The key to implementation is layered decision-making: exact match first (a hash of the normalized text), then vector nearest-neighbor retrieval, and finally allow direct returns only within a high-confidence band. Also tag answers with freshness labels: strongly dynamic data such as prices, inventory, and ticket status must never enter the semantic cache.

    3. Four Engineering Details That Determine Hit Rate

    Normalize prefix order. Move all volatile content to the end: timestamps, session IDs, user profiles, and retrieval results go last, while the system prompt and fixed knowledge go first. Many cases of “caching not working” come down to nothing more than putting the current date on the first line of the prompt.

    Govern prefix stability. Version numbers, build hashes, and randomly ordered few-shot examples can silently change the prefix. Hash the prefix and report it in monitoring; if the hit rate drops sharply, you can quickly trace it back to a specific release.

    Align TTL with business rhythm. The cache window should cover the real user revisit interval rather than a default value; for batch jobs, finish the same batch of data inside the window.

    Make hits observable. Sample three curves—“total input tokens / cached tokens / billed tokens after discount”—and make the cache hit rate a core dashboard metric, reported alongside business gross margin so you can answer “did profit grow year over year?”

    4. Working with RAG and Context Compression

    Caching only solves “repeated computation,” not “context that is too long.” Use them together: first use retrieval to narrow candidate documents to the minimum sufficient set, then apply context compression to remove redundant phrasing, and finally let the stable portion hit the cache. If you use an LLM platform such as Baidu AI Cloud Qianfan, you can combine it with general capabilities like object storage, log services, and monitoring alerts to bring knowledge base versions, cache hit rates, and call costs into a unified observability system, forming a closed loop of “retrieval precision—cache hit—unit cost” optimization.

    5. Pitfall Checklist

    • Do not embed user private data in cached prefixes; cache reuse creates a risk of unauthorized access.
    • Strongly dynamic data (prices, inventory, permissions) must not enter any cache layer.
    • Validate the hit rate with real traffic replay before launch, and avoid optimistic conclusions drawn from constructed samples.
    • Discount and write-premium rules differ by platform and change over time, so the cost model should be a configuration item rather than hard-coded.
    • Always keep a fallback path: when the cache is unavailable, revert automatically to direct calls, prioritizing availability over cost.