LLM Inference Cost Optimization: A Practical Guide

    This article explains why model capability gains do not translate linearly into inference costs, and how to turn an uncontrollable variable—price per token—into controllable architecture decisions. It covers a practical cost model for input and output tokens, the hidden cost of limited context windows, tiered model routing that treats models as a resource pool, and four general optimization techniques: caching, batch and asynchronous processing, output length constraints, and observability. A four-step rollout and validation path is included so cost reduction does not silently degrade quality.

    1. The Problem: Capability Gains and the Cost Curve Are Misaligned

    A pattern that keeps recurring in industry observation over the past year or two: the capability improvements delivered by model iterations do not always propagate to invocation costs in a linear way. When a new generation of general-purpose LLM is released, it typically ships in two tiers at the same time—a high-capability version aimed at complex reasoning and long-chain tasks, and a lightweight version aimed at high-concurrency, cost-sensitive scenarios. The price structure mentioned in the source material (roughly 12 CNY input and 24 CNY output per million tokens for the high-capability version; roughly 1 CNY input and 2 CNY output per million tokens for the lightweight version) drew attention not because it is “cheap,” but because of a re-layering of price bands within the same generation of capability: the lightweight version sits more than an order of magnitude below most same-tier competitors.

    It is worth stressing that specific prices are a commercial decision by each provider and change over time and by region. Engineering practice should never hardcode any unit price into code or into architectural assumptions. What is worth retaining is the methodology: how to convert “unit price,” an uncontrollable variable, into controllable architectural choices.

    2. The Cost Model: See Where the Money Actually Goes

    Billing for LLM calls usually distinguishes only two kinds of tokens: input (prompt) and output (completion). Most providers price output higher than input, because the generation stage is token-by-token autoregressive decoding and cannot be parallelized as fully as the prefill stage, making the per-unit compute cost higher. This explains a common misconception—choosing a model by input price alone tends to underestimate the real bill.

    An estimation formula you can apply directly:

    1. # Cost estimation for a single request (unit price: CNY per million tokens)
    2. def estimate_cost(in_tokens, out_tokens, price_in, price_out):
    3. return (in_tokens * price_in + out_tokens * price_out) / 1_000_000
    4. # Example: long-context summarization
    5. # 60K input, 2K output
    6. cost_long_ctx = estimate_cost(60_000, 2_000, 12, 24)
    7. cost_light = estimate_cost(60_000, 2_000, 1, 2)
    8. print(cost_long_ctx, cost_light) # 0.768 and 0.064

    The conclusion is intuitive: in input-heavy scenarios (document review, log analysis, code base retrieval Q&A), the input unit price is the dominant term; in output-heavy scenarios (long-form generation, report writing), the output unit price is what matters. Before selecting a model, you must first measure your own business input/output ratio rather than copying someone else’s benchmark conclusions.

    3. Context Length: An Underrated Hidden Cost

    The comparison in the source material—“a competitor offers only 128K context but at a slightly lower unit price”—points to a dimension that is often overlooked: cost per effective unit = unit price ÷ usable context capability. A small context window means long documents must be chunked and stitched across multiple turns, which multiplies actual token consumption and introduces cross-chunk information loss and consistency risk.

    Three things are recommended in engineering practice:

    1. Determine the distribution of your longest business inputs (P95, P99), not the average;
    2. For extra-long inputs, prefer “retrieval + fragment recall” over stuffing everything in;
    3. Include context length in the selection scorecard and evaluate it with the same weight as unit price.

    4. Tiered Selection: Treat Models as a Resource Pool, Not a Single Endpoint

    The core of a mature cost control approach is routing requests by difficulty:

    • High-capability version: complex multi-step reasoning, code refactoring, math and logic proofs, decision support on critical matters;
    • Lightweight version: classification and extraction, format conversion, intent recognition, batch summarization, event tagging;
    • Rules and small models: anything solvable with regex, keywords, or a traditional classifier does not enter the LLM path at all.

    A schematic routing implementation:

    1. def route(task):
    2. if task.complexity >= 0.7 or task.is_critical:
    3. return "reasoning_tier" # high-capability tier
    4. if task.complexity >= 0.3:
    5. return "light_tier" # lightweight tier
    6. return "rule_engine" # non-model path

    Practice data usually shows that more than seventy percent of real traffic consists of low-to-medium complexity requests. Migrating that portion to the lightweight tier often reduces the overall bill by far more than switching models does.

    5. Four General Optimization Techniques

    Cache reuse. Build a semantic cache or prefix cache for deterministic inputs (identical prompt prefixes, identical knowledge fragments); a hit costs nothing. Set similarity thresholds and invalidation policies to avoid stale results polluting output.

    Batching and asynchrony. Convert offline tasks (data cleaning, batch tagging) into queue-driven asynchronous batch processing, buffered with a message queue and object storage, which significantly improves throughput and smooths peaks.

    Output length constraints. Compress output tokens with structured output (JSON Schema constraints), explicit length caps, and field whitelists. A 50% reduction on the output side has the same effect as halving output length.

    Observability. Turn token usage, cache hit rate, and cost per request into monitoring and alerting metrics, aggregated by business line, so you can locate the real cost black holes.

    1. Suggested metrics:
    2. tokens_in / tokens_out, broken down by model tier
    3. cache_hit_ratio
    4. cost_per_business_action (more meaningful than cost per thousand tokens)

    6. Rollout Path and Validation

    A four-step approach is recommended: first establish a baseline by replaying real traffic; then run a small-traffic canary comparing quality metrics (accuracy, human spot-check pass rate) against cost metrics; then gradually expand the coverage of the lightweight tier; finally lock in the routing rules and a fallback plan. Quality thresholds must be defined up front, otherwise cost reduction quietly turns into quality regression.

    On Baidu AI Cloud, the above approach can be assembled from general-purpose capabilities: a container platform hosts the routing and inference gateway, a message queue handles asynchronous batch processing, object storage keeps raw corpora and results, logging and monitoring/alerting services handle cost and quality observability, and the model service itself is accessed through general-purpose LLM platform offerings such as Qianfan.

    7. Conclusion

    The real dividend from a new generation of models is not a particular unit price, but the scheduling space created by having a high-capability tier and an extremely cost-efficient lightweight tier coexist. Upgrading cost governance from “which model to choose” to “how to organize a model resource pool,” combined with caching, batching, output constraints, and observability, is what brings unit business cost down to a reasonable range without sacrificing quality.