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

    As LLM providers cut input, output, and cached-input prices, monthly bills often stay flat because cost depends on the token mix rather than unit price. This guide breaks a single call into its cost variables, explains how prefix-based prompt caching can be engineered through stable, semi-stable, and dynamic layers, and shows how to measure cost per completed task on your own sample set to find the quality-cost inflection point. It also covers tiered model routing, output and retry controls, per-business-line usage attribution, and common optimization mistakes. The approach is vendor-neutral and can be combined with general cloud capabilities from Baidu AI Cloud.

    1. Where the Problem Starts: Lower Unit Prices, Unchanged Bills

    Once LLMs move into engineering production, the discussion shifts from “can we use this” to “can we afford this.” A common pattern: a vendor announces a new price cut, input and output rates both drop, cached input drops even further, yet the monthly bill on the finance side barely moves. The reason is simple—unit price is only a coefficient in the pricing formula. What actually determines the amount is the quantity structure of each token type.

    The pricing shape in the source material is representative: a flagship-tier model charges $8 per million input tokens, $0.4 per million cached input tokens, and $40 per million output tokens. Compared with the previous generation, input and output each fell by roughly 20%, while cached input dropped from $1 to $0.4, about a 60% reduction. A mid-tier model keeps the same structure—$2 input, $0.1 cached input, $10 output—with better capability at an unchanged price. The material also notes that the pricing is identical to another recently released model, showing that top-tier model prices are converging into the same range.

    Two conclusions matter here. First, the sharp cut in cached-input pricing essentially removes “repeated context” from full-rate billing, and the benefit depends entirely on the hit rate. Second, vendors have shifted the comparison from unit price to “the cost of completing a task,” a two-dimensional curve of usability against spend. If engineering teams still make decisions on unit price alone, they will systematically misjudge.

    2. Breaking the Bill into Optimizable Variables

    The cost of a single call can be abstracted as:

    1. cost per call = (input tokens × input rate)
    2. + (cached-hit tokens × cache rate)
    3. + (uncached input tokens × input rate)
    4. + (output tokens × output rate)

    The first three variables are determined by how the request is constructed; the fourth is determined by task shape and generation strategy. The optimization space concentrates in three places: raising the cache hit rate, compressing uncached input, and controlling output length and retry count.

    It is worth stressing that caching does not take effect unconditionally. Common industry implementations require an exact prefix match—byte-for-byte identical from the start of the prompt through the reusable portion. Any change anywhere invalidates the entire prefix. This means putting timestamps, random IDs, or user nicknames at the beginning of the system prompt is the biggest killer of hit rate.

    3. Cache Hit Rate: From “Occasional” to “Designed”

    Moving dynamic content to the end is the highest-return step in cost optimization. The recommended prompt structure is:

    1. [stable layer] role definition, output format constraints, glossary, a few fixed examples
    2. [semi-stable layer] retrieved document fragments, code repository context
    3. [dynamic layer] user question, timestamp, session ID, random values

    Supporting engineering constraints include: put the stable layer under version control and change it through a release process rather than hot edits; fix the ordering rules for retrieved fragments so the same question does not return results in a different order twice; unify serialization to avoid byte drift from floating-point, whitespace, or key-order differences.

    Illustrative hit-rate reporting logic:

    1. def report(usage):
    2. total_in = usage.prompt_tokens
    3. cached = getattr(usage, "cached_tokens", 0)
    4. hit = cached / total_in if total_in else 0
    5. print(f"cache hit rate={hit:.2%} uncached={total_in - cached}")
    6. return hit

    Hit rate should be observed per business line. In practice, scenarios with long system prompts, fixed knowledge bases, and batched similar requests see the highest hit rates; highly personalized short conversations can barely benefit, and this kind of traffic is better served by lower- or mid-tier models.

    4. Rebuilding Evaluation Around “Cost per Task”

    The right way to evaluate is not to compare unit prices but to fix a task set and measure “the spend required to reach the target quality.” The executable steps are:

    1. Build 50–200 real business samples covering typical, boundary, and failure-recovery scenarios;
    2. Define an automatically checkable pass criterion for each sample, such as field completeness, format compliance, or unit test pass rate;
    3. Run in batch across multiple capability tiers and multiple prompt strategies, recording quality scores and total spend;
    4. Plot the “quality score—cost per task” curve and find the inflection point rather than the lowest-price point.

    The curve usually shows clear diminishing returns: switching from a low-tier to a mid-tier model yields a significant quality gain for a limited cost increase; switching from mid-tier to flagship narrows the quality gain while cost rises severalfold. The inflection point varies by task, so evaluation must be based on your own samples; public leaderboards serve only as an initial screen.

    5. Tiered Routing and Engineering Implementation

    Turning evaluation conclusions into a routing policy is the key to long-term cost control:

    1. intent classification → simple tasks (extraction/rewrite/classification) → low-tier model
    2. → medium tasks (structured generation/multi-turn Q&A) → mid-tier model
    3. → complex tasks (long-chain reasoning/code repair) → flagship model
    4. → low-confidence results → automatic upgrade and retry

    Supporting measures include: set output limits and prefer structured formats to reduce redundant generation; classify failed requests to avoid meaningless retries inflating the bill; connect logs, metrics, and alerts to general cloud capabilities (log service, monitoring and alerting, message queues, object storage) and aggregate token usage by business line; set budget thresholds and degradation switches so that, when limits are exceeded, traffic can automatically fall back to a lower tier or be queued to smooth peaks.

    6. Common Mistakes

    • Choosing models from the unit price table alone while ignoring that output tokens are often the main cost item;
    • Assuming caching takes effect automatically without governing prefix consistency;
    • Using public leaderboards instead of your own samples for evaluation, leading to a biased inflection-point judgment;
    • Optimizing only the prompt without governing retries and overly long outputs;
    • Lacking per-business-line usage attribution, making cost anomalies impossible to locate.

    7. Conclusion

    The signal from the latest round of model price cuts is clear: the focus of competition has moved from “how much per million tokens” to “how much to get one thing done.” For developers, the sustainable approach is to treat cost as a designed engineering variable—govern the prompt prefix to improve cache hits, use your own samples to locate the quality inflection point, and then apply tiered routing to direct budget precisely to the steps that genuinely need high capability. This method does not depend on any vendor’s proprietary interface, is reusable across mainstream LLM services, and can be combined with general cloud capabilities from Baidu AI Cloud.