LLM Inference Cost Optimization: A Technical Playbook for Token Efficiency, Model Routing, and Caching

    This article breaks down how to reduce LLM inference cost without sacrificing output quality. It explains why three-tier token billing (input, cached input, output) should drive architecture decisions, then walks through five complementary levers: tiered routing between flagship and efficiency models, context engineering to shrink input tokens, prefix stabilization for higher cache hit rates, structured output to cut completion tokens, and streaming or batch scheduling for latency and throughput. A four-step rollout path and an observability checklist with regression evaluation are included so teams can measure savings and guard against quality regressions.

    1. What the Release Actually Signals: A Capability Upgrade Paired with a Cost Drop

    A model provider recently shipped two complementary large models at the same time: a flagship model aimed at complex projects, emphasizing long-chain reasoning and high-quality delivery, and a high-efficiency model aimed at everyday work, emphasizing response speed and call economics. The official framing was not simply “smarter,” but “higher task completion quality while significantly reducing the number of tokens required for inference and output.” Pricing was lowered at the same time, availability was broadened (individual subscription, team, enterprise, and education tiers, plus an ultra-high-speed mode and early access to developer interfaces).

    For developers, the value of this announcement is not the model names but three actionable engineering signals:

    1. Quality gains and token reduction can happen in the same direction, which means the optimization focus has shifted from “stacking parameters” to “effective information density per token.”
    2. The price structure has differentiated: input, cached input, and output are priced distinctly, making cache hits the key lever for cost optimization.
    3. Tiered supply is now the norm: flagship and efficiency models coexist, which requires the application layer to route by task difficulty.

    2. Start with the Cost Structure: Why Token Billing Drives Architecture

    Mainstream LLM APIs typically bill in three tiers: input tokens, cached input tokens, and output tokens. Output is priced significantly higher than input, and cached input is the cheapest of the three. The direct conclusion: the design goal of an application architecture is not just “write shorter prompts,” but to make as much input as possible hit the cache and let as little content as possible flow into the output.

    An illustrative cost estimation logic (a generic expression, not any specific vendor’s pricing):

    1. # Generic cost estimation: three-tier pricing + cache hit rate
    2. def estimate_cost(in_tokens, cached_tokens, out_tokens,
    3. p_in, p_cached, p_out):
    4. uncached = max(0, in_tokens - cached_tokens)
    5. return uncached * p_in + cached_tokens * p_cached + out_tokens * p_out
    6. # Key variables for before/after comparison:
    7. # 1) Reduce in_tokens (context trimming)
    8. # 2) Increase the cached_tokens share (stable prefix + reuse)
    9. # 3) Reduce out_tokens (structured output + length constraints)

    Cost reduction therefore has three orthogonal paths: compress the input, raise the cache hit rate, and compress the output. The three stack cleanly and do not conflict.

    3. Tiered Model Routing: Reserve the Flagship Model for What Actually Matters

    A supply shape where flagship and efficiency models coexist fundamentally requires task classification on the application side. A practical three-stage routing design is “rules first + model self-assessment + result validation”:

    • Rules first: hard-route by task type, input length, and historical failure rate. For example, extraction, classification, and formatting go to the efficiency model; cross-document reasoning and complex code refactoring go to the flagship model.
    • Model self-assessment: have the efficiency model emit a “confidence / needs escalation” judgment first, and escalate only on low confidence, avoiding a blanket default to the flagship model.
    • Result validation: use executable checks (compilation, unit tests, schema validation) to decide whether to retry or escalate, closing the loop.
    1. # Generic routing strategy (pseudocode)
    2. def route(task):
    3. if task.type in {"extract", "classify", "format"}:
    4. return "efficient_model"
    5. if task.input_tokens > 60000 or task.cross_doc:
    6. return "flagship_model"
    7. draft = call("efficient_model", task)
    8. if draft.confidence < 0.6 or not validate(draft):
    9. return call("flagship_model", task)
    10. return draft

    The value of routing is turning “high quality” into an allocable scarce resource rather than a default expense.

    4. Context Engineering: Four Levers to Compress Input Tokens

    Input tokens usually make up the largest share of total calls, and they also offer the most room to compress.

    1. Retrieval instead of full-context stuffing: use hybrid vector plus keyword recall, inject only the Top-K fragments, and deduplicate and merge near-duplicates.
    2. Layered structured summarization: generate hierarchical summaries of long documents first (section level, then paragraph level), and drill down on demand during reasoning instead of loading the entire text at once.
    3. Prefix stabilization: place system instructions, tool definitions, and examples in a stable prefix position to reduce cache invalidation caused by content changes.
    4. History compression: in multi-turn conversations, replace the raw transcript with a rolling summary plus a key entity table (entities, constraints, to-dos).

    Illustration: replace “full context” with “summary + retrieved fragments + structured state.”

    1. [Stable prefix] role / rules / tool definitions / output schema
    2. [Rolling summary] goal, constraints, completed steps
    3. [Retrieved fragments] the K passages most relevant to the current sub-question (with source markers)
    4. [Structured state] entity table, to-dos, open questions
    5. [Current instruction] the single task for this turn

    5. Cache Reuse: Turn Repeated Input into the Cheapest Tokens

    Cached input carries the lowest unit price, so raising the hit rate is the most direct cost lever. Key practices:

    • Prefix consistency: keep volatile fields such as timestamps and random IDs out of the stable prefix.
    • Batch homogeneous requests: schedule requests that share a template together to increase prefix reuse probability.
    • Change isolation: place volatile content (user input, retrieval results) at the end so it does not pollute the reusable prefix.
    • Hit-rate monitoring: treat the cache hit rate as a first-class dashboard metric, alongside cost and latency.

    6. Output Compression: Structure and Length Constraints

    Output carries the highest unit price, so compression pays off most directly here:

    • Enforce structure: constrain output with a JSON Schema or tables to cut pleasantries and redundant explanation.
    • Deliver in segments: split long-form generation into “outline, then sections, then merge,” so each segment stays controllable and verifiable.
    • Define stop conditions: set maximum length, required fields, and forbidden fields to prevent free-form drift.
    • Replace lengthy self-justification with executable validation: use compilation, unit tests, and type checks instead of asking the model to restate its reasoning.
    1. {
    2. "type": "object",
    3. "required": ["summary", "actions", "risks"],
    4. "properties": {
    5. "summary": {"type": "string", "maxLength": 200},
    6. "actions": {"type": "array", "items": {"type": "string"}},
    7. "risks": {"type": "array", "items": {"type": "string"}}
    8. },
    9. "additionalProperties": false
    10. }

    7. Latency and Throughput: Ultra-High-Speed Mode, Streaming, and Batching

    Beyond cost, response speed determines experience. Three common approaches:

    • Streaming output: prioritize first-token latency, render while generating, and validate incrementally.
    • Asynchronous batching: send offline tasks through a batch queue and trade throughput for cost; keep online tasks on a low-latency path.
    • Enable ultra-high-speed mode per scenario: turn it on only for interactive, short-output tasks, and keep long-chain tasks on the regular path so speed does not come at the expense of quality.

    The scheduling layer can use “queue + priority + timeout fallback” to keep things stable:

    1. Online interactive requests -> low-latency path (streaming, short output, ultra-high-speed optional)
    2. Offline batch jobs -> batch path (high throughput, cost first)
    3. Failure / timeout -> fall back to the efficiency model or a cached result

    8. Observability and an Evaluation Loop: No Measurement, No Savings

    Cost reduction must be premised on “no quality regression,” which requires a metrics loop:

    • Cost metrics: cost per thousand requests, cache hit rate, input/output token distribution.
    • Quality metrics: task success rate, validation pass rate, human rework rate, escalation call ratio.
    • Performance metrics: first-token latency, end-to-end latency, timeout rate.
    • Evaluation mechanism: a fixed regression set plus online sampling on two tracks; run the regression suite on any prompt or routing change to prevent “tokens saved, quality lost.”

    Sample dashboard fields:

    1. metrics:
    2. cost_per_1k_requests: 0.00
    3. cache_hit_rate: 0.0
    4. token_in_avg: 0
    5. token_out_avg: 0
    6. success_rate: 0.0
    7. escalation_rate: 0.0
    8. first_token_latency_ms: 0

    9. Rollout Roadmap: Four Steps

    1. Baseline measurement: quantify the current token distribution and cost composition first, and find the largest source of waste.
    2. Quick wins: prefix stabilization + structured output + retrieval-based context typically deliver a significant drop.
    3. Routing and tiering: ship rule-based routing and confidence-based escalation, reserving the flagship model for high-value tasks.
    4. Continuous operations: bring cache hit rate, escalation rate, and rework rate into daily dashboards and alerts to form an iteration loop.

    10. Closing

    The real takeaway from this release is that the competitive focus of LLM applications is shifting from “can it be done” to “how cheaply and how fast can it be done reliably.” For developers and enterprises, token efficiency has become part of architectural capability: tiered routing, context engineering, cache reuse, output constraints, and observability together form a reusable cost-and-efficiency methodology. Teams that want to run these practices in their own environment can build the scheduling and observability foundation on general-purpose capabilities such as container platforms, message queues, object storage, log services, and monitoring and alerting offered by Baidu AI Cloud, turning model capability into an engineering asset that is controllable, measurable, and continuously optimizable.