LLM API Cost Optimization: Hidden Costs Beyond Per-Token Pricing

    This article explains why comparing LLM API list prices alone is not enough for cost optimization. It breaks down the factors that drive real spend—input size, output length, cache hit rate, retries, and tool calls—then introduces cost per task and cost per successful task as more useful metrics. It also covers common measurement pitfalls and practical ways to instrument usage data for budget alerts, canary rollouts, and regression baselines.

    1. Unit Price Is Only One Input to the Bill

    LLM APIs are typically billed by token, with separate prices for input and output. Some platforms offer a lower unit price for input tokens that hit the cache. The cost of a single call can be written as:

    Per-call cost = input tokens × input unit price + cache-hit tokens × cache unit price + output tokens × output unit price

    The unit price is only one multiplier in the formula. When usage changes, total cost changes even if the unit price stays the same. If a team only compares price tables, it sees only part of the formula.

    2. Four Factors That Drive Real Spend

    2.1 Input Size

    Input tokens include system prompts, conversation history, retrieved document chunks, and tool results. The longer the context, the higher the input cost per call. In many teams, input bloat comes from untrimmed message history or from stuffing entire documents into the prompt as retrieval results.

    2.2 Output Length

    Output tokens usually have a higher unit price than input tokens, so output length has a more direct effect on cost. Explanations, formatted text, and reasoning processes generated by the model may all count as output. Different models or versions can differ significantly in output length for the same task. If a new version produces longer output, cost per task rises even when the unit price does not change.

    2.3 Cache Hit Rate

    Caching reuses the computation results for identical prefixes. System prompts, fixed tool definitions, and long document prefixes are more likely to hit the cache if they remain stable. Mixing timestamps, random IDs, usernames, or other volatile content into prompt templates can invalidate the cache. Cache discount rates vary by provider, so rely on the official billing documentation and measure the hit rate on your own workload data.

    2.4 Retries and Tool Calls

    Network timeouts, rate limits, and format validation failures can all trigger retries, and each retry is billed as a complete call. Agent-style applications may also call tools multiple times, and the input at each step may include the content of all previous steps. When measuring cost, aggregate all calls within a task instead of looking only at a single request.

    3. Replace Unit Price with Cost per Task

    Cost per task is the sum of all call costs on a fixed task set divided by the number of tasks. Two conditions must be met before calculating it: task definitions must be fixed, and the sample must represent the real business distribution.

    The following fictional numbers demonstrate the calculation method only and do not represent any real product. Assume an input price of CNY 1 per million tokens and an output price of CNY 4 per million tokens:

    • Option A: average input of 3,000 tokens and output of 800 tokens. Cost per task = 3,000 × 1 / 10⁶ + 800 × 4 / 10⁶ = CNY 0.0062.
    • Option B: average input of 3,000 tokens and output of 960 tokens, a 20% increase in output. Cost per task = 0.0030 + 0.00384 = CNY 0.00684.

    The two options have exactly the same unit prices, yet Option B has a cost per task about 10% higher. When input accounts for a larger share, the total cost increase from a 20% rise in output is partially diluted, but it is still significant.

    You can use the following code to calculate cost per task:

    1. def cost_per_task(records, price):
    2. """records: list of per-task usage records; price: unit prices for token types (CNY per million tokens)"""
    3. total = 0.0
    4. for r in records:
    5. total += r["input_tokens"] * price["input"] / 1_000_000
    6. total += r["cached_tokens"] * price["cached"] / 1_000_000
    7. total += r["output_tokens"] * price["output"] / 1_000_000
    8. return total / len(records)

    Include all calls within a task in the calculation, including retries and tool calls.

    4. Factor Quality into Cost

    A low cost per task does not necessarily mean a better overall deal. If the success rate is low, failed tasks require manual review, repeated calls, or abandonment, and these hidden costs push up total cost. A more useful metric is therefore cost per successful task:

    Cost per successful task = cost per task ÷ task success rate

    Continuing with the fictional numbers above, Option A has a 70% success rate and Option B has a 60% success rate:

    • Option A: 0.0062 ÷ 0.70 ≈ CNY 0.0089
    • Option B: 0.00684 ÷ 0.60 ≈ CNY 0.0114

    The ranking by cost per task and the ranking by cost per successful task can be reversed. Model selection should consider both.

    The criteria for determining success must be defined in advance, for example through automated tests, structured field validation, or manual sampling. If the criteria are inconsistent, comparison results are unreliable.

    5. Common Pitfalls

    Looking only at unit price. Unit price is part of the formula; usage and retry counts also determine the bill.

    Looking only at aggregate benchmark scores. Aggregate benchmarks reflect performance on a specific evaluation set. They can indicate a model’s general capability range, but matching with your own business tasks must be validated with real samples.

    Ignoring output bloat. If a new version gives more detailed answers or longer reasoning, output tokens increase. Before upgrading, compare the output length distribution on the same task set.

    Inconsistent measurement scope. Some teams include cache hits in their statistics, while others do not; some count only successful calls, while others include failed calls. With different scopes, the numbers are not comparable.

    Sample bias. Testing with simple questions and then extrapolating the conclusion to complex, long-chain tasks can easily overestimate a model’s cost-effectiveness. Test samples should cover long-tail scenarios in real traffic.

    6. Operationalizing Cost Observability

    Cost optimization depends on observability. At minimum, record the following fields for each call:

    1. {
    2. "task_id": "order-summary-20261125-0042",
    3. "model": "model-v2",
    4. "input_tokens": 3120,
    5. "cached_tokens": 2048,
    6. "output_tokens": 812,
    7. "latency_ms": 1930,
    8. "retry_count": 1,
    9. "success": true
    10. }

    Based on these fields, you can do three things:

    1. Budget alerts. Use general monitoring and alerting capabilities to set daily or weekly budget thresholds. Trigger an alert when cost per task rises by more than a configured percentage (for example, 20%) compared with the previous period, and prompt the team to check changes in prompt length and output length.
    2. Canary rollout. Before launching a new model, route a small share of traffic (for example, 5%) to it and compare cost, success rate, and latency. Expand the share gradually only after the metrics meet expectations.
    3. Regression baseline. Keep a fixed test set for core tasks, rerun it after every model or prompt change, and record trends in cost per task and success rate.

    7. Where Competition Moves Next

    As different models converge in quality on similar tasks, cost becomes an important variable in engineering decisions. Teams need to treat cost per task and cost per successful task as first-class metrics, tracked alongside accuracy and latency. Those that can control usage, improve cache hit rates, and reduce ineffective retries at the same quality level will achieve a more stable cost structure over the long run.