Token Efficiency Optimization for LLMs: A Practical Guide to Lowering Costs and Latency
As model vendors shift their focus from parameter counts to doing more with fewer tokens, the marginal cost of LLM applications is becoming an architecture problem rather than a pricing problem. This guide breaks down where tokens are actually spent across system prompts, conversation history, retrieval context, tool definitions, output, and retries, then walks through four optimization tracks: semantic compression, cache reuse, tiered model routing, and output governance. It also covers how to use low-latency modes appropriately, which metrics prove that optimization works, and common pitfalls to avoid. The methodology is infrastructure-agnostic and can be applied on any general-purpose cloud platform.
1. The Real Engineering Problem Behind Model Releases
A notable signal has emerged in the industry recently: when vendors ship a new generation of models, they no longer compete purely on parameter counts and benchmark scores. Instead, they highlight “fewer tokens to complete the same task” as a core selling point, while cutting the per-unit prices of input, cached input, and output. The price drop for cached input is often far steeper than for regular input.
For developers and enterprise engineering teams, the value of this signal has nothing to do with any specific model. It validates an engineering judgment: the marginal cost of LLM applications is shifting from a “model pricing problem” to a “token efficiency problem.” As price declines flatten out, what truly separates cost profiles is how you design your invocation architecture.
This article sets aside product-specific details and focuses on a general technical question: how to systematically reduce the token consumption and end-to-end latency of a unit of work.
2. Breaking Down Token Consumption: Measure First, Optimize Second
No optimization is valid without observability. Start by instrumenting the calling layer so that a single request can be attributed to six categories of overhead:
- System prompt overhead: Constant across requests, but billed every single time. It is the most easily overlooked fixed cost.
- Conversation history overhead: Repeatedly carried across multi-turn conversations, usually the largest share of total input.
- Retrieval-augmented context overhead: Retrieved document chunks. Poor-quality retrieval is not only expensive but also degrades output quality and triggers retries.
- Tool and function definition overhead: Tool schemas grow linearly with the number of tools.
- Output overhead: Priced at several times the input rate, making it the most expensive component.
- Failure and retry overhead: Repeated billing caused by truncation, malformed output, and timeouts. This is pure waste.
An example instrumentation record:
{"trace_id": "req-8f21","task_type": "code_review","model_tier": "flagship","input_tokens": 12840,"cached_input_tokens": 9600,"output_tokens": 730,"retry_count": 1,"latency_ms": 4120,"cost_estimate": 0.0143}
With this data in place, you can finally answer the questions that matter: is the budget going into “thinking” or “writing,” and into the first call or into failed retries?
3. Four Main Optimization Tracks
3.1 Semantic Compression: Cut Input Without Losing Information
- Trim the prompt: Remove redundant examples, repeated constraints, and emotional phrasing. Rewrite long paragraphs of constraints as structured fields.
- Summarize history: Once history exceeds a threshold, apply rolling summarization to older turns and keep only conclusions and open items.
- Rerank and truncate retrieved chunks: Do coarse retrieval first, then fine-grained reranking, and feed only the top-K, high-relevance chunks into the context.
def build_context(history, k=4, max_chars=6000):summary = summarize(history[:-6]) if len(history) > 6 else ""recent = history[-6:]docs = rerank(retrieve(history[-1]), k=k)ctx = summary + "\n" + flatten(recent) + "\n" + join(docs)return ctx[:max_chars]
3.2 Cache Reuse: Turn Repeated Billing into Cache Hits
Cached input is priced significantly lower than regular input, which leads to a new principle for prompt design: put stable content first and volatile content last. System prompts, tool definitions, and domain specifications belong at the front; real-time user input goes at the end. This maximizes the prefix reuse rate.
You should also cache results at the application layer: build vector keys for semantically equivalent requests and return the cached result directly on a hit, avoiding the entire invocation.
3.3 Tiered Routing: Coordinating Flagship and Efficient Models
Routing tasks by complexity is the layer with the most obvious cost payoff:
| Task Characteristics | Recommended Tier | Rationale |
|---|---|---|
| Architecture design, hard-to-diagnose defects | Flagship model | One-shot correctness comes first |
| Classification, extraction, format conversion, routine Q&A | Efficient model | Throughput and unit price come first |
| Batch summarization, log consolidation | Efficient model + batching | Latency is tolerable |
Keep the routing decision rule-based and evaluated up front, so you avoid spending an extra call on a small model just to classify the task:
def route(task):if task.needs_deep_reasoning or task.risk_level == "high":return "flagship"return "efficient"
3.4 Output Governance: Spend the Most Expensive Tokens Wisely
- Use structured output to constrain formatting and cut explanatory filler.
- Set a reasonable maximum output length and stop conditions to prevent rambling, off-topic responses.
- For long-form generation, draft an outline first and fill in sections incrementally, avoiding repeated output from rewriting the whole piece.
4. Latency Optimization: Using High-Speed Mode Correctly
Low-latency modes trade more aggressive inference and scheduling strategies for response speed. They fit interactive completion, inline suggestions in AI coding tools, and real-time customer support responses. Latency-insensitive but quality-sensitive tasks, such as offline batch processing and complex repository-level refactoring, should retain the full reasoning budget.
The engineering recommendation is to run two channels: the interactive path uses the low-latency channel with short outputs enforced, while the background path uses the quality channel, writes results back asynchronously, smooths peaks through a message queue, stores results in object storage, and tracks P95 latency and failure rates end to end with logging and monitoring with alerting.
5. Measuring Results: Prove the Optimization with Data
Do not conclude with “it feels cheaper.” Establish three metrics instead:
- Cost per successful task = total billed amount / number of successful tasks (not number of calls, so retries cannot mask the real figure);
- Token efficiency ratio = amount of useful information in the output / total tokens, approximated via manual sampling or rule-based checks;
- Quality regression rate: the difference in pass rate on the same evaluation set before and after optimization. A non-reversible red line must be defined.
For the rollout, enable compression and routing for 10% of traffic first, observe for a week, then gradually increase the share.
6. Common Pitfalls
- Focusing only on unit price while ignoring architecture, so cost still grows linearly with context.
- Over-compressing until information is missing, so retry costs exceed the savings.
- Including volatile fields such as timestamps in the cache key, driving the hit rate toward zero over time.
- Sending every task to the flagship model, which yields limited quality gains while doubling cost.
7. Conclusion
The combination of “fewer tokens plus lower unit prices” within the same model generation essentially hands optimization control back to the application layer. What teams truly need to build are three things: an attributable token metering system, a reuse design based on stable prefixes and result caching, and a model routing strategy tiered by complexity. Get these three solid, and the cost per unit of work will keep falling no matter how the underlying models evolve. If you run on general-purpose cloud infrastructure with container platforms, object storage, message queues, and monitoring with alerting, such as Baidu AI Cloud, this methodology can be reused directly without binding to any proprietary interface.
