LLM API Cost Optimization: Pricing, Caching, and Token Consumption

    This article explains why per-token pricing does not equal the actual bill for large language model APIs. It covers four billing categories, a cost formula and illustrative calculation, unit-task cost evaluation, a reusable Python script, six engineering techniques for cost reduction, and common pitfalls, helping readers build an end-to-end cost accounting and optimization baseline.

    1. Correct an Intuition First: Unit Price Is Not the Bill

    When evaluating the cost-effectiveness of large language model APIs, the most common mistake is to compare only the two numbers “input/output per million tokens.” The actual bill is determined by four types of billable behavior that occur in a single call, and their unit prices often differ by an order of magnitude:

    Billing item Trigger condition Relative unit price magnitude (illustrative)
    Input (cache miss) Context appearing for the first time in a request Baseline
    Output Tokens generated by the model Usually several times the input price
    Cache read Prefix exactly matches cached content Significantly lower than input
    Cache write First write or rebuild after cache expiry Generally slightly higher than input

    The key point is that in long-context, multi-turn iterative, and agent-style workloads, cache-read tokens often account for more than 70% of total tokens. Therefore, even if the cache-read unit price is only one-tenth of the input unit price, its contribution to total cost may equal or even exceed that of the input item. A plan that sets cache reads too high (close to the input price) will make “seemingly reasonable input/output pricing” quickly spiral out of control under real workloads.

    2. Write Cost as a Formula, Not a Feeling

    Assume that in one session: cache-miss input is $T{in}$, output is $T{out}$, cache read is $T{cr}$, and cache write is $T{cw}$, with corresponding unit prices $p{in},p{out},p{cr},p{cw}$ (unit: per million tokens). Then the cost of a single call is:

    1. cost = (T_in * p_in + T_out * p_out + T_cr * p_cr + T_cw * p_cw) / 1e6

    Use a set of purely illustrative assumptions to show the difference in leverage: let $p{in}=8$, $p{out}=40$, and $p{cr}=0.4$. For a task round with $T{in}=0.05M$, $T{out}=0.02M$, and $T{cr}=1.2M$, the cost is approximately $0.4+0.8+0.48=1.68$ USD. If $p_{cr}$ for the same workload becomes $1.0$, only the cache item rises from 0.48 to 1.2, and total cost increases by about 43%, while input and output pricing remain unchanged. This is the quantitative meaning of “cache-read unit price is the main lever.”

    3. The Second Underestimated Variable: Tokens Required to Complete the Task

    Unit price is only a coefficient. What really determines the order of magnitude is the total number of tokens consumed to complete the same task. Two solutions may have similar unit prices, but if one requires more rounds of tool calls, longer intermediate reasoning, and more frequent context rebuilding, its total token count may be several times that of the other, and the bill gap will completely outweigh the unit-price difference.

    Therefore, the correct comparison metric is “cost per task,” not “price per token”:

    1. Cost per task = total spend / number of successfully completed tasks

    This requires that evaluation fix the task set and pass criteria, and persist the usage field (token counts for each billing item) for each call, rather than only checking whether the final result passes.

    4. Reusable Cost Measurement Script

    1. # Illustrative: calculate cost per task from real usage details
    2. PRICE = {"in": 8.0, "out": 40.0, "cache_read": 0.4, "cache_write": 8.8} # per million tokens
    3. def call_cost(u: dict) -> float:
    4. return sum(u.get(k, 0) * PRICE[k] for k in PRICE) / 1e6
    5. def report(records):
    6. total = sum(call_cost(r["usage"]) for r in records)
    7. ok = sum(1 for r in records if r["passed"])
    8. tokens = sum(sum(r["usage"].values()) for r in records)
    9. print(f"Total cost={total:.4f} Passed={ok}/{len(records)} "
    10. f"Cost per task={total/max(ok,1):.4f} Avg tokens={tokens/len(records):.0f}")

    With this report, model selection discussions move from subjective impressions to reproducible data comparisons.

    5. Six Engineering Cost-Reduction Techniques

    1. Stabilize the prompt prefix: Put system instructions, tool definitions, and few-shot examples at the very beginning and keep them byte-identical. This is a prerequisite for cache hits. Move volatile content such as timestamps and random IDs to later positions.
    2. Control context growth: Summarize and compress historical messages, use sliding windows, and retrieval-based recall to avoid resending the full history every turn.
    3. Tiered routing: Route simple intents to smaller models or rule-based branches, and escalate complex tasks. This reduces the share of high-cost tokens.
    4. Batch and async: Use batch channels for offline tasks, which usually provides better throughput cost.
    5. Budget guardrails: Set token and monetary limits for each session and each user. Degrade or circuit-break when limits are exceeded to prevent abnormal loops from burning quota.
    6. Observability: Send per-billing-item tokens, cache hit rate, and task success rate to logging services and monitoring alerts, and build cost dashboards and threshold alerts.

    6. Common Pitfall Checklist

    • Looking only at input/output unit prices and ignoring cache reads and cache writes;
    • Using “price per token” instead of “cost per task” for decisions;
    • Using a non-fixed evaluation set, which makes token consumption data incomparable;
    • Including volatile fields in the cache prefix, causing the hit rate to trend toward zero over time;
    • Launching without budget guardrails, allowing abnormal retries to amplify the bill.

    7. Conclusion

    Cost governance for model APIs is essentially upgrading from “unit-price comparison” to “end-to-end cost per task accounting”: first establish formulas and scripts based on the four billing categories, then use a fixed evaluation set to measure real token consumption and cache hit rate, and finally reduce cost to a predictable range through prefix stability, context compression, tiered routing, and budget guardrails. This method is vendor-agnostic and can be transferred to any model service that offers cache billing. When implemented on platforms such as Baidu AI Cloud, general capabilities such as object storage, logging services, and monitoring alerts can be combined to form a sustainable, iteratively improved cost baseline.