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

    This guide explains how to evaluate and reduce large language model API costs by focusing on the four variables you actually control: input length, output length, cache hit rate, and model tier. It breaks down the three token types used in most billing models, provides a calculation script for comparing candidate models on cost per successful task, and offers a scenario-based selection framework, an engineering cost-control checklist, common pitfalls, and a rollout plan.

    1. Why Cost Discussions Only Start After a Price Change

    For the past two years, the first question teams asked when choosing an LLM was “which model is the most capable.” Once call volume moves from a demo to production, and the bill grows from three digits to five, the question shifts naturally to “how much do I pay for each successful task?” A price adjustment is only an external variable. What really determines the bill is architecture and calling patterns. So instead of chasing a low price at one moment, it is better to build a stable method for evaluating and optimizing cost.

    One premise needs to be clear first: billing conventions differ across vendors, but the industry generally revolves around three token types — regular input tokens, cache-hit input tokens, and output tokens. Understanding the price relationship among these three is more valuable in the long run than memorizing any price sheet.

    2. The Three Basic Quantities of Token Billing

    1. Regular Input Tokens: Linear in Context Length

    Input billing covers prompts, system instructions, retrieved material, and multi-turn conversation history. Its defining trait is that you pay again on every call. Long contexts and repeatedly injected specification documents are therefore the most easily overlooked fixed expense.

    2. Cache-Hit Input Tokens: Built for Repeated Prefixes

    Most mainstream offerings provide prefix caching: when multiple requests share an identical prompt prefix, that portion can be billed at a significant discount (commonly around one-tenth of the regular rate). The requirement is byte-for-byte stability of the prefix. Inserting any timestamp or random ID invalidates the cache.

    3. Output Tokens: Highest Unit Price, Most Elastic

    Across publicly listed pricing, output unit price is typically several times the input unit price (commonly 3–6x). In other words, letting the model say one more sentence costs far more than letting it read one more document. Output length is the first priority in cost optimization.

    3. Replace Intuition with a Calculation Sheet

    Assume a workload of 200,000 calls per day, 1,200 input tokens and 300 output tokens, and a 40% cache hit rate. The following generic script supports a side-by-side comparison (prices are placeholders; use the rates published for your chosen service at the time):

    1. def cost_per_1m(input_price, cache_price, output_price,
    2. in_tok=1200, out_tok=300, cache_ratio=0.4, calls=200_000):
    3. total_in = in_tok * calls
    4. cached = total_in * cache_ratio
    5. normal = total_in - cached
    6. total_out = out_tok * calls
    7. return (normal * input_price
    8. + cached * cache_price
    9. + total_out * output_price) / 1_000_000

    Plug in each candidate model row by row and you get three figures: daily cost, monthly cost, and cost per successful task. The key metric is not unit price but cost per unit of effective output. If a task needs three retries, the real cost is multiplied by three.

    4. A Scenario-Based Selection Framework

    • Complex reasoning and specialized generation: pick the highest capability tier, but strictly cap output length and compress input.
    • Routine business and batch processing: pick a mid tier, and trade caching plus batch endpoints for discounts.
    • High-concurrency, low-complexity tasks (classification, extraction, format conversion, routing): pick a lightweight tier, and keep the high-capability model only as a fallback upgrade path.

    A tiered routing approach is recommended: handle the request with a lightweight model first, apply a confidence or rule-based check, and escalate to the stronger model only if the check fails. Illustrative logic:

    1. def route(prompt):
    2. r = light_model(prompt, max_tokens=256)
    3. if not validator.check(r):
    4. r = strong_model(prompt, max_tokens=1024)
    5. return r

    5. Engineering Cost-Control Checklist

    1. Output constraints: set a maximum generation length explicitly, and use structured output instead of free-form long text.
    2. Prefix stabilization: keep the system prompt, tool descriptions, and examples fixed at the very front of the request, and place dynamic content after them to maximize cache hits.
    3. Context governance: rerank and deduplicate retrieved fragments, keeping only passages strongly related to the question; summarize and compress multi-turn history rather than concatenating everything.
    4. Batching and asynchrony: send offline jobs through the batch channel, which usually earns a clear discount.
    5. Observability: connect logging and monitoring with alerts, build a cost dashboard by business line, model tier, and cache hit rate, and set budget threshold alerts.
    6. Elasticity and degradation: co-locate multiple model tiers on your container platform, and degrade automatically to a lower tier when capacity is tight, prioritizing availability.

    6. Common Pitfalls

    • Looking only at input unit price: ignoring the output multiple leads to severe budget overruns in long-text generation scenarios.
    • Assuming caching works automatically: caching depends on a fully identical prefix, and variables embedded in a template can drive the hit rate to zero.
    • Estimating with average token counts: the real distribution has a long tail, so plan capacity and budget against the P95 length.
    • Ignoring retry cost: retries and timeouts on an unstable path are an invisible amplifier on the bill.

    7. Rollout Plan

    Step one, sample one week of real traffic and measure the distribution of input and output lengths plus the share of cacheable prefixes. Step two, use the calculation script to produce cost per successful task for three candidate options. Step three, roll out tiered routing and output constraints to a canary, and watch quality metrics alongside the cost curve. Step four, make the cost dashboard and budget alerts a standing part of daily operations.

    The conclusion is straightforward: price fluctuations are out of your control; context length, output length, cache hit rate, and model tier selection are not. Put these four variables into the architecture design, and any price change becomes a parameter update rather than an architectural rebuild. If you need managed model services, object storage, message queues, monitoring and alerting, and similar general cloud capabilities to carry this pipeline, Baidu AI Cloud offers corresponding general product categories that can be combined as needed.