Prompt Caching for Cost Efficiency: Principles and Cost Accounting Guide
This guide explores the principles and cost-saving strategies of prompt caching in large language model applications. It covers prefix matching mechanics, integration methods, cost accounting models, and practical design tips to help developers optimize caching implementation, troubleshoot common issues, and evaluate net benefits effectively.
I. Why Focus on Prompt Caching
In practical large language model (LLM) applications, many requests contain large amounts of repeated content. Code review tools attach thousands of tokens of review guidelines each time, customer service bots carry the same product knowledge base, and agents repeatedly send tool definitions in every turn. These contents are reprocessed by the model and billed based on input volume for every request. The concept of prompt caching is straightforward: the server saves already-processed prefixes, and if the prefix of a subsequent request matches, it reuses these computation results, thereby reducing costs and shortening response times.
To determine whether a scenario is worth enabling caching, two factors are key: the proportion of fixed content in the total input, and the frequency at which the same prefix is called within its validity period. The benefits are usually most significant when both are high.
II. Basic Principles: Prefix Matching
Most caching mechanisms are based on prefix matching. The model reads the input sequentially, and the cache records the entire content from the beginning to a certain position. A cache hit occurs only when the beginning of a new request exactly matches the cached content. If even a single character differs in the middle, none of the subsequent content can be reused.
This characteristic dictates the arrangement order of your content. Stable content should be placed at the front, such as system instructions, role settings, tool definitions, fixed examples, and reference documents. Dynamic content should be placed at the back, such as the current user’s question and session state. If dynamic content is mixed into the front, cache hits become almost impossible.
III. Two Integration Methods
Common integration methods currently fall into two categories.
The first is explicit marking. Developers specify cache breakpoints in the request, telling the server “content up to this point can be cached.” There is usually an upper limit on the number of breakpoints, so they need to be placed at the most valuable positions, such as the end of a specification document or the end of an example set. Some interfaces also allow setting a flag at the top level of the request, letting the server choose the breakpoints. The advantage of the explicit method is controllability—developers know exactly what is cached. The disadvantage is that breakpoint positions require active maintenance.
The second is automatic caching. The server automatically identifies and caches repeated long prefixes, requiring no changes to the request structure from the developer. This method has the lowest integration cost, but the cache scope and validity period are not determined by the developer. The actual effect must be verified through usage data.
The choice between the two depends on whether the request structure is stable. When system instructions remain unchanged long-term and the team is cost-sensitive, explicit marking offers better control. For rapid prototyping or highly variable request structures, the automatic method is more hassle-free.
IV. Cost Model: Write, Read, and TTL
Caching typically involves three types of billing: the cost of writing to the cache for the first time, the read cost upon a cache hit, and the standard input cost upon a miss. Writing is generally more expensive than standard input, while reading is significantly cheaper. The longer the validity period (TTL), the higher the write premium usually is, but the cache can maintain hits over a longer duration.
Let’s use a set of hypothetical numbers to illustrate the calculation. Assume the standard input price is $2 per million tokens, the write premium is 25% ($2.5 per million tokens), and reads are billed at a 10% discount ($0.2 per million tokens). A 20,000-token review guideline needs to be sent across 50 requests, and the intervals are short enough that the cache remains valid throughout.
Without caching, the total input volume is 50 × 20,000 = 1,000,000 tokens, costing $2.
With caching, the first write is 20,000 tokens, costing $0.05. The subsequent 49 reads total 980,000 tokens, costing $0.196. The total is approximately $0.246, saving about 88%.
This result relies on three premises: the prefix is verbatim identical, it is called again within the TTL, and the write cost is accounted for. If the request interval exceeds the TTL, a rewrite is required every time. Under the above assumptions, the cost of rewriting all 50 times would be $2.5, which is higher than the $2 without caching. Therefore, for low-frequency call scenarios, you must first calculate the relationship between the interval and the TTL. The premiums and discounts above are for illustrative purposes only; actual ratios are subject to official platform pricing and may vary across different models.
V. Practical Design Points
- Prioritize fixed content. Arrange system instructions, tool definitions, examples, and documents from most to least stable.
- Remove dynamic noise. Timestamps, random request IDs, and session sequence numbers in the request prefix will break matches. Move them to the end or remove them from the prefix.
- Maintain serialization stability. The JSON key order, spaces, and line breaks of the same content must be exactly identical across different requests.
- Place breakpoints at semantic boundaries. Breakpoints placed at the end of a paragraph or example are easier to reuse than those in the middle of a sentence, and are easier to troubleshoot.
- Write first, then parallelize. When multiple requests arrive simultaneously, the cache may not have been written yet. You should initiate one request first to complete the write, then send the remaining requests concurrently.
Below is a pseudocode example. The field names are for conceptual illustration only and are not real parameters of any specific API:
# Pseudocode for illustration; field names represent concepts, not real API parametersREVIEW_GUIDE = load_review_guide() # Fixed review guidelines, a few thousand tokensdef build_request(user_code: str) -> dict:return {"system": [{"type": "text","text": REVIEW_GUIDE, # Stable content placed first"cache_breakpoint": True, # Set cache breakpoint here"ttl": "short", # TTL tier}],"messages": [{"role": "user", "content": user_code} # Dynamic content placed last],}
VI. Common Failures and Troubleshooting
- Prefix altered. Embedding the current time in the system prompt makes every request different, missing the cache.
- TTL expired. In low-frequency scenarios, if the interval between two requests exceeds the TTL, a rewrite is necessary.
- Tools or attachments changed. Adding/removing tool definitions or changing images alters the prefix.
- Serialization inconsistent. Differences in dictionary iteration order or whitespace characters make the content appear different.
- Improper breakpoint position. If a breakpoint falls after dynamic content, the stable portion preceding it cannot be cached independently.
When troubleshooting, first compare the prefixes of two requests to find the first differing character. Content after this point cannot be reused, so locating it usually directly points to the problem.
VII. Monitoring and Evaluation
After deployment, record the total input volume, cache write volume, and cache read volume for each request. Calculate the hit rate daily, defined as the ratio of cache read volume to the total volume of cacheable prefixes. If the hit rate is lower than expected, first check if the prefix is stable, then check the call intervals.
Additionally, conduct regular cost accounting. Subtract the extra write expenditure from the savings generated by caching to determine the net benefit. Focusing solely on the hit rate while ignoring write costs can easily lead to overestimating the actual value of caching.
VIII. Applicable Scenarios and Boundaries
Suitable scenarios include: long fixed contexts (e.g., guidelines, knowledge bases, tool definitions); high-frequency calls with the same prefix; and reuse of historical content in multi-turn dialogues.
Unsuitable scenarios include: one-time requests, highly personalized requests where content changes every time, and requests with intervals far exceeding the TTL. In these scenarios, write costs may exceed the saved read fees.
