How to Cut LLM API Costs: Three Caching Mechanisms and How to Apply Them

    LLM bills often grow because every request resends the same instructions, rules, and reference material. This article explains how to separate a request’s cost, compare automatic prefix caching, explicit context caching, and application-level result caching, and measure real savings without treating a “90% reduction” as a general result. It also covers prompt structure, break-even checks, cache keys, versioning, access control, and the metrics needed before production.

    1. Can a 90% Saving Be Achieved? Start with the Cost Breakdown

    After connecting an application to a large language model, many teams notice the same pattern: a single call looks inexpensive, but the bill keeps rising as usage grows. In knowledge Q&A, document analysis, and customer-support workflows, the system may resubmit the same role instructions, business rules, and reference material on every request.

    That repeated input is an important place to look for caching gains. A claim that “caching saves 90%” should not be treated as a general conclusion. Cache coverage, actual hit rate, pricing, and the balance between input and output all affect the result.

    The cost of one call can usually be split into:

    • Processing uncached input
    • Reading or processing cached input
    • Generating output
    • Possible cache-creation, storage, and other service charges

    A token is the basic unit a model uses to process text. It is not the same as a character or a word count. Different texts and models may be split differently, so budgets should be based on recorded usage.

    Two ideas must stay separate: the discount on the cached portion and the savings on the whole request. Even if the unit price of cached input falls sharply, the total request cost will not fall by the same proportion when output accounts for most of the bill.

    The right order is therefore to break down the bill, identify repeated content, and then choose a caching method—not to start from a promotional savings figure.

    2. What Each of the Three Cache Types Solves

    In engineering practice, LLM-related caching can be divided into three types:

    Type What is reused Main change after a hit Suitable use
    Automatic prefix caching Repeated input at the start of a request Less repeated input processing; an answer is usually still generated Fixed rules and repeated long material
    Explicit context caching A shared context created in advance Later requests refer to an existing context Continued analysis of the same material
    Application-level result caching A complete generated result A hit can be returned directly, avoiding another inference Frequent questions with relatively stable answers

    These mechanisms should not be treated as the same thing. The first two mainly reuse state related to input processing and usually do not return a historical answer directly. The third reuses the final result, so the application must judge validity and safety itself.

    Not every model service supports all three. Support, pricing, and retention time should be confirmed from the actual service documentation and from measurement.

    3. Automatic Prefix Caching: Make Repeated Content a Stable Prefix

    Automatic prefix caching identifies a continuous span at the beginning of a request that matches an earlier request and, when conditions are met, reuses the related computation state.

    It does not hit merely because two requests have a similar meaning. In many implementations, a hit depends on the same token sequence. Formatting changes, reordered fields, or dynamic information placed at the front can all reduce the reusable span.

    3.1 Why prompt order matters

    A request structure that works poorly with caching may look like this:

    1. Current time: ...
    2. Request ID: ...
    3. User question: ...
    4. Fixed business rules: ...
    5. Fixed reference material: ...

    The time, request ID, and user question change on every call. If they appear at the beginning, the fixed material that follows may not form an effective common prefix even when it is identical.

    A more suitable organization is:

    1. Fixed role and safety rules
    2. Fixed output format
    3. Fixed business instructions
    4. Shared reference material
    5. Current-turn user information
    6. Current-turn question

    Stable content then appears continuously near the front, while content that changes each turn stays toward the end.

    Caching must not be allowed to weaken instruction priority. Role boundaries, safety rules, and the boundary around untrusted material must remain clear. External documents should not be wrapped so that they look like high-priority instructions.

    3.2 Details that reduce the hit rate

    Common causes include:

    • Timestamps or random identifiers mixed into fixed rules
    • Different ordering of the same material
    • Unnecessary differences in spaces, line breaks, and template formatting
    • Frequent changes to tool descriptions or output constraints
    • Retrieved documents ordered without a stable policy

    Template versioning, stable serialization, and deterministic ordering can remove meaningless differences. Standardization must preserve meaning: real differences in amounts, dates, and permission scope should not be erased.

    3.3 Automatic caching still needs management

    Automatic caching can reduce integration complexity, but actual hits still need to be observed. Model version, request length, retention policy, and service load can all affect results.

    Do not assume a discount just because two prompts look the same. Check cache-usage information returned by the service first. If no direct metric is available, verify the benefit through bills, call statistics, and controlled experiments.

    4. Explicit Context Caching: A Reuse Cycle for Repeated Material

    With explicit context caching, the application creates a shared context and later requests refer to it. This makes the reused object and its lifecycle easier to manage, but it adds engineering work for creation, updates, and invalidation.

    The following flow explains the concept only. It does not represent any specific service API:

    1. Prepare and validate the shared material
    2. ↓
    3. Create a reusable context
    4. ↓
    5. Record the context reference and material version
    6. ↓
    7. Later requests refer to the context and add the current question
    8. ↓
    9. Recreate the context after the material changes or the cache expires

    4.1 Which workloads are worth it

    Shared context is often valuable when the same long document is used repeatedly for summarization, clause extraction, risk analysis, and Q&A.

    If the material is used only once, or changes substantially on every turn, creation and management costs may cancel the benefit.

    The decision should consider:

    • Whether the material is large enough
    • How many times it is expected to be reused
    • Whether repeated requests fall within the retention window
    • How often the material changes
    • How creation, reads, and storage are priced

    4.2 Use a break-even calculation, not intuition

    Let:

    • A be the cost of creating the cache
    • U be the cost of processing the shared material once without caching
    • R be the cost of processing the same material through the cache
    • S be the storage cost during the cache lifetime
    • N be the number of later reuses

    Under simplified assumptions, caching is worthwhile when:

    1. N × (U - R) > A + S

    This model compares only costs related to the shared material. Output generation, dynamic user input, and other service costs still belong in the overall budget.

    Actual pricing may differ on whether cache creation includes input-processing charges and whether storage cost grows over time. The calculation must avoid both double counting and omitted items.

    4.3 Version management matters more than the cache reference

    After a shared document changes, the old cache may still exist. If the application stores only a reference and does not record the material version, it can easily return answers based on stale content.

    Store the material version, content digest, access scope, and context reference together. Before using a business request, confirm that the versions match. If the cache is invalid or a read fails, there should be a path to recreate it or fall back to a normal request.

    5. Application-Level Result Caching: Avoid Repeated Inference

    Application-level result caching stores generated answers in the business system. On a hit, the stored result is returned and the model is usually not called again. For stable tasks with a high repeat rate, this can be more effective than input caching.

    The risk is also more direct: a poorly designed cache key can return an old answer, a wrong answer, or another user’s content to the current user.

    5.1 The cache key cannot be only the user question

    A more complete key should include the fields the business requires, such as:

    1. Tenant scope
    2. User permission scope
    3. Task type
    4. Normalized input
    5. Prompt version
    6. Knowledge version
    7. Model-configuration version
    8. Output-format version

    Together, these fields decide whether a result can be reused.

    For example, two users may ask the same question but have access to different internal material. Their answers cannot be shared. After a knowledge base changes, the previous result may be invalid even if the question is unchanged.

    5.2 Start with exact matching

    Exact matching is easier to verify and is a good starting point for fixed Q&A, repeated text processing, and stable format conversion.

    Semantic matching tries to reuse questions with similar meaning, but it increases the risk of a wrong hit. “Can I get a refund?” and “Can I still get a refund after the agreed deadline?” look similar, yet their conditions may differ.

    For sensitive tasks involving amounts, deadlines, eligibility, permissions, or operational instructions, an old answer should not be returned based only on semantic similarity. Entity, condition, and version checks can be added. High-risk workflows should prefer exact matching or regeneration.

    5.3 Do not turn abnormal results into long-lived answers

    Timeouts, truncated output, format errors, missing evidence, and results that fail quality checks should not go directly into a long-term cache.

    Before writing a result, check its structure, required fields, and business constraints. Error states that genuinely need a short cache should use a separate policy so they are not confused with normal results.

    6. How to Calculate the Real Savings Rate

    Suppose one request contains:

    • I total input tokens
    • H cached input tokens that hit
    • O output tokens
    • P as the normal input unit price
    • Q as the cached-input unit price
    • R as the output unit price
    • F as other cache costs allocated to the request

    The simplified costs are:

    1. Cost without cache = I × P + O × R
    2. Cost with cache = (I - H) × P + H × Q + O × R + F

    The real savings rate is:

    1. Savings rate = 1 - cost with cache ÷ cost without cache

    As an arithmetic illustration only, assume input is 70% of the original cost and output is 30%. Suppose 80% of the input can hit the cache, the price of that hit portion falls by 75%, and extra charges are ignored for the moment.

    The overall savings rate is:

    1. 70% × 80% × 75% = 42%

    This does not represent the actual price of any service. It shows that a cache discount is not the same as the reduction in total cost.

    An overall reduction close to 90% usually requires highly repetitive requests, a large share of cacheable input, low output cost, or result caching that avoids a large amount of inference. Whether that holds must be verified with real business data.

    7. Security and Operational Controls Required Before Launch

    7.1 Isolate by tenant and permission

    A cache must not bypass access control. Even after a result has been generated, the system should confirm that the current user may access its source material and content before returning it.

    Including permission scope in the cache key is one protection, but it does not fully replace an authorization check at read time. When a user’s permissions change, old results should expire or be checked again.

    7.2 Define a retention policy for sensitive data

    Caching can extend how long data exists. Before launch, confirm where data is stored, how long it is retained, how it is deleted, and who can access it. Do not write secrets, credentials, or unnecessary personal information into a shared cache.

    Enabling a cache does not by itself mean that data will not be stored or processed. Those boundaries should follow the actual service terms and the organization’s compliance requirements.

    7.3 Prevent concurrent cache stampedes

    When a hot cache entry expires, many requests may call the model at the same time, causing a sudden rise in cost and latency.

    Request coalescing for the same key, rebuild locks, staggered expiration, and rate limits can ensure that identical work is refreshed once as far as possible. For content that does not require strict freshness, briefly serving an old result may be acceptable when that behavior is explicitly allowed. It must not conceal data that has to be updated promptly.

    8. Close the Loop with Metrics, Not Hit Rate Alone

    At a minimum, track:

    • Request hit rate
    • Share of input tokens served from cache
    • Average cost per successful task
    • Cache creation and storage cost
    • Median and high-percentile latency
    • Rate of stale-content returns and wrong hits
    • Answer quality, retry rate, and user correction rate

    A high request hit rate does not necessarily mean large savings. If the requests that hit are very short, the benefit may be limited. Token-weighted and cost-weighted metrics should be observed as well.

    A practical rollout can start with one workload that uses substantial fixed material and whose results are easy to evaluate. Establish a no-cache baseline, then improve prompt structure and observe automatic caching. Next, evaluate explicit context caching. Finally, add result caching for stable tasks. Verify quality, cost, and latency independently at each step so that several changes are not mixed together and cannot be attributed.

    Conclusion

    Reducing LLM cost with caching means identifying which computation and results can be reused safely. It is not simply a matter of turning on a feature.

    A stable prefix reduces repeated input processing. Explicit context manages long material that is used repeatedly. Application-level result caching avoids repeated inference. The three can be combined, but each requires cost calculation, version management, permission isolation, and quality monitoring.

    More useful than a “90% savings” claim is a cost-reduction system that can be explained, verified, and sustained: one that shows how much was saved and which business boundaries were preserved.