LLM Token Cost Optimization: A Practical Guide to Context, Output, and Caching Controls
As large models iterate faster and gain stronger capabilities, per-request token consumption tends to rise. This guide breaks down the engineering side of LLM cost control: building a minimal cost model that includes retry rate, instrumenting usage, reducing input bloat through layered retrieval and context trimming, compressing output with tighter parameters and structured formats, reusing work via prefix caching, semantic caching, and batch APIs, and adding gateway routing, fallback, and observability. It also covers a measurement loop with baselines, canary releases, and common pitfalls such as ignoring retries or over-trimming context. The approach is vendor-neutral and can be assembled on general cloud infrastructure such as Baidu AI Cloud.
1. What Silent Overnight Model Releases Mean for Engineering
Large models are increasingly shipped quietly during off-peak hours, often alongside discussions of “stronger capability, higher token consumption.” For developers, the release time is not the point. Three engineering facts matter:
- Capability upgrades often come with larger context windows and longer reasoning chains, so token consumption per request naturally increases.
- Providers typically bill input tokens and output tokens separately, and output tokens usually carry a higher unit price.
- A new model version can shift output style and structured-output stability, so regression testing cannot be skipped.
“Stronger” and “more expensive” are not contradictory; they are two sides of the same coin. The engineering response is not to refuse upgrades, but to build a measurable cost governance system.
2. Cost Model: Do the Math First
Before optimizing, establish a minimal cost formula:
cost_per_request = input_tokens * input_price + output_tokens * output_pricedaily_cost = cost_per_request * daily_requests * (1 + retry_rate)
Retry rate is the most easily overlooked variable. Timeouts, rate limiting, and structured parsing failures all trigger retries, and the real bill can be 20%–50% higher than the theoretical value.
Instrumentation should capture at least the following fields:
{"request_id": "r-8f2c","model_version": "v-current","input_tokens": 1840,"output_tokens": 320,"latency_ms": 2260,"retry": 0,"cache_hit": false,"scene": "code_review"}
With this data in place, every later optimization has a baseline to compare against.
3. Context Governance: The Highest-Return Lever
Input tokens are usually the main cost driver, and input bloat mostly comes from stuffing context without a strategy. Practical measures:
- Layered retrieval: recall candidate fragments with a lightweight retriever first, then compress them to the necessary passages with a reranking model, instead of passing whole documents.
- Structured trimming: keep only the functions, type definitions, and call chains relevant to the current question; drop comment blocks and blank lines.
- Summary-first: apply rolling summaries to long conversation histories, compressing multiple turns of raw text into a fixed-length state description.
- Template slimming: remove repeated constraints from the system prompt and move variable content into the user message so it can hit the cache.
Illustrative code (pseudocode, only expressing the trimming idea):
def build_context(query, candidates, budget=2000):ranked = rerank(query, candidates)picked, used = [], 0for c in ranked:if used + c.tokens > budget:breakpicked.append(c.text)used += c.tokensreturn "\n\n".join(picked)
4. Inference Parameters and Output-Side Optimization
Output tokens cost more, so compressing output saves money directly:
- Set
max_tokensto the real upper bound of the business case rather than a large default, avoiding verbose endings. - Cut unnecessary explanatory output and constrain answers with a fixed format (such as a table or JSON).
- Set temperature per scenario: low for extraction and classification, high for creative generation, to avoid unproductive divergence.
- For enumerable results, return option IDs instead of long text, turning long answers into short identifiers.
Structured output example:
{"bug": true, "severity": "P1", "file": "cache.go", "line": 128}
5. Caching and Batching: Remove Repeated Work
- Prefix caching: place the stable system prompt and knowledge fragments at the very front of the request. Most platforms cache identical prefixes, which can significantly reduce input billing and time to first token.
- Semantic caching: build a vector index for high-frequency similar questions, return the historical answer directly when the similarity is above the threshold, and set a TTL plus manual spot checks.
- Batch APIs: use asynchronous batch processing for offline tasks (log classification, bulk labeling). It is usually cheaper with higher throughput, at the cost of latency tolerance.
- Persist results: write reusable conclusions to object storage or a cache service so the same analysis is not paid for twice.
6. Elasticity and Stability at the Architecture Level
- Unified gateway: route all calls through a single gateway to make rate limiting, retries, auditing, and cost accounting straightforward.
- Tiered routing: send simple tasks to smaller models or a rules engine, and escalate to larger models only for complex tasks.
- Circuit breaking and fallback: when the primary path fails, fall back to cached answers or template replies to keep the business available.
- Elastic scaling: let the container platform scale automatically based on queue length, avoiding long-term resource occupation at peak.
- Full-chain observability: have the logging service collect call chains, and set alert thresholds on token consumption, failure rate, and P95 latency.
7. Verification Loop: Optimization Must Be Measurable
Fix a load-test and regression process:
- Run a baseline on a fixed evaluation set, recording accuracy, structured parsing success rate, and average tokens.
- Re-run the same set after each change, checking that “quality holds and cost drops.”
- Release new versions gradually, starting at 5% traffic, comparing cost and failure rate before going full.
- Review the top token-consuming scenarios weekly, and run targeted governance on the three most expensive ones.
8. Common Pitfalls
- Compressing input while ignoring retries leaves the bill out of control.
- Semantic caching without an invalidation strategy serves stale answers.
- Over-trimming context causes hallucinations and parsing failures, which increase retry costs instead.
- Ignoring version drift means a silent model upgrade causes online quality swings that are hard to trace.
Conclusion
Against a faster model iteration cadence, the core of cost governance is treating each “call” as an observable, replayable, optimizable engineering object: quantify first, then trim context, compress output, reuse caches, and batch asynchronously, and finally hold the quality line with an elastic architecture and regression evaluation. This method does not depend on any specific vendor’s capabilities and can be assembled by category on general cloud infrastructure such as Baidu AI Cloud, helping teams balance capability upgrades with a controllable bill.
