RAG Pipeline Design: Build Retrieval That Works

RAG Pipeline Design: Build Retrieval That Works

What good is a brilliant language model if it confidently invents an answer to a question it never really understood? That is the problem RAG pipeline design exists to solve. Retrieval-Augmented Generation (RAG) lets a model answer from your own documents instead of only from its training data. But a RAG system is not a magic box you switch on. It is a chain of decisions, and every link in that chain can quietly break the one after it.

This article walks through how a RAG pipeline is actually built: what each stage does, where teams go wrong, and how to tune the knobs that matter. The tone is practical. The goal is a pipeline that retrieves the right passage and then uses it honestly.

What Is a RAG Pipeline, Really?

The term Retrieval-Augmented Generation was introduced in a 2020 paper by Patrick Lewis and colleagues, which combined a dense retriever with a sequence-to-sequence generator. You can read the original RAG paper by Lewis et al. for the retriever-and-generator architecture that started it all. That original design looked quite different from today’s LLM-based pipelines, so it helps to separate the core idea from the specific implementation.

The core idea is simple. Instead of asking a model to remember everything, you fetch relevant text at query time and hand it to the model as context. The model then writes an answer grounded in that text. A typical pipeline moves through several stages:

  • Ingestion and parsing – pull in documents and turn them into clean text.

  • Chunking – split text into passages small enough to retrieve precisely.

  • Embedding – convert each chunk into a vector.

  • Indexing – store vectors in a searchable structure.

  • Query processing – embed the user’s question the same way.

  • Retrieval – find the closest chunks, often combining dense and keyword search.

  • Reranking – reorder candidates by relevance.

  • Prompt assembly – fit the best passages into the model’s context window.

  • Generation – produce a grounded answer.

A broad survey of RAG for large language models describes this decomposition and notes that exact stage boundaries vary by source. That flexibility is a feature, not a bug. But it also means you cannot copy a pipeline wholesale and expect it to work on your data.

Chunking: The Decision Nobody Wants to Make

Chunking: The Decision Nobody Wants to Make

If there is one stage where teams waste the most time chasing a magic number, it is chunking. Chunk size and overlap trade retrieval precision against context completeness. Small chunks retrieve precisely but fragment meaning. Large chunks preserve context but dilute the embedding, so a passage about many things looks vaguely similar to everything.

There is no consensus optimal chunk size. Any claim of a universal “best” setting should be treated as unverified. The honest approach is empirical tuning per corpus. Practical guidance that holds up:

  • Start with chunks that match natural document boundaries (a section, a paragraph, a table row) rather than fixed character counts.

  • Add modest overlap so sentences are not cut in half at the edges.

  • Test retrieval quality on real questions before touching the generator.

  • Keep metadata (source, section, date) attached to every chunk; it helps both filtering and citation.

A common mistake is optimizing chunking against a handful of cherry-picked questions. Build a small, varied evaluation set first, then tune. If you want a structured method for that, the guide on designing an evaluation set for enterprise assistants is a useful starting point.

Embeddings and Indexing: The Retrieval Backbone

Dense retrieval relies on bi-encoders, which embed passages and queries separately so similarity search stays fast. The Sentence-BERT work by Reimers and Gurevych established the bi-encoder pattern that most vector search still uses today; the Sentence-BERT paper explains how sentence embeddings are trained for efficient similarity comparison.

Once you have vectors, you need an index. The trade-off is straightforward:

Index type Speed Recall Best for
Exact (brute force) Slow at scale Lossless Small corpora, ground-truth checks
Approximate (HNSW, FAISS) Fast Slightly reduced Large corpora, low latency

Approximate nearest-neighbour indexes trade recall for speed and memory. The HNSW algorithm, described in the original HNSW paper by Malkov and Yashunin, is a graph-based approach common in vector stores. The practical lesson: approximate search is not lossless, so measure recall against exact search on a sample before you trust it.

Hybrid Retrieval and Reranking: Where Quality Is Won

Dense retrieval is good at meaning but weak on exact terms, product codes, and rare names. Hybrid retrieval combines sparse lexical search (BM25) with dense search, and it generally improves recall over either method alone. Reciprocal rank fusion is a simple, widely used way to merge the two ranked lists, described in the reciprocal rank fusion paper by Cormack, Clarke and Büttcher.

Then comes reranking. A cross-encoder reranker scores each query-passage pair jointly, which typically improves precision over bi-encoder retrieval alone, at the cost of higher latency. The same Sentence-BERT work discusses the bi-encoder versus cross-encoder distinction in detail. A practical pattern that works well:

  • Retrieve a generous candidate set (say 50 to 100 chunks) with hybrid search.

  • Rerank the candidates with a cross-encoder.

  • Keep only the top handful for the prompt.

This two-stage approach gives you recall from the cheap first pass and precision from the expensive second pass. Skipping reranking is one of the most common reasons a pipeline retrieves the right document but the wrong passage.

Prompt Assembly and the “Lost in the Middle” Problem

Here is a failure mode that surprises people. Even when retrieval works, the model may ignore the evidence. Research on long-context behavior found that models attend less reliably to information placed in the middle of a long context, a phenomenon known as “lost in the middle,” documented in the lost in the middle study by Liu et al.

The design implication is concrete. Do not stuff twenty chunks into the prompt and hope. Put the strongest passages near the beginning or end of the context, keep the context tight, and instruct the model to answer only from the provided text. If the answer is not there, the model should say so rather than guess.

Evaluation: Measure Retrieval and Generation Separately

A RAG system fails in two different places, so it needs two different kinds of measurement. Retrieval quality is measured with recall@k, mean reciprocal rank (MRR), and nDCG. Generation quality is measured with faithfulness (also called groundedness) and answer relevance.

RAGAS, a framework by Es and colleagues, proposes reference-free metrics for these generation-side qualities; the RAGAS evaluation framework paper explains the metrics in depth. Reference-free matters because writing gold answers for every question is expensive.

A balanced evaluation plan includes:

  • A question set that covers easy, hard, and unanswerable queries.

  • Retrieval metrics tracked separately from answer metrics.

  • A regular check for retrieval misses, irrelevant context, and misattributed evidence.

Keeping an eye on industry developments in evaluation practice is worth the effort; the news section at 9481.org covers emerging methods and tooling. For broader background reading, the blog at 9481.org collects related write-ups on building and testing assistant systems. (News)

Common Mistakes and What Actually Works

After the theory, here is the field-tested reality. These are the mistakes that show up again and again, and the habits that fix them.

Mistake: tuning the generator before fixing retrieval. If the right passage never arrives, no prompt engineering saves you. Fix retrieval first, then generation.

Mistake: treating chunk size as a fixed default. Chunking is a design lever. Tune it against your own corpus and questions.

Mistake: skipping reranking to save latency. A cheap reranker often buys more quality than a bigger model. Measure the trade-off rather than assuming.

Mistake: no evaluation set. Without a fixed set of questions, every change is a guess. Build the set early and grow it as you find failures.

Mistake: ignoring unanswerable questions. A pipeline that always answers is a pipeline that sometimes lies. Test what happens when the answer is not in the corpus.

What works: small, measured changes, one at a time, each checked against the same evaluation set. Document what you changed and why. The teams that ship reliable RAG are rarely the ones with the most clever architecture. They are the ones who measured honestly and iterated.

Conclusion

RAG pipeline design is less about picking the trendiest vector database and more about disciplined engineering across a chain of stages. Parse cleanly, chunk thoughtfully, embed consistently, retrieve hybrid, rerank for precision, assemble context tightly, and evaluate retrieval and generation separately. Each stage has known trade-offs, and none has a universal best setting. The approach that works is empirical: build a real evaluation set, change one thing at a time, and let your own data show what works. Do that, and your pipeline will retrieve text worth trusting.

Frequently Asked Questions

What is the most important stage in a RAG pipeline?

Retrieval is usually the highest-leverage stage. If the correct passage never reaches the model, generation quality cannot recover. That said, retrieval and prompt assembly are tightly coupled, so both deserve attention before you tune the generator itself. (Blog)

How do I choose a chunk size for RAG?

There is no universal best chunk size. Start with chunks that follow natural document boundaries, add modest overlap, and tune against a varied evaluation set of real questions. Treat any claim of a single optimal number with skepticism.

Do I need reranking if I already use a good embedding model?

Not always, but often yes. A cross-encoder reranker typically improves precision over bi-encoder retrieval alone, at the cost of extra latency. Test both configurations on your own data and keep reranking if the quality gain justifies the delay.

What is hybrid retrieval and why does it help?

Hybrid retrieval combines dense vector search with sparse keyword search such as BM25. Dense search captures meaning, while keyword search catches exact terms, codes, and names. Merging the two ranked lists, often with reciprocal rank fusion, generally improves recall over either method alone.

How should I evaluate a RAG system?

Measure retrieval and generation separately. Use recall@k, MRR, and nDCG for retrieval, and faithfulness and answer relevance for generation. Include unanswerable questions in your test set, and rerun the same evaluation after every change so you can compare fairly. (Retrieval-augmented generation (Wikipedia))

Why does my model ignore retrieved context?

Long-context models can attend less reliably to information buried in the middle of a long prompt. Keep the context tight, place the strongest passages near the start or end, and instruct the model to answer only from the provided text and to admit when the answer is missing.

Mistake: evaluating with the same model family that generated your test set. Self-evaluation inflates scores. Where possible, use a different judge model or human spot-checks to calibrate the automated metrics.

What works, in order: fix parsing and chunking, establish hybrid retrieval, add a reranker, tighten prompt assembly, then tune the generator. Each step is measurable against the fixed evaluation set, so improvements compound rather than cancel. Document every change with its before-and-after metrics; a short changelog of retrieval recall and answer faithfulness is worth more than any architecture diagram. Finally, plan for drift. Corpora change, documents age, and user questions shift. Schedule periodic re-evaluation and re-indexing so the pipeline degrades gracefully instead of silently. The teams that sustain quality treat RAG as an ongoing operation, not a one-time build.

Latest articles

Scroll to Top