The RAG Cost Challenge
After deploying our first production RAG system for internal technical documentation, we hit a predictable wall: the token bill was growing faster than the user base. The culprit wasn't the LLM itself—it was the retrieval strategy. Every query, whether a simple "what version of Python is supported?" or a complex "debug this distributed tracing issue," triggered the same expensive pipeline: embed the query, retrieve top-10 chunks from a 50,000-document corpus, and send everything to a premium model.
In the early stages of deployment, we prioritized correctness above all else. We assumed that providing the model with as much context as possible would minimize hallucinations and maximize accuracy. However, we quickly realized that we were treating all queries as equally complex. A simple factual query—one that could be answered by a single sentence in a single document—was being processed with the same resource intensity as a deep architectural analysis.
The economics of this approach were unsustainable. Each request to a premium model like Claude 3.5 Sonnet or GPT-4o comes with a cost that scales with the number of input tokens. When you retrieve ten large chunks of context, you are often sending 5,000 to 10,000 tokens per request. For a system handling thousands of queries a day, this "premium-by-default" strategy led to a massive overhead of redundant token spend. We were paying for high-reasoning capabilities and massive context windows for queries that only required a simple lookup.
This post walks through how we implemented a lightweight query classifier to route simple queries to cheaper models and smaller context windows, cutting our per-query cost by roughly 60% without degrading answer quality. All numbers and examples are drawn from our internal production deployment.
The Classification Strategy
We realized that user queries naturally fall into distinct categories of complexity. To optimize for cost, we needed a way to identify these categories before the expensive retrieval and generation steps. We built a three-tier classifier that acts as a gateway for every incoming request.
Tier 1: Fact Lookup These are simple, closed-form questions with definitive answers. Examples include "What is the current stable version of X?", "Where is the config file located?", or "What is the timeout setting for the API?". These queries usually have a single "golden" document that contains the answer. Consequently, they only need 1-2 relevant chunks and can be handled by a fast, low-cost model (like Claude 3 Haiku) without any loss in accuracy.
Tier 2: Procedural/How-To These questions require step-by-step guidance but have a bounded scope. Examples include "How do I rotate the API keys?" or "What are the steps to deploy the staging environment?". These queries typically require a few related passages to build a complete answer. We route these to 3-5 retrieved chunks and a balanced model that can handle basic sequencing and formatting.
Tier 3: Analysis/Debugging These are open-ended questions requiring synthesis across multiple documents. Examples include "Why is my distributed trace showing a gap between service A and B?" or "Compare the performance trade-offs of using Redis vs. Postgres for this specific use case." These queries are the "heavy lifters" of the system. They require the full retrieval budget (top-10 chunks) and our most capable reasoning model to synthesize a coherent, accurate response.
Implementation Approach
A common mistake in building such routers is jumping straight to a complex machine learning model for classification. We avoided this to keep the system interpretable and low-latency. Instead, we used a two-pass approach: a set of fast heuristics followed by a targeted LLM validation step.
Pass 1: Heuristic Scoring
We started by identifying linguistic signals that correlate with query complexity. We used a simple scoring system based on regular expressions and keyword matching.
def classify_query(query: str) -> Tier:
signals = {
"version_number": bool(re.search(r"\\b\\d+\\.\\d+(\\.\\d+)?\\b", query)),
"config_key": any(k in query.lower() for k in ["setting", "parameter", "config", "env"]),
"api_signature": "def " in query or "function" in query.lower(),
"troubleshooting": any(k in query.lower() for k in ["error", "fail", "debug", "issue", "problem"]),
"synthesis": any(k in query.lower() for k in ["compare", "analyze", "architecture", "design", "tradeoff"]),
"length": len(query.split()),
}
score = (
signals["version_number"] * 3 +
signals["config_key"] * 2 +
signals["api_signature"] * 2 +
signals["troubleshooting"] * 1 +
signals["synthesis"] * 3
)
if score >= 5:
return Tier.ANALYSIS
elif score >= 2:
return Tier.PROCEDURAL
return Tier.FACT_LOOKUP
This heuristic pass takes less than 1ms and correctly classifies about 70% of our traffic. However, natural language is messy. A user might ask a complex question using simple words, or a simple question using complex terminology.
Pass 2: LLM Validation
For queries that fall into the "ambiguous" range (scores between 2 and 4), we trigger a second pass. We send a highly optimized, short prompt to our cheapest model (Haiku) asking it to categorize the query into one of the three tiers.
The prompt is strictly constrained: "Categorize this query as FACT, PROC, or ANALYS. Respond with one word only." This adds roughly 50-100ms of latency but significantly increases the accuracy of the routing. By using the cheapest model for this meta-task, the cost of the classifier is negligible compared to the savings gained from correct routing.
Routing Configuration
Once a tier is assigned, the system applies a specific configuration for the rest of the pipeline. This is where the real savings happen.
| Tier | Retrieval K | Model | Context Budget | Est. Cost/Query |
|---|---|---|---|---|
| Fact Lookup | 2 | Haiku-class | 1,500 tokens | ~$0.0008 |
| Procedural | 4 | Sonnet-class (small) | 4,000 tokens | ~$0.004 |
| Analysis | 10 | Sonnet-class (full) | 12,000 tokens | ~$0.025 |
The "Context Budget" refers to the maximum number of tokens we allow the retriever to inject into the prompt. For Tier 1, we aggressively truncate retrieved chunks to the most relevant snippets. For Tier 3, we allow the full context to ensure the model has all the evidence it needs for a complex synthesis.
Handling Edge Cases and Misclassifications
No classifier is perfect. The biggest risk in a tiered system is "under-routing"—assigning a Tier 3 query to Tier 1. When this happens, the model receives insufficient context and produces a "I don't know" response or, worse, a hallucination.
To mitigate this, we implemented a Confidence-Based Escalation pattern. In the generation prompt for Tiers 1 and 2, we instruct the model to signal if it feels the provided context is insufficient to answer the query fully. If the model returns a specific token (e.g., [INSUFFICIENT_CONTEXT]), the system automatically re-routes the query to the next higher tier and retries the request.
While this occasionally adds latency to a few requests, it ensures that quality never drops below the baseline of our original "premium-by-default" system.
Integrating with Observability
One of the unexpected benefits of query classification is the wealth of metadata it provides. By logging the assigned tier for every request, we turned our observability stack into a product discovery tool.
We began tracking the "Tier Distribution" over time. We noticed a significant spike in Tier 3 (Analysis) queries every Tuesday morning. After investigating, we discovered that this coincided with our weekly engineering sync, where developers were asking complex questions about a specific legacy module. This insight allowed us to identify a "knowledge gap" in our documentation. Instead of just spending more on tokens to answer these queries, we tasked the team with updating the documentation for that module, which eventually shifted many of those Tier 3 queries down to Tier 2.
Furthermore, we can now calculate the "Cost per Tier," allowing us to see exactly where our budget is going. We discovered that a small percentage of "power users" were responsible for 40% of our Tier 3 spend, leading us to implement tiered rate limits based on user roles.
Results After Two Months
The impact of the routing system was immediate and measurable across three key dimensions:
1. Drastic Cost Reduction We saw an average per-query cost drop of approximately 60%. The bulk of our traffic (roughly 65%) consists of simple lookups and procedural questions. Shifting this traffic from a $0.025/query path to a $0.0008/query path resulted in thousands of dollars in monthly savings.
2. Latency Improvements Our P50 latency dropped from ~2.8s to ~1.1s. This is because Tier 1 and Tier 2 queries use faster models and smaller contexts, which significantly reduces the time the model spends in the "pre-fill" phase of generation.
3. Stable Quality We tracked quality using a "Golden Dataset" of 500 queries with human-verified answers. The aggregate accuracy score remained flat, and in some cases, improved. We found that providing too much context to the model for simple questions actually increased the likelihood of the model getting distracted by irrelevant information (the "lost in the middle" phenomenon).
What We'd Do Differently
If we were to build this again from scratch, we would make three key changes:
First, we would invest in an embedding-based classifier earlier. While our heuristic + LLM approach worked, it required manual tuning of weights. A small, fine-tuned BERT-style model trained on our own query logs would likely be faster and more accurate.
Second, we would build a more robust A/B testing harness. We deployed the router in a "big bang" release, which made it difficult to isolate exactly which part of the routing logic was driving the most improvement. A gradual rollout with a control group would have provided better data.
Third, we would add user-facing indicators. Some users noticed that answers to simple questions were more concise than they used to be. Adding a small UI tag like "Fast Mode: Based on 2 sources" would have managed user expectations and signaled the efficiency of the system.
Takeaway
For any team running a production RAG system at scale, query classification is one of the highest-ROI optimizations available. It requires minimal changes to the core architecture but delivers massive gains in cost and performance.
The fundamental lesson is that not all questions are created equal. By respecting the diversity of user intent and routing accordingly, you can build a system that is both high-performance and economically sustainable. Whether you use simple heuristics or a fine-tuned classifier, the goal remains the same: match the resource spend to the complexity of the task.
For a deeper dive on how to validate the quality of your RAG outputs after implementing these changes, check out our comprehensive guide on Evaluating RAG Systems: Metrics, Frameworks, and Production Best Practices.
What's your experience with RAG cost optimization? Have you tried query classification, or did you take a different approach like semantic caching or retrieval pruning? We'd love to hear your thoughts in the comments.