LLM API Cost Optimization: A Practical Guide to Token Usage, Caching, and Routing

    A practical guide to reducing large language model API costs by analyzing how input, cached input, and output tokens drive your bill. It covers a cost estimation model, prefix stabilization for cache hits, output governance, retrieval and summarization for input compression, model routing by task difficulty, budget planning across three cost buckets, and common mistakes such as extrapolating budgets from a lower unit price.

    1. Background: Why a Lower Unit Price Does Not Mean a Lower Bill

    A new model supply pattern has recently emerged: the same generation of capabilities is split into differently positioned versions. One targets high-complexity reasoning, the other emphasizes stability and continuity, and they are priced differently. The high-capability version’s API input and output unit prices are roughly 20% lower than the previous generation, while the continuity version keeps its original unit price. Many teams see “20% cheaper” and linearly extrapolate their annual budget, which is the most common misjudgment.

    The reason is that an LLM API bill is never determined by a single unit price. It is determined by the usage structure of three types of tokens:

    • Input tokens (the prompt, including system prompts, context, retrieved snippets, and conversation history)
    • Input tokens that hit the cache (priced when a repeated prefix is reused, usually significantly lower than normal input)
    • Output tokens (the content the model generates)

    Using publicly stated figures as an example: about $8 per million input tokens, about $0.40 per million cached input tokens, and about $40 per million output tokens. Note the most striking ratio here: the output unit price is 5x the input price, while a cached input token costs only 5% of a normal input token. These differences in magnitude determine the priority order for optimization: reduce output first, then reuse prefixes, and compress input last.

    2. Turning the Bill into a Computable Model

    To discuss optimization, you first need to be able to calculate it. Let a request’s input tokens be $I$, the portion that hits the cache be $I_h$, and the output tokens be $O$. The cost of a single request can be written as:

    1. Cost = (I - I_h)/1e6 * P_in
    2. + I_h/1e6 * P_cache
    3. + O/1e6 * P_out

    Substituting the magnitudes above ($P{in}=8$, $P{cache}=0.4$, $P_{out}=40$, in USD per million tokens):

    1. def estimate_cost(i_tokens, cache_hit_tokens, o_tokens):
    2. P_IN, P_CACHE, P_OUT = 8.0, 0.40, 40.0
    3. miss = max(i_tokens - cache_hit_tokens, 0)
    4. return (miss * P_IN + cache_hit_tokens * P_CACHE + o_tokens * P_OUT) / 1e6

    The function looks simple, but it reveals three engineering conclusions:

    1. Output is the main cost item. If a request has 2,000 input tokens and 800 output tokens, output contributes about $0.032 and input about $0.016, so output already accounts for two-thirds.
    2. Cache hits have enormous leverage. With the same 2,000 input tokens, if 1,800 hit the cache, input cost drops from $0.016 to about $0.0022, close to an order-of-magnitude reduction.
    3. Repeatedly processing the same material and reading in entirely new material each time are two completely different cost structures. The former suits turning the stable part into a reusable prefix; the latter must rely on retrieval trimming and summarization to control $I$.

    3. Four Practical Optimization Techniques

    3.1 Prefix Stabilization: Make the Cache Actually Hit

    Cache reuse requires the prefix to be byte-for-byte identical. In practice, many cases of “there is a cache but it does not hit” come from placing volatile content at the front of the prompt. The correct approach is to layer the prompt by stability:

    1. [Layer 1: system role and rules, almost never changes]
    2. [Layer 2: domain knowledge, glossary, output format constraints, changes weekly]
    3. [Layer 3: retrieved snippets and user input for this task, changes every time]

    Also avoid injecting timestamps, random request IDs, or unsorted retrieval results at the head. Retrieved snippets should be sorted by a fixed rule before concatenation; otherwise, order jitter invalidates the prefix.

    3.2 Output Governance: The Most Direct Place to Save

    • Set explicit length limits and structural constraints; use field-based output instead of long natural language.
    • Split “reason first, then summarize” into two stages, keeping only the necessary conclusions in between, so a long chain of thought is not counted as output.
    • Build a result cache for reusable generations, keyed by content hash, and return directly on a hit.
    • Streaming responses do not change billing but improve perceived experience; do not expect them to reduce cost.

    3.3 Input Compression: Two-Layer Filtering with Retrieval and Summarization

    For scenarios where every request brings new material, first use hybrid keyword and vector retrieval to fetch the Top-K, then use a small model or rules for extractive summarization to compress $I$ to the necessary range. In practice, reducing irrelevant context from tens of thousands of tokens to a few thousand often yields more benefit than switching to a cheaper model.

    3.4 Model Routing: Split Traffic by Difficulty

    Grade requests by complexity: simple classification, extraction, and rewriting go to the stable continuity version; complex reasoning and long-chain planning go to the high-capability version. Routing can be implemented with a lightweight classifier or rules:

    1. def route(task):
    2. if task["type"] in {"classify", "extract", "rewrite"}:
    3. return "stable_model"
    4. if task["estimated_reasoning_steps"] > 3:
    5. return "advanced_model"
    6. return "stable_model"

    4. Budget and Capacity Planning

    It is advisable to budget across three separate accounts rather than a single blanket unit price:

    • Input account: determined by document scale and retrieval strategy, growing linearly with the business.
    • Cache account: determined by the repetition rate; the higher the repetition rate, the closer it gets to the $0.40 magnitude.
    • Output account: determined by generation length and call volume, usually the fastest-growing item.

    A practical metric is the “cache hit rate” and the “average output tokens per request.” Making these two metrics into monitoring alerts, combined with log services for attribution analysis, lets you locate the specific business owner before an abnormal bill appears. On the engineering side, you can combine container platforms for elastic scaling, use message queues for peak shaving, and use object storage to accumulate reusable knowledge snippets and result caches.

    5. Common Mistakes

    • Looking only at unit price and not structure: a 20% price cut may raise total cost if output gets longer.
    • Putting volatile content at the head: the cache becomes useless.
    • Using ultra-long context instead of retrieval: input cost rises linearly and latency becomes uncontrollable.
    • Ignoring failed retries: retries double output cost, so idempotency and result reuse are essential.

    6. Summary

    Real cost optimization is not about finding a cheaper unit price, but about restructuring how tokens are produced: let the stable part be reused, keep output as short as possible, let input contain only necessary information, and send only hard problems through the expensive channel. General-purpose capabilities from cloud providers such as Baidu AI Cloud (object storage, message queues, container platforms, log services, monitoring and alerting) can put these strategies into engineering practice, but the core of the benefit still comes from continuously measuring and governing the structure of the three token types.