Cutting LLM Token Costs: Routing, Caching, and Context Optimization
This article presents practical engineering strategies for reducing large language model (LLM) API costs in production. It outlines a three-step approach: analyzing cost distribution by request type, implementing intent-based routing to assign tasks to appropriately sized models, and using semantic caching to avoid redundant calls. It also covers context window management techniques like sliding windows and summarization to control input token growth. Designed for engineering teams, the guide emphasizes realistic prerequisites, common pitfalls, and the importance of validating thresholds with real-world data.
After deploying a large language model (LLM) application, many teams encounter a familiar problem: the feature works, but the bill is far higher than expected. Frontier model pricing often remains high for extended periods, and under significant concurrent load, token expenditure can quickly become a primary cost driver. Rather than waiting for prices to drop, it is more effective to examine the call chain from an engineering perspective and identify areas where usage can be compressed. This article follows a logical order—first calculate the cost, then route traffic, then compress tokens—to introduce several common cost-reduction techniques, along with their prerequisites and common misconceptions.
1. Calculate Your Costs Before Making Changes
Token fees are typically divided into input and output costs, which may have different unit prices, with output frequently being more expensive. Therefore, before optimizing, you should analyze your call volume, average input tokens, and average output tokens by request type. The sample table below is for illustrative purposes only and does not represent real data:
| Request Type | Traffic Share | Suggested Model | Avg Input Tokens | Avg Output Tokens |
|---|---|---|---|---|
| Chit-chat & casual conversation | 30% | Smaller model | 200 | 50 |
| Information lookup | 35% | Smaller model or cache | 600 | 150 |
| Data format conversion | 15% | Smaller model | 800 | 800 |
| Complex reasoning & code generation | 20% | Frontier model | 3000 | 1500 |
Once you have this data, estimate the monthly cost by multiplying the call volume by the cost per request. The cost per request equals (input tokens × input price) + (output tokens × output price). Refer to your model provider’s current price list for accurate unit costs. With a clear cost breakdown, you can identify which request types are worth optimizing first.
2. Intent-Based Classification for Tiered Routing
Not every request requires a frontier model. You can place a lightweight classifier at the entry point of your application. This classifier, typically a smaller and cheaper model, determines the type of user query and outputs both a category and a confidence score. Only requests that require complex reasoning, in-depth code generation, or long-form creative writing should be routed to your flagship model. All other requests can be handled by a smaller model or answered from a cache.
There are two critical aspects to routing design:
- Calibrate thresholds with labeled data. Collect several hundred real user queries and manually label which model tier each one should be routed to. Then, compare the precision and recall of different confidence thresholds against this labeled dataset to find the optimal cutoff.
- A missed route is more damaging than a misroute. If a complex query that should go to the flagship model is incorrectly classified and sent to a smaller model, the user will notice a significant drop in answer quality. As a result, you should default to sending low-confidence queries to the flagship model rather than the cheaper path.
The savings from tiered routing depend heavily on your request distribution. If most of your traffic consists of complex tasks, the potential for savings is limited. Before going live, use historical logs to simulate and estimate the real savings ratio; do not simply rely on industry averages.
3. Semantic Caching: Reducing Redundant Calls
Traditional exact-match caching only works when the input string is identical. It provides limited benefit for natural language processing where users ask the same question in many different ways. Semantic caching solves this by converting a user query into a vector embedding and searching a vector database for similar historical questions. If the similarity score exceeds a threshold, the cached answer is returned directly.
Below is a corrected pseudocode example:
def generate_response(user_query):query_embedding = embedding_model.encode(user_query)similar_hit = vector_db.search(query_embedding, threshold=0.95)if similar_hit and similar_hit.is_valid():# Cache hit - no LLM call is made, but embedding and search costs remainreturn similar_hit.responseresponse = frontier_llm.generate(user_query)if response.ok:vector_db.insert(query_embedding, response, ttl=86400)return response
Several important caveats apply to this approach:
- Threshold tuning. A score of 0.95 is a starting point. You must calibrate the threshold using labeled pairs of similar and dissimilar questions. If the threshold is too low, questions that are worded similarly but have different intents will be served incorrect cached answers.
- Time-to-Live (TTL). Cached entries must have an expiration time. For content that is time-sensitive—such as pricing, inventory, or policy details—the TTL should be set to a short duration. You should also actively invalidate relevant cache entries when your knowledge base is updated.
- Personalized content. Caching is unsuitable for responses that contain user-specific account information, permissions, or other personalized data.
To measure the effectiveness of your semantic cache, track both the hit rate and the false-hit rate. You can estimate the false-hit rate by randomly sampling the cached responses that were served. If you have a high hit rate but also a high false-hit rate, you should raise your similarity threshold.
4. Context Engineering: Controlling Input Tokens
In multi-turn conversations, if you send the complete history with every request, your input token count will grow continuously with each turn. A common solution is to combine a sliding window with summarization.
The sliding window retains the most recent N turns of the conversation. There is no one-size-fits-all value for N; for most use cases, you can start with 4 to 8 turns and then run A/B tests to balance quality against cost. Earlier parts of the conversation are condensed into a summary by a smaller, cheaper model, which then replaces the raw historical record. You can trigger summarization when the history length exceeds a certain threshold—for instance, 3000 tokens—or after every few turns.
The summarization process itself can fail. If the model times out or produces a poor-quality summary, the system should have a fallback plan, such as simply keeping only the recent N turns and the system instructions. Any key parameters that the user has already confirmed should be stored in a dedicated field that is never truncated.
Prompt optimization is just as effective. Remove adjectives and filler words that are irrelevant to the task, and keep only the necessary instructions. On the output side, use structured output formats and set a maximum token limit. For example, you can instruct the model to output only the following JSON:
{"label": "complaint", "confidence": 0.82}
Additionally, set the max_tokens parameter in your API request to prevent the model from generating lengthy explanatory text. If parsing fails, limit the retry logic to a maximum of one attempt.
