How Context Caching Reduces Large Language Model API Costs

    Large language model costs are often driven less by the answer itself than by repeatedly sending the same long context. This article explains how context caching separates stable prefixes from changing prompts, compares automatic, explicit, and persistent caching approaches, provides a cost model, and outlines practical techniques for stabilizing prefixes, designing cache-aware architectures, monitoring usage, and deciding when caching is not worthwhile.

    Why Repeated Context Drives Up Costs

    Large language model API billing is essentially the accumulated cost of how much data is read and generated. Input and output tokens are usually priced separately. Long responses can be expensive, but in document Q&A, policy search, codebase explanation, and customer-support knowledge bases, the larger cost often comes from repeatedly sending the same long context with every request.

    First, clarify the billing unit. A token is a model-side measurement unit, not a fixed equivalent of one Chinese character or one English word. Chinese, English, code, and tables can produce different token counts, and the same material may tokenize differently across models. A reliable engineering practice is to count tokens with the service you actually use and then estimate costs using that service’s published input and output prices, rather than relying on conversion ratios found online.

    The biggest cost difference comes from request design. Suppose an annual report, contract, or API specification has been prepared as a stable context of approximately 100,000 tokens. A user asks three independent questions about revenue, profit growth, and cash flow. If every request places the entire document at the beginning of the message and appends the current question, the input is not merely “100,000 tokens plus three short questions.” The document is read roughly three times, for a total of about 300,000 context tokens. The document never changes; only the final question does.

    This is not primarily a problem of the model being slow. It is a stateless full replay of the request. Caching addresses this by separating the stable prefix from the changing suffix: the prefix is processed once and reused, while subsequent requests pay full price mainly for new content and generated output.

    What Context Caching Does

    Context caching does not mean storing a model’s answer in a database and returning it unchanged. Different questions should produce different answers. Instead, caching stores intermediate results from processing a completed prefix, so the service does not need to fully process and charge for the same prefix again. Caching therefore works only when the prefix is consistent.

    A single extra space, a modified system prompt, or a change in the order of the document and question may produce an entirely new prefix.

    Three common approaches are widely used. Their exact capabilities depend on the service you use; the following describes the mechanisms rather than any particular provider’s API or pricing.

    1. Automatic Prefix Caching

    With automatic prefix caching, the caller does not add an explicit marker. If the beginning of consecutive requests is identical, the service attempts to reuse it.

    The advantage is low integration effort. The disadvantages are that the matching rules may not be transparent and the retention period is often short. If a user returns several minutes later, the prefix may need to be processed again. This approach is suitable for consecutive follow-up questions within a session, but less suitable for asking questions about the same contract on different days.

    2. Explicit Cache Markers

    With explicit caching, the caller identifies the content that should be cached in the message structure. The service then creates or reads the cache accordingly.

    Responses often report how many tokens were newly written to the cache and how many cached tokens were read, which makes cost reconciliation easier. The trade-offs are that the request structure must be changed, the initial cache write may cost more than ordinary input, and the cache may expire after a short period without use. This approach works well when the same context is reused frequently within a limited time window.

    3. Longer-Lived or Persistent Explicit Caches

    Some services support longer-lived explicit caches or persistent cache objects. The caller registers stable content, receives a cache identifier, and references that identifier in later requests instead of pasting the full document every time.

    Retention periods, capacity limits, and pricing rules vary significantly. They must be implemented according to the current documentation. Do not assume that a cache written once remains valid forever.

    After a cache hit, the cached portion of the input is usually priced below an equivalent amount of new input. The current question, newly attached content, and model output are still charged according to the normal rules. Cache writes may also incur additional fees.

    As a result, the savings are not determined by a single fixed discount. They depend on the hit rate, number of writes, retention period, and output length.

    A Cost Model for Context Caching

    Do not start by memorizing a percentage. Start with the correct formula.

    Let:

    • P_in be the normal input price
    • P_read be the cached-input read price
    • P_write be the cache-write price
    • P_out be the output price
    • C be the length of the stable prefix
    • q_i be the length of the new question in request i
    • a_i be the output length of request i

    Without caching, the input cost for N questions is approximately:

    1. N × C × P_in + (sum of all q_i) × P_in

    If the prefix is written once and successfully read by all subsequent requests, the input cost is approximately:

    1. C × P_write
    2. + (N − 1) × C × P_read
    3. + (sum of all q_i) × P_in

    You must then add the output cost for every request:

    1. sum of all (a_i × P_out)

    The difference becomes significant when C is much larger than each q_i, the number of requests is sufficiently large, and cache hits are not lost because of expiration or prefix drift.

    If a user typically asks only one question and leaves, the cache-write premium may cause the total cost to increase rather than decrease. If responses are very long, output may dominate the bill, reducing the benefit of compressing the input prefix.

    Using the annual-report example, assume C = 100,000, the three questions are negligible in size, and P_read is considerably lower than P_in. With full replay, the document portion costs:

    1. 3 × 100,000 × P_in

    With caching and two successful reads, it costs:

    1. 100,000 × P_write + 200,000 × P_read

    Only the actual prices of the service you use can determine whether changing the request design is worthwhile. Claims such as “90% savings” are realistic only when the prefix is very long, users ask many follow-up questions, the read price is very low, and nearly every request hits the cache. They should not be treated as universal guarantees.

    How to Keep the Prefix Stable

    Cache hits depend on byte-level or token-level prefix consistency. This is a request-design problem, not a matter of luck.

    System instructions, tool definitions, output-format requirements, and long documents should appear at the beginning of the message and remain exactly the same across requests. The current user question, timestamps, request IDs, and random greetings should appear after the stable prefix.

    For example, placing “Today is [date]” in the first line of the system prompt can change the prefix every day—or even every hour—making automatic caching ineffective.

    Normalize long documents before caching them:

    • Use consistent line breaks.
    • Remove random filenames added during upload.
    • Remove watermark page numbers when appropriate.
    • Keep heading levels consistent.

    Two parses of the same PDF may differ in whitespace. Although they represent the same annual report to a human reader, they may be two different prefixes to the caching system.

    In multi-document workflows, avoid reordering and concatenating entire documents by relevance for every request. Reordering changes the prefix. More stable approaches include:

    • Caching a stable full document or stable chunks, then placing the selected chunk IDs or selection instructions in the short suffix.
    • Creating a separate cache for each stable chunk and referencing the required chunks when needed.

    Overly small chunks increase write and management overhead. Overly large chunks waste read tokens when only one section is needed. Choose a strategy by testing it against real user questions.

    An explicitly cached request can be represented by the following conceptual structure. This is only an instructional example, not a real provider’s field names. Adapt it to the syntax required by the service documentation you use.

    1. {
    2. "messages": [
    3. {
    4. "role": "system",
    5. "content": "Fixed role and response format without a timestamp"
    6. },
    7. {
    8. "role": "user",
    9. "content": [
    10. {
    11. "type": "text",
    12. "text": "Stable long document",
    13. "cache_hint": "ephemeral"
    14. },
    15. {
    16. "type": "text",
    17. "text": "Current question: Is the cash flow healthy?"
    18. }
    19. ]
    20. }
    21. ]
    22. }

    The cache marker should be applied to the stable segment, not to the question that changes on every request. If the service requires a minimum cacheable length, a short system prompt may be too small to create a cache by itself. In that case, combine the stable document and fixed instructions into one cacheable segment.

    How to Integrate Caching into the Architecture

    A maintainable document-Q&A system should not have the frontend insert the original document into every conversation request. A clearer flow is:

    1. Parse, clean, and count tokens after upload. Produce normalized text and a content hash.
    2. Use the hash as the key to determine whether an existing cache identifier can be reused or a new cache must be created. If the content has not changed, do not write it again.
    3. Store the document ID, cache ID, and expiration time in the session rather than a full document copy that may be rewritten with every request.
    4. Before asking a question, check whether the cache is still valid. If it is close to expiration and more follow-up questions are expected, consider extending or rebuilding it. If the user is likely to ask only one occasional question, use a normal request instead of paying a cache-write fee for a very low hit rate.
    5. Record cache creation tokens, cache read tokens, uncached input tokens, and output tokens for every request. Aggregate them by document and tenant.

    In a multi-tenant system, cache keys must include tenant boundaries. Even if two companies upload byte-identical public annual reports, their cache identifiers should not be shared across sessions. Authorization, auditing, and data isolation require separate key spaces even when the content is identical.

    Logs may contain hashes and token statistics, but avoid writing full documents or cache identifiers to uncontrolled logging platforms.

    Conversation history can also disrupt prefix stability. If a previous question and answer is inserted into the middle of the document, or the entire history is rewritten on every request, the prefix is no longer stable.

    A common design is to let the cache cover the system instructions and original document, while placing conversation history after the document and before the current question. The changing history will then prevent reuse of only that smaller segment. When history becomes too long, summarize it. The summary should itself be stored consistently rather than rewritten with different wording on every request.

    Monitoring, Validation, and When Caching Does Not Help

    Before launch, run a controlled comparison with a fixed document. Ask the same set of questions in two groups: one that sends the full context every time and one that uses caching.

    Compare more than the total cost. Also measure:

    • Time to first token
    • End-to-end latency
    • Refusal rate
    • Whether key facts remain consistent

    A cache hit should not change the answer. If the answer changes, first check whether the prefix was truncated or whether the original document was replaced with a summary.

    At minimum, monitor these four metrics in production:

    • Cache creation tokens
    • Cache read tokens
    • Uncached input tokens
    • Output tokens

    You can estimate the cache hit rate as:

    1. read tokens / (read tokens + cacheable prefix tokens that should have been reused)

    If creation volume is high but read volume is low, the cache window may be too short or the prefix may be unstable. Fix the request structure before adding more cache writes.

    If read volume is high but the bill declines only slightly, return to the pricing formula and examine the share of output costs and the cache-write premium.

    Caching provides limited value, or may be inappropriate, in the following situations:

    • Each input is a short sentence with no reusable long prefix.
    • The material changes on every request, such as real-time market data or a paragraph that was just edited.
    • Requests are so infrequent that the interval exceeds the cache retention period.
    • The task requires strict isolation between requests and the service terms do not permit retaining context across requests. In this case, follow the terms and use alternatives such as shorter prompts or retrieval of only relevant passages. Do not attempt to extend retention of data that should not be retained.

    Reducing context remains the first optimization. If retrieval can identify the relevant pages, do not send the entire document by default. If a metric can be answered from structured fields, do not require the model to read the surrounding narrative.

    Caching is a cost and computation optimization for cases where the same full context must repeatedly appear. It is not a reason to ignore retrieval design.

    If you use a large-model service from Baidu AI Cloud, verify whether caching is automatic, which marker fields are supported, the minimum cacheable length, retention period, and applicable prices in the current official documentation. Then reconcile the rules against your own request samples.

    The same principle applies to other providers: read the current rules, substitute the actual prefix length and number of follow-up questions into the cost formula, and then decide whether automatic caching, explicit caching, or no caching is appropriate.

    Keep stable material in the prefix and changing content in the suffix. Evaluate the result with measurements rather than marketing claims. When implemented this way, repeated context no longer enters the bill in direct proportion to the number of questions. The savings reflect the input processing that was actually avoided, not an unverifiable discount promise.