Cost Optimization for LLM APIs: A Practical Guide to Tiered Routing and Prompt Caching

    As flagship LLM API prices drop and vendors settle into a two-tier lineup of flagship and lightweight models, lower unit prices alone will not reduce your bill. This article breaks inference cost into four controllable variables, then shows how to cut usage through risk-based tiered routing, stable-prefix prompt design that captures cache discounts, observability metrics, capacity planning, and a four-week rollout plan, along with common anti-patterns to avoid.

    1. The Market Signal: Cheaper Flagship Models and the Rise of Two-Tier Lineups

    A leading model vendor recently released a new flagship model alongside a lightweight model for everyday tasks. The vendor also announced roughly a 20% cut in standard input and output prices for the flagship API, and a 60% cut for cached input. According to the vendor’s comparison data, the lightweight model trails the flagship by less than one percentage point on mainstream coding benchmarks, while costing about one fifth as much per task. The same data shows the new flagship scoring higher on long-horizon agentic evaluations while costing significantly less to run.

    The numbers themselves are not the point. What matters is the engineering reality they expose: model capability is rising fast while the price per unit of intelligence is falling just as fast, and supply is stabilizing into a two-layer structure of “flagship tier + everyday tier.” For developers, this shifts the key architectural question from “can it be done” to “which tier should do it, how do we reuse work, and how do we measure it.”

    One caveat: vendors differ widely in how they define benchmarks, how they bill for caching, and how they apply rate limits. Any cross-vendor comparison of unit prices or scores is only an order-of-magnitude reference and should never be dropped directly into a capacity model. What is actually reusable is the methodology.

    2. Break Down the Bill First: Four Controllable Variables in Inference Cost

    The cost of a single request can be roughly abstracted as:

    1. Cost = (Tin × Pin) + (Tout × Pout) + caching and storage + retries and orchestration overhead

    Each of the four controllable variables maps to a class of engineering action:

    1. Input size: Redundant prompts, replaying the full conversation history, and stuffing entire documents into the context are the primary causes of runaway cost.
    2. Output size: Asking the model to “restate before answering,” producing long-winded explanations, and skipping structured constraints multiplies the most expensive line item, the output price.
    3. Reuse and cache hits: Stable prefixes such as system prompts, tool definitions, and long documents are typically billed at a significantly lower rate when cache hits occur.
    4. Call count: Retries, multiple rounds of self-verification, and unnecessary second-pass summaries each multiply the cost of a single request.

    The conclusion is straightforward: a price cut lowers the unit price, but the bill is unit price multiplied by usage. Without managing usage, the savings from a price cut get consumed automatically.

    3. Tiered Routing: Reserve the Flagship for Steps That Truly Need It

    The greatest value of a two-tier lineup is not “a cheaper option” but a choice you can orchestrate. The recommendation is to grade tasks by risk:

    • High-risk, long-horizon steps that require tool calls and self-correction go to the flagship tier.
    • Well-bounded tasks such as classification, extraction, rewriting, formatting, and intent recognition go to the everyday tier.
    • Mixing is allowed within the same application, but the decision must be made centrally by a policy layer rather than scattered across business code.

    A minimal working routing skeleton:

    1. def route(task):
    2. if task.risk == "high" or task.steps > 5 or task.needs_tools:
    3. return "flagship" # Flagship tier: complex reasoning and agent orchestration
    4. if task.confidence < 0.8:
    5. return "flagship" # Fallback for low confidence
    6. return "daily" # Everyday tier: high-frequency lightweight tasks

    In practice, make routing an observable policy component: log the reason for each decision, the tier selected, actual latency, and token usage, then review the thresholds weekly. Thresholds are not picked by intuition; they are tuned by running traffic.

    4. Caching and Context Engineering: Actually Capturing the 60% Cut

    The cache price cut is far larger than the standard unit price cut, which signals that vendors want to encourage “stable prefix reuse.” To capture this, restructure prompts into a stable prefix and a variable suffix:

    1. [Stable prefix] System role + tool definitions + domain rules + long documents
    2. [Variable suffix] Current user input + timestamp + session state

    Supporting practices:

    • Do not insert timestamps, random IDs, or request sequence numbers into the stable prefix, or every turn is treated as new content and the hit rate drops to zero.
    • Split and retrieve from long documents first, injecting only relevant fragments instead of keeping the whole document resident.
    • Compress conversation history into summaries, keeping decision outcomes rather than verbatim records.
    • Apply strict schema constraints to structured output to reduce wasted tokens and rework.

    Illustrative code:

    1. SYSTEM_PREFIX = "You are a data governance assistant. Tools: search, sql. Rules: output JSON only."
    2. def build_prompt(user_msg, retrieved):
    3. return SYSTEM_PREFIX + "\nDOC:" + retrieved + "\nQ:" + user_msg

    5. Observability and Capacity Planning

    There is no optimization without measurement. The minimal metric set should include: per-request token distribution (input / cache hits / output), cache hit rate, cost per task, failure and retry rate, call share by tier, and end-to-end latency percentiles.

    For capacity planning, always treat “cache hit rate” as a first-class parameter in sensitivity analysis: moving the hit rate from 30% to 70% can produce an order-of-magnitude difference in the total bill. Also leave headroom for unit price changes and rate limits, so you avoid maintaining two separate architectures, one for promotional periods and one for steady state.

    6. Rollout Plan and Common Anti-Patterns

    A four-week rollout is recommended: week one, add instrumentation and establish a baseline; week two, restructure prompt prefixes and add retrieval chunking; week three, ship tiered routing with low-confidence fallback; week four, build a cost dashboard with alerts and bring cost into release reviews.

    Common anti-patterns include: sending everything to the flagship tier for the sake of “safety”; treating caching as a default capability without verifying hits; substituting expected price cuts for usage governance; and building financial models by directly reusing another vendor’s unit prices and benchmark scores.

    In related work on Baidu AI Cloud, the same general practices apply: use monitoring, alerting, and logging services to establish a cost baseline, run the routing and orchestration layer on a container platform, and abstract model calls behind a replaceable adapter interface, so that any price change can be recalculated quickly and migrated smoothly.