How to Cut LLM Inference Costs: Model Selection and Engineering Practices
A practical guide to reducing LLM inference costs after API price increases. It breaks down the cost structure, explains how to tier tasks by tolerance, and shows how routing, caching, context compression, batching, and distillation lower spending without sacrificing acceptable quality. It also covers observability, cost attribution, and a four-week rollout plan.
Recently, LLM API price adjustments have drawn widespread attention, and many teams are re-evaluating their inference costs. To be clear, model pricing is a commercial decision made independently by each provider. This article does not evaluate any specific vendor’s pricing. Instead, it frames the problem as a more universal engineering question: in an environment where the cost per token is rising, how can you reduce overall inference spending through engineering means without sacrificing business-acceptable quality.
1. Break Down the Cost Structure First
Many teams focus only on the “price per million tokens,” but the actual bill is determined by several variables. A useful approximation is:
Monthly cost ≈ Σ(request volume × (input tokens + output tokens × output premium factor) × unit price) + retry cost + operations cost
This reveals four intervention points: request volume, context length, output length, and retry rate. In practice, the most common waste is context bloat—stuffing entire conversation histories, full documents, and lengthy system prompts into every request, so input tokens are often more than ten times the output tokens. The second is retry amplification: timeouts, rate limits, and format validation failures all trigger a second call. Without backoff and idempotency design, retry costs can account for a significant share of total spending.
2. Tier Capabilities: Not Every Task Needs the Strongest Model
Segmenting workloads by “fault tolerance” is the most effective first step toward cost reduction. You can divide them into three tiers:
- L1, high tolerance: log summarization, tag extraction, format conversion, simple classification. A small-parameter or lightweight model is enough; focus on throughput and unit price.
- L2, medium tolerance: customer support Q&A, retrieval-augmented generation, code completion. These require some reasoning and instruction-following ability and are suited to a mainstream general-purpose model.
- L3, low tolerance: complex multi-step reasoning, long-document structuring, and decision support for critical cases. Use the most capable model with the longest context, paired with human review.
The key is to build a measurable evaluation set. Cost reduction without an evaluation set is blind cost cutting. It is recommended to prepare 100–300 real samples for each tier and record three metrics: accuracy, format compliance rate, and manual rework rate. Any model replacement must first pass the evaluation threshold.
3. Routing and Caching: Send Requests to What Is “Just Enough”
The idea behind a routing layer is to judge difficulty first, then split traffic. The judgment can start with rules and a lightweight classifier to avoid the classification itself consuming expensive calls:
def route(prompt: str, ctx: dict) -> str:# Rules first, at almost zero costif len(prompt) < 200 and ctx.get("need_reasoning") is False:return "small"if ctx.get("domain") in {"finance", "legal"}:return "large"# Fall back to a lightweight classification modelreturn classify_difficulty(prompt)
Caching has two layers: semantic caching and result caching. For high-frequency repeated questions, use vector similarity to determine a hit. The similarity threshold must be calibrated per business: too loose returns wrong answers, too strict makes it meaningless. Result caching suits deterministic tasks, such as summarizing the same document, where a content hash can serve as the key, with a TTL and invalidation policy. Note that the cache key must include the model version and prompt version; otherwise, hard-to-diagnose stale data will appear after an upgrade.
4. Context and Output Compression
On the input side, possible optimizations include: reranking retrieved fragments and keeping only the Top-K most relevant passages, applying rolling summaries to conversation history instead of concatenating everything, and splitting long documents while pre-extracting structured fields. On the output side, use structured constraints to reduce redundancy—for example, require JSON with limited fields rather than free text that must be parsed afterward:
Output JSON only: {"sentiment": "pos|neg|neu", "score": 0-1, "reason": "<=30 words"}
Such constraints usually reduce both output tokens and parsing failure rates, making them a win-win change that cuts cost and improves quality. In addition, setting max_tokens to the actual upper limit the business needs, rather than a large default, prevents the model from gradually drifting in long outputs.
5. Batching, Async, and Distillation
For offline tasks, batch APIs offer a lower unit price at most providers, at the cost of latency shifting from seconds to minutes or even hours. This makes them suitable for data cleaning, batch labeling, and offline report generation. Architecturally, it is recommended to decouple with a message queue: slice tasks, pull them concurrently, and re-submit failures, with monitoring and alerts to watch for backlog and failure rates.
Distillation and fine-tuning are mid-to-long-term measures: use a strong model to generate high-quality labeled data, then train a small model to handle L1 and L2 traffic. A common mistake here is prioritizing data volume; in fact, labeling consistency and difficulty coverage matter more. Before launch, be sure to keep the strong model as a fallback channel that automatically escalates when the small model’s confidence falls below a threshold, forming a hybrid setup of “cheap as primary, expensive as fallback.”
6. Observability and Cost Attribution
Cost reduction must be measurable, or it cannot be sustained. It is recommended that instrumentation include at least: the model identifier for each call, input and output tokens, latency, whether the cache was hit, whether it was retried, and a business identifier. After attributing costs by business line, you will often find that a few scenarios consume most of the budget, making optimization gains concentrated and clear. Also set budget alerts and rate-limiting/degradation policies to prioritize the L3 critical path under sudden traffic spikes.
7. Recommended Rollout Plan
Week one: establish a baseline by wiring up instrumentation, running the evaluation set, and obtaining the real cost distribution. Week two: make low-risk optimizations—context trimming, output structuring, tightening max_tokens, and enabling caching. Week three: migrate to routing and batching. Week four: evaluate distillation and fine-tuning while keeping fallback strategies. Throughout the process, use evaluation metrics as the gate, so any change can be rolled back.
In summary, price fluctuations are only an external variable; what truly determines long-term spending is architectural choice. Capability tiering puts requests in the right tier, routing and caching cut redundant computation, context governance compresses input size, batching and distillation change the cost curve, and observability keeps optimization on track. This approach does not depend on any single provider’s pricing strategy and works equally well when budgets tighten. If an enterprise wants to run model serving and cost governance in its own environment, relevant general-purpose capabilities from Baidu AI Cloud (such as container platforms, message queues, log services, and monitoring and alerting) can be evaluated as the underlying components for the architecture above.
