RAG Architecture: Complete Technical Guide
An end-to-end blueprint for RAG systems: the indexing and query pipelines, component choices at each stage, evaluation, access control and operations.
A retrieval-augmented generation (RAG) architecture has two pipelines and a feedback loop. An offline indexing pipeline turns your documents into searchable chunks; an online query pipeline retrieves the most relevant chunks for each question and passes them to a language model to write a grounded, cited answer; and an evaluation loop measures both so you can improve them. Every quality problem in RAG traces back to a specific stage, which is why it pays to design each one deliberately.
This guide is the system-level blueprint. If you are new to the idea, start with What Is RAG?. Deeper dives on individual stages are linked throughout.
Where the architecture came from
The term comes from a 2020 paper by Lewis and colleagues, which combined a pre-trained generator ("parametric memory") with a dense vector index of Wikipedia ("non-parametric memory") accessed by a neural retriever [1]. They found RAG models produced more specific, diverse and factual language than a parametric-only baseline [1]. Many modern systems keep the same split, but often pair an off-the-shelf LLM with a retrieval stack rather than training them together.
A 2023 survey groups RAG designs into three stages of maturity: Naive RAG (retrieve, then read), Advanced RAG (adds pre- and post-retrieval optimizations such as query rewriting and reranking) and Modular RAG (swappable components and flexible flows) [2]. This guide describes an Advanced-to-Modular design.
The reference architecture
Stage | Pipeline | Key decision | Deep dive |
|---|---|---|---|
Connectors and parsing | Indexing | Which sources, how to extract clean text and structure | This guide |
Chunking | Indexing | Unit size, boundaries, overlap, metadata | |
Embedding | Indexing and query | Model choice, dimensions, domain fit | |
Indexing | Indexing | Vector index type, keyword index, ACL metadata | |
Query processing | Query | Rewriting, expansion, routing | This guide |
Retrieval | Query | Dense, sparse or hybrid; top-k | |
Reranking | Query | Cross-encoder or LLM reranker; cut-off | |
Generation | Query | Prompt structure, citations, refusal rules | This guide |
Evaluation and monitoring | Both | Metrics, test sets, tracing | This guide |
The indexing pipeline
1. Connectors. Pull content from document stores, wikis, ticketing systems and databases. Capture source metadata at this stage: URL or ID, owner, last-modified date and, critically, who is allowed to see it.
2. Parsing and cleaning. Extract text while preserving structure that carries meaning: headings, tables, list hierarchy. Strip navigation, boilerplate and duplicate copies. Poor parsing can silently cause bad answers, because the right content never makes it into the index in usable form.
3. Chunking. Split documents into retrievable units. Chunk size trades precision against context: small chunks match queries tightly but lose surrounding meaning. Anthropic's "contextual retrieval" technique addresses this by prepending a short, model-generated description of each chunk's place in its document before embedding and keyword indexing; it reported that this reduced the top-20 retrieval failure rate by 49%, and by 67% when combined with reranking, on its test sets [5]. Our chunking guide compares the main strategies.
4. Embedding. Convert each chunk into a vector with an embedding model. The same model must embed queries at search time. Changing models means re-embedding the corpus, so version your embeddings.
5. Indexing. Store vectors in an approximate nearest neighbor index. HNSW, which builds a hierarchy of proximity-graph layers and searches from the sparse top layer down, is one well-known option [3]. Alongside it, keep a keyword (BM25-style) index for exact terms, product codes and names that embeddings handle poorly. Attach access-control and freshness metadata to every chunk so the query pipeline can filter on it.
The query pipeline
1. Query processing. Clean the question, resolve references from earlier conversation turns ("what about the second one?"), and optionally rewrite or expand it. For multi-part questions, decompose into sub-queries. Routing logic can send different question types to different indexes or tools.
2. Retrieval with permission filtering. Run dense (vector) and sparse (keyword) retrieval, filtering by the user's permissions inside the search, not after generation. Filtering after the fact risks leaking restricted content into the model's context.
3. Fusion. Merge the result lists. Reciprocal Rank Fusion is a simple, robust method that scores each document by the sum of 1/(k + rank) across lists; its authors found k = 60 near-optimal in their experiments [4]. See hybrid search for alternatives.
4. Reranking. Re-score the top candidates with a stronger but slower model, such as a cross-encoder, and keep the best few. In Anthropic's tests, reranking the top 150 retrieved chunks down to 20 lowered retrieval failures further on top of contextual embeddings and BM25 [5]. Details in reranking models explained.
5. Context assembly. Order and format the chosen chunks with their source labels. Position matters: research on long contexts found models perform best when relevant information is at the beginning or end of the input, and significantly worse when it is in the middle [6]. Put the strongest evidence first, and keep the context focused rather than maximal.
6. Generation. Instruct the model to answer only from the provided context, cite sources by label, and say when the context does not contain the answer. This is your main defense against hallucinations.
Evaluation: measure each stage separately
End-to-end "does the answer look right" testing hides where failures come from. Evaluate retrieval and generation separately:
Layer | Question | Example metrics |
|---|---|---|
Retrieval | Did we fetch the right chunks? | Recall@k, precision@k, MRR on a labeled set |
Context | Is the context focused? | Context relevance |
Generation | Is the answer supported by the context? | Faithfulness, citation accuracy |
Answer | Did it address the question? | Answer relevance, human ratings |
The Ragas framework proposed metrics for these dimensions, including faithfulness to retrieved passages, that can be computed without human-written reference answers [7]. Automated judges are useful for fast iteration; keep a smaller human-labeled test set to calibrate them.
Operating RAG in production
- Freshness. Re-index changed documents incrementally and delete removed ones. Show the source's last-modified date in citations.
- Versioning. Record which embedding model, chunking settings and index version produced each answer, so regressions can be traced.
- Tracing. Log the query, retrieved chunk IDs, scores, prompt and output for every request (with appropriate privacy controls).
- Security. Retrieved content is untrusted input. A poisoned document can carry instructions aimed at the model. See RAG security: prompt injection and guardrails.
- Cost and latency. Reranking and long contexts add latency and tokens. Tune top-k and reranker cut-offs on your evaluation set, not by intuition.
When to extend the architecture
A single-pass pipeline handles most fact-lookup questions. Questions that need several hops, comparisons or tool use may benefit from an agent that plans and retrieves iteratively; see agentic RAG architecture and our comparison of agentic RAG vs traditional RAG. If the problem is style or format rather than knowledge, fine-tuning may fit better; see RAG vs fine-tuning.
Frequently asked questions
What are the main components of a RAG architecture?
An indexing pipeline (connectors, parsing, chunking, embedding, indexing), a query pipeline (query processing, retrieval, fusion, reranking, context assembly, generation) and an evaluation and monitoring loop. The 2023 survey describes retrieval, generation and augmentation as the "tripartite foundation" of RAG frameworks [2].
Do I need both vector search and keyword search?
Often, yes. Vector search captures meaning, while keyword search catches exact identifiers and rare terms. Combining them with a fusion method such as Reciprocal Rank Fusion is a common, robust default [4].
How many chunks should I pass to the model?
As few as reliably contain the answer. Long contexts are not used evenly; models tend to miss information placed in the middle [6]. Tune the number on an evaluation set after reranking.
How do I enforce document permissions in RAG?
Store access-control metadata with every chunk and filter by the user's permissions during retrieval, so restricted content never reaches the model. Do not rely on the model to withhold information it has already seen.
How do I know if my RAG system is getting better?
Keep a fixed test set of questions with known relevant documents and answers. Track retrieval recall and answer faithfulness separately [7], and re-run the set after every change to chunking, embeddings, retrieval or prompts.
Sources
- Lewis, P. et al. "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks." arXiv:2005.11401, 2020. https://arxiv.org/abs/2005.11401
- Gao, Y. et al. "Retrieval-Augmented Generation for Large Language Models: A Survey." arXiv:2312.10997, 2023. https://arxiv.org/abs/2312.10997
- Malkov, Y. and Yashunin, D. "Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs." arXiv:1603.09320. https://arxiv.org/abs/1603.09320
- Cormack, G., Clarke, C. and BΓΌttcher, S. "Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods." SIGIR 2009. https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf
- Anthropic. "Introducing Contextual Retrieval." 2024. https://www.anthropic.com/news/contextual-retrieval
- Liu, N. et al. "Lost in the Middle: How Language Models Use Long Contexts." arXiv:2307.03172, 2023. https://arxiv.org/abs/2307.03172
- Es, S. et al. "Ragas: Automated Evaluation of Retrieval Augmented Generation." arXiv:2309.15217, 2023. https://arxiv.org/abs/2309.15217