Prompt Caching Optimization: How to Cut Large Language Model API Costs
This article explains why large language model (LLM) API bills can climb far faster than expected even when prompt caching looks like it is enabled, and how to fix it. It walks through building an accurate cost model, a three-step method for verifying whether caching is truly active by inspecting usage fields and unit token cost, and a four-layer approach to enabling caching across the protocol, request, routing, and client layers. It also covers engineering practices for keeping prefixes stable and the metrics to monitor so that cost stays observable. By following the six-step workflow, you can usually cut call costs down to a fraction of their original value without changing any business functionality.
1. The Symptom: Bills That Grow Faster Than Intuition Suggests
In scenarios like AI coding assistants, multi-turn chat bots, and long-document analysis, there is a common and frustrating experience: you top up a few dozen dollars, and after just a few conversation turns more than 30% of the balance is gone. Scanning the per-call breakdown, each request costs on the order of a few tenths of a dollar — completely at odds with the expectation that “cached hits come with a discount.”
The root cause is a misunderstanding of the billing model. Taking a rate like “$5 per million input tokens and $25 per million output tokens” as a reference, a session that has grown to roughly 100,000 tokens of context could cost around $0.50 on the input portion alone in a single turn. If every turn is billed on the full input, cost grows roughly linearly with the number of turns; but when caching is correctly enabled, the cost of a repeated prefix should drop by about an order of magnitude.
So when you observe that “the cost per turn stays basically constant, scales with context length, and there is no cache-related field anywhere in the breakdown,” you can be fairly certain that caching in this call path is not actually taking effect. The rest of this article breaks down this “looks configured but is not working” problem.
2. Why the Config “Looks Fine” While the Cache Stays Off
This is where people most often misjudge the situation. The endpoint connects, the model returns normally, and tokens are deducted as expected — which shows the path itself works. But “usable” and “cost-optimal” are two independent things. There are three common causes of failure:
1. The routing platform’s protocol translation silently drops the cache-control fields.
When you call through a compatibility-style Chat Completions interface on the client while the actual backend speaks a different native protocol, the request passes through an adaptation layer. A compatibility protocol’s request body follows a “lowest common denominator” design — it only guarantees that basic fields (messages, tools, temperature, and so on) pass through. Caching capability lives in protocol extension fields, which are extremely easy to drop silently during conversion: no error, no warning, the effect just disappears.
2. The routing layer never selected a cache-supporting channel.
A typical aggregation router picks an upstream provider automatically based on price, latency, availability, context length, and similar criteria. A price-first strategy is not the same as “cache-friendly,” because different upstreams support the same model to different degrees — some channels pass caching fields through, others do not. Simply switching the routing preference from “default” to “price-first” usually does not solve the problem.
3. An unstable prefix causes the cache to invalidate repeatedly.
Caching is fundamentally exact prefix matching: the system compares tokens from the start of the request, matches the longest identical prefix, and runs full inference only on the new suffix. Any change to any content at the beginning invalidates all subsequent content. This is the most hidden and, in engineering practice, the most common source of waste.
3. Build the Right Cost Model Before Optimizing
Understanding the billing structure is the prerequisite for judging whether caching is active. Abstracting the common pattern used by mainstream providers, the cost of a single request can be written as:
Cost per request = uncached input tokens × base input price+ cache write tokens × cache write price # usually slightly above base input price+ cache read tokens × cache read price # usually significantly below base input price+ output tokens × output price
Specific multipliers vary widely across vendors, so always defer to the official documentation of the service you use. That said, three universal rules hold:
- Cache reads are cheap while writes are slightly more expensive, so enabling caching on short or one-off requests can actually cost more;
- Caches have a time-to-live (typically on the order of minutes) and must be reused within that window; after too long a gap, a re-write is required;
- Caches usually have a minimum length threshold (generally on the order of a thousand tokens), so short prefixes below the threshold are not cached;
- The output portion generally does not participate in caching, which caps the savings by the input share — the longer the context and the more turns, the more pronounced the benefit.
Here is a rough magnitude estimate (numbers are illustrative only): a 100,000-token context across 10 consecutive turns.
- Without caching: 10 × 100,000 = 1,000,000 input tokens billed at full price;
- With roughly 90% cache hits: about 100,000 tokens at the write price + 900,000 tokens at the read price (assuming the read price is around one-tenth of the input price), which is equivalent to about 190,000 tokens of full-price input.
In scenarios where output does not dominate, the overall bill can drop by several times. This is exactly why “long-context, multi-turn” applications must take caching seriously.
4. Quantified Diagnosis: Three Steps to Confirm Whether Caching Is Active
Don’t guess — locate the problem with data.
Step 1: Inspect the usage fields in the response body.
Mainstream services return cache-related counts inside usage. Common names include the number of cache-read tokens and cache-write tokens (naming varies by platform, so defer to the documentation). If these fields are entirely absent or always 0, caching is not being triggered.
Step 2: Back-calculate the unit token cost.
Compute (amount charged this turn ÷ total tokens this turn) to get a blended unit price, then compare it against the official rates:
- Close to the “input price” → full-price billing, caching is not active;
- Significantly below the “input price” → caching is active;
- Above the “input price” → a cache write may have been triggered; this is cold-start behavior and is normal.
Step 3: Run a single-variable control experiment.
Keep the same prompt and run two identical request rounds each through the “compatibility protocol” and the “native protocol,” then compare the usage fields and the charges. This cleanly isolates “client-side problems” from “routing-layer problems.”
5. Enabling Caching: Four Layers of Implementation
5.1 Protocol Layer: Prefer a Direct Connection Over the Native Protocol
If your business allows it, the optimal approach is to have the client send a request body in the model’s native protocol, avoiding the intermediate conversion layer that swallows extension fields. If you must use a compatibility protocol, confirm that the route in question explicitly promises to pass caching fields through; when unsure, validate it with a single minimal request.
5.2 Request Layer: Explicitly Mark Cache Breakpoints
Most services that support caching require the caller to explicitly declare “which content is cacheable” in the request, rather than caching everything automatically. The typical approach is to place a cache-control marker at the end of a reusable prefix. Example code (Python; field names follow the actual service documentation):
import copydef enable_prompt_cache(messages, tools=None):"""Explicitly mark cache breakpoints for reusable prefixes in a compatible request."""req = {"messages": copy.deepcopy(messages)}# Breakpoint 1: end of the system prompt (length must exceed the provider's minimum cacheable token count)sys_msg = req["messages"][0]if sys_msg["role"] == "system":text = sys_msg["content"]sys_msg["content"] = [{"type": "text", "text": text,"cache_control": {"type": "ephemeral"}}]# Breakpoint 2: end of an early history message to extend the reusable rangeif len(req["messages"]) >= 4:idx = len(req["messages"]) - 2msg = req["messages"][idx]if isinstance(msg["content"], str):msg["content"] = [{"type": "text", "text": msg["content"],"cache_control": {"type": "ephemeral"}}]if tools:req["tools"] = tools # Tool definitions come first and are naturally part of the cacheable prefixreturn req
Key points:
- Caching is prefix-based, so the breakpoint position sets the upper bound of the reusable range; placing breakpoints on stable content further back yields greater savings;
- There is usually a limit on the number of breakpoints, so don’t mark every message — pick 1–2 key positions;
- Some platforms support an automatic caching mode that needs no manual marking, but you must verify the actual usage fields before drawing conclusions.
5.3 Routing Layer: Explicitly Select Cache-Supporting Upstreams
In the aggregation router’s configuration, beyond price and latency preferences, you can usually also restrict the upstream scope or enable options like “allow fallback / use only the specified channel.” A workable strategy is:
- Narrow the candidate upstreams to the one or few that explicitly support caching fields;
- Turn off “automatically pick the cheapest channel,” because the cheapest channel is often exactly the one that does not support caching;
- Build separate routing policies for different use cases: route long-context sessions to cache-friendly channels and short requests to low-cost channels.
5.4 Client Layer: Inject Uniformly at the Middle Tier
If you use a general-purpose AI coding tool or a self-built client, the least-effort approach is to deploy a lightweight proxy layer locally that uniformly handles “injecting cache markers + validating usage fields + recording metrics,” so the business code needs no changes. Some major cloud platforms also offer context-caching capabilities for their model services; before integrating, consult the relevant product documentation to confirm the field format, activation threshold, and billing method.
6. Engineering Practice: Making the Prefix Truly Stable
Even with correct markers, prefix jitter will drive the cache hit rate toward zero. This checklist delivers high returns in real projects:
- Freeze the system prompt: put the system prompt, tool definitions, and few-shot examples at the very front, and keep their content and order unchanged throughout the session lifecycle;
- Never put dynamic values into the prefix: a current timestamp, a random session ID, a request trace number, a user nickname, randomly ordered examples — any one of these changing invalidates the entire cache;
- Append to history, never rewrite it: don’t summarize, trim, or reorder past turns; once you change them, everything from the change point onward degrades to full price;
- Keep knowledge-base retrieval results in a stable order: RAG-concatenated content must be sorted by a fixed rule (such as ascending document ID) and inserted at a stable relative position, so that tiny similarity fluctuations don’t reorder it;
- Avoid mixing different models or different sampling configurations within a session: switching models usually means a different cache namespace, so previously written caches can’t be reused;
- Share a common prefix across sessions: when many requests share the same system prompt and tool definitions, this significantly amortizes the cache-write cost.
7. Monitoring and Alerting: Turn Cost Into an Observable Metric
After optimizing, you need long-term upkeep. It’s recommended to collect the following metrics and hook them into a monitoring and alerting system (which can rely on logging and monitoring capabilities):
- Cache hit rate = cache-read tokens ÷ (cache-read + cache-write + uncached input);
- Blended unit price per request = amount charged ÷ total tokens, used to quickly detect whether the billing mode has regressed;
- Cache-write share: a high share signals insufficient prefix reuse or request intervals that exceed the cache TTL;
- Cost distribution by model / routing channel: makes it easy to spot a channel that has quietly bypassed the cache.
A reasonable practical target: in long-context, multi-turn scenarios, keep the cache hit rate high (many projects reach 70%–90% or more) and drive the blended unit price per request down to a level significantly below the base input price.
8. FAQ Summary
- Only short requests — is it worth enabling? Usually not. Cache writes carry a premium and have a relatively high threshold; the benefit only appears as context length and turn count grow.
- The context keeps growing — will that offset the savings? No. The growing portion is only a small part of a single turn’s input; the main prefix is still reused, which is exactly why this pattern saves money.
- Limited savings when output is long? Yes. Output generally doesn’t participate in caching, so the higher the output share, the smaller the overall reduction.
- Does changing the routing guarantee it works? Not necessarily. You must go back and verify with the usage fields; “price-first” and “caching active” have no necessary relationship.
- How can I quickly tell which layer the problem is in? Run a control experiment with a direct native-protocol connection; if it works directly but fails through the router, the problem lies in the conversion or channel-selection stage.
In short: in long-context, multi-turn LLM applications, runaway costs are often not because the model is too expensive, but because this caching capability has been quietly turned off by protocol conversion, channel selection, or prefix jitter. Following the six steps — confirm the billing model → check the usage fields → explicitly mark cache breakpoints → narrow down routing channels → stabilize prefix design → establish cost monitoring — you can usually compress call costs down to a small fraction of their original value without changing any business functionality.
