Production-grade guide to rag architecture deep dive covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
RAG architecture transforms static knowledge into dynamic, context-aware intelligence. It matters when retrieval and generation must work together seamlessly—when a model must answer questions using up-to-date, domain-specific documents without retraining. This is the architecture for systems that answer like a human expert, citing sources, adapting to new data, and recovering gracefully when facts are missing.
A query begins with a user’s natural language input. The system must map this query to relevant documents, then use those documents to guide a generation model. The core step is embedding the query and matching it against a corpus of pre-embedded documents.
To retrieve relevant documents, a vector database stores embeddings generated from document chunks. Each chunk is a unit of text—typically 256–1024 tokens—preprocessed and embedded with a model like sentence-transformers/all-MiniLM-L6-v2.
The retrieval process is a query to a vector store. It expects a vector and returns a list of document IDs, scores, and metadata.
POST /v1/search
Content-Type: application/json
{
"query_vector": [0.45, -0.12, 0.88, ...],
"k": 5,
"filter": {
"source": "manuals",
"year": 2023
}
}
The response is a list of hits:
{
"results": [
{
"id": "doc-7a3b2c",
"score": 0.93,
"metadata": {
"title": "API Rate Limiting Guide",
"source": "manuals",
"year": 2023,
"chunk_id": 42
},
"content": "Rate limiting prevents API overload by restricting requests per time unit..."
},
{
"id": "doc-1f8d9e",
"score": 0.87,
"metadata": { "title": "OAuth 2.0 Best Practices", "source": "manuals", "year": 2023 },
"content": "Use refresh tokens to reduce client-side state..."
}
]
}
The query vector is generated by a model. If the model is sentence-transformers/all-MiniLM-L6-v2, the input is a string, and the output is a 384-dimensional vector.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
query_vector = model.encode("How do I handle 429 Too Many Requests in my API?")
The vector is sent to the vector store with a k parameter to return the top-k most similar documents. A filter object can restrict the search to documents with matching metadata.
Failure here is common: missing query embedding. If the model is not loaded, or the input is not properly tokenized, the vector is misaligned. The most frequent error is a mismatched embedding dimension—a 384D vector sent to a 768D index, resulting in low scores and irrelevant results. The error message is often silent: vector dimension mismatch: expected 768, got 384.
Another silent failure: filtering on non-indexed fields. If the source field is not indexed in the vector store, filtering by source: "manuals" performs a full scan, slowing retrieval from 1ms to 100ms.
Documents arrive in various formats—PDFs, Markdown, HTML, plain text. The first step is parsing, which extracts text and metadata.
A typical pipeline uses pdfplumber to extract text from PDFs and BeautifulSoup for HTML.
import pdfplumber
from bs4 import BeautifulSoup
def parse_document(file_path: str) -> list[str]:
if file_path.endswith(".pdf"):
with pdfplumber.open(file_path) as pdf:
pages = [page.extract_text() for page in pdf.pages]
return [page for page in pages if page.strip()]
elif file_path.endswith(".html"):
with open(file_path) as f:
soup = BeautifulSoup(f.read(), "html.parser")
text = soup.get_text()
return [text]
else:
with open(file_path) as f:
return [f.read()]
After parsing, documents are chunked. Each chunk is a contiguous segment of text, typically 256–1024 tokens. The chunking strategy affects retrieval accuracy.
A common approach uses fixed-size windows with overlap:
def chunk_text(text: str, chunk_size: int = 512, overlap: int = 128) -> list[str]:
chunks = []
start = 0
while start < len(text):
end = start + chunk_size
chunk = text[start:end]
chunks.append(chunk)
start += chunk_size - overlap
return chunks
The chunks are then embedded and stored in a vector database.
The embedding process is stateless. A model loads once and processes batches of text.
curl -X POST http://embedder:8000/embed \
-H "Content-Type: application/json" \
-d '{
"texts": [
"Rate limiting prevents API overload...",
"Use refresh tokens to reduce client-side state..."
],
"model": "sentence-transformers/all-MiniLM-L6-v2"
}'
The response returns a list of vectors, one per input text.
{
"vectors": [
[0.45, -0.12, 0.88, ...],
[0.32, 0.05, -0.21, ...]
]
}
The vector database receives these vectors with associated metadata.
POST /v1/index
Content-Type: application/json
{
"vectors": [
{
"id": "chunk-123",
"vector": [0.45, -0.12, 0.88, ...],
"metadata": {
"document_id": "doc-7a3b2c",
"title": "API Rate Limiting Guide",
"source": "manuals",
"chunk_id": 42,
"page": 3
}
}
]
}
The vector database must support efficient nearest-neighbor search. The most common failure is inconsistent chunking: two documents with similar content have different chunk boundaries, leading to duplicate or fragmented information in retrieval.
Another silent failure: metadata not propagated. When a document is split into chunks, the metadata (like document_id, source, year) is often lost or mismatched. A chunk may appear under the wrong document, causing retrieval to return a document that contains only part of the expected content.
With retrieved documents, the next step is assembling a context for the generation model.
The context is a string built by concatenating the retrieved documents, often with a header and a separator.
def build_context(retrieved: list[dict], template: str = "### {title}\n{content}\n\n") -> str:
context_parts = []
for hit in retrieved:
part = template.format(
title=hit["metadata"]["title"],
content=hit["content"]
)
context_parts.append(part)
return "".join(context_parts)
The resulting context is appended to a prompt template.
Answer the question based on the following context:
{context}
Question: {question}
Answer:
The prompt is sent to a generative model, such as mistralai/Mistral-7B-Instruct-v0.2.
POST /v1/generate
Content-Type: application/json
{
"prompt": "Answer the question based on the following context:\n\n### API Rate Limiting Guide\nRate limiting prevents API overload...\n\n### OAuth 2.0 Best Practices\nUse refresh tokens...\n\nQuestion: How do I handle 429 Too Many Requests in my API?\nAnswer:",
"max_tokens": 512,
"temperature": 0.3,
"top_p": 0.9
}
The response is a completion:
{
"text": "To handle 429 Too Many Requests, you should implement exponential backoff and include the Retry-After header in your response.",
"tokens": 142,
"finish_reason": "stop"
}
The most common failure is context length overflow. When the context exceeds the model’s maximum input length (e.g., 32,768 tokens for Llama 3), the model truncates the context. The top-k results are kept, but the later chunks are lost.
A subtle failure: context overlap not handled. If the same content appears in two chunks, the model sees the same information twice. The response may repeat the same idea, and the model may treat the first occurrence as more important, even when both are equally relevant.
Another failure: prompt template not versioned. The prompt changes over time—new sections, new metadata fields—but the generation model uses an outdated template. This leads to inconsistent answers and poor user experience.
The full pipeline combines all steps into a single service.
def rag_pipeline(query: str) -> dict:
# Step 1: Retrieve
search_response = requests.post(
"http://vector-store:8000/v1/search",
json={
"query_vector": query_embedding(query),
"k": 5,
"filter": {"source": "manuals"}
}
).json()
retrieved = search_response["results"]
# Step 2: Build context
context = build_context(retrieved)
# Step 3: Generate
generation_response = requests.post(
"http://generation-model:8000/v1/generate",
json={
"prompt": f"Answer the question based on the following context:\n\n{context}\n\nQuestion: {query}\nAnswer:",
"max_tokens": 512,
"temperature": 0.3
}
).json()
return {
"answer": generation_response["text"],
"retrieved": retrieved,
"context": context,
"metadata": {
"query_vector_length": len(query_embedding(query)),
"retrieval_count": len(retrieved),
"generation_tokens": generation_response["tokens"]
}
}
The service returns the answer, the retrieved documents, and metadata for monitoring.
A common configuration file for this pipeline:
vector_store:
host: "vector-store:8000"
model: "sentence-transformers/all-MiniLM-L6-v2"
index: "docs_manuals"
k: 5
filter_fields: ["source", "year", "document_id"]
chunking:
strategy: "sliding_window"
size: 512
overlap: 128
split_on: "paragraphs"
prompt_template: |
Answer the question based on the following context:
### {title}
{content}
Question: {question}
Answer:
generation:
model: "mistralai/Mistral-7B-Instruct-v0.2"
max_tokens: 512
temperature: 0.3
top_p: 0.9
stop_sequences: ["\n\n", "###", "Answer:"]
The pipeline is deployed as a Docker container with a Dockerfile and docker-compose.yml:
# Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY rag_pipeline.py .
COPY config.yaml .
CMD ["python", "rag_pipeline.py"]
# docker-compose.yml
version: '3.8'
services:
vector-store:
image: weaviate/weaviate:latest
ports:
- "8000:8000"
environment:
- AWS_ACCESS_KEY_ID=...
- AWS_SECRET_ACCESS_KEY=...
volumes:
- weaviate_data:/var/lib/weaviate
generation-model:
image: ghcr.io/huggingface/transformers-inference:latest
ports:
- "8000:8000"
environment:
- MODEL_NAME=mistralai/Mistral-7B-Instruct-v0.2
- MAX_BATCH_SIZE=8
rag-pipeline:
build: .
ports:
- "8080:8080"
depends_on:
- vector-store
- generation-model
volumes:
- ./config.yaml:/app/config.yaml
volumes:
weaviate_data:
A query fails silently when the retrieved documents are irrelevant. The most common cause is query embedding not aligned with document embedding. If the query is embedded with all-MiniLM-L6-v2 but the documents use all-mpnet-base-v2, the vectors are incompatible.
Another failure: retrieval without filtering. The user queries “API rate limiting,” but the vector store returns results from “tutorials,” “blogs,” and “changelogs.” The user expects a focused answer, but the model sees a mix of topics.
A diagnostic pattern: logging the top-3 retrieved documents and their scores. High scores but low relevance suggest a mismatched embedding model. Low scores but relevant content suggest a poor filter or a bad chunking strategy.
Another pattern: evaluating retrieval quality with a test set of questions and expected documents. The pipeline is tested by running 100 queries, each with a known correct set of documents. The system fails when a document is missing from the top-k results—especially when the correct document has a high score but is not retrieved.
Finally, context length overflow is diagnosed by tracking the total context length and the model’s input token limit. When the context exceeds the limit, the model truncates the context, and the answer is incomplete. The solution is to either reduce the chunk size, increase k, or implement a re-rank step after retrieval.
After initial retrieval, the results can be re-ranked using a cross-encoder.
A cross-encoder takes the query and a document together and returns a single score.
POST /v1/rerank
Content-Type: application/json
{
"query": "How do I handle 429 Too Many Requests in my API?",
"documents": [
{
"id": "doc-7a3b2c",
"title": "API Rate Limiting Guide",
"content": "Rate limiting prevents API overload..."
},
{
"id": "doc-1f8d9e",
"title": "OAuth 2.0 Best Practices",
"content": "Use refresh tokens..."
}
]
}
The response is a list of documents with re-ranked scores:
{
"results": [
{
"id": "doc-7a3b2c",
"score": 0.95,
"metadata": { "title": "API Rate Limiting Guide" }
},
{
"id": "doc-1f8d9e",
"score": 0.72,
"metadata": { "title": "OAuth 2.0 Best Practices" }
}
]
}
The re-ranked results are used to build the final context.
This step is often overlooked. The default pipeline assumes top-k retrieval is sufficient, but re-ranking improves accuracy—especially when the initial retrieval is noisy.
Another post-processing step: merging overlapping chunks. When two chunks contain the same content, they are merged into a single, longer chunk before context assembly.
def merge_overlapping_chunks(chunks: list[dict], threshold: float = 0.8) -> list[dict]:
merged = []
for chunk in chunks:
if not merged:
merged.append(chunk)
continue
last = merged[-1]
if similarity(last["content"], chunk["content"]) > threshold:
merged[-1]["content"] += "\n" + chunk["content"]
merged[-1]["metadata"]["combined"] = True
else:
merged.append(chunk)
return merged
This step reduces redundancy and improves the model’s understanding.
This page was rewritten on 14 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy