Abdelhafid Guesmia
All posts
Building a Production RAG Pipeline That Actually Works
RAGLLMPythonProduction

Building a Production RAG Pipeline That Actually Works


Building a Production RAG Pipeline That Actually Works

Most RAG tutorials get you a working prototype in 50 lines. Then you hit production and the wheels come off. Documents get chunked poorly, retrieval misses obvious matches, latency spikes under load, and you have no visibility into any of it.

This post covers what I've learned from deploying RAG systems for real clients.

The Chunking Problem

The single biggest source of retrieval failure is bad chunking. Splitting on token count alone destroys semantic coherence — you end up with chunks that start mid-sentence or mid-argument.

What works:

  • Semantic chunking — split at paragraph and section boundaries first, then by size if needed
  • Overlapping windows — 10–20% overlap between chunks prevents edge-case misses
  • Metadata injection — prepend the document title and section heading to each chunk
def smart_chunk(text: str, max_tokens: int = 512, overlap: int = 50) -> list[str]:
    paragraphs = text.split("\n\n")
    chunks = []
    current = []
    current_len = 0

    for para in paragraphs:
        para_len = len(para.split())
        if current_len + para_len > max_tokens and current:
            chunks.append(" ".join(current))
            # keep last N words for overlap
            current = current[-overlap:]
            current_len = sum(len(w) for w in current)
        current.append(para)
        current_len += para_len

    if current:
        chunks.append(" ".join(current))

    return chunks

Hybrid Retrieval

Dense retrieval (vector search) is great for semantic similarity. Keyword search is great for exact matches — names, IDs, technical terms. In production, you need both.

BM25 + vector search with Reciprocal Rank Fusion (RRF) consistently outperforms either alone:

def reciprocal_rank_fusion(results_a: list, results_b: list, k: int = 60) -> list:
    scores = {}
    for rank, doc_id in enumerate(results_a):
        scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank + 1)
    for rank, doc_id in enumerate(results_b):
        scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank + 1)
    return sorted(scores, key=scores.get, reverse=True)

Observability

You cannot improve what you cannot measure. At minimum, log:

  • Query and retrieved chunk IDs
  • Retrieval latency
  • A "relevance signal" — whether the LLM's response cited the retrieved context or fell back to parametric knowledge

I use a simple heuristic: if the response contains phrases from the chunks, it likely used them. If it doesn't, the retrieval probably failed.

Latency

The two biggest latency killers are embedding generation and LLM response time. For the embedding side:

  • Cache embeddings — store them in ChromaDB or FAISS, never regenerate
  • Batch embed on ingest — not at query time
  • Use smaller embedding models for retrieval (text-embedding-3-small is 5x faster and barely worse than large)

For LLM latency, streaming is table stakes for any user-facing interface. Don't wait for the full completion.

Summary

RAG in production requires:

  1. Semantic chunking with overlap and metadata
  2. Hybrid retrieval (dense + sparse)
  3. Observability from day one
  4. Streaming responses
  5. Caching at the embedding layer

The prototype is 50 lines. The production system is a pipeline. Treat it like one.