RAG Architecture in 2026: From Naive to Production-Grade Systems
Retrieval-Augmented Generation (RAG) has evolved from a simple "search + generate" pattern into a sophisticated engineering discipline. This guide covers the architecture decisions, optimization strategies, and evaluation frameworks used in production RAG systems.
The Evolution of RAG
The three generations differ in how much of the pipeline is decided per query. Generation one retrieved the same way for every question, which is why it failed on anything needing a filter, a comparison, or a second hop. Generation two added hybrid search and re-ranking, raising recall on identifier-heavy queries — part numbers, case ids, exact phrases — where pure vector search is weakest. Generation three classifies intent first and then chooses which retrievers to run, so a definitional question takes a cheap path while a multi-hop question fans out to several sources and fuses the results.
The practical reading: each generation added latency in exchange for a specific measured failure. Adopt a stage only after you can name the failure it fixes. A system running generation three machinery on a corpus of two hundred documents has added a classifier, a planner, and a validator without any of them having a decision to make.
Generation 1: Naive RAG (2023-2024)
Query → Embedding → Vector Search → Top-K Chunks → LLM → Answer
Problems: Poor chunking, no re-ranking, hallucinated answers, no source attribution.
Generation 2: Advanced RAG (2024-2025)
Query → Query Enhancement → Hybrid Search → Re-ranking → Context Optimization → LLM → Answer
Improvements: Better chunking, hybrid search, re-ranking, query transformation.
Generation 3: Modular RAG (2026)
Query → Intent Classification → Query Planning → Multi-Source Retrieval →
Fusion & Deduplication → Context Assembly → LLM → Validation → Answer
Architecture: Pluggable components, self-correcting, multi-hop reasoning.
Production Architecture
End-to-end latency is a budget, and generation dominates it. A representative 1,925 ms request splits roughly 40 ms to embed the query, 120 ms to search, 90 ms to re-rank, and 1,675 ms to generate — so tuning chunk size while leaving the model untouched moves about 8 percent of the total. Profile the six stages separately before optimising anything. The second structural decision is where to cap the context: stuffing 40 retrieved chunks in hoping for coverage usually hurts, because the model attends to the middle of a long context less reliably than to a short, ordered set. Ten chunks of about 400 tokens each, ordered by re-rank score, is a defensible starting point.
Core Components
class ProductionRAG:
def __init__(self):
self.query_analyzer = QueryAnalyzer()
self.retrievers = {
'vector': VectorRetriever(),
'keyword': BM25Retriever(),
'graph': GraphRetriever(),
'sql': SQLRetriever()
}
self.reranker = CrossEncoderReranker()
self.context_assembler = ContextAssembler()
self.generator = LLMGenerator()
self.validator = AnswerValidator()
async def answer(self, query: str) -> RAGResponse:
# Step 1: Analyze query intent
analysis = await self.query_analyzer.analyze(query)
# Step 2: Retrieve from multiple sources
results = await self._multi_source_retrieve(query, analysis)
# Step 3: Re-rank and filter
reranked = await self.reranker.rerank(query, results, top_k=10)
# Step 4: Assemble context
context = self.context_assembler.assemble(reranked, analysis)
# Step 5: Generate answer
answer = await self.generator.generate(query, context)
# Step 6: Validate and ground
validated = await self.validator.validate(answer, context)
return validated
Chunking Strategies That Actually Work
Chunk count is a derived number: corpus tokens divided by chunk size minus overlap. A 266M token corpus at 512 token chunks with 50 of overlap yields about 575,000 vectors, and at 1,024 dimensions in float32 that is roughly 2.2 GB before compression — so chunk size is a storage decision as much as a quality one. Smaller chunks raise retrieval precision and lower the chance that a chunk straddles two topics, but they split answers across boundaries; overlap of 10 to 15 percent recovers most boundary misses for a proportional increase in index size. Keep structure in metadata — section path, page number, document type — because post-retrieval filtering on metadata is cheaper and more precise than re-embedding with constraints.
1. Semantic Chunking
Split documents at semantic boundaries, not arbitrary token counts:
from langchain.text_splitter import RecursiveCharacterTextSplitter
import numpy as np
class SemanticChunker:
def __init__(self, embedding_model, threshold=0.75):
self.embedding_model = embedding_model
self.threshold = threshold
def chunk(self, document: str) -> list[Chunk]:
# Split into sentences first
sentences = self._split_sentences(document)
# Embed each sentence
embeddings = self.embedding_model.encode(sentences)
# Find semantic boundaries (where similarity drops)
chunks = []
current_chunk = [sentences[0]]
for i in range(1, len(sentences)):
similarity = cosine_similarity(
embeddings[i-1], embeddings[i]
)
if similarity < self.threshold:
# Semantic boundary found
chunks.append(Chunk(
text=' '.join(current_chunk),
metadata={'start_idx': i - len(current_chunk)}
))
current_chunk = [sentences[i]]
else:
current_chunk.append(sentences[i])
# Don't forget the last chunk
if current_chunk:
chunks.append(Chunk(text=' '.join(current_chunk)))
return chunks
2. Parent-Child Chunking
Small chunks for retrieval, large chunks for context:
class ParentChildChunker:
def __init__(self, parent_size=2048, child_size=256, overlap=50):
self.parent_size = parent_size
self.child_size = child_size
self.overlap = overlap
def chunk(self, document: str) -> ChunkTree:
# Create large parent chunks
parents = self._create_chunks(document, self.parent_size)
# Create small child chunks within each parent
children = []
for i, parent in enumerate(parents):
child_chunks = self._create_chunks(
parent.text, self.child_size, self.overlap
)
for child in child_chunks:
child.parent_id = i # Link to parent
children.extend(child_chunks)
return ChunkTree(parents=parents, children=children)
# Retrieval uses small chunks for precision
# Generation uses parent chunks for context
3. Document-Level Chunking
For structured documents, respect the document structure:
class DocumentAwareChunker:
def chunk(self, document: str, doc_type: str) -> list[Chunk]:
if doc_type == "code":
return self._chunk_code(document) # Split at functions/classes
elif doc_type == "academic":
return self._chunk_paper(document) # Split at sections
elif doc_type == "legal":
return self._chunk_contract(document) # Split at clauses
elif doc_type == "markdown":
return self._chunk_markdown(document) # Split at headers
else:
return self._chunk_generic(document)
def _chunk_code(self, code: str) -> list[Chunk]:
import ast
tree = ast.parse(code)
chunks = []
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.ClassDef)):
chunks.append(Chunk(
text=ast.get_source_segment(code, node),
metadata={
'type': type(node).__name__,
'name': node.name,
'line': node.lineno
}
))
return chunks
Embedding Models: 2026 Landscape
Two properties matter more than the benchmark table. First, dimension: storage and search cost scale linearly with it, so 3,072 dimensions costs 3× the memory of 1,024 for a quality gain that is often under 2 MTEB points on in-domain data — and if you need 128 dimensions, learn a projection on your own corpus rather than trusting a vendor's claim of parity. Second, input length: a model that reads 512 tokens will silently truncate a 900 token chunk, which means half the chunk was never embedded at all. Check the tokenizer limit against your real chunk size, not against the marketing figure.
Re-embed everything when you change models. Vectors from two encoders live in different spaces, and a hybrid index mixing them returns neighbours chosen for embedding compatibility rather than relevance.
| Model | Dimensions | Speed | Quality | Best For |
|---|---|---|---|---|
| OpenAI text-embedding-3-large | 3072 | Fast | Excellent | General purpose |
| Cohere embed-v4 | 1024 | Fast | Excellent | Multi-lingual |
| BGE-M3 | 1024 | Medium | Very Good | Open source |
| Jina embeddings v3 | 1024 | Fast | Very Good | Long documents |
| GTE-Qwen2 | 1536 | Medium | Excellent | Code + text |
| Voyage-3 | 1024 | Fast | Excellent | Retrieval-optimized |
Choosing the Right Embedding Model
def select_embedding_model(use_case: str) -> str:
if use_case == "code_search":
return "gte-qwen2" # Best for code
elif use_case == "multi_lingual":
return "cohere-embed-v4" # 100+ languages
elif use_case == "long_documents":
return "jina-v3" # 8K token input
elif use_case == "general_purpose":
return "text-embedding-3-large" # Best overall
elif use_case == "budget_conscious":
return "bge-m3" # Open source, self-hostable
Vector Database Comparison
Filtering behaviour separates these options more than raw speed does. A metadata filter applied during the search can collapse recall when it is too selective — asking for the top 5 among documents from one author after a global ANN search may return fewer than 5 unless you over-fetch. Qdrant and Milvus apply payload filters inside the index and let you raise the candidate count; pgvector keeps everything in SQL, which makes joins trivial and makes large-scale ANN tuning harder. Pick on the operations you already run: a team with strong Postgres skills and 10M vectors gets a simpler life from pgvector than from a cluster it has never administered.
| Database | Best For | Scale | Price |
|---|---|---|---|
| Pinecone | Managed, easy start | 10B+ vectors |
| | Qdrant | Performance, filtering | 1B+ vectors | $ | | Milvus | Enterprise, distributed | 10B+ vectors | $$ | | pgvector | Simple, SQL ecosystem | 10M+ vectors | $ | | Chroma | Local dev, small apps | 1M vectors | Free |
Re-ranking: The Secret Weapon
Re-ranking converts recall into precision. The first stage retrieves 50 to 100 candidates cheaply and must be tuned for recall alone; the cross-encoder then scores each query-document pair jointly, which is slow but far more accurate than comparing two independently produced vectors. The economics work out: MiniLM-class re-ranking at 50 pairs costs about 8 to 12 ms per request on a single CPU worker, and on a labelled set it commonly moves hit rate at 5 from around 0.62 to 0.81 — the single largest quality jump available without touching the generator. Recall at the candidate stage is the hard limit, so if the right chunk never enters the top 100, no re-ranker can rescue it.
After initial retrieval, re-rank results with a cross-encoder:
from sentence_transformers import CrossEncoder
class CrossEncoderReranker:
def __init__(self, model_name="cross-encoder/ms-marco-MiniLM-L-6-v2"):
self.model = CrossEncoder(model_name)
async def rerank(self, query: str, documents: list[Doc], top_k: int = 5):
# Create query-document pairs
pairs = [(query, doc.text) for doc in documents]
# Score each pair
scores = self.model.predict(pairs)
# Sort by score
ranked = sorted(
zip(documents, scores),
key=lambda x: x[1],
reverse=True
)
return [doc for doc, score in ranked[:top_k]]
Evaluation Framework
Build the evaluation set before the pipeline, because the set defines what the pipeline is for. Fifty questions with the document ids that should answer them is enough to catch most regressions, and each question should carry a difficulty label — lookup, comparison, multi-hop, unanswerable — so a drop can be attributed to a stage rather than to the system as a whole. Include unanswerable questions deliberately: a RAG system that answers them confidently is telling you its refusal clause is missing, and that failure is invisible on a set where every question has an answer.
Run the suite on every retrieval change and on every prompt change, and store the scores next to the index version. Two numbers per run — recall at 5 and faithfulness — are enough to decide whether the change ships.
Metrics That Matter
class RAGEvaluator:
def evaluate(self, test_cases: list[TestCase]) -> EvalResults:
results = {
'retrieval': {
'precision_at_k': [],
'recall_at_k': [],
'mrr': [], # Mean Reciprocal Rank
'ndcg': [], # Normalized Discounted Cumulative Gain
},
'generation': {
'faithfulness': [], # Is the answer grounded in context?
'relevance': [], # Does the answer address the query?
'completeness': [], # Does the answer cover all aspects?
},
'end_to_end': {
'answer_correctness': [],
'hallucination_rate': [],
'source_attribution': [],
}
}
for test_case in test_cases:
# Run RAG pipeline
response = self.rag.answer(test_case.query)
# Evaluate retrieval quality
results['retrieval']['precision_at_k'].append(
self._precision_at_k(
retrieved=response.sources,
relevant=test_case.relevant_docs,
k=5
)
)
# Evaluate generation quality (using LLM-as-judge)
faithfulness = await self._judge_faithfulness(
answer=response.answer,
context=response.context
)
results['generation']['faithfulness'].append(faithfulness)
# Check for hallucinations
hallucination_rate = await self._detect_hallucinations(
answer=response.answer,
context=response.context
)
results['end_to_end']['hallucination_rate'].append(
hallucination_rate
)
return self._aggregate_results(results)
LLM-as-Judge for Faithfulness
async def _judge_faithfulness(self, answer: str, context: str) -> float:
prompt = f"""Rate how faithful the answer is to the context (0-1).
Context:
{context}
Answer:
{answer}
Score (0-1, where 1 = fully grounded in context):"""
score = await self.llm.generate(prompt)
return float(score)
Production Checklist
Before deploying a RAG system, verify:
- Chunking: Semantic boundaries, appropriate size, metadata preserved
- Embeddings: Model matches use case, dimensions appropriate
- Vector DB: Scalable, supports filtering, backup configured
- Hybrid Search: BM25 + vector search combined
- Re-ranking: Cross-encoder or LLM-based re-ranking
- Context Window: Token counting, context assembly
- Evaluation: Automated eval pipeline, regular eval runs
- Monitoring: Latency, retrieval quality, hallucination rates
- Fallbacks: What happens when retrieval fails?
- Cost Controls: Token budgets, embedding costs, caching
Three of those lines need a number attached before the checklist is useful. Fallbacks means: when zero chunks clear the similarity threshold, does the system say it found nothing, or does it answer from the model's weights? Set the threshold from your evaluation set — the value that maximises precision at 5 on labelled queries — rather than from a default of 0.75. Cost controls means measuring embedding spend per document and generation spend per query: a 10M document re-embed of a 750 docs/s encoder takes about 3.7 hours of GPU time, which is a scheduled job with a budget, not a surprise. Monitoring means tracking p95 for each of the six stages separately, because a single end-to-end number cannot tell you whether the index or the generator regressed.
Conclusion
Building a production RAG system in 2026 requires understanding the full pipeline — from document ingestion through chunking, embedding, retrieval, re-ranking, and generation. The key insights are:
- Chunking matters more than you think — semantic chunking improves retrieval by 20-40%
- Hybrid search beats pure vector search — combine BM25 + vector for best results
- Re-ranking is essential — it's the single biggest quality improvement
- Evaluate continuously — automated eval pipelines catch regressions
- Monitor everything — retrieval quality, hallucination rates, costs
The difference between a demo RAG system and a production one is the engineering rigor applied to each component.
Order of work for a team starting from scratch: build the labelled evaluation set with difficulty labels and unanswerable cases, then pick chunking and embedding against it, then add hybrid search, then re-ranking, then generation tuning. Teams that invert this order spend weeks tuning a prompt while the correct chunk was never retrieved — a generation-side change cannot fix a retrieval-side miss, and the evaluation set is the only thing that makes the boundary visible.
Common Mistakes
Tuning the generator for weeks while the correct chunk never enters the retrieved set
Fix: Measure recall at 5 on a labelled set first, and treat any generation change as blocked until recall is above 0.8
Setting the similarity threshold at a framework default so weak matches still get stuffed into context
Fix: Choose the threshold that maximises precision at 5 on your own labelled queries, and return an explicit refusal below it
Mixing vectors from two embedding models in one index after a model change
Fix: Re-embed the whole corpus and swap the index atomically; vectors from different encoders are not comparable
Key Takeaways
- Latency is a stage budget in which generation is roughly 90 percent of a 1,925 ms request, so profile the six stages before optimising
- Chunk count is corpus tokens over chunk size minus overlap, and smaller chunks trade storage and boundary splits against retrieval precision
- Re-ranking is the largest single quality gain available: about 12 ms to move hit rate at 5 from 0.62 to 0.81 on a labelled set
- Build the evaluation set first, with difficulty labels and unanswerable questions, because it is the only instrument that attributes a regression to a stage