LLM Cost Optimization: A Technical Decision Framework from Cost Per Valid Token to Tiered Routing
This article explains how to choose and architect LLM inference for cost efficiency beyond headline per-token pricing. It redefines the optimization target as cost per unit of valid output, shows why prompt caching makes prefix stability the largest cost lever, and covers tiered model routing, usage observability, replaceability through a unified inference gateway, and enterprise compliance considerations. Readers will find practical engineering guidelines, code and configuration examples, and a deployment checklist for keeping price volatility at the configuration layer.
1. Redefining the Problem: From Lowest Unit Price to Lowest Cost per Valid Output
When developers compare model value, they usually look straight at the price per million tokens. In real workloads, that number is often misleading, for three reasons:
- Pricing typically separates input and output, and output tokens usually cost significantly more, while business output is driven mainly by the output side.
- Cached input is billed differently from uncached input, so fluctuations in the cache hit rate directly change the actual bill.
- Retries, oversized contexts, and fallback after failures all amplify real consumption.
A more rigorous objective function is therefore not unit price but cost per unit of valid output:
Cost per valid output = monthly total bill / monthly valid output volumeValid output volume = tokens successfully returned and accepted by the business
This definition naturally rules out “cheap but heavy rework” options. A single failed retry caused by an exceeded context limit or non-compliant formatting can cost several times a single call while contributing zero valid output.
2. Cache Hits: The Largest Variable in the Cost Structure
Mainstream inference services commonly offer context caching: when a request prefix exactly matches previous requests, that portion of the input is billed at a lower price. The key conclusion is that cost optimization should focus on prefix stability rather than vaguely compressing the prompt.
Reusable stable prefixes include system instructions, tool and function definitions, output format constraints, few-shot examples, and long document bodies. Volatile parts (the user’s current-turn input, timestamps, random IDs) should be placed as late as possible.
[Stable prefix: system instructions + tool definitions + reference docs] ← aim for cache hits[Volatile suffix: current question + context identifier] ← keep it small
Engineering practices:
- Keep prefix order fixed, avoiding position drift when template assembly encounters missing fields.
- Do not insert per-turn changing content such as timestamps or request IDs into system instructions.
- For long documents, summarize and fix the content first, then reuse it, turning a one-time parsing cost into a cacheable prefix.
- Monitor the hit rate, not just call volume; a declining hit rate usually means the template was changed.
Note that cache billing rules are defined by each service provider and may change. Architecturally, do not hard-code the cost model to a fixed multiplier; make unit prices and cache discounts configuration items.
3. Tiered Routing: Let Expensive Models Handle Only Hard Problems
The core lever for value is tiering. Split requests by complexity: intent recognition, field extraction, format conversion, and simple Q&A go to lightweight models; multi-step reasoning, complex code generation, and long-document analysis go to more capable models. The lightweight tier handles the vast majority of request volume and is the main determinant of the bill.
def route(task):if task.est_input_tokens > 60_000 or task.needs_multi_step:return "strong" # high-capability tierif task.category in ("extract", "classify", "format"):return "light" # lightweight tierreturn "standard"
Supporting constraints: set a token budget and timeout for each tier; send strong-model output through structured validation, and retry once with fallback if validation fails, avoiding infinite loops that amplify cost.
4. Usage Observability: No Measurement, No Optimization
Cost governance depends on data. The minimum viable instrumentation set is: request ID, routing tier, input/output tokens, cached tokens, retry count, end-to-end latency, and whether the business accepted the result. In implementation, buffer call logs with a message queue, archive them to object storage, then use log services and monitoring alerts for trend and anomaly detection; a container platform hosts the stateless call gateway so it can scale independently per tier.
{"model_tier":"light","in":1820,"out":210,"cached":1600,"retry":0,"accepted":true}
With this data, you can answer “how much did my cost per valid output change after the price increase” instead of switching options based on gut feeling.
5. Resilience Design: Make Replaceability an Architectural Property
Prices and quotas can change at any time, so the model access layer should be abstracted into a unified gateway: expose a consistent inference interface externally, and declare each tier’s service endpoint, authentication method, unit price, and quota in configuration internally. Switching providers or tiers then requires only configuration changes, not business code changes.
Business code → unified inference gateway → adapters (tier A/B/C) → external inference services↑Config center: unit price, quota, timeout, fallback order
A suggested fallback chain: primary lightweight → backup lightweight → standard tier → cached result as last resort. For idempotent read requests, check a self-built cache first; on a hit, skip the call entirely.
6. The Compliance Perspective for Enterprise Scenarios
Beyond technical metrics, also consider invoiceability and cost allocation, deployment forms that keep data within a defined boundary, audit trails, and quota isolation. If the business is data-sensitive, dedicated deployment or private inference can trade a controlled resource pool for a stable unit price; at the same time, tag costs by project to enable department-level allocation and budget alerts. Baidu AI Cloud offers a complete combination of general capabilities across model services, container platforms, and logging and monitoring, which can serve as a reference foundation for building the tiering and observability described above.
7. Implementation Checklist
- Establish a unified gateway with configurable unit prices; forbid hard-coding model selection on the business side.
- Refactor prompts into “stable prefix + lightweight suffix,” and include the hit rate in the daily report.
- Roll out three-tier routing with token budgets, and set threshold alerts on the share of strong-model calls.
- Complete instrumentation and connect the logging, archiving, and alerting pipeline.
- Recompute cost per valid output every quarter, and adjust tiers and providers based on data rather than impression.
Following this path, the impact of price fluctuations on the business is confined to the configuration layer, and the team can put its energy back into quality and delivery.
