Reducing LLM Inference Costs: A Practical Guide to Token Optimization
This guide explains how to model and control large language model inference costs by reducing unnecessary tokens, improving cache hit rates, using retrieval instead of full-document injection, routing tasks across model tiers, and balancing latency against cost. It also covers evaluation practices and an implementation checklist for maintaining quality while making usage costs more predictable.
1. Why Inference Costs Need Dedicated Management
Large language model services are typically billed by token. The cost of a request consists of three components: input tokens, cache-hit input tokens, and output tokens. These categories often have different prices, with output tokens usually being the most expensive.
As adoption grows, cost problems typically appear in three ways:
- Growing request volume: A single request may seem inexpensive, but tens or hundreds of thousands of daily calls can cause costs to increase linearly.
- Expanding context: Multi-turn conversations, long documents, and retrieved passages accumulate over time, continuously increasing the number of input tokens.
- Latency and user experience: Longer outputs and more reasoning steps increase both time to first token and total response time, while reducing concurrency capacity.
For this reason, cost management should be included during architecture design rather than addressed only after the bill becomes unexpectedly high.
2. Build a Cost Model
Before optimizing, break the bill into measurable variables. The cost of a single request can be represented as:
Cost = (uncached input tokens × input price+ cached input tokens × cached price+ output tokens × output price) ÷ 1,000,000
Prices are expressed per million tokens. The following code wraps this formula in a function, making it easier to track the cost of individual requests and cumulative usage in logs or monitoring systems:
from dataclasses import dataclass@dataclassclass Pricing:input_per_m: float # Price per million uncached input tokenscached_per_m: float # Price per million cached input tokensoutput_per_m: float # Price per million output tokensdef estimate_cost(pricing: Pricing, input_tokens: int,cached_tokens: int, output_tokens: int) -> float:"""input_tokens is the total input token count, including cached_tokens."""fresh_tokens = input_tokens - cached_tokensreturn (fresh_tokens * pricing.input_per_m+ cached_tokens * pricing.cached_per_m+ output_tokens * pricing.output_per_m) / 1_000_000
Assume a model is priced at 2 units per million input tokens, 0.2 units per million cached input tokens, and 10 units per million output tokens. If a request contains 3,000 input tokens, 2,400 of which are cached, and generates 500 output tokens:
- Uncached input: 600 × 2 = 1,200
- Cached input: 2,400 × 0.2 = 480
- Output: 500 × 10 = 5,000
- Total: 6,680 ÷ 1,000,000 ≈ 0.00668 units
This example highlights two important points: output tokens are the primary cost driver, while cache hits can significantly reduce input costs.
3. Four Ways to Reduce Token Usage
3.1 Make Prompts More Concise
Common prompt issues include repeated instructions, unnecessarily long background descriptions, and examples that are unrelated to the task. The following practices can help:
- Combine similar rules and remove duplicate constraints.
- Replace long natural-language descriptions with structured fields, such as input, constraints, and output format.
- Keep the number of examples limited to what is necessary. One or two representative examples are often sufficient.
After simplifying a prompt, use an evaluation set to verify that performance has not declined. Otherwise, the apparent cost savings may simply be offset by a higher error rate.
3.2 Control Output Length
Because output tokens are often expensive, limiting output length can produce immediate savings. There are three practical approaches:
- Define an explicit format: Require the model to return only the specified JSON fields and avoid greetings, filler text, or repeated summaries.
- Set an upper bound: Use request parameters to limit the maximum number of output tokens and prevent runaway generation in abnormal cases.
- Split the task: Instead of asking the model to analyze a topic and generate a complete report in one step, first extract the key points and then generate the report from those points. Each step can produce a shorter output.
3.3 Improve Cache Hit Rates
Prefix caching works by charging a lower price for a leading section of a request when it is exactly the same as the corresponding section in previous requests. To take advantage of this behavior, place stable content at the beginning of the request and variable content at the end.
def build_messages(system_rules: str, reference_docs: str, user_question: str):# Put stable content first and the dynamic question last for prefix reusereturn [{"role": "system", "content": system_rules + "\n" + reference_docs},{"role": "user", "content": user_question},]
Keep the following points in mind during implementation:
- The prefix must match byte for byte. Timestamps, random IDs, or unstable ordering can all prevent a cache hit.
- System instructions and fixed knowledge-base content should be version-controlled. Frequent changes can invalidate the cache.
- Track the number of cached input tokens in logs and regularly verify that the cache hit rate meets expectations.
3.4 Use Retrieval Instead of Full-Document Injection
Many applications place an entire document into the context by default. A more efficient approach is to retrieve passages relevant to the user’s question and inject only those passages. This approach is commonly known as retrieval-augmented generation, or RAG.
It reduces irrelevant tokens and lowers the risk of the model being distracted by noise. Retrieval quality should be evaluated separately. If recall is too low, the model may lack essential information, causing overall performance to decline.
4. Route Requests Across Model Tiers
Not every task requires the most capable model. Common tasks can be grouped into three categories:
| Task type | Typical examples | Recommended strategy |
|---|---|---|
| Simple classification | Sentiment classification, intent detection | Lightweight model |
| Structured extraction | Field extraction, form parsing | Lightweight model, with fallback on failure |
| Complex reasoning | Multi-step planning, code review, long-document analysis | More capable model |
The following example shows a rule-based routing strategy:
SIMPLE_TASKS = {"classify", "extract"}def pick_tier(task_type: str, prompt_chars: int, low_confidence: bool = False) -> str:if low_confidence:return "large" # Escalate when the lightweight model lacks confidenceif prompt_chars > 20_000:return "large" # Send very long inputs to the more capable modelreturn "small" if task_type in SIMPLE_TASKS else "large"
Before deploying a routing strategy, compare it with a baseline that uses the flagship model for all requests. Confirm that the accuracy gap for the target tasks remains within an acceptable range.
5. Balance Speed and Cost
Low-latency modes, priority channels, and high-concurrency quotas often involve higher unit costs or require higher-tier resource configurations. The right choice depends on the workload:
- Interactive applications: Users are sensitive to waiting time, so time to first token may matter more than unit price. Low-latency resources can be reserved for critical paths.
- Offline batch processing: Report generation, data cleaning, and label completion are less latency-sensitive. They are suitable for asynchronous queues and batch submission, which can reduce unit costs.
- Peak traffic: Apply rate limiting at the client or gateway layer. A token bucket algorithm can smooth traffic bursts and prevent large numbers of failures and retries after quotas are exceeded.
Retry behavior also affects cost. Exponential backoff with random jitter can prevent many requests from retrying simultaneously and reduce duplicate charges.
6. Use Evaluation to Protect Quality
Cost reduction is acceptable only when performance remains within an appropriate range. Establish an evaluation process with the following components:
- Build an evaluation set: Sample representative data from real workloads, including both common and edge cases.
- Define metrics: Choose metrics such as accuracy, recall, human ratings, or structured-field match rates based on the task, and set minimum thresholds.
- Run comparative experiments: Whenever you change a prompt, switch models, or adjust routing rules, run the same evaluation set and record the changes in both quality and cost.
- Roll out gradually: Apply new strategies to a small percentage of traffic first, monitor production metrics, and then increase coverage progressively.
Looking only at cost while ignoring quality often causes error rates to rise quietly. The problem may not become visible until users begin reporting it.
7. Implementation Checklist
- Track token usage and cost for every request across uncached input, cached input, and output.
- Set a maximum output-token limit for every interface and require structured output.
- Place stable prefix content first and include cache hit rates in monitoring.
- Replace full-document injection with retrieved passages and evaluate retrieval quality separately.
- Test tiered routing for simple tasks and retain a fallback mechanism.
- Configure separate resources and queues for online and offline workloads.
- Record evaluation comparisons and gradual rollout results for every strategy change.
Reviewing this checklist item by item can help keep large language model costs predictable without sacrificing critical quality.
