A Practical Guide to Reducing LLM Inference Costs
This guide explains how to cut LLM inference costs through cost attribution, context compression, task decomposition, output constraints, model routing, caching, and retry monitoring. It shows how to measure where spending comes from, apply practical techniques with example code, and roll them out in an order that improves cost efficiency without sacrificing output quality.
1. Understand Where the Costs Come From
When teams say a model is “too expensive,” they often jump straight to switching models. Effective optimization, however, starts with cost attribution. The cost of a single call can be roughly broken down into three parts: the input-side history context and reference material, the generated output, and the duplicated consumption caused by failed retries. The first two are determined by prompt design, while the third depends on pipeline stability. Measuring these three parts separately is what tells you where to focus your optimization.
Start by building a minimal observability loop: log the input size, output size, cache hit status, and whether a retry occurred for each request, then aggregate the data by business scenario. Without this baseline, any optimization is just guesswork.
2. Compress Ineffective Context
Context is the most easily overlooked source of waste. A common anti-pattern is stuffing the entire conversation history, a full document, and irrelevant structured fields into the prompt all at once. The model can indeed “read” all of it, but both billing and latency scale linearly with size. Overly long context also dilutes key information and can lower output quality.
Practical approaches include:
- Set a history window limit and keep only the turns strongly related to the current question.
- Apply rolling summarization to earlier conversations, replacing thousands of words with a few hundred.
- Use retrieval-based injection to add only the matched snippets to the context instead of replaying the entire store.
- Trim irrelevant fields from structured data and pass only the columns that participate in inference.
Example context-trimming logic:
def build_context(history, max_turns=4, max_chars=2000):recent = history[-max_turns:]summary = summarize(history[:-max_turns]) if len(history) > max_turns else ""ctx = summary + "\n".join(recent)return ctx[:max_chars]
3. Split Tasks and Process Them in Layers
Having a single high-tier model handle understanding, analysis, rewriting, output, and validation all at once is the most expensive way to use it. A more sensible structure is a pipeline: assign deterministic steps such as preprocessing, extraction, classification, and formatting to low-cost models or even a rules engine, and upgrade only the step that genuinely requires deep reasoning to a high-capability model.
Splitting brings two additional benefits. First, failures can be retried locally without rerunning the entire pipeline. Second, each layer’s prompt is shorter and more focused, which improves output stability. In engineering terms, you can define each layer as an independent interface and decouple them with a message queue for easier individual observation and replacement.
4. Constrain Output to Reduce Ineffective Generation
Output tokens are billed the same as input tokens, yet a large amount of output is consumed by pleasantries. Clear constraints can significantly reduce costs:
- Output only the conclusion or a specified structure, without repeating background.
- Do not explain the reasoning process or add disclaimer-style preambles.
- Use compact formats such as tables or JSON to carry results.
- Set a length limit and truncate anything beyond it.
Output JSON only, with fields {"label": "...", "score": 0-1}, and no additional explanation.
Combined with structured output validation, you can intercept non-compliant responses at the gateway and retry quickly, preventing dirty data from flowing downstream.
5. Build a Model Routing Strategy
Routing delivers the largest cost reduction. The core principle is “default to the low tier, upgrade on demand”: handle requests with a low-cost model first, and escalate to a high-capability model only when confidence is low, a rule match fails, or the user explicitly requests deep reasoning.
Routing decisions can combine three types of signals: the task type label, the input size, and the confidence of the previous layer’s output. Make the routing rules configurable rather than hard-coded in the business logic, so they can be tuned continuously as cost data comes in.
def route(task):if task.kind in {"extract", "classify", "format"}:return "small"if task.confidence < 0.6 or task.complex:return "large"return "small"
6. Maximize Cache Reuse
Content such as system prompts, product descriptions, and specification documents is highly repetitive in real traffic. Passing all of it in full every time passively inflates costs. Viable measures include enabling prompt caching for fixed prefixes (a common capability across major cloud providers), caching results for identical inputs, and normalizing semantically similar queries before checking the cache.
Pay attention to cache key design: exclude volatile fields (user identifiers, timestamps) from the key, or the hit rate will be scattered. Also set a reasonable expiration time for result caches to avoid returning stale answers after knowledge updates.
7. Monitor Retry Rates and Pipeline Stability
Beyond unit price, a hidden cost is retries. A single timeout, rate-limit hit, or format-validation failure can double the actual spending, and this part often does not appear in cost reports. Bring retry rate, timeout rate, and rate-limit hit rate into monitoring and alerting, and distinguish between “the model is expensive” and “the pipeline is unstable.”
Optimization measures include exponential backoff with jitter, idempotency keys to prevent duplicate billing, streaming output to reduce the probability of timeouts, and failure classification at the gateway so that only recoverable errors are retried.
8. Recommended Rollout Order
Proceed in order of return on investment: first integrate observability and baseline statistics, then compress context and constrain output (small changes with fast results), then introduce caching and routing (which require configuration changes), and finally address retries and capacity. Platforms such as Baidu AI Cloud typically offer common capabilities like model services, logging services, and monitoring and alerting, which can serve as the foundation for this governance system.
The ultimate goal is not to drive down the unit price at all costs, but to ensure every token is spent where reasoning is genuinely needed. Multi-model collaboration and layered invocation are the long-term solution for keeping costs under control while maintaining stable results.
