LLM Inference Cost Optimization: A Practical Guide to Token Pricing and Context Caching

    This article breaks down how large language model inference costs are structured across input tokens, output tokens, and context caching, and explains why input and output are priced separately. It covers how cache hits and cache writes are billed, how to calculate the minimum number of hits needed to break even, the trade-offs between short-lived and long-lived retention and accelerated tiers, and a reusable cost estimation template. A practical engineering checklist for reducing costs without sacrificing quality is also included.

    1. Why Inference Costs Need to Be Understood Structurally

    When enterprise applications integrate large language models, cost is often the most underestimated factor. Many teams focus only on “getting it working” during the prototype stage, and only when traffic grows and contexts get longer does the bill become a bottleneck. To truly control costs, the first step is to abandon the intuition of “estimating by number of calls” and instead break cost down into parts that can be observed and optimized independently.

    In common industry billing practices, the cost of a single inference request is typically made up of three types of tokens: input tokens, output tokens, and the hit and write behavior generated around context caching. These three are not a simple linear sum; each corresponds to a different resource consumption profile:

    • The input side corresponds to the computation and memory bandwidth pressure of the prefill stage, and long contexts significantly amplify this cost;
    • The output side corresponds to token-by-token autoregressive generation, where latency and throughput directly determine unit cost;
    • The cache side converts “repeated computation” into “storage and reuse,” trading one write for multiple low-cost hits.

    Understanding this layering is the prerequisite for all subsequent optimization actions.

    2. Why Input and Output Are Priced Separately

    A common question is: why is the input price several times lower than the output price? This is not an arbitrary pricing decision, but is determined by computational characteristics.

    The prefill stage can be highly parallelized, with high hardware utilization; the decoding stage is serial, where generating each token requires a full forward pass through the model and continuously reads a growing key-value cache, with memory access overhead rising as context length increases. Therefore, the marginal cost of output tokens is naturally higher than that of input tokens. In public pricing systems, an output unit price around five times the input unit price is a fairly common range.

    The direct takeaway for developers is: controlling output length often reduces costs more immediately than compressing input. A verbose system prompt, asking the model to “think at length before giving a conclusion,” and the lack of explicit output format constraints can all cause output tokens to spiral out of control.

    A reusable example of an output constraint:

    1. Role: You are a code review assistant.
    2. Task: Output only a list of issues, each containing [Location] [Risk Level] [Suggested Fix].
    3. Constraint: No more than 5 items in total, no more than 40 words per item, no explanatory preamble.

    3. Context Caching: Turning Repeated Prefixes into an Asset

    Multi-turn conversations, fixed system prompts, repeated Q&A over long documents, and batch structured extraction all share one thing: the request prefix is highly repetitive. Without a caching mechanism, every request has to redo the prefill for the same prefix, and this compute is repeatedly wasted.

    The idea behind context caching is to persist the intermediate state corresponding to the prefix, so that subsequent requests with an identical prefix can reuse it directly and only compute the new portion incrementally. In billing, this is usually reflected in two tiers:

    • Cache hit: the unit price is far lower than a regular input, commonly around one-tenth of the input price;
    • Cache write: the first write incurs an additional cost, tiered by retention duration, with short periods (such as minutes) and long periods (such as an hour) priced differently; the longer the retention, the more expensive the write.

    From this we can derive a key conclusion: the economics of caching depend entirely on how well the number of reuses matches the retention window. If a prefix is used only once, the write is a net loss; if it can be hit more than twice within the retention window, it has usually already crossed the break-even point.

    A rough break-even judgment can be written as:

    1. Let input unit price = P_in, hit unit price = P_hit, short-period write unit price = P_write
    2. Savings per request ≈ P_in - P_hit
    3. Minimum required hits N ≈ P_write / (P_in - P_hit)

    Under the common structure where the hit price is about 10% of the input price and the short-period write price equals the input price, N is about 1.1, meaning as long as it is reused more than once within the same window, caching is already worthwhile.

    4. Choosing Between Tiered Retention and the Accelerated Tier

    The appearance of both short-period and long-period write tiers in the price list corresponds to different business rhythms: short periods suit continuous follow-up questions within a single session; long periods suit stable prefixes across turns and requests, such as fixed domain knowledge descriptions or long documents.

    Another common design is an “accelerated tier” version, whose input and output unit prices are about twice those of the standard version, while the cache hit price stays the same. This means the economics of the accelerated tier rest entirely on a “high hit rate”: when there are enough hits, the overall cost is diluted; once the hit rate drops, the bill can quickly double. Therefore, before choosing the accelerated version, you must first measure the prefix hit rate with real traffic rather than enabling it based on intuition.

    5. An Actionable Template for Cost Estimation

    Teams are advised to build a minimal usable estimation table with fields including: average input length, average output length, prefix reuse rate, cache retention window, and daily request volume. The calculation order is:

    1. Use the prefix reuse rate to split “cacheable input” from “regular input”;
    2. Use the minimum required hits to decide whether writing is worthwhile;
    3. Sum the four items—input, output, hit, and write—to get the daily cost;
    4. Run a sensitivity analysis on output length and hit rate to find the most sensitive item and prioritize it.

    Illustrative pseudocode:

    1. def estimate(reqs, in_len, out_len, reuse, p_in, p_out, p_hit, p_write):
    2. cacheable = in_len * reuse
    3. normal_in = in_len - cacheable
    4. hit_cost = cacheable * p_hit
    5. write_cost = cacheable * p_write / max(reuse, 1)
    6. return reqs * (normal_in * p_in + hit_cost + write_cost + out_len * p_out)

    6. An Engineering Checklist for Reducing Costs

    • Stable prefix layout: put the system prompt, tool descriptions, and fixed examples at the front, and variable content at the back, to avoid the prefix being “polluted” and invalidating the cache;
    • Precise history truncation: trim conversation history by token budget rather than by message count, to prevent uncontrolled context growth;
    • Structured output constraints: replace “please be as detailed as possible” with format and length limits;
    • Tiered model routing: send simple tasks to lightweight configurations and only escalate to heavier ones for complex reasoning, avoiding full high-spec usage;
    • Observability first: integrate logging services and monitoring alerts, and build dashboards and threshold alerts for token usage, hit rate, and cost per request;
    • Elastic capacity: run stateless inference services on a container platform, combined with a message queue to smooth peaks, avoiding paying for peak capacity year-round.

    7. Conclusion

    The essence of inference cost governance is turning the bill from a “black box” into “attributable line items.” Once input, output, cache hits, and cache writes are measured separately, optimization has a clear handle: reduce output, stabilize prefixes, improve hit rates, and choose the right retention window. This approach does not depend on any vendor’s proprietary interface and can be applied across mainstream LLM service offerings, helping teams push the cost per call into a reasonable range without changing quality.