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 [add dataset size] 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 [add link].

