Back to Writing

RAG

How to Build a RAG Pipeline: From Demo to Production

The six stages of a production RAG pipeline, chunking and retrieval defaults, the evals that catch regressions, failure modes and what it costs to run.

13 min read

Key takeaways

  • A production RAG pipeline has six stages: ingestion, chunking, embedding, indexing, retrieval, and generation, and most failures happen upstream of the LLM.
  • Start with 256-512 token chunks and 10-15% overlap, splitting on headings and paragraphs before counting tokens.
  • Build a golden dataset of 50-100 real questions with known source chunks before tuning anything, and run evals on every change.
  • Measure retrieval and generation separately with recall@k, MRR, groundedness, and answer relevance so you can trace bad answers to the stage that caused them.
  • Upgrade to hybrid search and reranking only when retrieval metrics stall, and treat top-k as a cost and quality dial starting at k=5.

To learn how to build rag pipeline systems that survive real traffic, you need six connected stages: ingestion, chunking, embedding, retrieval, generation, and evaluation, with an eval loop measuring recall@k, MRR, groundedness, and answer relevance so you can trace every bad answer back to the stage that caused it. This guide covers each stage and how to debug the system.

What is a RAG pipeline and how does it work?

A RAG pipeline retrieves relevant documents from your own data and feeds them to an LLM as context, so answers are grounded in your corpus instead of the model's training weights.

The six stages in one sentence each

  1. Ingestion pulls documents from your sources into a processing queue.
  2. Chunking splits them into passages small enough to retrieve precisely.
  3. Embedding converts each chunk into a vector, following your embedding model's guidance on chunk size and dimensions.
  4. Indexing stores those vectors for fast similarity search.
  5. Retrieval finds the top chunks matching a query at request time.
  6. Generation passes them as context to the LLM, which writes the answer.

Where most pipelines actually break

Demos fail at stage six; production fails earlier. Bad chunking, stale ingestion, and retrieval that misses on real user phrasing account for most wrong answers, which is why evaluation has to cover retrieval quality, not just the final output. If you are debugging a pipeline that works on canned questions but breaks on real traffic, that is the gap to close first โ€” or bring in someone who has closed it before (fractional AI engineering).

How do you build a RAG pipeline from scratch step by step?

Build in this order: ingestion, chunking, embedding and indexing, retrieval, generation. Each stage feeds the next, so a mistake upstream (bad parsing, oversized chunks) shows up downstream as weak answers that look like model problems. Fix stages in order, not all at once.

Step 1: Ingestion and parsing

Pull raw documents from their sources and convert them to clean text. PDFs, HTML pages, and docs each need their own parser; a PDF table read as flat text will poison every later step. Keep the source URL and document ID attached to every chunk so you can trace any answer back to its origin.

Step 2: Chunking

Split text into chunks of roughly 200 to 500 tokens with 10 to 20 percent overlap. The right size depends on your content: prose tolerates larger chunks, while FAQs and tables should stay intact. Add section headers to each chunk so context survives the split.

Step 3: Embedding and indexing

Run each chunk through an embedding model and store the vectors in an index that supports approximate nearest-neighbor search. Store the chunk text alongside the vector; re-embedding thousands of chunks because you forgot metadata is a bill you do not want.

Step 4: Retrieval

At query time, embed the user's question, pull the top-k chunks (start with k between 3 and 10), and rank them. Log every retrieval with scores and chunk IDs so you can diagnose failures later. This is the stage most demos skip and most production incidents live in.

Step 5: Generation and prompting

Assemble the retrieved chunks into a prompt with clear instructions: answer only from the provided context, cite which chunk supports each claim. Keep the prompt template versioned like code, because a wording change can shift answer quality as much as a model swap. When the pipeline is live, the work shifts from building to measuring, which is where most teams get help.

How should you chunk and embed documents for retrieval?

Chunk size and overlap in practice

Start with 256-512 tokens per chunk and 10-15% overlap. Smaller chunks improve retrieval precision but starve the generator of context; larger chunks do the opposite. Treat these numbers as a starting grid, then tune against your eval metrics, not intuition.

Structure-aware splitting beats fixed windows

Split on headings, paragraphs, and code blocks before you count tokens. A fixed 400-token window that cuts a table in half or severs a definition from its term produces chunks that retrieve well but answer badly. Keep headers attached to their section body so each chunk carries its own context.

Choosing an embedding model

Pick on three criteria: performance on a retrieval benchmark, embedding dimension (drives vector-store cost), and context length. Judge candidates with recall@k and MRR, standard retrieval metrics defined in the BEIR benchmark paper. Re-embed your corpus whenever you swap models; mixing embedding spaces silently degrades retrieval. I log chunking and embedding decisions alongside eval results so regressions trace back to a cause, a pattern I write about more on the blog.

How do you retrieve and rank the right context at query time?

Top-k is a cost and quality dial

Top-k controls how many chunks you pass to the model. Every extra chunk costs tokens on every query and adds noise that degrades generation, so treat k as a tunable dial, not a default. Start at k=5, then adjust based on eval results and your token bill.

Hybrid search and reranking

Dense embeddings miss exact matches: product codes, names, rare terms. Combine vector search with keyword search (BM25) and merge results with reciprocal rank fusion. Then rerank the merged candidates with a cross-encoder, keeping only the top few. A two-stage setup, retrieve 50, rerank to 5, usually beats a single-stage top-50 pass on both quality and cost.

Metadata filters as a first-class tool

Filter by tenant, date, document type, or status before retrieval runs. This shrinks the search space, prevents cross-tenant leakage, and fixes stale-answer failures cheaply. Design your schema so filters map to real user segments. When retrieval still misses after filtering, hybrid search, and reranking, the gap is usually upstream in chunking, or a hiring problem I cover in my background.

How do you evaluate a RAG pipeline for retrieval and generation quality?

You evaluate two stages separately: did retrieval surface the right context, and did generation turn that context into a correct answer. Measuring only end-to-end answer quality hides which stage is broken.

Build a golden dataset before you tune anything

Write 50-100 real questions with known answers and, critically, the source chunk that should be retrieved for each. Pull them from support tickets, sales calls, or actual user queries, not from your imagination. This dataset is your regression suite; without it, every chunking or model change is a guess. This is the first thing I set up with clients taking a pipeline to production (selected work).

Retrieval metrics: recall@k and MRR

Recall@k answers: for what percentage of queries does the correct chunk appear in the top k results? Start with k=5. MRR (mean reciprocal rank) tells you how high the right chunk ranks on average, which matters when your context window can't fit everything.

Generation metrics: groundedness and answer relevance

Groundedness checks whether every claim in the answer is supported by the retrieved context, catching hallucination. Answer relevance checks whether the response actually addresses the question. An LLM judge with a strict rubric works well enough to catch regressions, even if it's imperfect.

Run evals on every change, not once

ChangeWhat to runWhat to watch
New chunking strategyFull suiterecall@5, MRR
New embedding modelFull suiterecall@5, latency, cost
Prompt or model changeGeneration subsetgroundedness, relevance
New rerankerRetrieval subsetMRR, latency

Treat metric drops like failing tests: block the change until you understand them.

What are the most common RAG pipeline failure modes and how do you fix them?

Most failures trace back to one stage, so diagnose by symptom.

Hallucinated answers. The generator is filling gaps because retrieval returned weak or empty context. Fix retrieval first: check whether the right chunk exists in your index, then whether ranking pushed it out of the top-k. If retrieval is fine, tighten prompts to refuse when context is insufficient.

"Not in the docs" answers despite the docs containing it. A chunking or ingestion problem. Overlapping chunks, better boundaries, and re-embedding the affected source usually resolve it.

Slow, expensive queries. Too much context per request. Reduce k, compress retrieved text, or cache embeddings and frequent retrievals.

Measure each fix instead of eyeballing outputs. The RAGAS documentation defines groundedness and answer-relevance metrics you can run on every pipeline change, so regressions surface before your users report them.

When should you move beyond naive RAG to hybrid or reranked retrieval?

Signals your evals should trigger the upgrade

Upgrade when your retrieval metrics stall, not when a blog post tells you to. If recall@k plateaus below your target while you tune chunk sizes, or your failure diagnosis shows queries with keyword-specific terms (error codes, product names, part numbers) retrieving nothing, dense embeddings alone are the bottleneck. A second trigger: precision is fine at k=20 but your generation step degrades with long context, meaning you need fewer, better-ranked chunks rather than more of them.

What each upgrade costs in latency and complexity

Hybrid search (dense plus BM25) adds modest complexity: a second index and a fusion step like reciprocal rank fusion, usually under 50ms extra. A reranker is the bigger trade: running a cross-encoder over your top 20-50 candidates adds hundreds of milliseconds per query, so most teams rerank a smaller candidate set or cache aggressively. Query rewriting adds an extra LLM call before retrieval, doubling your p50 latency and your token bill on every request. Run each upgrade behind a flag and re-run your eval set; if recall@k or answer quality doesn't move by a margin you care about, revert it.

What does it cost to run a RAG pipeline in production?

Three levers drive your token bill: context length (prompt + retrieved chunks), top-k, and reranker calls. Doubling top-k doubles the tokens you send per query, and a cross-encoder reranking 50 candidates adds its own inference cost on every request. At scale, retrieval choices dominate spend more than the LLM you picked.

Keep costs predictable by capping chunk tokens, setting a hard context budget per query, and logging tokens per request so you can attribute spikes to a specific change. Tracing per-stage token counts makes regressions visible before the invoice is.

One caveat: hybrid retrieval with BM25 (see Weaviate's hybrid search documentation) sends fewer irrelevant chunks to the LLM, which cuts wasted tokens rather than adding them.

Should you build RAG in-house or get senior help?

If your team already ships software and owns the eval loop, build in-house. Naive RAG is a few hundred lines of code; the hard parts are chunking strategy, retrieval diagnosis, and keeping the token bill sane under real traffic. A mid-level engineer with a good tracing setup can hold that. The trap is skipping evaluation: teams ship a demo, wire it into the product, and only discover retrieval failures when users complain, at which point every fix is a guess because there is no golden dataset to measure against. Build the eval loop first, even if it is only fifty questions in a spreadsheet, and wire it into your CI so a chunking change that drops recall@5 blocks the merge. That discipline costs a day up front and saves weeks of debugging later, and it is the single biggest predictor of whether a pipeline survives its first quarter of real traffic.

If nobody on the team has run retrieval in production before, the cheapest fix is senior part-time help, not a full-time AI-architecture hire you cannot yet justify. Marketplaces sell you an individual; embedded fractional engagements put a senior operator inside your repo and evals for a defined scope.

My own offer sits in that last category: fractional AI engineering where I take your pipeline from demo to production, work inside your repo and evals, and hand back architecture your team can run. The honest limitation: I am one person, so capacity is capped. If you need three engineers next month, hire; if you need the right architecture this month, that is the trade.

FAQ

How long does it take to build a RAG pipeline from scratch?

A working demo takes days, since naive RAG is a few hundred lines of code. Production takes weeks, mostly because of chunking strategy, a golden dataset of 50-100 real questions, and an eval loop covering recall@k, MRR, groundedness, and answer relevance. Fix stages in order rather than all at once.

Do I need a vector database, or can I use Postgres for RAG?

You need an index that supports approximate nearest-neighbor search, but it does not have to be a dedicated vector database. Postgres with a vector extension works at modest scale. What matters more is storing chunk text and metadata alongside vectors, supporting metadata filters like tenant and date, and logging retrieval scores so failures stay diagnosable.

What chunk size should I use for RAG?

Start with 256-512 tokens per chunk and 10-15% overlap, then tune against eval metrics rather than intuition. Prose tolerates larger chunks; FAQs and tables should stay intact. Split on headings, paragraphs, and code blocks before counting tokens, and keep section headers attached so each chunk carries its own context.

How much context should I pass to the LLM in a RAG prompt?

Treat top-k as a cost and quality dial, not a default. Start at k=5, within a range of 3 to 10, and set a hard context budget per query. Every extra chunk costs tokens on every request and adds noise that degrades generation. Adjust based on eval results and log tokens per request to catch spikes.

Can I evaluate a RAG pipeline without labeled data?

Not usefully. Write 50-100 real questions with known answers and the source chunk that should be retrieved, pulled from support tickets, sales calls, or actual queries. That dataset is your regression suite; without it, every chunking or model change is a guess. An LLM judge with a strict rubric can score groundedness and relevance, but the golden dataset comes first.

Got an AI system that works in the demo but not in production?

Book a call