A Practical Guide to Cutting LLM API Costs by 90% with Context Caching
Learn how prompt caching reduces LLM input costs, why cache write premiums and short TTLs change the math, which metrics to monitor, and which workloads should skip caching altogether.
1. Where the Cost Actually Goes
Many teams get their first real LLM bill and find it far higher than expected. The problem is rarely the per-token price. It is how requests are structured: input tokens are treated as a free resource.
Under the billing model common across the industry, a request is charged for input tokens and output tokens. The input side is usually split into three parts: new content that is not reused, content explicitly marked and written to a cache, and content served directly from a cache hit. Each part is priced differently, and that difference is the entry point for cost optimization.
Break the bill apart and one counterintuitive finding stands out: in agents, coding assistants, and document Q&A, input tokens often make up more than 80% of the total tokens in a single call. System prompts, tool definitions, conversation history, and retrieved document fragments are all resubmitted on every turn. You are paying dozens of times for content that barely changes.
2. The Economics of Context Caching: Why Hits Cost an Order of Magnitude Less
The idea behind context caching is simple: keep a stable prefix on the server for a period of time. As long as the prefix of a later request matches exactly, the already-computed intermediate state is reused instead of being billed as ordinary input. The more aggressive discounts in the industry charge the cached portion at roughly 10% of the original price, which is where the “90% savings” claim comes from.
The discount is not unconditional, though. It introduces two cost items that are easy to overlook.
The first is the cache write premium. When a cache is created for the first time, the marked content is typically billed at a rate above the normal price, commonly around 25% higher. This is an upfront cost that only gets amortized if the content is reused enough times.
The second is the lifetime limit. Caches are not permanent. Retention is usually measured in minutes (for example, 5 minutes), and once it expires the next request pays the write premium again. Cache economics therefore depend heavily on temporal locality: the same context has to be reused repeatedly inside the window.
A minimal break-even check:
# Rough estimate of whether caching pays off (illustrative logic, not a specific vendor API)WRITE_PREMIUM = 1.25 # cache write premium factorHIT_DISCOUNT = 0.10 # cache hit discount factordef cache_is_worth(prefix_tokens, hit_count):no_cache = prefix_tokens * hit_count # full price every timewith_cache = prefix_tokens * WRITE_PREMIUM \+ prefix_tokens * HIT_DISCOUNT * (hit_count - 1)return with_cache < no_cache, with_cache / no_cache
With a write premium of 1.25 and a hit discount of 0.1, more than two hits inside the window already brings the cost ratio below 30% of the original price. At around ten hits, the overall bill approaches 15% to 20% of the original. That is why “90% savings” is achievable in high-reuse scenarios and nearly impossible for one-shot long-document summarization.
3. Observability: Turning Cache Behavior into Metrics
Cost optimization cannot rely on guesswork. Mature setups return cache-related usage details in the response, usually two counters: tokens consumed writing to the cache, and tokens read from the cache. Feed those two fields into your logging and alerting stack and you get three operational metrics:
- Hit rate = cache read tokens / (cache read tokens + regular input tokens)
- Write amortization ratio = write tokens / read tokens, which shows whether you keep rebuilding the cache
- Cache effectiveness = cache-hit requests / total requests, which shows whether the lifetime setting is reasonable
An example telemetry payload:
{"input_tokens": 12000,"cache_creation_input_tokens": 8000,"cache_read_input_tokens": 6000,"output_tokens": 700}
If the write amortization ratio stays above 1 over time, the cache is barely being reused. Fix the call cadence first rather than continuing to tune parameters.
4. An Engineering Pattern That Works
For caching to take effect, request content must satisfy one hard constraint: a stable prefix. In practice, prompts are usually organized in this order:
- Global system instructions and compliance constraints (almost never change)
- Tool/function definitions and calling conventions (change infrequently)
- Long-term knowledge, domain rules, a few examples (updated by version)
- Conversation history and retrieved fragments (change frequently)
- The current user input (different every time)
Only by pushing volatile content to the end can the long prefix in front stay identical. A single timestamp, random ID, or unsorted retrieval result inserted into the prefix invalidates the whole cache. In RAG scenarios especially, fix the fragment order and truncation length, or the hit rate will drop to single digits.
In code, the cache marker is usually attached to a “cacheable content block” in the request parameters, together with a control item that carries an expiration time:
response = client.messages.create(system=[{"type": "text", "text": LONG_STABLE_POLICY, "cache_control": {"type": "ephemeral"}},{"type": "text", "text": TOOL_SPEC},],messages=[{"role": "user", "content": current_question}],)print(response.usage.cache_creation_input_tokens,response.usage.cache_read_input_tokens)
On the scheduling side, add a cost controller: within the lifetime window, queue requests that share the same prefix serially or merge them with a short delay, so concurrent requests do not all decide the cache is missing and write it repeatedly. When the window is about to expire and traffic is still arriving, trigger a warm-up write ahead of time.
5. When Not to Use It, and How to Fall Back
Caching is not a universal fix. Three scenarios see little or negative benefit: the first pass over a one-off very long document, offline batch jobs whose request intervals far exceed the lifetime window, and exploratory calls where the prefix changes materially every time. Send that traffic through regular calls instead, or switch to a smaller model, a shorter context, or a two-stage summarize-then-answer approach.
A fallback is also mandatory: caching is a performance and cost optimization, not a correctness guarantee. Output structure should not change whether a request hits or misses. The business layer needs timeout retries and result validation so a cache miss does not destabilize the pipeline.
6. Deployment Checklist
- Is the prefix strictly stable, with volatile fields moved to the end?
- Is the average hit count within the window at least 3?
- Does the write amortization ratio stay below 1?
- Are hit rate and cache effectiveness on a dashboard with threshold alerts?
- Do low-value traffic paths have a fallback configured?
Run this end to end and cutting input-side spend to a tenth is not marketing language. It is the combined result of prompt structure, call cadence, and an observability layer. To lower the barrier further, you can build a unified cost observability and scheduling layer on top of Baidu AI Cloud’s LLM services and general cloud components such as log services, alerting, and message queues, turning optimization from a one-time tuning exercise into a sustainable engineering capability.
