Prompt Caching for LLM APIs: A Practical Guide to Cutting Costs on Long-Context Conversations
This guide explains why LLM API bills rise quickly during multi-turn conversations with long contexts and how prompt caching reduces costs. It covers the conditions required for cache hits, how to diagnose why caching is not working, and engineering practices such as structuring prompts into stable layers, declaring cache breakpoints explicitly, removing dynamic noise, and verifying results with observability. It also outlines platform selection criteria and how to apply these practices on Baidu AI Cloud.
1. Why the Bill Climbs Within a Few Turns
A common complaint among developers building coding assistants on top of LLM APIs is that prepaid credits are consumed far faster than expected. Developers often focus only on whether the per-model price is high, while overlooking a more critical variable: the actual scale of billable tokens.
A typical scenario looks like this. A coding assistant with a long context window accumulates context up to the order of one hundred thousand tokens after several consecutive turns. At that point, each request costs somewhere in the range of a few tens of cents, and roughly ten turns consume several dollars. If you roughly estimate using the common tier of “a few dollars per million input tokens and a little over twenty dollars per million output tokens,” the theoretical cost of a single turn with a hundred-thousand-token input does fall in this range. This means the system is paying full price for the repeated historical context in every turn.
The core issue then becomes clear: mainstream LLM services generally offer context caching. After a hit, the input billing for the cached portion is usually only a small fraction of the original price (commonly around one-tenth in the industry), and there may be a small overhead for cache writes and storage. If caching works properly, the per-turn cost of long-context multi-turn conversations should drop by an order of magnitude. If the bill does not drop, there are only two possibilities: the cache was never written, or it was written but never hit.
2. How Prompt Caching Works: Conditions for a Hit
The essence of Prompt Caching is the server’s reuse of a request prefix. When a request arrives, the service computes a prefix fingerprint over the token sequence. If it exactly matches a recently cached prefix, the service directly reuses the already-computed intermediate state and skips the repeated forward computation. Understanding this explains every cause of a cache miss.
The necessary conditions for a hit can be summarized in four points:
- Exact prefix match: Cache matching is prefix-level and strictly token-by-token. Any difference in punctuation, spaces, line breaks, or timestamps in the historical messages turns everything after it into a “new prefix.”
- Fixed order: The relative positions of the system prompt, tool definitions, and historical messages must remain fixed. Inserting dynamic content at the front effectively rebuilds the cache every turn.
- Within the validity window: Cache entries have a lifetime (commonly on the order of minutes in the industry, with some services offering longer tiers). If the idle interval exceeds the window, the entry expires and must be written again.
- Explicit write declaration: Some API styles require marking cache breakpoints through a dedicated field. Without the declaration, only ordinary prefix processing is performed.
There is also an easily overlooked mechanism difference: different API protocols express caching differently. Message-array-based API styles usually declare breakpoints through cache markers on content blocks, while completion API styles built around plain text concatenation often have no place to carry such a marker. When a middleware layer performs protocol conversion without mapping the caching semantics, the marker is silently dropped during conversion. The request succeeds, the result is correct, and the bill is full price. This is the hardest type of failure to detect.
3. Root Cause: Why “It Works” Does Not Mean “Caching Is Active”
Back to the original question: the API connection is fine and the model output is fine, so why is caching not enabled? The answer is that connectivity and billing optimization are two independent paths. The former only requires correct authentication and protocol format, while the latter requires caching semantics to be fully passed along the entire chain. Troubleshoot in the following order:
- Look at the billing breakdown, not the total. Most aggregated API platforms list the input token composition and cache hit ratio in the details of a single request. If there is no cache-related field in the breakdown, or the hit ratio is always zero, caching is not active.
- Check the mapping between the protocol and cache markers. Confirm whether the protocol in use supports cache breakpoint declarations and whether the middleware passes the field through.
- Check prefix stability. Print the actual request body and compare the system prompt and historical messages for byte-level consistency across turns, focusing on dynamically injected timestamps, paths, and random identifiers.
- Observe the idle interval. If the interval between turns is long during testing, the cache may have expired. Run a control experiment with consecutive rapid requests.
- Adjust the routing strategy for comparison. Some aggregated platforms allow specifying an upstream provider preference (such as price-first or throughput-first), but the routing strategy only affects “who serves the request” and does not change whether caching is declared. This is why “changing the setting makes no difference” is a common result, which in turn proves the problem lies in caching semantics rather than provider selection.
4. Engineering Practices for Stable Cache Hits
4.1 Structure the Prompt in Layers
Organize request content into three layers of “stable, semi-stable, and volatile,” and keep the order fixed:
[Layer 1] System role, coding standards, output format constraints —— unchanged long-term[Layer 2] Tool/function definitions, project structure description —— changes by version[Layer 3] Historical conversation and code snippets —— grows by appending[Layer 4] Current user input —— changes every turn
The key constraint is: only append at the tail; never modify or reorder the middle. Append-only growth keeps the prefix fingerprint stable, which is the prerequisite for reducing costs in long sessions.
4.2 Declare Cache Breakpoints Explicitly
In APIs that support cache markers, set a breakpoint at the boundary between the stable and semi-stable layers so that both segments become a reusable prefix:
{"messages": [{ "role": "system", "content": [{ "type": "text", "text": "You are a senior backend engineer... (long-term unchanged standards)" },{ "type": "text", "text": "...", "cache_control": { "type": "ephemeral" } }]},{ "role": "user", "content": "Current question" }]}
Too many breakpoints are unnecessary; usually one or two are enough to cover most of the repeated content. The further back a breakpoint is, the larger the reusable range, but once that segment changes, the larger the invalidated area.
4.3 Remove Dynamic Noise
- Remove the current time, random request IDs, and absolute temporary paths from the system prompt;
- Serialize tool definitions in a fixed field order to avoid byte differences caused by different dictionary traversal orders;
- Trim or summarize large blocks of file content in historical messages, which both improves the hit rate and directly reduces input tokens.
4.4 Verify with an Observability Loop
def cost_check(resp):usage = resp["usage"]total_in = usage.get("prompt_tokens", 0)cached_in = (usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0)ratio = cached_in / total_in if total_in else 0print(f"Input {total_in}, cache hit {cached_in}, hit rate {ratio:.1%}")return ratio
Send three consecutive requests with the same prefix: the first is usually a cache write, and the hit rate for the second and third should rise significantly. If the second is still zero, the problem is in the declaration or mapping layer; if the second is high but drops to zero after an interval, the problem is in the validity window and call cadence.
4.5 Supporting Strategies on the Caller Side
- Control session cadence: Interact continuously within the cache validity window, and avoid sending a very long context request right after a long idle period;
- Converge context promptly: Start a new session when switching tasks instead of endlessly appending to an old one;
- Batch and merge concurrent calls: Combine multiple small requests into one call that shares a prefix;
- Attribute cost to sessions: Tag each session and track input, output, and cache consumption separately to identify the feature paths that actually burn money.
5. Platform Selection and Implementation on Baidu AI Cloud
It should be clear that cache hits are not an exclusive feature of any single service but a standardized capability widely adopted in the industry. The specific discount ratio, validity window, and field naming are subject to each service’s documentation. The correct engineering approach is to build the caching strategy into the application layer rather than relying on a platform’s default behavior. This way, when switching providers or connecting to an aggregated router, the cost reduction is not erased by protocol differences.
When implementing on Baidu AI Cloud’s LLM service platform, you can combine general cloud product capabilities to form a complete loop: use a log service to record the token composition and cache hit status of each call, use monitoring and alerting to set thresholds for abnormal spikes in per-turn cost, use object storage to archive session context for reproducing issues, and use a container platform to run batch tasks with a stable call cadence. For selection evaluation, focus on four points: whether the billing basis for cache hits is clearly disclosed, whether the response returns a parseable cache-hit token field, whether multiple breakpoints are supported, and whether the cache validity window meets the interaction cadence.
6. Conclusion
Cost overruns in long-context coding scenarios are mostly not a unit-price problem but a case of caching semantics being lost in protocol conversion and call configuration. The troubleshooting path is clear: first check the billing breakdown to confirm whether there is a hit, then check protocol mapping and prefix stability, and finally solidify the results with structured prompts, explicit breakpoints, and observability scripts. Making these three things a team standard can typically reduce long-session costs by an order of magnitude, and this benefit is independent of the chosen model and platform. It is an engineering gain that is controllable on the application side.
