Prompt Caching and Input Billing Optimization for LLMs: A Practical Guide

    This guide explains how cache-hit input pricing works in model-as-a-service platforms and how to reduce per-request cost without changing output pricing. It breaks a request into three token categories (missed input, cache-hit input, and output), shows how savings scale with cached tokens, and lays out how to structure prompts so long, stable prefixes actually hit the cache. It also covers regional pricing differences, architecture and traffic governance, retries and streaming, observability and budgeting, key risks, and a step-by-step rollout. The goal is to treat caching as a lever that only pays off when prefixes are stable, long enough, and consistent across region and model version.

    Model-as-a-service delivers large-model capabilities to applications through metered, on-demand calls. Beyond model quality, the billing structure directly determines whether a workload can scale sustainably over the long term. A common industry practice is to split a single request into separately priced input and output, and to further distinguish “cache-hit input” from “uncached input that requires full processing.” When the cache-hit portion is billed at a rate clearly below the standard input price while other prices stay unchanged, workloads with heavy repeated context can often lower their per-request cost significantly without altering the output-side pricing logic.

    First, Separate the Three Token Categories

    A single inference request typically contains a system prompt, conversation history, retrieved documents, the current user question, and the model’s generated answer. For cost accounting, it helps to break this into at least three categories:

    • Missed input: content sent for the first time in this request that could not reuse an already-cached prefix, billed at the full input rate.
    • Cache-hit input: a prefix shared with earlier requests and confirmed as reusable by the service side, billed at the discounted input rate.
    • Output: newly generated content by the model, generally not discounted because of input caching.

    The discount applies only to the portion of input that is “confirmed as a hit.” If the prompt rewrites the prefix every time, injects a dynamic timestamp, or places volatile fields at the very front of a long context, the cache becomes hard to hit and the bill stays close to the full input price. So the prerequisite for cost reduction is not “fewer calls,” but “a reusable prefix that is long enough and stable enough.”

    What Cache Hits Actually Solve

    The prompts in many enterprise applications are not new down to every character. A customer-service bot’s role definition, compliance clauses, and tool descriptions; a coding assistant’s repository conventions; the same set of policy documents in a knowledge Q&A system—all of these recur across large numbers of requests. If the service side reuses the inference state for an identical prefix, it can cut repeated prefill computation and reflect that saving in the price of cache-hit input.

    The boundaries matter too. Caching is not permanent free storage, nor does it guarantee that arbitrary text will hit. Common limitations include: caches have a time-to-live; they apply only to prefixes that meet a minimum length threshold; a change in region, model version, or routing policy requires rebuilding the cache; dynamic concatenation and randomized phrasing lower the hit rate. Output length, tool-call rounds, and failed retries are still billed under the original rules. When evaluating, replay real traffic rather than extrapolating a full month’s cost from a single demo request.

    How the Billing Change Affects Your Bill

    Let the missed-input rate be Pi, the cache-hit input rate be Pc, and the output rate be Po. When the provider announces that cache-hit input is adjusted to a certain proportion of the original input price while other prices stay unchanged, the cost of a single request can be written as:

    cost ≈ missed_input × Pi + hit_input × Pc + output × Po

    If Pc is clearly lower than Pi, the savings are roughly hit_input × (Pi − Pc). Savings are proportional to the number of hit tokens and have no direct relation to output length. Tasks with long outputs and short prefixes save little; tasks with long system prompts, multi-turn shared history, or batch-repeated context are more sensitive. The regional dimension must be accounted for separately: if a price adjustment covers only specific regions, cross-region failover or nearest-access routing will send traffic to unadjusted regions, and the average unit price will not drop.

    An illustrative estimate does not need to be tied to any vendor console—usage logs are enough:

    1. def estimate(miss_in, hit_in, out, pi, pc, po):
    2. return miss_in * pi + hit_in * pc + out * po
    3. # After replaying a batch of requests, compare pc = pi with pc = pi * ratio
    4. base = estimate(miss, hit, out, pi, pi, po)
    5. new = estimate(miss, hit, out, pi, pi * ratio, po)
    6. saving_rate = (base - new) / base if base else 0

    Before launch, measure the share of hit input in total input, the proportion of hit requests, and the average length of cached prefixes. When the ratio is very low, the price change barely moves the bill, and the optimization focus should return to prompt structure rather than waiting for the unit price itself to drop.

    Making the Prefix Truly Reusable

    What is reusable is the portion that is “continuously identical from the beginning,” not any repeated passage within the text. In practice:

    1. Put stable segments first. Place rarely changing content—model role, output format, safety policy, tool definitions—at the front, and control it with versioned releases. Avoid writing meaningless whitespace, timestamps, or random seeds into the prefix.
    2. Put semi-stable segments in the middle. Place confirmed history from multi-turn conversations and documents retrieved this round that will be reused in the short term after the stable segment. Each round should only append; do not rewrite already-sent content in the middle.
    3. Put volatile segments last. Place the current user question, session ID, real-time inventory, and personalized recommendations at the end. This way the long prefix in front can still hit, and only the tail is billed as missed input.
    4. Control useless bloat. Piling on irrelevant text just to “pad the length” increases storage, latency, and the risk of a miss at the same time. The caching discount cannot offset meaningless tokens.
    5. Make version switches explicit. After a model version or major prompt-template version change, the old cache usually becomes invalid. The release window should reserve time for cache warm-up to avoid a simultaneous spike in cost and latency at the moment of the switch.

    In retrieval-augmented scenarios, do not stuff the full re-ranked text into the prefix every time. You can use chunk-level cache identifiers for a stable knowledge base and place only the short evidence relevant to the current question at the back. A coding assistant is better suited to caching project conventions and common dependency notes, leaving the current file diff at the tail of the request.

    Architecture and Traffic Governance

    On the application side, separate “prompt assembly” from “business data.” A template service generates the stable prefix and provides a template version number; the gateway records the three usage categories—input, hit, and output—by region and model version; the business service submits only the variables. This lets finance reconcile accounts and lets engineering pinpoint whether a hit-rate drop is caused by template jitter or a shift in traffic structure.

    Regional strategy must align with pricing strategy. If only certain regions offer the caching discount, core batch jobs can be scheduled to those regions, while latency-sensitive interactive requests can still use nearest access—but they must be listed separately in the cost model rather than hidden behind a single average. In multi-availability-zone failover, the cache is usually not shared across zones, so the first wave of requests after a switch falls back to full-price input, and capacity planning must include this transient cost.

    Retries and streaming also change the bill. If a timeout retry replays the entire prefix as-is, it may hit again and pay only for the unfinished output; but if the prompt is rewritten before the retry, it may pay twice for missed input. Streaming scenarios should be billed on the finally successful output tokens, and the client should avoid immediately replaying without backoff after a disconnect.

    Observability, Budgeting, and Risk

    At a minimum, monitor these metrics: cache hit rate (hit input / total input), proportion of hit requests, per-request input-to-output ratio, regional unit price, retry amplification factor, and the hit-rate gap before and after a template version change. Setting an alert for the hit rate falling below a threshold often surfaces problems earlier than watching the total amount alone.

    For budgeting, use a “baseline plus elastic” approach. The baseline covers the fixed prefix and routine Q&A; the elastic portion covers event peaks and long-output tasks. When only the cache-hit input price is adjusted, do not budget all input at the discounted rate for the whole year, or hit-rate fluctuations will blow through the quota. For tasks whose output price is unchanged, still control total cost by capping maximum generation length and constraining the number of tool-loop iterations.

    The main risks include: compliance review before writing sensitive data into a long-lived cache; whether cross-tenant isolation is guaranteed by the platform; latency rebound caused by cache expiry; and prompt injection amplifying cost through an overlong prefix. Technically, minimize the personal information that enters the prefix, periodically rotate templates containing keys or internal paths, and set a per-request token limit at the gateway.

    Rollout Steps

    Step one: extract one week of real requests from call logs, cluster them by template, and compute the potential reusable prefix length. Step two: restructure the template order to put stable content first, and validate the hit rate with a small amount of shadow traffic rather than switching all production traffic at once. Step three: recompute the bill by “missed, hit, output,” and expand traffic only to scenarios whose hit rate is stably above the threshold. Step four: bring the template version, region, and model version into the change ticket to avoid unnoticed rewrites that break the cache. Step five: review monthly whether the savings come from an improved hit rate or merely from a drop in call volume, to avoid misattribution.

    Discounted cache-hit input is a lever, not an automatic cost-reduction switch. The lever works only when the prefix is stable, long enough, and consistent across region and version, and when output and retries are still governed separately. By splitting the billing, layering the prompt, and making usage observability request-level, teams can push the cost of repeated context into a reasonable range without sacrificing quality. The general billing and monitoring capabilities in model-as-a-service offerings such as Baidu AI Cloud are suitable as a承载 layer for usage aggregation and budget alerts; the specific unit prices, cache TTLs, and hit rules should still follow the provider’s current public documentation, and one should not extrapolate a particular ratio to all models and all regions based on experience.