Introduction
Most Retrieval-Augmented Generation (RAG) tutorials stop at a naive implementation: load a PDF, split it into arbitrary 500-character chunks, generate embeddings with a standard model, store them in a vector database, and pass the top-k results to an LLM. While this works for a local prototype or a simple FAQ bot, it frequently fails in production. Real-world documents have complex structures, user queries rarely match keyword-for-keyword semantic distributions, and naive top-k retrieval often introduces noise that degrades generation quality.
Building a production-grade RAG system requires treating retrieval as a rigorous data engineering and search problem. This article outlines a systematic approach to document ingestion, hybrid retrieval, reranking, hallucination reduction, and evaluation.
Document Ingestion and Chunking Strategies
The foundation of any RAG system is how raw data is parsed and segmented. Treating documents as flat text streams destroys hierarchical context.
Semantic vs. Fixed-Size Chunking
Fixed-size chunking (e.g., splitting every 500 tokens with a 50-token overlap) is easy to implement but dangerous. It frequently cuts sentences in half, separates tables from their headers, or groups unrelated paragraphs together.
A better approach is structural chunking:
-
Markdown or HTML Parsing: Parse documents into hierarchical trees based on header tags (
H1,H2,H3). Keep sections intact unless they exceed token limits. - Recursive Character Splitting: Fallback to splitting by paragraphs, then sentences, maintaining semantic boundaries.
- Parent-Child Chunking: Index small chunks (e.g., 128 tokens) for precise vector matching, but return the larger parent chunk (e.g., 512 tokens) to the LLM to provide adequate context.
Hybrid Retrieval: Combining Sparse and Dense Search
Dense vector search excels at capturing semantic intent, but it often struggles with exact keyword matches, such as product SKU numbers, proper nouns, or specific technical terminology. Conversely, sparse search (like BM25) excels at exact matches but fails to understand synonyms or conceptual similarity.
Production systems use hybrid search, combining both approaches:
- Dense Retrieval: Vector similarity search using cosine distance or inner product over embeddings.
- Sparse Retrieval: BM25 or TF-IDF indexing for keyword matching.
- Reciprocal Rank Fusion (RRF): Combine the ranked lists from both search algorithms without needing to normalize disparate score distributions.
def reciprocal_rank_fusion(dense_results, sparse_results, k=60):
fused_scores = {}
for rank, doc in enumerate(dense_results):
fused_scores[doc.id] = fused_scores.get(doc.id, 0) + 1 / (k + rank + 1)
for rank, doc in enumerate(sparse_results):
fused_scores[doc.id] = fused_scores.get(doc.id, 0) + 1 / (k + rank + 1)
return sorted(fused_scores.items(), key=lambda x: x[1], reverse=True)
Reranking for Precision
Retrieving the top 50 candidates via hybrid search is cheap and fast, but passing all 50 to an LLM is expensive and introduces noise (the "lost in the middle" phenomenon). Inserting a cross-encoder reranker solves this.
Bi-encoders (used for vector embeddings) encode the query and document independently, making them fast for initial retrieval. Cross-encoders process the query and document together through a transformer network, allowing full attention between query and context terms at the cost of higher latency.
- Initial Pool: Retrieve top 50 documents using hybrid search.
- Reranking: Pass the query and each document pair through a cross-encoder model (e.g., Cohere Rerank or BGE-Reranker).
- Final Selection: Keep the top 3-5 documents for the generation step.
Mitigating Hallucinations and Managing Context
Even with optimal retrieval, LLMs can hallucinate or extrapolate beyond the provided text. To enforce groundedness:
- Explicit Prompt Instructions: Instruct the model to rely only on the provided context. If the answer is not present, it must state that it does not know.
- Source Citation: Require the model to output the citation ID for every factual claim, allowing automated verification against the retrieved chunks.
- Guardrails: Implement output validation layers to check if the generated claims are supported by the source text using secondary lightweight models or NLI (Natural Language Inference) classifiers.
Production Architecture
A production RAG pipeline must handle asynchronous ingestion, low-latency querying, and observability.
Key architectural considerations include:
- Asynchronous Updates: Ingestion pipelines should run via message queues (e.g., Celery, RabbitMQ) so document updates do not block the API.
- Caching: Cache frequent queries and their corresponding retrieved context blocks to reduce latency and API costs.
- Rate Limiting and Fallbacks: Handle upstream LLM provider rate limits gracefully with exponential backoff and fallback models.
Evaluation Frameworks
Measuring RAG performance requires decomposing the system into retrieval and generation metrics:
- Context Recall: Did the retrieval system fetch all necessary information to answer the query?
- Context Precision: Are the retrieved chunks relevant, or is there unnecessary noise?
- Faithfulness: Is the generated response derived entirely from the retrieved context without hallucinated additions?
- Answer Relevance: Does the response actually address the user's initial prompt?
Using frameworks like Ragas or TruLens allows continuous evaluation against a test dataset of golden queries during CI/CD pipelines.
Conclusion
Moving from a basic prototype to a production-ready RAG system requires replacing shortcuts with robust engineering practices. By implementing structural chunking, hybrid search, cross-encoder reranking, and rigorous evaluation frameworks, you can build reliable systems that scale predictably in production. For further reading, consult.

Top comments (5)
The evaluation section is where I'd add one warning: the number of golden queries matters more than the framework choice. On a small set, a single question flips the headline. I measured this on my own 24-question eval â one grading artifact (an answer of '3' vs '3 attempts' on question rag-4) flipped which system looked better. And on a real 30-question set, a reranker's +2 gain sat entirely inside single-question noise until a bootstrap CI showed it straddling zero. Ragas/TruLens will happily report context recall to two decimals on 20 questions; the CI is the number that tells you whether the improvement is real.
The second thing I'd measure one layer below retrieval: extraction. A chunk can only be retrieved if the page made it into the index, and scanned pages fail silently â a page with no text layer indexes as zero characters, no error, and every query about that page returns 'not found'. Before tuning hybrid search or reranking, I assert per-page character counts at ingest (every page above a floor, or routed to OCR), because no amount of RRF fixes a document that was never indexed. The '[add dataset size]' placeholder is actually the most important line in the section â pin the size, then report the interval, not just the point estimate.
This is a really valuable perspective. I especially agree with the point about extraction being a prerequisite for retrieval, it's easy to spend hours tuning search strategies when the actual problem is that some pages never made it into the index.
The point about evaluation size is equally important. Reporting a score without understanding its uncertainty can make small improvements look much more significant than they actually are.
I like your suggestion of validating per-page character counts during ingestion. That's a practical safeguard I'll definitely keep in mind.
Thanks for sharing your actual evaluation experience. These are exactly the kinds of details that make RAG discussions more useful.
Glad it resonated. The extraction failure is the one that stung me most â a page with no text layer indexes as zero characters and nothing errors, so you can tune search for a week before realising the document was never there. The per-page floor is cheap insurance; I route anything under it to OCR and it catches most of it.
And yes â the CI is the number that matters; the point estimate is just the headline. Thanks for writing this one up, it's a solid, honest checklist.
the cache line is the other place i'd be careful. key the stored context to the source document version, not just the query. otherwise a later ingest can update the index while a frequent question still returns last week's chunks. if that version moves, drop the entry and retrieve again.
Good point. Cache invalidation is easy to overlook in RAG systems, especially when the underlying documents can change over time. Keying cached context to the source document version makes much more sense than relying on the query alone. Otherwise, we risk serving stale context even when the index has already been updated.
Thanks for bringing this up!