Retrieval-Augmented Generation Architecture: An End-to-End Guide

How a production RAG system fits together: chunking, embeddings, hybrid search, reranking, evaluation, and the failure modes that sink most projects.

DIDatainter TeamFEB 14, 20268 MIN READTECHNOLOGY

Retrieval-augmented generation, or RAG, is the dominant way to make a language model answer questions about data it was never trained on: your contracts, your product documentation, your tickets. The idea is simple. Find the passages that are relevant to the question, put them in the prompt, and ask the model to answer using only that material.

The idea is simple and the execution is not. Most RAG systems that disappoint do so because of retrieval, not generation. The model is usually good at reading the passages it is given. The problem is that the right passages were never found, or were found and buried among irrelevant ones. This guide walks through the pipeline stage by stage, with the trade-offs that matter in practice.

The pipeline at a glance

A RAG system has two flows. The offline flow prepares the knowledge: ingest documents, clean them, split them into chunks, compute embeddings, and write everything to an index. The online flow answers a query: rewrite the question if needed, retrieve candidates, rerank them, build a prompt, generate an answer, and optionally verify it.

Each stage has a measurable output, which means each can be evaluated separately. That is the single most useful property of the architecture, and the reason to resist building it as one opaque chain.

If you cannot tell whether a bad answer came from retrieval or from generation, you cannot fix it. Measure the stages separately.

Ingestion and cleaning

Quality starts before chunking. Real corpora are messy: PDFs with two-column layouts, scanned pages, tables, slide decks, wiki pages with navigation menus. A naive text extraction that interleaves columns or drops table structure poisons everything downstream.

Practical guidance:

  • Use a layout-aware parser for PDFs. For scanned documents, run OCR and keep confidence scores so low-quality pages can be flagged.
  • Convert tables to a text form that preserves row and column relationships, such as Markdown tables or one sentence per row. Raw cell text in reading order loses meaning.
  • Strip boilerplate: headers, footers, cookie banners, repeated disclaimers. They dominate embeddings and pollute search results.
  • Keep metadata: source, title, section path, author, date, language, access control group, version. You will need it for filtering, citations and permission checks.
  • Deduplicate. Near-duplicate documents fill the top results and crowd out diversity.
Technology · Retrieval-Augmented Generation Architecture: An End-to-End Guide

Chunking

Embedding models and prompts work on bounded text, so documents must be split. Chunk size is the most consequential parameter in the system, and there is no universal right value.

Small chunks, around 100 to 200 tokens, give precise matches but lose context. A paragraph that says “this does not apply to the exemption above” is meaningless alone. Large chunks, 800 to 1,500 tokens, preserve context but dilute the embedding, because one vector has to represent many topics, and they consume prompt budget quickly.

A reasonable starting point for prose is 300 to 500 tokens with 10 to 15 percent overlap, then tune against your evaluation set. Better than fixed size is structure-aware splitting:

  • Split on headings, paragraphs and list boundaries before falling back to sentence or token limits.
  • Prepend the section path (for example “Billing > Refunds > Annual plans”) to each chunk, either in the embedded text or as metadata. This single trick fixes many ambiguity failures.
  • Keep code blocks, tables and numbered procedures intact.
  • Consider parent-child retrieval: embed small chunks for precision, but return the surrounding section to the model for context.

Some teams add a generated summary or a list of hypothetical questions per chunk and embed those too. This helps when users phrase queries very differently from the source text, at the cost of ingestion time and tokens.

Embeddings

An embedding model maps text to a vector so that semantically similar passages are close. Choices that matter:

  • Dimension and cost. Vectors of 384 to 1,024 dimensions are common, and some models allow truncation (Matryoshka representations) so you can trade a little accuracy for a lot of storage. At one million chunks with 1,024 float32 dimensions you store roughly 4 GB of raw vectors before index overhead.
  • Language coverage. If your users write in Spanish, Portuguese and English, test a multilingual model on your own queries. English-centric models degrade silently.
  • Domain fit. General models handle most business text. Legal, medical and code corpora sometimes benefit from specialized or fine-tuned embeddings, but verify with data before paying that cost.
  • Query versus document encoding. Some models expect a different prefix or instruction for queries and documents. Using the wrong one costs several points of recall.
  • Versioning. Changing the embedding model means re-embedding the entire corpus. Store the model name with every vector and plan for migration with a parallel index.

Dense vector search captures meaning but is weak on exact tokens: part numbers, error codes, names, acronyms, version strings. Lexical search with BM25 is the reverse. Production systems almost always combine them.

The standard recipe runs both retrievers, takes the top 30 to 100 from each, and merges the lists with reciprocal rank fusion (RRF), which scores each document by the sum of 1 / (k + rank) across lists, with k around 60. RRF needs no score calibration, which is why it is popular. A weighted sum of normalized scores also works if you tune the weights.

Add metadata filters before ranking, not after. Filtering by tenant, language, date range or permission group inside the search query avoids the situation where the top 10 results are all filtered out afterward. Access control deserves special attention: enforce it in the retrieval layer using the user’s real permissions, never by asking the model to withhold information.

Query rewriting

Users ask short, vague or conversational questions. A rewriting step can expand abbreviations, resolve pronouns using chat history (“what about the second one?”), or split a compound question into sub-queries. Keep the rewriter small and fast, log its output, and compare against the raw query in evaluation, because rewriting sometimes hurts.

Reranking

First-stage retrieval is optimized for speed and recall. A reranker, usually a cross-encoder, reads the query and each candidate together and scores relevance much more accurately. The pattern is to retrieve 50 to 100 candidates cheaply, rerank them, and pass the top 5 to 10 to the model.

Rerankers add 100 to 500 milliseconds depending on size and hardware, and an additional per-query cost. In most evaluations they deliver the largest single quality gain after getting chunking right. A language model can also act as a reranker, which is flexible but slower and costlier.

Choose the final context size deliberately. More passages raise recall but also add noise, cost and latency, and models can lose information placed in the middle of a long prompt. Order the best passages first and last if you use many.

Generation

The prompt should be explicit about the contract:

  • Answer only from the provided context.
  • If the context does not contain the answer, say so plainly rather than guessing.
  • Cite sources by identifier for every claim.
  • Keep the passages clearly delimited and labeled with their metadata.

Citations are not decoration. They let users verify answers, and they give you a mechanical check: parse the cited identifiers and confirm they exist in the retrieved set. For high-stakes domains, add a verification pass that checks each claim against its cited passage.

Temperature should be low for factual question answering. If answers must be in a fixed format, use structured output.

Evaluation

Build the evaluation set early, before tuning anything. Collect 100 to 300 real questions, each with the document or passages that answer it, and a reference answer. Source them from logs, support tickets or subject matter experts. Include hard cases: ambiguous questions, questions with no answer in the corpus, and multi-document questions.

Then measure the stages separately.

Stage Metric What it tells you
Retrieval Recall@k, MRR, nDCG Whether the right passage was found and how high it ranked
Reranking Precision@k Whether noise was filtered out
Generation Faithfulness, answer correctness Whether the answer is supported by the context and right
Whole system Task success, user feedback Whether the product works

Recall@k is the diagnostic that matters most: if the correct passage is not in the retrieved set, nothing downstream can save you. Faithfulness and correctness are commonly scored with an LLM judge calibrated against human labels on a sample. Run the evaluation on every change to chunking, embeddings, prompts or models, in continuous integration, with a threshold that blocks regressions.

Failure modes

These are the failures we see repeatedly.

  1. The answer is split across chunks. A condition and its exception sit in adjacent paragraphs, and only one is retrieved. Fix with overlap, parent-child retrieval or larger context windows around hits.
  2. Vocabulary mismatch. The user says “cancel,” the document says “terminate the subscription.” Hybrid search, query expansion and embedding fine-tuning help.
  3. Stale or conflicting sources. Two versions of a policy are both indexed. Store effective dates and versions, prefer the newest, and remove superseded documents.
  4. Confident answers without evidence. The model fills gaps from its own memory. Enforce abstention in the prompt, check citations, and include unanswerable questions in your evaluation.
  5. Questions needing aggregation. “How many contracts expire this quarter?” is not a retrieval problem. It needs a database query. Route such questions to structured tools instead of text search.
  6. Prompt injection through documents. Retrieved text can contain instructions. Treat retrieved content as untrusted data, delimit it, and never give the model privileges the user does not have.
  7. Silent drift. Content changes, new documents arrive, and quality decays. Monitor retrieval hit rates, the share of answers with no citation, and user feedback, and refresh the evaluation set regularly.

Operating the system

Keep the index fresh with incremental updates keyed by content hash, and handle deletions explicitly, since a removed document that remains in the index is both a quality and a legal problem. Cache query embeddings and frequent results. Log each query with retrieved identifiers, scores, and the final prompt so that any bad answer can be replayed.

Start simple. A reasonable first version is structure-aware chunking, one good embedding model, hybrid search with RRF, a reranker, and a strict prompt. Add query rewriting, parent-child retrieval or agentic multi-step search only when your evaluation set shows a specific gap that the addition closes. Datainter often starts client RAG projects with a two-week evaluation-set sprint before writing pipeline code, because the set determines every later decision.

Key takeaways

  • RAG quality is mostly a retrieval problem; evaluate retrieval and generation as separate stages.
  • Use structure-aware chunking of roughly 300 to 500 tokens, and keep section paths with each chunk.
  • Combine dense and lexical search with reciprocal rank fusion, filter by metadata inside the query, and enforce permissions in the retrieval layer.
  • Add a reranker once basics are right; it is usually the biggest remaining gain.
  • Build a 100 to 300 question evaluation set first and run it on every change.
  • Plan for the known failure modes: split answers, stale sources, unanswerable questions, aggregation queries and injected instructions.
#rag#embeddings#search#architecture
DI
Datainter TeamEngineers, designers and operators building software and fintech products from Medellín, Tigard and Luxembourg.

Building something in this space?

Talk to the team that ships and operates it. We reply within one business day.

Start a project
Chat with us on WhatsAppUSUALLY REPLIES WITHIN MINUTES