LLM Inference Cost Optimization: A Practical Guide to Per-Task Cost, Model Routing, and Caching

    This guide explains why per-token pricing is a misleading metric for LLM API cost optimization and how engineering teams can lower real expenses instead. It covers the shift to per-task cost and the score-cost curve, a tiered model lineup of flagship, standard, and light models with a routing mechanism, the engineering impact of changing price structures, prefix caching and context engineering techniques for improving cache hit rates, cost observability and governance with offline evaluation, and a five-step rollout plan.

    1. The Real Problem: From Price per Token to Cost per Task

    When evaluating the cost-effectiveness of a large language model API, many teams first look at the input and output price per million tokens and compare vendors side by side. That view was reasonable early on, but it no longer reflects the actual bill once model lineups become tiered, context windows keep growing, and caching is widely adopted.

    There are three reasons. First, different tasks consume completely different token structures: long-document summarization is input-heavy, code generation and structured extraction are output-heavy, and multi-turn conversations amplify both. Second, mechanisms such as cached input and batch inference cause the nominal unit price to deviate significantly from what is actually billed. Third, differences in quality turn into retries and human review costs, so a cheap model that often answers incorrectly may cost more in reality than a more expensive flagship model.

    A more rigorous approach is to build a score-cost curve: the horizontal axis is the actual spend per unit of completed work, and the vertical axis is task success rate or quality score. Configurations in the upper-left of the curve are both cheap and good; those in the lower-right are both expensive and poor. What engineering teams really need to do is map business tasks to the right position on this curve, rather than chasing the lowest unit price.

    1. cost per task ≈ (input tokens × input price + cached tokens × cache price
    2. + output tokens × output price) / task success rate

    This formula reveals a frequently overlooked fact: the success rate in the denominator is also part of the cost.

    2. A Tiered Model Lineup: One “Star” and One “Planet”

    Major providers now generally offer tiered model systems, which can be abstracted into three roles:

    • Flagship reasoning model: aimed at the hardest engineering and research problems, with stronger long-chain reasoning and code comprehension, and the highest unit price.
    • Standard workhorse model: covers the vast majority of business requests with balanced capabilities, and acts as the “planet” that carries default traffic.
    • Lightweight fast model: aimed at short tasks such as classification, rewriting, extraction, and routing, with the best latency and cost.

    The original analogy of “one galaxy, one sun, one earth, and one moon” essentially describes the alignment between the capability gradient and the cost gradient. The key to engineering practice is not to pick the strongest model, but to build a routing mechanism: first use a lightweight model for intent recognition and difficulty assessment, let simple requests be resolved entirely by the lightweight model, hand medium requests to the standard model, and escalate only requests judged to be highly difficult to the flagship model.

    A simplified routing sketch:

    1. def route(task):
    2. if task.estimated_difficulty < 0.3:
    3. return "light" # classification, extraction, rewriting
    4. elif task.estimated_difficulty < 0.75:
    5. return "standard" # routine Q&A, business writing
    6. else:
    7. return "flagship" # complex reasoning, cross-file refactoring

    Routing criteria can come from rules (input length, whether the input contains code blocks), the confidence of a lightweight model, or difficulty labels obtained from historical offline evaluation. For implementation, it is recommended to launch a rule-based version first and then gradually replace it with a data-driven one.

    3. Engineering Implications of Changing Price Structures

    The source material notes that the input and output prices of the new generation of flagship models are about 20% lower than the previous generation, while cached input prices drop by a larger margin of around 60%; the standard model keeps its original price but gains capability. Translating these changes into engineering language yields three conclusions.

    First, the cost-effectiveness of caching is significantly amplified. When the cached input price is only about one twentieth of the regular input price, the reuse value of stable prefixes such as system prompts, tool definitions, knowledge base snippets, and long documents rises sharply. Every ten-percentage-point increase in hit rate brings a noticeable drop in the bill for long-context scenarios.

    Second, better capability at an unchanged price is equivalent to a lower cost per task. A higher first-pass rate for the standard model directly reduces retries and human intervention; this benefit does not appear on the price list but is truly reflected in total cost.

    Third, the flagship price cut lowers the barrier to escalating. Scenarios that were previously forced to downgrade due to cost concerns and ended up retrying repeatedly can now be handed to the flagship model with more confidence to get it right the first time.

    4. Caching and Context Engineering: Raising the Hit Rate

    For caching to work, the prefix must be stable. Common failure points in practice include concatenating timestamps or random request IDs into the system prompt, placing user input at the very front of the prompt, and re-serializing tool definitions on every request. The fix is to split content into three parts: a stable prefix, a semi-stable middle, and a dynamic tail:

    1. [stable prefix] system role, output spec, tool schema, domain knowledge
    2. [semi-stable] conversation summary, retrieved document snippets (concatenated in a fixed order)
    3. [dynamic tail] current user input

    Four supporting engineering constraints apply: put prompt templates under version control and require review for changes; fix the ordering of retrieval results to avoid recall-order jitter for the same question; use segmented caching for long documents instead of recomputing the whole document; and treat cache hit rate as a first-class metric in monitoring, displayed alongside latency and error rate.

    5. Cost Observability and Governance

    Without measurement there is no optimization. The recommended minimum observability set includes tokens and spend broken down by business line, model tier, and call source; cache hit rate; retry rate and first-pass rate; and end-to-end latency percentiles. On top of this, set budget alerts and quotas, and throttle callers with abnormal growth rather than blocking them outright.

    For evaluation, establish a fixed offline benchmark set that covers the real business distribution, and run the same score-cost comparison every time you switch models or adjust prompts, avoiding upgrades or downgrades based on gut feeling. For high-value scenarios, a dual-run canary is an option: run the new and old configurations in parallel for a period and use statistical significance to decide whether to roll out fully.

    1. Inventory existing calls and classify tasks by token structure into input-intensive, output-intensive, and mixed.
    2. Build a three-tier model router, launch the rule-based version first, and make it data-driven after canary validation.
    3. Refactor prompt templates to enable stable prefixes and cache reuse, and put hit rate on the dashboard.
    4. Set up an offline evaluation set and a cost dashboard to form a weekly score-cost review.
    5. Explicitly allow high-difficulty tasks to escalate to the flagship tier, replacing multiple retries with getting it right once.

    Overall, the tiering of model lineups and the adjustment of price structures give the engineering side more room for optimization, but the gains do not materialize automatically. What really determines the bill are three foundational capabilities: routing strategy, cache hit rate, and the evaluation loop. They are independent of any specific vendor and also apply to infrastructure combinations offered as general-purpose categories on platforms such as Baidu AI Cloud, including model services, object storage, log services, and monitoring and alerting.