Cost Optimization Practices for LLM APIs Amid Falling Prices
As LLM API prices continue to drop, cost control shifts from unit price to architecture. This guide explains how input, cached input, and output tokens are priced, and lays out five reusable optimization practices: raising cache hit rates, tiered model routing, compressing inputs and outputs, asynchronous batching and streaming, and observability-driven cost governance. It also includes a four-week rollout plan and the key metrics to track.
1. Introduction: Falling Prices Are the Start of Cost Engineering
A cloud provider recently released a new generation of general-purpose large models and cut API prices at the same time. Input and output unit prices for the flagship model both dropped noticeably, with a larger reduction for cached input, while the lightweight model kept the previous generation’s pricing. For developers, the value of this news is not “how much cheaper it got” but the long-term trend it reveals: LLM inference is turning from a scarce resource into a utility that can be managed at scale, like water and electricity.
Once unit prices enter a sustained decline, the main tension in your bill shifts from “high unit price” to “unreasonable structure.” The same workload can cost several times more or less depending on architecture. This article offers a reusable cost optimization methodology from a general technical perspective.
2. Understand Your Bill Structure First: How Three Token Types Are Priced
Most mainstream LLM APIs split billing into three categories:
- Input tokens: all text carried in the request, including system prompts, conversation history, and retrieved material.
- Cached input tokens: the portion of input that hits a server-side prefix cache, priced significantly lower than regular input. A hit usually requires an identical request prefix that is still within the cache’s validity window.
- Output tokens: content generated by the model, typically priced at several times the input rate and the main cost source for long-text generation.
With that in mind, the optimization directions are clear: make inputs hit the cache, shrink input size, control output length, and route simple tasks to smaller models.
3. Practice 1: Raise the Cache Hit Rate
Cache price cuts are often larger than input price cuts, which means every 10-percentage-point gain in hit rate can improve the overall bill far more than a unit price reduction does.
Engineering essentials for a higher hit rate:
- Prefix stability: put unchanging content (system instructions, tool definitions, domain knowledge) at the very front of the request, and volatile content (the user’s current turn, timestamps, random IDs) at the end.
- Avoid concatenating dynamic data into prompts: a common anti-pattern is writing the current time or a request ID at the beginning, which invalidates the entire prefix.
- Control cache invalidation cadence: rebuild the knowledge base in batches when it is updated, rather than writing scattered changes.
- Monitor the hit rate metric: treat cache hit rate as a first-class metric in your monitoring and alerting system.
Illustrative structure (pseudocode):
[Stable prefix] System role + output format constraints + tool schema + domain knowledge snippets[Semi-stable] Multi-turn conversation history (append-only, never modify existing content)[Volatile] Current user input + timestamp + trace ID
4. Practice 2: Model Tiering and Request Routing
Not every request deserves the flagship model. A workable approach is to tier requests by difficulty:
- L1 simple tier: intent recognition, format conversion, keyword extraction, classification and tagging → lightweight model.
- L2 standard tier: summarization, rewriting, routine Q&A → mid-tier model.
- L3 complex tier: multi-step reasoning, long-document analysis, code generation and review → flagship model.
Routing can start with rules and gradually evolve into a cascade strategy of “small model first, escalate when confidence is insufficient”:
def route(prompt: str) -> str:if is_simple_task(prompt): # rule- or classifier-based checkreturn "light_model"draft, confidence = call_model("light_model", prompt)if confidence >= THRESHOLD:return draftreturn call_model("flagship_model", prompt)
The key to a cascade strategy is monitoring the escalation rate as well; a high rate means the tiering thresholds need recalibration.
5. Practice 3: Compress Inputs and Outputs
Input side:
- In retrieval-augmented scenarios, rerank and deduplicate first, keeping only genuinely relevant snippets instead of stuffing a whole document into the context.
- Summarize conversation history on a rolling basis rather than concatenating everything.
- Represent structured data in compact formats (such as tabular text) instead of verbose natural-language descriptions.
Output side:
- State explicit length limits and a “no information, no output” constraint in the prompt.
- When structured results are needed, constrain the output to fixed fields to cut redundant explanatory text.
- For long-form generation, generate in segments with incremental validation to avoid large-scale rework after a single pass.
6. Practice 4: Batching, Async, and Streaming
- Async: move non-real-time pipelines (offline tagging, batch summarization, log analysis) to queue-driven asynchronous tasks, using a message queue to smooth peaks and avoid resource contention during peak hours.
- Batching: merge multiple small requests to reduce network round trips and repeated prefix overhead.
- Streaming: use streaming responses for user-facing scenarios; it improves perceived responsiveness and makes it easy to terminate low-value generation at any time.
- Timeout and retry policy: set reasonable timeouts with exponential backoff so failed requests do not repeatedly consume tokens.
7. Practice 5: Observability and Cost Governance
No measurement, no optimization. Collect at least these dimensions:
| Dimension | Purpose |
|---|---|
| Token consumption per business line | Cost attribution and quota management |
| Cache hit rate | Whether prefix design is effective |
| Input/output ratio | Whether prompts or generations are too long |
| Escalation rate | Evaluating tiered routing thresholds |
| Cost per request | Budget alerts and rate-limiting baselines |
Supporting mechanisms include setting quotas and budget alerts per business line, automatically rate-limiting anomalous calls, and connecting the cost dashboard with logging and alerting to form a closed loop of detect, locate, and fix.
8. Suggested Rollout Plan
- Week 1: add cost instrumentation, map the current token consumption distribution, and identify the top three consumers.
- Weeks 2–3: restructure prompt prefixes, move stable content to the front, and build a cache hit rate dashboard.
- Week 4: launch tiered model routing, rules first then cascade, and watch the escalation rate and quality metrics.
- Continuous iteration: extend async batching to offline pipelines and add cost per request to the release review checklist.
9. Conclusion
Falling unit prices are an industry dividend for developers, but architecture is what really separates cost outcomes. Do these five things well — cache hit rate, model tiering, input/output compression, async batching, and observability — and your bill will drop far more than the price adjustment alone. For fuller engineering support, you can look at how Baidu AI Cloud approaches general capabilities such as container platforms, message queues, object storage, and monitoring and alerting to carry the cost governance pipeline described above.
