LLM Prompt Caching Configuration and Cost Optimization: A Practical Guide

    This guide explains why a working API call does not guarantee that prompt caching is active, what prompt caching actually reuses, and how to verify cache hits with real cost evidence. It walks through checking cache configuration along the request chain (client, protocol conversion, routing), restructuring context to increase the reusable prefix, running minimal controlled experiments, and setting up ongoing monitoring. It also corrects common misconceptions and outlines a step-by-step implementation order so you can confirm that repeated requests produce verifiable cache-read usage and that total task cost genuinely drops.

    1. A Working API Call Does Not Mean Caching Is Active

    In scenarios like intelligent coding, knowledge Q&A, and multi-step task execution, applications often resend system instructions, tool definitions, reference material, and a growing history of messages. Once the input context reaches tens of thousands or even hundreds of thousands of tokens, each turn can add noticeable cost even if only a small amount of new content is added per turn.

    A common misconception here is that because the API is connected and the model answers normally, caching should be enabled automatically. In reality, a successful call only proves that authentication, request formatting, and model routing are basically working; it does not prove that the request meets the requirements for prompt caching.

    Whether caching takes effect usually depends on the entire chain:

    Application builds the request → client serialization → gateway conversion → backend service processing → usage metering and billing.

    If any link fails to preserve the necessary cache configuration, or alters the reusable prefix, the final request may be billed as ordinary input.

    So the key to solving the problem is not to look for a switch with a name like “savings mode,” but to build a verification loop between “configuration, request, hit evidence, and actual cost.”

    2. What Prompt Caching Actually Caches

    2.1 Prompt caching is not response caching

    Response caching stores the result for a given question and returns the existing answer directly under the same conditions. Prompt caching mainly reuses the already-processed stable prefix in the input, reducing the cost of processing repeated content in subsequent requests.

    For example, a request can be logically divided into:

    1. Fixed system rules
    2. Fixed tool definitions
    3. Fixed background material
    4. Existing conversation history
    5. New question this turn

    If the earlier portion stays consistent and meets the server’s caching conditions, subsequent requests may reuse the processing result of that portion. But the model still needs to process the new input and generate new output.

    So prompt caching does not make all requests free, and it usually does not waive output costs.

    2.2 Hits usually depend on a stable prefix

    Many prompt caching mechanisms match on the input prefix rather than freely searching for identical segments across the whole request.

    Suppose the first input is:

    1. Common rules + tool definitions + document material + Question A

    The next input is:

    1. Common rules + tool definitions + document material + Question B

    The stable part at the front has a chance to be reused.

    But if the second one becomes:

    1. Current time + common rules + tool definitions + document material + Question B

    the beginning of the request has changed, which may shorten or even break the matchable prefix.

    Note that different services handle cache boundaries, content matching, and request composition differently. Always rely on the actual documentation and test results, and do not generalize the behavior of one implementation to all APIs.

    2.3 Caching has conditions

    Common constraints include a minimum cacheable length, a validity period, the model scope, and isolation by account, tenant, or backend service. Some services automatically detect the stable prefix, while others require you to explicitly declare the cache boundary.

    Therefore, both “using the native API always caches automatically” and “using a compatible API can never cache” are imprecise. What you really need to check is the specific API capability, the client implementation, and the actual request content.

    3. First Determine Whether the Cost Is Abnormal, Then Whether Caching Failed

    3.1 Do not look only at the amount on a single bill

    A high cost for one request can come from multiple factors:

    • The input context is very long;
    • The output is large;
    • The cache has not been established yet;
    • The cacheable portion is only a small part of the input;
    • The cache has already expired;
    • After a route switch, the original cache cannot be reused;
    • The application retried or made multiple model calls;
    • The service has additional billing items.

    So “each turn is charged a lot” alone cannot prove that caching is not enabled.

    3.2 Break down cost by billing category

    An easy-to-understand cost model is:

    1. Request cost =
    2. ordinary input volume × ordinary input unit price
    3. + cache write volume × cache write unit price
    4. + cache read volume × cache read unit price
    5. + output volume × output unit price
    6. + other billing items

    The various input volumes here should be non-overlapping billing buckets. If the “total input volume” in the usage report already includes cache reads, you cannot simply add the two together, or you will double count.

    Also, some services do not charge a separate cache write fee, while others apply different rules based on the cache validity period or other conditions. The formula above is only an accounting framework and does not mean all APIs have the same billing fields.

    To illustrate, suppose a service’s ordinary input unit price is 6 billing units per million tokens and the cache read unit price is 0.6 billing units. A request has 100,000 input tokens, of which 90,000 hit the cache successfully and the remaining 10,000 are processed as ordinary input. The input cost is:

    1. Ordinary input: 10,000 ÷ 1,000,000 × 6 = 0.06
    2. Cache read: 90,000 ÷ 1,000,000 × 0.6 = 0.054
    3. Total: 0.114

    If all of it were processed as ordinary input, it would be 0.6 billing units.

    These numbers only illustrate the calculation method, do not correspond to any actual service pricing, and do not include output or the initial cache establishment cost.

    3.3 For multi-turn scenarios, calculate cumulative savings

    The first request usually has no existing cache to read and may incur a cache write cost. What really matters is the cumulative cost of a group of requests:

    1. Cumulative savings =
    2. cost if everything were processed as ordinary input
    3. - actual total cost of ordinary input, cache writes, and cache reads

    When the stable content is large enough and repeated calls are frequent enough, caching is more likely to pay off. If the content is used only once, or the next call happens after the cache has expired, the optimization value may be limited.

    4. Check Cache Configuration Along the Request Chain

    4.1 Client: being able to fill in a config does not mean it can send it

    Some clients mainly expose the model identifier, endpoint address, authentication info, and API type, and may not support passing the full set of server-side extended capabilities.

    You should focus on confirming:

    • Whether it supports the relevant cache configuration;
    • Whether it allows setting the cache boundary or other necessary options;
    • Whether it filters out unknown fields;
    • Whether it reassembles structured content into plain text;
    • Whether it inserts dynamic information before the system prompt;
    • Whether it can read and display cache usage.

    If the client lacks the relevant support, usually just changing the endpoint address will not solve the problem.

    4.2 Protocol conversion: core messages may be compatible, extended capabilities may not

    A gateway can convert one request format into another, but this conversion does not necessarily preserve all semantics.

    For example, structured content passed in by the client may be merged during conversion, and the original content boundaries change; some extended fields may also be ignored.

    When troubleshooting, you cannot look only at the configuration on the client UI. A more reliable approach is to inspect the actual request being sent, the fields the gateway explicitly supports, and the usage info returned by the service. When necessary, use a controlled small test program that bypasses the complex application to determine whether the problem is on the application side or in the access chain.

    4.3 Routing strategy: lowest unit price is not lowest actual cost

    “Price-first routing” usually just selects among candidate backends and is not the same as enabling caching.

    If consecutive requests are assigned to different backends and the cache cannot be shared across backends, the cache established in the previous turn may not be readable in the next.

    Given that the API provides the relevant capability, you can consider:

    • Choosing a backend that explicitly supports prompt caching;
    • Keeping routing conditions stable during the validation phase;
    • Observing whether failed retries change the backend;
    • Comparing cache capability, success rate, and total cost together, rather than only the listed price.

    Do not assume all gateways support fixed routing, and do not assume all backends use the same caching mechanism.

    5. Adjust Context Layout to Increase the Reusable Ratio

    5.1 Put stable content first

    Content suitable for the stable region usually includes:

    • Long-term unchanged system constraints;
    • Fixed tool definitions;
    • Fixed output specifications;
    • Material shared across multiple turns;
    • Confirmed history messages that will not change in the short term.

    The current question, real-time query results, and temporary task state should be placed toward the back as much as possible.

    This layout not only helps caching but also makes the context easier to maintain: the boundary between common configuration and real-time information becomes clearer.

    5.2 Eliminate unnecessary dynamic changes

    The following details can all affect prefix stability:

    • Timestamps updated on every request;
    • Randomly generated tracking identifiers;
    • Changes in tool definition order;
    • Changes in document fragment ordering;
    • Changes in spaces, line breaks, or formatting;
    • Temporary debug notes inserted at the beginning.

    You can reduce meaningless variation by fixing the ordering, unifying serialization rules, and versioning system prompts. Real-time information that the business genuinely needs should not be deleted, but should be moved to the dynamic region when conditions allow.

    5.3 Handle multi-turn appending and history compression separately

    Appending new messages usually does not change existing content, but rewriting a history summary, deleting early messages, or adjusting tool definitions changes the caching basis.

    So context compression can be given a clear trigger threshold rather than regenerating the summary every turn. Once the threshold is reached, compress all at once and treat it as a cache rebuild event.

    However, do not retain history indefinitely just to maintain the hit rate. Caching only reduces the partial cost of repeated input; it does not solve context window limits, irrelevant information interference, or output costs.

    6. Use a Minimal Experiment to Confirm Caching Really Works

    Step 1: Establish a controlled baseline

    Prepare a fixed prefix that meets the service’s requirements, then append a short question. Fix the model, routing conditions, and output length limit, and record:

    • Input and output usage;
    • Cache write and read usage, if the service provides it;
    • Request cost;
    • First-response wait time;
    • Request identifier and actual backend info, if available.

    The first request is mainly for establishing a baseline and should not be expected to show cache reads immediately.

    Step 2: Repeat the stable prefix within the validity period

    Keep the prefix unchanged, modify only the question at the end, and run several consecutive requests.

    Observe whether cache read usage appears and whether the ordinary input cost drops. Changes in response speed can serve as supporting information but cannot alone prove a hit, because network, queuing, and service load also affect latency.

    Step 3: Set up a control group

    Actively modify a small segment at the beginning of the prefix, then run the request. If the read volume drops noticeably, it supports the judgment that “the stable prefix is being reused.”

    Also test different wait intervals to confirm the impact of the actual cache validity period on your workload.

    Step 4: Retest in the real application

    After the minimal experiment succeeds, add tool definitions, history messages, and dynamic material. If the hit situation gets worse, add variables one by one to locate the cause rather than restoring all the complex configuration at once.

    If the service does not return a breakdown of cache usage, you can only infer from the bill and controlled experiments, and the conclusion should retain uncertainty.

    7. Set Up Continuous Monitoring So Optimization Does Not Stop at One Test

    It is recommended to record three types of metrics:

    Usage metrics: ordinary input, cache reads, cache writes, output volume, and the statistical definition of each field.

    Chain metrics: model, backend, retry count, request status, and route changes.

    Cost metrics: cost per request, total cost per task, cost per unit of new input, and the cost difference between cold start and steady state.

    The cache read ratio can be observed as follows:

    1. Cache read ratio = cache read tokens ÷ total input tokens

    This formula only applies to a statistical definition where total input volume includes cache reads. If the API defines it differently, unify the definition first before calculating.

    Logs should prioritize storing usage, configuration version, and statistical info, and avoid directly recording full sensitive prompts, authentication credentials, or user data. Cache-related logs also need to comply with the application’s access control and retention policies.

    8. Common Misconceptions and Final Implementation Recommendations

    Misconception 1: After a cache hit, the total cost must drop significantly.
    If output cost makes up a large share, the total bill reduction from input caching may be limited.

    Misconception 2: If the first request does not hit, the configuration failed.
    The first call is usually for establishing the cache; focus on subsequent requests.

    Misconception 3: Choosing the lowest-price route gets you the lowest cost.
    Frequent backend switching may break cache reuse, and the final cost may not be lower.

    Misconception 4: Resending the same document always hits.
    You also need to meet conditions like length, prefix consistency, validity period, and API support.

    Misconception 5: More caching is always better, and the context no longer needs trimming.
    Low-priced input still incurs cost and takes up context space. Cache optimization should be used together with retrieval, summarization, output control, and staged task execution.

    In practice, you can proceed in this order: verify billing rules → confirm client pass-through → check gateway compatibility → stabilize the request prefix → run controlled tests → monitor cumulative cost.

    The ultimate basis for judging whether the optimization succeeded is not that the UI shows it enabled, nor that the model returns normally, but that under the same business quality requirements, repeated requests have verifiable cache-read evidence and the cumulative cost of the complete task genuinely drops.