Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  The RAG Handbook
Handbook~15 min readIntermediate
Deep Dive

Retrieval-augmented
generation, grounded.

An LLM's knowledge is frozen, private data is invisible to it, and it will confidently make things up. RAG fixes all three by doing something simple: look up the right documents first, then answer from them. Here is the whole pipeline, from a raw corpus to a cited answer.

01

Why an LLM needs RAG

A large language model answers from its parametric memory — everything baked into its weights during training. That has three hard limits: it's frozen at the training cutoff (it can't know recent events), it can't see your private data (your docs, your database), and when it doesn't know, it hallucinates a plausible answer with no sources to check.

Retrieval-augmented generation flips the order: before answering, retrieve the most relevant documents from an external source, put them in the prompt, and instruct the model to answer from that context and cite it. Knowledge now comes from retrieval — fresh, private, and attributable — while the model does what it's good at: reading and synthesizing. It's the difference between "recall from memory" and "open-book with the right pages already found."

→ The one-sentence version

RAG separates knowledge (retrieved, current, citable) from reasoning (the LLM), so answers stay grounded in real sources instead of the model's frozen, lossy memory.

02

The two-phase pipeline

RAG has an offline index-time phase and an online query-time phase. Index-time prepares the corpus once (and on updates); query-time runs per question.

Index-time — prepare the corpus
Docs
PDFs, pages, tickets
→
Chunk
split into passages
→
Embed
vector per chunk
→
Store
vector index
Query-time — answer a question
Query
user question
→
Retrieve
top-k chunks
→
Rerank
best few
→
Generate
grounded, cited

Every step below is one of these boxes. Get any one wrong and the answer suffers: bad chunks or bad retrieval mean the model never sees the right passage, and no amount of clever prompting recovers information that isn't in the context.

03

Chunking — splitting the corpus

You can't embed a whole document as one vector — models have input limits, and cramming a long document into a single vector blurs its many topics into mush. So documents are split into chunks (passages). This is quietly one of the highest-leverage decisions in RAG, because retrieval and the final answer both operate at chunk granularity.

Chunk size is a tradeoff. Too large and a chunk covers several topics, so its embedding is unfocused and retrieval is imprecise (and it wastes context). Too small and it loses the surrounding context needed to make sense. Add overlap between chunks so a sentence split across a boundary isn't orphaned, and prefer structure-aware splitting (by heading, paragraph, or semantic boundary) over blind fixed-size cuts, so each chunk is a coherent unit of meaning.

Too large

  • Mixes multiple topics
  • Unfocused embedding → poor recall
  • Wastes prompt space

Well-sized + overlap

  • One coherent idea per chunk
  • Sharp, retrievable embedding
  • Overlap preserves boundary context

The chunk count is arithmetic — and it sets your bill

For a document of L tokens split at chunk size s with overlap o, each new chunk advances by a step of s − o, so the number of chunks is a ceiling divide:

chunks = ⌈(L − o) / (s − o)⌉  =  ⌈(1000 − 40) / (200 − 40)⌉  =  ⌈960 / 160⌉  =  6

A 1,000-token doc at s=200, o=40 → 6 chunks.

Now watch what happens when you shrink chunks for sharper embeddings. Halve the size to s = 100 (same overlap) and the count doesn't just double:

chunks = ⌈(1000 − 40) / (100 − 40)⌉  =  ⌈960 / 60⌉  =  16   (2.7× more)

Every chunk is one vector to embed, store, and search. So chunk size isn't just a quality knob — it multiplies your index size, your embedding API bill, and your query-time work. Overlap makes it worse: the more you overlap, the smaller the step, the more chunks. This is why "just make chunks tiny for precision" is a trap.

04

Embeddings & the vector store

Each chunk is turned into an embedding — a vector that places its meaning in a space where similar meanings sit close together. Store these in a vector database that supports fast approximate nearest-neighbor search. At query time, the question is embedded with the same model, and the store returns the chunks whose vectors are closest — semantic search that matches on meaning, not keywords, so "reset my password" finds a doc titled "recovering account access."

→ The rule that silently breaks RAG

The query and the entire corpus must be embedded with the same model and version. Vectors from different models live in different spaces and aren't comparable — mix them and search returns nonsense with no error. Change the embedding model and you must re-embed everything.

Embeddings are the bridge from text to retrievable geometry. Their quality (and consistency) sets the ceiling on how good retrieval can be.

05

Retrieval — casting a wide net

Given the query embedding, retrieve the top-k most similar chunks. But pure vector search has a blind spot: it matches meaning, so it can miss exact terms — a product code, a rare name, an error string that must match literally. So strong RAG uses hybrid retrieval: combine vector search (semantic) with keyword/BM25 search (exact terms) and fuse the results (e.g. reciprocal rank fusion).

The first stage optimizes for recall: make sure the truly relevant chunks are somewhere in the candidate set, even if not perfectly ordered — because the next stage can only reorder what retrieval found. Pull a generous candidate set (dozens to a couple hundred), wide enough to almost certainly contain the answer.

MethodMatches onGood atMisses
Vector searchMeaning (embeddings)Paraphrase, synonyms, intentExact rare terms, codes
Keyword / BM25Literal termsNames, IDs, exact stringsSynonyms, rephrasing
Hybrid (fused)BothRecall across both worlds—
06

Reranking — precision at the top

Retrieval finds relevant chunks but orders them roughly — because the embedding of the query and of each chunk are computed separately (a bi-encoder), so subtle query-document relevance is missed. Since the LLM only reads the top few chunks, ordering matters enormously. So add a second stage: a reranker.

A reranker is a cross-encoder: it looks at the query and a candidate chunk together and outputs a precise relevance score, far more accurate than comparing separate vectors — but too slow to run over the whole corpus. That's why it's a second stage: retrieve wide and cheap (recall), then rerank the top ~100 candidates and keep the best few (precision). This "retrieve wide → rerank narrow" pattern is often the single biggest quality win in a RAG system.

→ Recall gates precision

A reranker can only reorder chunks retrieval already found — it can't conjure a missing one. If the right passage isn't in the candidate set, no reranker can surface it. Both stages matter: the first must not miss it, the second sorts it to the top.

07

Grounded generation with citations

Now the payoff. Put the reranked chunks into the prompt and instruct the model to answer only from the provided context, attach an inline citation to every claim, and say "the sources don't cover this" rather than guess when the context is missing. Grounding must drive generation — answer from the evidence, citing as you go — not be bolted on afterward.

This is what turns an LLM into a trustworthy answer engine: every sentence is traceable to a source the user can check. Refusing when the evidence is absent is a feature, not a bug — it's the line between "I don't have a source for that" and a confident hallucination. Because the model can still misattribute, high-stakes systems add a verification step that checks each citation actually supports its claim.

DoAnswer only from context — treat retrieved chunks as the sole source of truth.
DoCite each claim — attach the source chunk so answers are checkable.
DoRefuse gracefully — "the sources don't cover this" beats a made-up answer.
Don'tFree-associate — never let the model fill gaps from parametric memory unmarked.
08

Evaluating a RAG system

A RAG pipeline has two failure surfaces. Measure them separately.

Evaluate retrieval and generation independently, because a bad answer could come from either. Retrieval: metrics like recall and precision — did the relevant chunks get retrieved, and how highly ranked? If retrieval misses, nothing downstream can fix it. Generation: groundedness / faithfulness (is every claim supported by the retrieved context, or did the model hallucinate?) and answer relevance (did it actually address the question?). LLM-as-judge is commonly used to score these at scale.

Crucially, RAG quality drifts: the corpus changes, new documents arrive, embeddings age, and query patterns shift. So evaluation is continuous, not a one-time check — a quietly stale index degrades answers with no error message. Treat the eval harness as part of the system, not an afterthought.

→ Where to look first when RAG is wrong

Check retrieval before blaming the model. Most "the LLM gave a bad answer" bugs are actually "the right chunk was never retrieved." Fix chunking and retrieval first; the generator can only work with what it's given.

RUN IT YOURSELF

A whole RAG pipeline in 60 lines

Don't take "hybrid + rerank" on faith — watch it happen. This is a real, tiny RAG: it chunks four docs, embeds them, and runs vector search, keyword (BM25-lite) search, reciprocal-rank fusion, and a cross-encoder reranker. The embedder folds synonyms to shared concepts and drops exact codes — exactly how a real semantic model behaves. So you can see the two failure modes for real: vector search is blind to the code ERR-4021, and keyword search is blind to a synonym query with no shared words. Hybrid + rerank is what survives both. Change the query and re-run.

CPython · WebAssembly
By the numbers

Worked example: fusing two ranked lists, step by step

Query: ERR-4021 after a password reset, over the page’s four docs. Vector search drops the code and matches “password reset”. BM25 latches onto the rare code. Each returns a top 3 (the rankings are illustrative). Reciprocal rank fusion gives every chunk 1 / (60 + rank) from each list it appears in.

StepWhatArithmeticResult
1Vector top 3meaning only; the code has no vectorD1, D3, D2
2BM25 top 3rare term, high idfD4, D1, D3
3Fuse D11/61 + 1/620.0164 + 0.0161 = 0.0325
4Fuse D31/62 + 1/630.0161 + 0.0159 = 0.0320
5Fuse D41/61, one list only0.0164
6Fuse D21/63, one list only0.0159
7Fused ordersort by scoreD1, D3, D4, D2
8Rerank all 4, keep 2cross-encoder reads query and chunk togetherD4, D1
9Context sent to the LLM2 chunks × 200 tokens400 tokens

Step 7 is the lesson. D4 is the only chunk that explains the error code, and BM25 ranked it first, yet fusion puts it third: with k = 60, being found by both lists beats being first in one. Fusion is a recall tool. It gets D4 into the candidate set, and step 8, which actually reads the words, is what moves it to the top. Cut the candidate set to two before reranking and D4 never reaches the model.

Trade-offs

Cost and trade-offs per stage

Say 10,000 documents of 1,000 tokens each, chunked like the page’s example and embedded as 1,024-dimension float32 vectors. Time is the work per run; Space is what it stores or sends.

CaseTimeSpaceWhy
Chunk + embed (index time)One embedding call per chunk: 60,000 at s=200, 160,000 at s=100Paid once, then again for every changed docSwitching embedding model repeats the whole pass.
Vector storeExact search: 60,000 × 1,024 ≈ 61M multiply-adds per query60,000 × 1,024 × 4 B ≈ 246 MB (656 MB at s=100)ANN indexes such as HNSW answer in far fewer comparisons but store extra graph links and may miss a true neighbour.
BM25Proportional to the postings of the query termsAn inverted index, usually smaller than the vectorsCheap; catches the exact terms vectors drop.
RerankOne cross-encoder pass per candidate: 100 per queryNothing storedUsually the largest retrieval latency. The candidate count is the knob.
GenerateGrows with the context: 5 chunks × 200 = 1,000 extra prompt tokensPaid on every queryMore chunks cost tokens on every request and add distractors.

Index-time cost is paid once per corpus version. Query-time cost is paid on every question. So chunk size and top-n, which multiply the query-time terms, deserve more tuning than the one-off embedding bill.

Watch for

Common mistakes

  • Retrieving what the user may not read

    The index holds every team’s documents. Without a permission filter applied at query time (store each chunk’s access list as metadata), an intern’s question can retrieve and quote the salary sheet. Filtering the answer afterwards is too late.

  • Deleting the doc but not its chunks

    A policy is withdrawn at the source, but its chunks stay in the vector store and keep getting cited. Key every chunk by source id and version, and delete or replace them together when the source changes.

  • Chunks that lost their subject

    “It must be renewed every 90 days” is useless once split from the heading that said what. Prepend the document title and section path to each chunk before embedding, so the chunk is still clear on its own.

  • Stuffing in more chunks

    Sending 20 chunks “to be safe” multiplies the prompt cost and buries the right passage among near-misses. Models are known to use the middle of a long context less reliably than its start and end. Rerank and send a few.

  • Eval questions written from the chunks

    Questions written by reading a chunk reuse its wording, so keyword overlap makes retrieval look far better than it is on real phrasing. Build the eval set from real user queries, or at least paraphrase them.

In the wild

Where this shows up in production and interviews

  • Support assistants

    Help-centre bots retrieve from docs, past tickets and release notes, cite the article, and hand off to a human when nothing relevant comes back. Refusing gracefully is a product requirement here, not a nice-to-have.

  • Internal knowledge search

    Company wikis, drives and chat history, where the hard parts are connectors, freshness and per-user permissions, not the model.

  • Coding assistants

    Tools that index a repository retrieve relevant files and symbols before answering, and lean on exact matching for identifiers, the same blind spot hybrid search covers.

  • The interview version

    “Design a chatbot over our docs” is a RAG question. Walk the two phases, size the index out loud as in the table above, name hybrid retrieval plus reranking, then say how you would evaluate retrieval and generation separately and keep permissions and deletions correct.

Self-check

Check yourself

Users search for part number XJ-220 and get unrelated pages. The system uses vector search only. What do you change?

Add keyword (BM25) retrieval and fuse it. An embedding has no learned meaning for a novel code, so vectors can’t match it; BM25 treats the rare token as highly informative. A better embedding model won’t fix this.

Recall@50 is 0.6. You add a much better reranker that picks the top 5 from those 50. What is the most it can achieve?

At most 0.6 of questions can have the right chunk in the top 5. The reranker can only reorder what retrieval found. To go higher, fix retrieval first: chunking, hybrid search, or a larger candidate set.

A 2,000-token document is chunked at s = 300 with overlap o = 50. How many chunks?

⌈(2000 − 50) / (300 − 50)⌉ = ⌈1950 / 250⌉ = 8, using the page’s formula.

An answer cites a chunk, but the chunk doesn’t say what the answer claims. Which half of the system failed, and which metric catches it?

Generation. The right source was retrieved but misused, so retrieval recall looks fine. Groundedness (faithfulness) catches it by checking each claim against its cited context.

Frequently asked

Quick answers

What is RAG?

Retrieval-augmented generation: instead of answering from frozen memory, the LLM is given relevant documents retrieved at query time and answers from them — grounding answers in current, private, citable data and reducing hallucination.

Why is chunking important?

Documents are split into chunks because embedding models have input limits and retrieval works at passage granularity. Chunk size trades focus against context; overlap and structure-aware splitting preserve meaning across boundaries.

Retrieval vs reranking?

Retrieval (vector + keyword) casts a wide, fast net for high recall. Reranking is a slower, accurate cross-encoder second stage that reorders the candidates for precision, so the best passages rise to the top.

How do you evaluate RAG?

Separately: retrieval with recall/precision (did the right chunks come back?), and generation with groundedness/faithfulness and answer relevance. Because the index drifts, evaluate continuously.

Finished this one? 0 / 209 Handbooks done
NextThe Vector Databases Handbook Next on the “Retrieval” ladder · rung 2 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks