Understanding RAG: A Practical Guide for Engineers - Part 3: RAG in Production — What Actually Matters
Part 1 covered what RAG is. Part 2 explained the mechanics — vectors, embeddings, the three stages. Now let’s talk about what actually matters when you’re building something people depend on.
Because here’s the uncomfortable truth: if you followed the first two parts and built a basic RAG system, it probably gets about 60% of questions right. That’s the dirty secret of every RAG tutorial — the version they walk you through isn’t good enough to ship.
The gap between 60% and 90% is where the real engineering lives. This article covers the five things that close that gap.
Hybrid Search: Why Vectors Alone Aren’t Enough
Semantic search is powerful. It understands that “authentication” and “login” mean the same thing. But it has a blind spot that will bite you in production: it’s terrible at exact matches.
User query: "error code 4012"
Semantic search retrieves:
1. "Common API error handling patterns" (similarity: 0.82)
2. "Authentication failures and error responses" (similarity: 0.79)
3. "Debugging production errors in distributed systems" (similarity: 0.76)
What the user actually needed:
"Error 4012: Rate limit exceeded. Wait 60 seconds before retrying."
The vector for “error code 4012” is semantically close to anything about errors. But the user doesn’t want documents about errors — they want the specific document that contains the string “4012.” Semantic search doesn’t do string matching. It does meaning matching.
This shows up constantly in production:
- Product SKUs and model numbers — “XR-7200” has no semantic meaning
- Error codes — “ECONNREFUSED” isn’t conceptually searchable
- Names and identifiers — “Jonathan Penny” shouldn’t match “John Pennington”
- Exact phrases from policy docs — “section 4.2.1” needs an exact hit
- Version numbers — “v2.3.1” vs “v2.3.2” matters enormously
The Fix: Combine Both
Hybrid search runs semantic search and keyword search in parallel, then merges the results:
User query: "error code 4012"
Semantic search results: Keyword (BM25) results:
1. "API error handling" 1. "Error 4012: Rate limit exceeded"
2. "Auth failures" 2. "Error codes 4010-4015 reference"
3. "Debugging errors" 3. "Changelog: added error 4012"
Combined + reranked:
1. "Error 4012: Rate limit exceeded" ← Exact match wins
2. "Error codes 4010-4015 reference" ← Also contains "4012"
3. "API error handling" ← Semantically relevant backup
BM25 is the keyword search algorithm most systems use. It’s the same algorithm behind Elasticsearch and Solr — battle-tested for decades. It’s fast, it handles exact matches well, and it doesn’t need embeddings.
The combination covers both failure modes: semantic search catches the “different words, same meaning” cases, and BM25 catches the “I need this exact string” cases.
How to Weight Them
Most systems let you control the balance:
score = (alpha × semantic_score) + ((1 - alpha) × keyword_score)
Start with alpha = 0.7 (favor semantic) and adjust based on your data. If your documents are full of codes, IDs, and technical identifiers, push it toward 0.5. If they’re mostly natural language prose, 0.8 works.
There’s no universal right answer. This is why evaluation matters — which we’ll get to.
Chunking: The Difference Between 60% and 90%
Chunking is how you split documents into pieces before embedding them. It sounds like a minor implementation detail. It’s not. Bad chunking is the single most common reason RAG systems give wrong answers.
Why Chunking Matters So Much
Remember from Part 2: you retrieve chunks, not documents. If the answer to a question is split across two chunks, and you only retrieve one, the LLM gets an incomplete picture and generates an incomplete (or wrong) answer.
Original document:
"The refund policy allows returns within 30 days of purchase.
Items must be in original packaging. Electronics have a 15-day
window instead. Refunds are processed within 5-7 business days."
Bad chunking (split at 100 characters):
Chunk 1: "The refund policy allows returns within 30 days of purchase. Items must be in original packa"
Chunk 2: "ging. Electronics have a 15-day window instead. Refunds are processed within 5-7 business days."
User asks: "What's the return window for electronics?"
Retrieved: Chunk 1 (mentions "returns" and "30 days")
LLM answers: "The return window is 30 days." ← WRONG
The correct answer (15 days for electronics) was in Chunk 2, but Chunk 1 scored higher because it contained “returns” and a timeframe. The chunking broke a paragraph that needed to stay together.
Strategies That Work
Fixed-size with overlap — The simplest approach that’s actually usable. Split every N tokens with M tokens of overlap between chunks:
Chunk size: 200 tokens
Overlap: 50 tokens
Chunk 1: tokens 1-200
Chunk 2: tokens 151-350
Chunk 3: tokens 301-500
The overlap means information at chunk boundaries appears in two chunks, reducing the chance of splitting critical context. Start with 200-400 tokens and 10-20% overlap.
Semantic chunking — Split at natural boundaries: paragraph breaks, section headers, topic changes. This preserves the logical structure of the document.
Input: A technical doc with clear sections
Split at:
- Section headers (## Configuration, ## Authentication)
- Double newlines (paragraph breaks)
- Topic shifts detected by embedding similarity
Result: Chunks that map to coherent ideas, not arbitrary byte offsets
This is harder to implement but produces better chunks for structured documents like documentation, policies, and technical specs.
Document-aware chunking — Different document types need different strategies:
| Document type | Strategy | Why |
|---|---|---|
| API docs | Split by endpoint | Each endpoint is a self-contained unit |
| Legal/policy | Split by section/clause | Cross-referencing matters |
| Chat logs | Split by conversation turn | Context flows between messages |
| Code | Split by function/class | Logical code units |
| FAQ | Split by question-answer pair | Each Q&A is atomic |
The right chunking strategy depends on what your documents look like and what questions people ask. This is not something you set once and forget — it’s something you iterate on as you see what questions your system gets wrong.
Chunk Size Tradeoffs
Smaller chunks (100-200 tokens):
- More precise retrieval
- Less noise in the context
- Higher risk of missing surrounding context
- More chunks to store and search
Larger chunks (500-1000 tokens):
- More context preserved per chunk
- Fewer storage and search costs
- Higher risk of diluting the relevant information
- May hit context limits faster when retrieving multiple chunks
There’s no universally correct size. But I’ll save you some experimentation: 200-400 tokens with 10-20% overlap is a reasonable starting point for most text documents. Adjust from there based on your evaluation metrics.
Evaluation: How to Measure Quality
You can’t improve what you can’t measure. And “it feels like it’s working better” is not a measurement.
RAG evaluation is harder than it sounds because there are multiple points of failure, and a wrong answer could be caused by bad retrieval, bad generation, or both.
The Two Things to Measure Separately
Retrieval quality — Did you find the right chunks?
Generation quality — Given the right chunks, did the LLM produce a good answer?
Separating these matters. If retrieval is the problem, improving your prompt won’t help. If generation is the problem, better chunking won’t help. You need to know which one to fix.
Retrieval Metrics
Recall@k — Of all the relevant chunks in your database, what percentage did you retrieve in the top k results?
Database has 3 chunks relevant to "refund policy"
You retrieve top 5 chunks
2 of the 3 relevant chunks are in your top 5
Recall@5 = 2/3 = 0.67
High recall means you’re finding most of the relevant information. Low recall means you’re missing important context.
Precision@k — Of the chunks you retrieved, what percentage were actually relevant?
You retrieve top 5 chunks
2 of the 5 are relevant to the question
Precision@5 = 2/5 = 0.40
High precision means you’re not flooding the LLM with irrelevant context. Low precision means you’re wasting context window space on noise.
MRR (Mean Reciprocal Rank) — How high in the results does the first relevant chunk appear?
Query 1: First relevant result at position 1 → 1/1 = 1.0
Query 2: First relevant result at position 3 → 1/3 = 0.33
Query 3: First relevant result at position 2 → 1/2 = 0.5
MRR = (1.0 + 0.33 + 0.5) / 3 = 0.61
MRR tells you if relevant results are showing up near the top. A high MRR means users get good context on the first try.
Generation Metrics
Faithfulness — Does the answer only use information from the retrieved context? An answer that’s technically correct but draws from the LLM’s training data instead of your documents is a faithfulness failure — and a hallucination risk.
Answer relevance — Does the answer actually address the question? The LLM might generate a perfectly faithful summary of the retrieved chunks that doesn’t answer what the user asked.
Correctness — Is the answer factually right? This requires ground truth answers for comparison, which means building an evaluation dataset.
Building an Eval Dataset
This is the part everyone skips and then regrets. You need a set of questions with known correct answers to measure against.
Evaluation dataset:
┌─────────────────────────────────┬──────────────────────────────────┬──────────────────────┐
│ Question │ Expected answer │ Relevant chunks │
├─────────────────────────────────┼──────────────────────────────────┼──────────────────────┤
│ "What's the return window │ "15 days for electronics, │ refund-policy.md │
│ for electronics?" │ 30 days for everything else" │ chunk 3, chunk 4 │
├─────────────────────────────────┼──────────────────────────────────┼──────────────────────┤
│ "How do I reset my password?" │ "Go to Settings > Security > │ user-guide.md │
│ │ Reset Password" │ chunk 12 │
├─────────────────────────────────┼──────────────────────────────────┼──────────────────────┤
│ "What does error 4012 mean?" │ "Rate limit exceeded. Wait 60s." │ error-codes.md │
│ │ │ chunk 7 │
└─────────────────────────────────┴──────────────────────────────────┴──────────────────────┘
Start with 50-100 question-answer pairs that represent the kinds of questions your users actually ask. Pull them from support tickets, search logs, or user interviews. Don’t guess — use real questions.
Then run your system against this dataset every time you change something. Changed chunking strategy? Run the eval. Tweaked the retrieval weights? Run the eval. Updated the prompt? Run the eval.
This is the difference between “I think it’s better” and “recall went from 0.72 to 0.81 and faithfulness held steady.”
Tools That Help
Frameworks like RAGAS, DeepEval, and LlamaIndex’s evaluation module can automate parts of this. They use an LLM to judge answer quality against ground truth, which isn’t perfect but scales much better than manual review.
The important thing isn’t which tool you pick. It’s that you measure at all.
Data Freshness: Handling Updates Without Starting Over
Your documents change. Policies get updated, new support articles get published, product specs change, someone fixes a typo. If your RAG system serves stale information, users learn not to trust it.
The naive approach — re-index everything when anything changes — works when you have 100 documents. It doesn’t work when you have 100,000.
Incremental Updates
The goal is to update only what changed:
Document updated: refund-policy.md (last indexed: Jan 15)
1. Detect the change (file watcher, webhook, polling)
2. Re-chunk only refund-policy.md
3. Delete old vectors for refund-policy.md
4. Generate new embeddings for the new chunks
5. Insert new vectors
Everything else stays untouched.
This requires tracking which vectors came from which source document — metadata that naive implementations skip. Store the source document ID, chunk index, and a content hash with every vector. Then when a document changes, you can find and replace exactly its chunks.
The Stale Data Problem
Even with incremental updates, there’s a window where your index is out of date. How much this matters depends on your use case:
- Internal knowledge base: Minutes to hours of staleness is usually fine
- Customer-facing support: Hours are acceptable, days aren’t
- Compliance/legal: Any staleness could be a liability
- Real-time data: RAG might not be the right pattern at all
Design your update pipeline around your tolerance for staleness, not around what’s technically easiest.
Versioning and Rollback
When you re-index a document and the answers get worse, you need to be able to go back. This means:
- Keep previous versions of your chunks and vectors
- Tag each indexing run with a version or timestamp
- Have a way to swap back to a previous version without re-embedding
This sounds like over-engineering until the first time a document update breaks your highest-traffic query.
Cost: Why Production Surprises Everyone
RAG has three cost centers, and most teams only budget for one of them.
Embedding Costs
Every chunk needs an embedding. Every query needs an embedding. This adds up.
Initial indexing:
10,000 documents × 20 chunks each = 200,000 chunks
200,000 × ~100 tokens per chunk = 20M tokens
At $0.02/1M tokens (text-embedding-3-small): $0.40
Cheap. This is the part people budget for.
Daily queries:
1,000 queries/day × 365 days = 365,000 queries
365,000 × ~20 tokens per query = 7.3M tokens
At $0.02/1M tokens: $0.15/year
Negligible.
Embedding costs are rarely the problem. The problem is the next two.
LLM Generation Costs
Every query sends retrieved chunks to the LLM. Those chunks are input tokens, which cost real money at scale:
Per query:
5 retrieved chunks × 200 tokens = 1,000 input tokens
+ system prompt: ~200 tokens
+ generated answer: ~200 tokens
Total: ~1,400 tokens per query
At Claude Sonnet pricing (~$3/1M input, $15/1M output):
Input: 1,200 tokens × $3/1M = $0.0036
Output: 200 tokens × $15/1M = $0.003
Per query: ~$0.007
1,000 queries/day:
$7/day = $210/month = $2,520/year
That’s for a modest workload with a mid-tier model. Scale to 10,000 queries/day with a larger model and longer contexts, and you’re looking at $25,000-50,000/year just in LLM costs.
Infrastructure Costs
Vector databases aren’t free, especially at scale:
Self-hosted (pgvector on existing Postgres):
Marginal cost if you're already running Postgres
Performance degrades past ~1M vectors without tuning
Managed vector database:
Pinecone: $70/month starter, scales with storage/queries
Weaviate Cloud: Similar range
Can easily reach $500-2,000/month at production scale
The Real Cost Equation
Monthly cost = embedding + LLM generation + infrastructure + engineering time
Typical production system (10K queries/day, 50K documents):
Embeddings: ~$5/month
LLM generation: $2,000-5,000/month
Vector DB: $200-1,000/month
Engineering: ??? (the biggest cost nobody accounts for)
LLM generation dominates. This is why prompt optimization, chunk size tuning, and choosing the right model matter so much. Retrieving 10 chunks instead of 5 doubles your input token cost. Using a model that’s more expensive than you need burns money on every query.
Cost Optimization Levers
Reduce retrieved chunks — Do you really need 10? Often 3-5 with good retrieval quality outperforms 10 with mediocre retrieval.
Compress context — Summarize retrieved chunks before sending to the LLM. Trades a small amount of quality for significant token savings.
Cache common queries — If 20% of queries are the same questions repeated, cache the answers. Simple and high-impact.
Right-size your model — Not every query needs the most capable model. Route simple factual lookups to a smaller model and save the expensive one for complex reasoning.
Batch where possible — If you’re processing documents for indexing, batch your embedding calls. Most providers offer batch pricing at 50% discounts.
The Key Insights
-
Vector search alone isn’t enough. Hybrid search (semantic + keyword) catches the cases that pure vector search misses — exact codes, identifiers, specific terms.
-
Chunking is where most systems fail. Bad chunking splits critical context across pieces. Match your strategy to your document types, and iterate based on what questions get wrong answers.
-
Measure retrieval and generation separately. A wrong answer from bad retrieval needs a different fix than a wrong answer from bad generation. Build an eval dataset from real user questions.
-
Plan for data freshness from day one. Incremental updates, source tracking, and versioning aren’t premature optimization — they’re table stakes for anything users depend on.
-
LLM generation costs dominate. Embedding costs are negligible. Infrastructure is manageable. But input tokens at scale add up fast. Optimize chunk count, context size, and model selection.
Wrapping Up the Series
This series covered RAG from concept to production:
- Part 1: What RAG is, why it beats fine-tuning, and where you’re already seeing it
- Part 2: Vectors, embeddings, semantic search, and the three-stage pipeline
- Part 3 (this post): Hybrid search, chunking, evaluation, freshness, and cost — the production concerns that matter
The pattern is straightforward. The engineering is in the details. And the details are what separate “I built a RAG demo” from “users trust this system with real decisions.”
If you’re evaluating RAG platforms or building your own, I hope this gives you better questions to ask and a clearer picture of what to look for.
I built Stache to solve these production RAG problems — hybrid search, intelligent chunking, incremental updates, and evaluation built in. Connect on LinkedIn or check out the project on GitHub.