Workflows.guru

Building Production RAG Pipelines: From Basic Retrieval to Reliable Systems

By Abdesslem Amri - Published

Retrieval Augmented Generation (RAG) has become a common architecture for applications that need to answer questions using private documents, internal knowledge bases, technical documentation, or business data.

The idea is pretty simple: instead of asking a Large Language Model (LLM) to answer a question using its training data, we retrieve our private data and provide that information as context for the LLM.

A basic RAG pipeline can be implemented in a few steps. Load documents, split into chunks, generate embeddings, retrieve relevant chunks for a question, and pass them to an LLM.

This guide is divided into two sections. First, we will build an understanding of basic RAG pipelines. Then, we will show how to evolve the architecture to a production system.

Section 1: Understanding and building basic RAG pipelines

What is a RAG pipeline?

A RAG pipeline is composed of stages: indexing and query. The indexing stage prepares documents and the query stage runs when a user submits a question.

A basic RAG pipeline follows the following steps:

  1. Load the documents.
  2. Split the documents into chunks, for more details about chunking.
  3. Convert the chunks into embeddings.
  4. Store the embeddings in index.
  5. Convert a user question into an embedding using the same embedding model.
  6. Retrieve the relevant chunks.
  7. Send the question and retrieved context to the LLM.
  8. Return the generated answer.

Building a basic RAG pipeline

The quality of a RAG pipeline depends on the documents you ingest. These documents will then be split into smaller units called chunks. A simple approach is to split text into fixed size chunks with some overlap. Other strategies include, recursive chunking and semantic chunking.

Once documents have been split into chunks, each chunk must be converted into a representation called embedding. This is done using an embedding model (for example text-embedding-3-large from OpenAI) which maps text into a vector space where semantically related passages can be found near each other.

The resulting vector is than stored with the chunk and its associated metadata in a vector database such as PostgreSQL with pgvector, Qdrant... At query time, we use the same embedding model to encode the user question and then we search for chunks whose vectors are similar to the query vector.

Retrieving context and generating an answer

After embedding the user question, the system retrieves the top-K most similar chunks and the application combines them into a prompt and asks the LLM to answer using that context.

A simplified prompt might look like this:

1You are a technical support assistant.
2Answer the question using the supplied context.
3If the context does not contain enough information,
4say that you cannot determine the answer.
5
6Context:
7{retrieved_chunks}
8
9Question:
10{user_question}

The application then sends this prompt to the language model. A basic implementation can be as follow:

1def answer_question(question):
2 query_vector = embed(question)
3
4 chunks = vector_store.search(
5 vector=query_vector,
6 limit=5,
7 )
8
9 context = "\n\n".join(
10 chunk.text for chunk in chunks
11 )
12
13 return generate_answer(
14 question=question,
15 context=context,
16 )

This is the essential RAG loop: retrieve evidence then generate an answer using that evidence. In the next section we will see what are the limitations of this basic RAG pipeline.

What a basic RAG pipeline cannot guarantee

A basic RAG pipeline is a good starting point, but several problems become apparent when it is used with real documents and real users. the following are some of the most common limitations:

Retrieval misses relevant information. Vector similarity is not the same as answer relevance. The top-ranked chunk might discuss the same subject without containing the answer.

Exact terms can be difficult to retrieve. A user might search for a product identifier, an error code, a version number, or a policy reference. Pure semantic search may not rank the passage containing that exact identifier highly enough.

Document updates can produce stale answers. If a document changes but its old chunks remain indexed, the system may return outdated information.

Answers can contain unsupported claims. Even when relevant chunks are retrieved, an LLM can introduce information that is not supported by those chunks.

Quality is difficult to measure without evaluation. A few successful manual questions do not establish that the system works reliably across different topics, query types, or document versions.

Production constraints are missing. A simple function does not address authentication, permissions, concurrent requests, retries, resource limits, monitoring, or operational recovery.

These limitations are not reasons to abandon RAG. They are reasons to treat it as a system that needs engineering, testing, and continuous improvement.

Section 2: How RAG pipelines should work in production

Production RAG architecture

A production RAG system needs more than document embeddings and an LLM call. It needs reliable indexing, controlled retrieval, grounded generation, security, observability, and evaluation.

Evaluation, logging, cost tracking, and security controls operate across these stages rather than belonging to only one component.

The production architecture also needs to distinguish between the online request path and the background indexing path. They have different latency requirements, failure modes, and scaling needs.

Build a reliable document ingestion pipeline

The indexing pipeline is often overlooked because it runs outside the user immediate request. However, document processing errors can silently undermine the entire system.

Consider a PDF containing a table of configuration parameters. If the parser extracts the table as an unordered collection of words, the embedding model cannot reconstruct the original relationships reliably.

A production ingestion pipeline should typically include: Document discovery and ingestion, parsing and text extraction, normalization and cleaning, structure-aware chunking and publication of the updated document version

Process documents asynchronously

Document ingestion should not run inside the same HTTP request that answers a user question. Instead, a user uploads a document, the application records an ingestion job, and a worker processes it in the background.

1def ingest_document(document):
2 parsed = parse_document(document)
3 chunks = split_document(parsed)
4 chunks = enrich_metadata(chunks)
5
6 embeddings = embed_chunks(chunks)
7
8 index_chunks(
9 chunks=chunks,
10 embeddings=embeddings,
11 )
12
13 validate_indexed_document(document.id)

This is an illustrative processing function. A production implementation would add durable job state, retries, version tracking, and error reporting.

A workflow orchestrator can coordinate document parsing, chunking, embedding, and indexing. Independent documents can be processed concurrently. For related workflow concepts, see Mastering Apache Airflow and Creating Workflows with Prefect.

Make indexing incremental and version-aware

Reprocessing an entire knowledge base every time a document changes is not necessary. A production system should identify new, changed, and deleted documents, then reprocess only the affected content.

Each indexed chunk should retain enough information to trace it back to its source, such as: Document ID and version, page or section information and tenant or access-control metadata.

Indexing should also avoid exposing partially updated document versions to users. Depending on the system, this can be achieved through versioned indexes, staging collections, or an atomic publication step.

A basic RAG pipeline usually starts with vector search. In production, combining semantic retrieval with keyword search is often worth evaluating.

Vector search helps identify passages with similar meaning. Keyword retrieval is effective when exact words, identifiers, acronyms, and codes matter.

Semantic search may find general passages about retry policies. Keyword search can help find the exact occurrence of ERR-482. Hybrid retrieval combines the strengths of both approaches:

The two result lists can be combined using Reciprocal Rank Fusion (RRF), a rank-based method that combines rankings without requiring their raw scores to be directly comparable. Conceptually, the RRF score for a document d is:

RRF(d) = ∑r ∈ R 1 / (k + rankr(d))

Here, R is the set of ranked result lists, rankr(d) is the position of d in list r, and k is a smoothing constant (60 is a common default).

Hybrid search is not automatically better for every dataset. Its value should be measured on representative questions. It can be especially useful when the corpus contains technical identifiers, exact terminology, and natural-language descriptions.

Apply metadata filters during retrieval

Production systems often need to restrict search by date, product, document type, customer, or access permissions. These filters should be applied as part of retrieval, not left for the LLM to interpret.

For example, if a user is allowed to access only documents belonging to a particular organization, the retriever should search only the authorized document set. A prompt instruction such as "do not reveal other customers information" is not a substitute for enforcing authorization in the application and retrieval layer.

Add a reranking stage

Hybrid retrieval improves candidate discovery, but the initial ranking may still contain irrelevant passages. A reranker evaluates the query and each retrieved candidate together, then reorders the candidates according to their estimated relevance.

This creates a two-stage retrieval process:

  • Candidate retrieval: quickly retrieve a relatively broad set of candidates.
  • Reranking: apply a more expensive relevance model to a smaller set.

Reranking is especially useful when the correct chunk appears among the retrieved candidates but is ranked too low to reach the LLM.

However, a reranker cannot recover a passage that the candidate retrieval stage never found. If the correct evidence is absent from the initial candidate set, investigate chunking, query handling, indexing, and retrieval recall first.

Evaluate retrieval before tuning the LLM

One of the most common mistakes in RAG development is to judge the entire system only by whether the final answer looks correct. A poor answer might result from:

  • The relevant document never being indexed.
  • Chunking separating important information.
  • The retriever missing the relevant chunk.
  • The reranker demoting the correct passage.
  • Context assembly removing useful evidence.
  • The LLM misinterpreting retrieved information.

Build a golden dataset

A golden dataset contains representative questions and the relevant source passages expected to answer them. For example:

QuestionExpected evidence
What is the maximum retry count?Chunk 12
Which service owns the authentication configuration?Chunks 24 and 25
When does the backup policy expire?Chunk 41

These examples are illustrative. Real evaluation data should come from actual user questions, known business requirements, and manually verified evidence.

For each question, record the expected relevant chunks or documents. You can then compare retrieval strategies, embedding models, chunk sizes, and reranking configurations against the same dataset.

Measure retrieval quality

Several metrics are useful:

  • Hit Rate@K: the proportion of questions for which at least one relevant result appears in the top K.
  • Recall@K: the proportion of expected relevant items retrieved in the top K.
  • MRR (Mean Reciprocal Rank): rewards systems that rank the first relevant result highly.
  • nDCG@K: evaluates ranking quality while accounting for the positions and, where applicable, degrees of relevance of retrieved results.

For example, a system might achieve a high Hit Rate@5 but still have poor Recall@5 if each question has multiple relevant chunks and only one is retrieved. That difference matters when an answer requires evidence from several parts of a document.

Evaluate generation separately

Retrieval metrics do not tell you whether the LLM produces a correct answer. Generation evaluation should also examine:

  • Faithfulness: whether the answer claims are supported by the supplied context.
  • Answer relevance: whether the answer addresses the user question.
  • Citation accuracy: whether cited passages actually support the associated claims.
  • Abstention behavior: whether the system declines to answer when the available evidence is insufficient.

A good evaluation process tracks retrieval and generation separately before combining them into an end-to-end assessment.

For further reading on structured LLM workflows, see Common Agentic Workflow Patterns. An agentic architecture may help when a query requires multiple retrieval steps or conditional tool use, but it does not replace retrieval evaluation.

Make generation grounded and traceable

A production RAG system should make it clear where its answers come from. The generation prompt should define how the LLM uses the retrieved context, how it handles missing evidence, and how it formats citations. For example:

1def build_prompt(question, chunks):
2 context = "\n\n".join(
3 f"[{chunk.id}] {chunk.text}"
4 for chunk in chunks
5 )
6
7 return f"""
8Answer the question using the supplied context.
9
10Rules:
11- Do not invent facts that are absent from the context.
12- If the context is insufficient, say so.
13- Cite the chunk IDs supporting your answer.
14
15Context:
16{context}
17
18Question:
19{question}
20"""

This code demonstrates prompt construction, not a complete guarantee against hallucinations. The application should validate citation IDs and retain the mapping between each chunk and its original source.

Where practical, answers should provide source links, page numbers, section titles, or other references that users can inspect. For high-impact applications, additional validation may be required before an answer is shown or acted upon.

Add security and access control

Production RAG frequently handles confidential information. The retrieval system must respect the same authorization rules as the underlying data sources.

Suppose a company has three departments, each with its own internal documentation. A user from one department should not receive another department's restricted documents simply because they are semantically similar to the question.

Security controls should include:

  • Tenant and document-level access filtering.
  • Authentication and authorization before retrieval.
  • Protection of API keys and provider credentials.
  • Safe handling of uploaded files.
  • Appropriate retention and deletion policies.
  • Protection against prompt injection contained in retrieved documents.
  • Logging policies that avoid unnecessarily exposing confidential prompts or document contents.

The LLM should treat retrieved documents as untrusted content, not as instructions that can override system-level rules. Authorization must be enforced by trusted application logic. It should never depend solely on the model choosing to obey a prompt.

Make the pipeline observable and resilient

A production system needs to explain what happened during a request. When a user reports an incorrect answer, engineers should be able to investigate the retrieval results, selected chunks, model configuration, and generation response.

Useful telemetry includes:

  • Query and request identifiers.
  • Retrieval strategy and configuration.
  • Retrieved chunk IDs and ranking scores.
  • Reranking results.
  • Embedding and generation model versions.
  • Latency for each stage.
  • Token usage and estimated cost.
  • Errors, retries, and timeouts.
  • Evaluation outcomes, where available.

Avoid storing sensitive document contents or personal data unnecessarily. Access to traces should be controlled, and retention should match security requirements.

Set timeouts and retry policies

Not every external call will succeed. Embedding providers, vector databases, and LLM APIs can experience timeouts, rate limits, and temporary failures.

Retries should be limited and use backoff for transient failures. Permanent errors, such as invalid requests, should not be retried indefinitely. For a deeper look at which network failures are safe to retry, see Connection Refused, Timeouts and Unreachable Hosts.

For document ingestion, durable jobs and retryable stages can prevent a temporary failure from requiring the entire corpus to be reprocessed.

For online queries, define a latency budget across retrieval, reranking, and generation. If an optional reranking stage times out, decide explicitly whether to fail the request or use the initial retrieval results.

Tools and services for building production-ready RAG

You do not need to build the evaluation and monitoring layers from scratch. The following tools cover different stages of the lifecycle, so choose them based on the question you need to answer.

ToolMain question it answersWhere it fits
TruvecWhich embedding model, chunking strategy, and reranker work best on my documents?Retrieval design, before building or migrating
RagasHow good are my pipeline's retrieved contexts and answers?Offline evaluation and experiments
DeepEvalDid this change break quality?Automated tests and CI/CD
TruLensAt which step did this request go wrong?Tracing and evaluation of application runs

Truvec: choose a retrieval configuration

Truvec is a hosted service for evaluating retrieval on your own documents. You upload a sample, it generates an editable golden set of questions linked to the chunks that answer them, and it compares embedding models, chunking settings, hybrid search, and rerankers. Results include hit rate, recall, MRR, and nDCG alongside latency and cost.

It evaluates retrieval only: it does not grade generated answers or run your production pipeline. Because it is a hosted service, check its data handling against your requirements before uploading confidential documents.

Ragas: measure retrieval and generation

Ragas is an open-source Python library for evaluating LLM applications. Its RAG metrics include context precision and context recall for retrieval, and faithfulness and response relevancy for generation. It can also generate synthetic test data from your documents, which helps when you do not yet have enough real user questions.

DeepEval: turn quality into automated tests

DeepEval is an open-source framework that brings LLM evaluation into a pytest-style workflow. Each metric has a threshold, and a test fails when a score falls below it. This makes it a natural fit for CI/CD workflows. the following example shows how to evaluate a RAG pipeline using DeepEval:

1import pytest
2from deepeval import assert_test
3from deepeval.metrics import ContextualRecallMetric, FaithfulnessMetric
4from deepeval.test_case import LLMTestCase
5
6from my_app import golden_dataset, rag_pipeline
7
8
9@pytest.mark.parametrize("example", golden_dataset)
10def test_rag_quality(example):
11 result = rag_pipeline(example["question"])
12
13 test_case = LLMTestCase(
14 input=example["question"],
15 actual_output=result["answer"],
16 expected_output=example["expected_answer"],
17 retrieval_context=result["contexts"], # list of strings
18 )
19
20 assert_test(
21 test_case,
22 [
23 ContextualRecallMetric(threshold=0.8),
24 FaithfulnessMetric(threshold=0.8),
25 ],
26 )

TruLens: trace and evaluate each step

TruLens is an open-source library that instruments an application and evaluates its execution traces. It is known for the RAG triad: context relevance checks whether the retrieved context matches the question, groundedness checks whether the answer is supported by that context, and answer relevance checks whether the answer addresses the question.

Together, these scores help distinguish a retrieval failure from a generation failure. Its instrumentation is compatible with OpenTelemetry, so traces can also be exported to an existing observability backend.

How to combine them

A practical approach is to introduce tools as the system matures:

  1. Design: compare retrieval configurations with Truvec and review the golden set by hand.
  2. Develop: use Ragas to evaluate the end-to-end pipeline while tuning prompts and context assembly.
  3. Release: use DeepEval to block regressions on a small, stable test set in CI.
  4. Operate: use TruLens to trace requests, evaluate a sample of them, and feed failures back into the golden dataset.

Ragas, DeepEval, and TruLens overlap, and many teams need only one of them. Start with the one that closes your largest gap.

Many of these metrics use an LLM as a judge. Their scores can vary between runs, they add cost and latency, and they can be wrong. Pin the judge model version, validate a sample of scores against human review, and avoid comparing scores across tools, since similarly named metrics may be computed differently.

Conclusion

Building a basic RAG pipeline is relatively straightforward: prepare documents, generate embeddings, retrieve relevant chunks, and ask an LLM to generate an answer using the retrieved context.

Building a production RAG system requires a broader approach. Document ingestion must be reliable, retrieval must be measured, answers must be grounded and traceable, permissions must be enforced, and the entire system must be observable and maintainable.

The most important principle is to treat RAG as a pipeline of independently testable components. When the system produces an incorrect answer, identify whether the failure occurred during indexing, retrieval, ranking, context assembly, or generation before changing the architecture.

Start with a simple baseline, establish an evaluation dataset, and introduce additional retrieval and operational complexity only when measurements justify it.

A RAG system should not merely produce plausible answers in a demo. It should provide useful, verifiable answers consistently as the corpus, workload, and application evolve.

Further reading on Workflows.guru