Agentic AIAutomationAI-Powered DashboardsArticlesContact Me
← All articles
AI Agents11 min read·May 6, 2025

RAG Pipelines in Production: Beyond Basic Retrieval

How to build retrieval-augmented generation pipelines that work at enterprise scale — chunking strategies, embedding models, re-ranking, hybrid search, and the failure modes that only appear in production.

RAGretrieval-augmented generationvector searchembeddingsproduction AIpgvector

RAG Pipelines in Production: Beyond Basic Retrieval

Most RAG tutorials cover the same basic flow: chunk your documents, embed them, store in a vector database, embed the query, retrieve the top-k chunks, stuff them into the prompt. This works well in demos. In production, it fails in ways the tutorial never mentions.

This article covers what actually breaks in production RAG pipelines, how to fix it, and the architectural decisions that separate a reliable retrieval system from one that confabulates half the time.

Why Basic RAG Fails

Problem 1: Chunking Destroys Context

The default chunking approach — split by character count every 512 tokens — severs semantic units at arbitrary boundaries. A paragraph explaining a concept gets split between chunk 3 and chunk 4. The retriever finds chunk 4, which begins mid-thought, and the LLM hallucinates the missing context.

Fix: Chunk by semantic unit, not character count. For structured documents (manuals, policies, contracts), chunk by section. For unstructured text, use a sentence window approach — embed sentences but retrieve the surrounding paragraph.

# Sentence window chunking
def create_sentence_windows(text: str, window_size: int = 3) -> list[Chunk]:
    sentences = sent_tokenize(text)
    chunks = []
    for i, sentence in enumerate(sentences):
        start = max(0, i - window_size)
        end = min(len(sentences), i + window_size + 1)
        window = " ".join(sentences[start:end])
        chunks.append(Chunk(content=window, anchor=sentence, index=i))
    return chunks

You embed the anchor sentence for precision, but retrieve the full window for context.

Problem 2: Embedding Models Have Recall Ceilings

Generic embedding models (text-embedding-ada-002, BGE-large) have high average recall on benchmark datasets. They have low recall on domain-specific terminology your enterprise uses: product names, internal jargon, regulatory codes, industry acronyms.

Fix: Fine-tune the embedding model on your domain corpus, or use a hybrid retrieval approach that combines dense vector search with sparse BM25 keyword search:

from rank_bm25 import BM25Okapi

class HybridRetriever:
    def __init__(self, vector_store, documents):
        self.vector_store = vector_store
        tokenized = [doc.content.split() for doc in documents]
        self.bm25 = BM25Okapi(tokenized)
        self.documents = documents

    def retrieve(self, query: str, k: int = 10) -> list[Document]:
        # Dense retrieval
        dense_results = self.vector_store.similarity_search(query, k=k)
        
        # Sparse retrieval
        bm25_scores = self.bm25.get_scores(query.split())
        top_bm25_indices = bm25_scores.argsort()[-k:][::-1]
        sparse_results = [self.documents[i] for i in top_bm25_indices]
        
        # Reciprocal Rank Fusion
        return self._rrf_merge(dense_results, sparse_results, k=k)

Hybrid search consistently outperforms either approach alone, especially on keyword-heavy enterprise queries.

Problem 3: Top-K Retrieval Returns Irrelevant Chunks

Cosine similarity finds the most similar chunks — but "similar" does not mean "relevant to the question." The retriever might return five chunks about the same tangentially related topic while missing the one chunk that actually answers the query.

Fix: Add a re-ranking step after initial retrieval:

from sentence_transformers import CrossEncoder

reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

def retrieve_and_rerank(query: str, k_retrieve: int = 20, k_return: int = 5):
    # Over-retrieve
    candidates = vector_store.similarity_search(query, k=k_retrieve)
    
    # Re-rank with cross-encoder (more accurate but slower)
    pairs = [(query, doc.content) for doc in candidates]
    scores = reranker.predict(pairs)
    
    # Return top-k by re-ranking score
    ranked = sorted(zip(scores, candidates), reverse=True)
    return [doc for _, doc in ranked[:k_return]]

Cross-encoders score query-document relevance jointly, which is significantly more accurate than cosine similarity of independent embeddings. The tradeoff is latency — use a small cross-encoder model and only re-rank the top 20 candidates, not your entire corpus.

Problem 4: Stale Embeddings After Document Updates

Vector databases do not automatically re-embed documents when the source changes. If a policy document is updated, the old embedding persists and the RAG system continues retrieving outdated content.

Fix: Implement incremental indexing with content hashing:

def upsert_document(doc_id: str, content: str, metadata: dict):
    content_hash = hashlib.sha256(content.encode()).hexdigest()
    
    # Check if content has changed
    existing = vector_store.get(doc_id)
    if existing and existing.metadata.get("content_hash") == content_hash:
        return  # No change, skip re-embedding
    
    # Re-embed and upsert
    embedding = embed(content)
    vector_store.upsert(
        id=doc_id,
        embedding=embedding,
        metadata={**metadata, "content_hash": content_hash, "indexed_at": datetime.utcnow().isoformat()}
    )

Run this as a scheduled job that syncs from your source of truth (Confluence, SharePoint, internal docs) rather than embedding on every read.

Architecture Decisions

Database: Dedicated Vector DB vs. pgvector

pgvector (Postgres extension) is the right default for most enterprise use cases:

  • Single database for both relational and vector data
  • ACID transactions across document metadata and embeddings
  • Familiar tooling, existing backup infrastructure
  • Adequate performance up to ~5M vectors with ivfflat indexing

Dedicated vector databases (Pinecone, Weaviate, Qdrant) make sense when:

  • You have > 10M vectors
  • You need sub-10ms retrieval at high concurrency
  • Your team wants features like multi-tenancy, built-in re-ranking, or hybrid search without building it yourself

Most enterprise RAG implementations do not need a dedicated vector database. Start with pgvector; migrate when you have a measured performance problem.

Embedding Model Selection

Model Dimensions Best For
text-embedding-3-small 1536 Low cost, good baseline
text-embedding-3-large 3072 Higher quality, higher cost
BGE-large-en-v1.5 1024 Open source, strong performance
E5-mistral-7b 4096 Best open source quality

For enterprise use: text-embedding-3-large if cost is not a constraint; BGE-large-en-v1.5 self-hosted if it is. Avoid using the same model for both indexing and retrieval if you switch providers later — re-embed the entire corpus when you change models.

Chunking Parameters

There is no universal correct chunk size. As a starting point:

  • Technical documentation: 512 tokens, 10% overlap
  • Legal/policy documents: By section or subsection
  • Email/chat history: By conversation turn
  • Code: By function or class definition

Always store the source document, chunk index, and character offset in metadata. You need these for attribution and debugging.

Evaluation

You cannot improve what you cannot measure. Build an evaluation harness before you optimize:

def evaluate_retrieval(test_cases: list[QACase], retriever) -> RetrievalMetrics:
    hits_at_1, hits_at_5, mrr = [], [], []
    
    for case in test_cases:
        results = retriever.retrieve(case.question, k=5)
        result_ids = [r.doc_id for r in results]
        
        # Hit rate: was the correct doc in top-k?
        hits_at_1.append(case.relevant_doc_id == result_ids[0])
        hits_at_5.append(case.relevant_doc_id in result_ids[:5])
        
        # MRR: how high was the correct doc ranked?
        rank = next((i + 1 for i, id in enumerate(result_ids) if id == case.relevant_doc_id), None)
        mrr.append(1.0 / rank if rank else 0.0)
    
    return RetrievalMetrics(
        hit_rate_at_1=mean(hits_at_1),
        hit_rate_at_5=mean(hits_at_5),
        mrr=mean(mrr)
    )

Target: Hit@5 > 0.85 before worrying about generation quality. If your retriever is only returning the right document 60% of the time, prompt engineering will not save you.

Guardrails and Hallucination Mitigation

Even with excellent retrieval, LLMs will sometimes generate content not supported by the retrieved context. Implement citation enforcement:

SYSTEM_PROMPT = """
Answer the question using ONLY the provided context.
For every factual claim, cite the source document ID in brackets: [doc-123].
If the context does not contain enough information to answer, say "I don't have enough information" rather than guessing.
"""

Post-generation, verify that every citation in the response corresponds to an actually retrieved document. Strip or flag uncited claims.

The Pragmatic Path

Production RAG is not a single algorithm — it is a retrieval pipeline with multiple tunable stages. Optimize them in order:

  1. Chunking — get semantically coherent chunks first
  2. Hybrid retrieval — combine dense and sparse search
  3. Re-ranking — add a cross-encoder after initial retrieval
  4. Evaluation — measure Hit@5 and MRR against a golden test set
  5. Incremental indexing — keep embeddings fresh
  6. Generation guardrails — enforce citations, detect hallucinations

Each stage independently improves quality. Do not skip to re-ranking before fixing your chunking strategy — garbage in, garbage out at every layer.