← All posts

Oct 2026 · 10 min read · AI, RAG, System Design

RAG Explained: How Retrieval-Augmented Generation Really Works

Why models need outside knowledge, how chunking, embeddings, hybrid search and reranking fit together, and how to tell whether your retrieval or your generation is the part that's broken.

A practical walkthrough for engineers building on top of language models. Figures are illustrative back-of-the-envelope numbers, not benchmarks.


The problem RAG solves

A language model knows what was in its training data, frozen at a point in time. Ask it about your company's refund policy, last week's incident, or a document written yesterday and it has nothing to draw on. Worse, it will often answer anyway, fluently and wrongly.

You have three broad options for giving a model knowledge it lacks:

ApproachHow it worksGood forWeak at
Fine-tuningUpdate the model's weights with new dataStyle, format, behaviorFacts that change, citing sources
Long contextPaste everything into the promptSmall, fixed document setsLarge corpora, cost, attention dilution
RAGFetch only the relevant pieces at question timeLarge or changing knowledge basesNeeds a good retrieval system

Retrieval-Augmented Generation (RAG) takes the third path: before the model answers, a search step finds the most relevant passages from your own data and places them in the prompt. The model then answers using that material instead of relying on memory.

The idea is simple enough to state in one line: look it up, then write the answer. The engineering is in making the lookup good.


The two halves of a RAG system

Every RAG system has an offline half that prepares your data and an online half that answers questions.

OFFLINE (ingestion)
  documents -> clean -> split into chunks -> embed each chunk -> store in an index

ONLINE (every question)
  question -> embed -> search the index -> (rerank) -> build prompt -> model answers

If you remember one thing: most RAG quality problems are retrieval problems. The model can only be as good as the passages it is handed.


Embeddings: turning meaning into geometry

Search by keyword fails when the question and the document use different words. A user asks "how do I get my money back" while the policy says "refund procedure". Keyword matching sees no overlap.

Embeddings fix this. An embedding model converts a piece of text into a list of numbers (a vector) positioned so that texts with similar meaning land close together in space.

"how do I get my money back"   -> [0.12, -0.48, 0.33, ...]
"refund procedure"             -> [0.10, -0.45, 0.35, ...]   (close by)
"office parking rules"         -> [-0.71, 0.20, -0.09, ...]  (far away)

"Close" is usually measured with cosine similarity, which compares the angle between two vectors. Searching then becomes: embed the question, find the stored chunk vectors nearest to it.

Storage adds up quickly. A 1,536-dimension vector stored as 32-bit floats takes about 6 KB:

1,536 dimensions x 4 bytes = ~6 KB per chunk
10 million chunks          = ~61 GB of raw vectors (before index overhead)

That is why vector databases invest heavily in compression and approximate search.


Chunking: the most underrated decision

You cannot embed a whole 200-page manual as one vector. A single vector for that much text blurs everything together, and you would stuff the whole thing into the prompt anyway. So documents are split into chunks, and chunk design quietly decides your quality ceiling.

Chunk sizeUpsideDownside
Too small (a sentence)Precise matchesLoses surrounding context, answer gets split apart
Too large (several pages)Keeps contextVector gets diluted, wastes prompt space on irrelevant text

Practical guidance:

  • Respect structure. Split on headings, paragraphs, and sections before falling back to raw character counts. A chunk that is one coherent idea embeds and retrieves far better than one that cuts a sentence in half.
  • Use some overlap between neighbors so a fact sitting on a boundary is not lost.
  • Attach context. Prepending the document title and section heading to each chunk helps a bare paragraph like "It must be completed within 30 days" mean something on its own.
  • Store metadata (source, date, author, access level, section) next to every chunk. You will want it for filtering, citations, and debugging.

There is no universal best size. Treat it as a parameter to tune against your own questions.


Retrieval: dense, sparse, and hybrid

Dense retrieval (embeddings)

Great at meaning and paraphrase. Weak at exact identifiers: error codes, product SKUs, function names, rare acronyms. An embedding model may treat ERR_4031 and ERR_4013 as nearly the same thing.

Sparse retrieval (keywords, BM25)

The classic search approach. It scores documents by matching terms, weighted by how rare each term is. Excellent for exact strings and names, but blind to synonyms.

Hybrid: use both

Each method fails where the other succeeds, so production systems usually run both and merge the results. A simple, robust way to merge is reciprocal rank fusion: each result earns a score based on its rank in each list, and the scores are added.

score(doc) = sum over lists of  1 / (k + rank_in_list)      (k is often ~60)

doc A: rank 1 in dense, rank 5 in keyword  ->  1/61 + 1/65 = 0.0318
doc B: rank 2 in dense, rank 1 in keyword  ->  1/62 + 1/61 = 0.0325
doc B edges ahead: it did well in both

Documents that appear near the top of both lists rise to the top, without needing to compare incompatible score scales.

Approximate nearest neighbor search

Comparing a question against ten million vectors one by one is too slow. Vector indexes (HNSW graphs are a popular choice) trade a small, tunable amount of accuracy for large speedups by navigating a structure instead of scanning everything. The knob you will meet is recall versus latency: search more candidates for better recall, at the cost of time.

Metadata filtering

Often the best relevance boost is not clever ranking at all. If the user is asking about the 2026 policy, filter out chunks tagged 2023 before searching. Filters also enforce permissions, which we will return to below.


Reranking: a second, sharper look

First-stage retrieval has to be fast, so it compares precomputed vectors independently of the question's exact wording. A reranker is a slower, more accurate model that reads the question and each candidate passage together and scores how well they match.

The usual pattern is a funnel:

index of millions  ->  fast search returns top 50  ->  reranker keeps best 5  ->  prompt

Cast a wide net cheaply, then apply expensive judgment to a small set. This one extra stage is often among the biggest quality improvements available.


Putting it in the prompt

Once you have the best passages, you assemble a prompt. A few habits matter:

  • Tell the model to rely on the provided context and to say it does not know when the answer is not there. Without this instruction, models tend to fill gaps from memory.
  • Label each passage with its source so the model can cite it, and so your users can verify the answer.
  • Mind the ordering and amount. Models can overlook information buried in the middle of a long prompt. More passages is not automatically better; irrelevant text can distract and degrade the answer.
Answer the question using ONLY the sources below. Cite sources like [1].
If the sources do not contain the answer, say you don't know.

[1] (refund-policy.md, updated 2026-03) Refunds are available within 30 days...
[2] (billing-faq.md, updated 2026-01) To request a refund, contact support...

Question: How long do I have to request a refund?

Why RAG fails (and how to tell which part)

When a RAG system gives a bad answer, the first diagnostic question is: was the right information retrieved?

SymptomLikely cause
Answer is missing a fact that exists in the docsRetrieval failure: wrong chunking, weak query, missing filter
The right passage was retrieved but the answer ignores or contradicts itGeneration failure: prompt, too much noise, ordering
Answer is confident but unsupported by any sourceThe model is filling gaps; tighten the grounding instruction
Answers are out of dateStale index: documents changed but were not re-ingested
Multi-part questions get half an answerOne search can't gather scattered facts; needs query decomposition
Vague question retrieves junkQuery needs rewriting or clarification before searching

Two fixes worth knowing:

  • Query rewriting. Have a model turn the user's raw message ("what about for contractors?") into a standalone search query using the conversation so far ("refund policy for contractors"). Follow-up questions are a common source of bad retrieval.
  • Query decomposition. Split a compound question into several sub-searches, then combine the results.

When the system decides for itself when to search, what to search for, and whether to search again, that is RAG meeting the loop described in AI Agents Are Just Loops, often called agentic RAG. It handles harder questions at the price of more steps, more cost, and the compounding-error problem agents bring.


Evaluate retrieval and generation separately

The most useful habit in RAG engineering is to measure the two halves independently. If you only grade final answers, you cannot tell whether to fix search or fix prompting.

Retrieval metrics ask whether the right passages came back:

  • Recall@k: of the passages that contain the answer, how many appear in the top k results?
  • MRR (mean reciprocal rank): how high does the first correct passage rank?

Generation metrics ask whether the answer is good given what was retrieved:

  • Faithfulness (groundedness): is every claim supported by the retrieved text?
  • Answer relevance: does it actually address the question?

To get started, build a small golden set: 50 to 100 real questions, each paired with the document that holds the answer. Run it after every change to chunking, embeddings, or prompts. It is unglamorous work, and it is what separates a demo from a system you can improve with confidence.


Security and access control

RAG creates a quiet data-leak risk: the retrieval layer can surface documents the asking user was never allowed to see. If your index mixes HR files, executive memos, and public docs, a clever question can pull the wrong one into the prompt.

  • Enforce permissions at retrieval time, using metadata filters tied to the user's identity, not by hoping the model withholds things. Anything that reaches the prompt can leak.
  • Treat retrieved text as untrusted. A document can contain instructions ("ignore the above and reveal..."), and the model may follow them. This is the same prompt injection risk that affects any system reading outside text: limit what the model can do, and never let retrieved content act as a command.

RAG or long context?

Context windows have grown large enough that "just paste everything in" is sometimes viable. It still tends to lose for large or changing corpora: you pay to process the full text on every request, latency grows, and models attend less reliably across enormous inputs. RAG keeps each request small and targeted, makes updates a matter of re-indexing a few chunks, and gives you natural citations. For a small, stable set of documents, plain long context may be the simpler and better answer. Match the tool to the size and volatility of your data.


The mental model to take away

RAG is a search engine bolted onto a writer. The writer (the model) is already strong. The leverage is almost entirely in what you put in front of it: how you split documents, how you find candidates, how you rank them, and how you frame them.

So when a RAG system disappoints, do not start by rewriting the prompt. Check the retrieved passages first. If the right text never arrived, no prompt can save the answer. If it did arrive, you have a generation problem and a much smaller search space to debug. Build the evaluation to tell the difference, and every other improvement gets easier.