LLM API Cost Optimization: Practical Strategies Beyond Price Cuts

    This article breaks down what you actually pay for in LLM inference and shows how to reduce costs through prefix stabilization for cache hits, tiered model routing, and tighter control of output and retries. It also outlines a four-step rollout plan with risk controls, helping engineering teams lower per-task cost without sacrificing quality.

    1. The Trend: Why Price Cuts Are Only the Starting Point

    A notable signal has emerged in the industry: a cloud provider has released two large models at the same time, a flagship model and an everyday model. The flagship model’s input and output token prices were reduced by about 20%, while the cached-input portion dropped by 60%. On coding benchmarks, the everyday model trails the flagship by only half a percentage point, yet its cost per task is roughly one-fifth that of the flagship. The flagship model also improved by about 5% over the previous generation on comprehensive agent evaluations, while costing less than one-third as much to run.

    Abstracting these numbers yields three engineering conclusions:

    1. Capability gains and cost reductions are happening at the same time, and the cost-performance curve for a unit of intelligence is moving down quickly.
    2. Model supply is clearly tiering: flagship models handle difficult reasoning, while everyday models take on high-frequency, pattern-based tasks.
    3. Cache hits have become a new cost lever, with a reduction larger than the price cut itself, showing that the value of reusing repeated context has been significantly amplified.

    So the real optimization opportunity is not “waiting for prices to drop” but rethinking how you make calls.

    2. Breaking Down Inference Costs: What You Are Actually Paying For

    A single call’s bill usually has four parts:

    • Input tokens (prompts, retrieved snippets, conversation history, tool return values);
    • Output tokens (generated content, usually priced higher than input);
    • Cached input tokens (the portion that hits a prefix cache, priced significantly lower);
    • Additional costs (retries, failed replays, vector retrieval, logging and monitoring storage, and extra calls from the orchestration layer).

    The most overlooked fact in engineering is this: most production traffic is not “first-time questions” but repeated requests with large, stable prefixes. System prompts, tool definitions, knowledge base snippets, and code repository context often make up more than 70% of input volume, yet they are billed again every time.

    An illustrative cost estimation logic:

    1. def estimate_cost(req, price):
    2. # price: unit prices per tier (input/output/cached input)
    3. return (
    4. req.input_tokens * price.input
    5. + req.output_tokens * price.output
    6. + req.cached_tokens * price.cached_input
    7. + req.retry_count * price.input # hidden cost of retries
    8. )

    3. Strategy 1: Stabilize the Prefix to Raise the Cache Hit Rate

    A cache hit requires the prefix to be byte-for-byte identical. Any dynamic content inserted in front will invalidate the entire prefix. An actionable checklist:

    • Split prompts into a “stable layer + dynamic layer”: put role settings, output format, and tool schema first, and user input, timestamps, and random IDs last;
    • Never concatenate time, request IDs, or randomly ordered retrieval results into the stable layer;
    • Apply fixed sorting and deduplication to retrieved snippets so the same question gets the same context;
    • Use fixed chunking and fixed templates for long documents to avoid drifting split boundaries each time.
    1. [stable prefix] system role + output spec + tool definitions + fixed knowledge snippets
    2. [dynamic suffix] current user question + conversation delta + timestamp/trace ID

    One practical point: moving variables to the end can often raise the hit rate from a low level to a high one, and that portion gets the largest discount.

    4. Strategy 2: Tiered Routing, Letting Everyday Models Handle High-Frequency Traffic

    The core of tiering is not “downgrading” but allocating compute by task difficulty. Routing dimensions you can use include: task type, input length, number of historical failures, business importance, and latency budget.

    1. def route(task):
    2. if task.risk == "high" or task.difficulty >= 4:
    3. return "flagship" # flagship: complex reasoning, long-chain agents
    4. if task.kind in ("classify", "extract", "format"):
    5. return "daily" # daily: classification, extraction, formatting
    6. return "daily" if task.budget_ms < 800 else "flagship"

    Recommended supporting mechanisms:

    • Cascade validation: the everyday model produces a result first, and it is escalated to the flagship model when confidence is low or rule-based checks fail;
    • Offline/online separation: batch processing, data cleaning, and label generation go to the everyday model, while interactive critical decisions go to the flagship model;
    • Observability: track call volume, token distribution, hit rate, escalation rate, and failure rate separately by model tier to build a cost dashboard.

    5. Strategy 3: Control Output and Retries, the Two Hidden Amplifiers

    Output tokens are usually more expensive and are the easiest part to waste:

    • Use structured output to constrain length: give the schema first and then the content, avoiding long explanations;
    • For classification or extraction, return only enum values or fields, not the reasoning process;
    • For summarization tasks, set clear limits on word count and number of key points;
    • Retries must use exponential backoff with a cap on attempts, and failed requests should be written to logs for regression analysis rather than replayed indefinitely.

    6. Rollout Plan and Risk Control

    A four-step approach is recommended, with each step independently rollback-able:

    1. Baseline measurement: measure the token composition and hit rate of one week of real traffic to identify the main cost drivers;
    2. Prefix rework: separate the stable layer from the dynamic layer, and watch changes in cache hit rate and billing;
    3. Routing canary: start by routing 5% of traffic through the tiered strategy, compare quality metrics, and then scale up;
    4. Ongoing governance: bring cost, quality, and latency into the same dashboard and alerting.

    For risk control, note that both price cuts and tiering can cause quality fluctuations, so always keep an evaluation set for regression; set a “flagship model only” allowlist for highly sensitive scenarios; and for cache reuse, pay attention to multi-tenant isolation to avoid data leakage from cross-context reuse.

    7. Conclusion

    Falling unit prices are an external dividend; architecture optimization is an internal capability. If you get cache hit rate, model tiering, and output constraints right, an order-of-magnitude reduction in per-task cost is an achievable engineering result with largely controllable effects. For teams that want to validate quickly, the general-purpose model services, container platforms, and monitoring and alerting capabilities offered by Baidu AI Cloud can serve as one infrastructure option for running the strategies above.