Slides · Retrieval-augmented generation
RAG architecture and chunking
1 / 25
RAG architecture and chunking
How a RAG system finds the right text before the model answers, and why the way you cut documents decides what can ever be found.
Concept
Why this is worth 30 minutes
- Kavya cut the refund policy into small pieces. One now reads “…and so it is refunded within five days, for all items.” Which refund? Which items?
- A model has a training cutoff, no view of your private documents, and no way to show where a claim came from. The original RAG paper frames updating knowledge and giving provenance as open problems for knowledge stored in model weights (Lewis et al., 2020).
- RAG puts the right text in the prompt at question time. It lowers hallucination risk but does not remove it.
- Retrieval can only return what ingestion produced, so a bad cut cannot be repaired later.
Four things you will be able to do:
- Describe the two phases of a RAG pipeline.
- Choose a chunking strategy and justify the trade-offs.
- Say which metadata a chunk needs and why permissions live inside retrieval.
- Pick a chunk size from evidence, not habit.
Source[1] Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks
Concept
RAG is an open-book exam
- Retrieval-augmented generation (RAG) fetches relevant pieces of text from an external store and puts them in the prompt.
- The model answers from those pieces. Its weights do not change.
- Each piece is a chunk. How you cut documents into chunks decides what the retriever can find.
Mental model: nobody memorises the textbook. Right before the question, someone hands over the few pages that matter. Chunking decides what counts as a “page”.
Diagram
Two phases: ingest ahead of time, query on every question
Process
Ingest, step by step
- Parse and clean. Turn PDFs, HTML and wiki pages into clean text. A multi-column PDF read in the wrong order gives nonsense that no later stage can fix.
- Chunk. Split the text into pieces. Most of this lesson is about this step.
- Embed. Turn each chunk into a vector with an embedding model.
- Store. Save the vectors together with metadata in a vector database.
Ingest is a pipeline of its own. Changing the chunker or the embedder means re-processing the whole corpus.
Process
Query, step by step
- Embed the question with the same model used for the chunks.
- Fetch the top-k nearest chunks (an optional rerank step can reorder them).
- Build a prompt from the question and the chunks.
- The model generates the answer.
Because ingest is separate from the model, updating knowledge means re-ingesting the changed document: re-chunk, re-embed, replace its old chunks. No retraining is involved. That is the main reason RAG suits facts that change.
Check yourself
Check: which phase breaks?
A team ingests a two-column PDF, but the text extractor reads straight across both columns, so sentences from the left and right columns are interleaved. Which phase is at fault, and can a better embedding model fix it?
Answer
The ingest phase, in its first step (parse and clean). The chunks are built from scrambled text, so any embedding of them is an embedding of nonsense. A better embedder cannot repair it. Fix the parser (layout-aware extraction), then re-ingest the document.
Compare
Why not one vector per document?
One vector is one summary of everything in the text. A 50-page document as a single vector dilutes relevance and loses the specific detail a question asks about. So we cut, and every cut has a price:
| Choice | Benefit | Cost |
|---|---|---|
| Small chunks | Precise matches | A chunk may lose the context that gives it meaning |
| Large chunks | More context per hit | The embedding blurs several topics; more irrelevant tokens in the prompt |
| Overlap between neighbours | A fact on a boundary survives whole in at least one chunk | More chunks to store and embed; near-duplicate hits |
There is no universal best size. The corpus and the questions decide.
Worked example
What overlap costs, with numbers
An illustrative 1,000-token section cut into chunks of 200 tokens. The next chunk starts at previous start+(size−overlap).
| Overlap | Stride | Chunk starts (tokens) | Chunks | Tokens stored |
|---|---|---|---|---|
| 0 | 200 | 0, 200, 400, 600, 800 | 5 | 5×200=1,000 |
| 40 (20%) | 160 | 0, 160, 320, 480, 640, 800 | 6 | 6×200=1,200 |
| 100 (50%) | 100 | 0, 100, … , 800 | 9 | 9×200=1,800 |
- 20% overlap stores 20% more tokens here (1,200 against 1,000). 50% overlap stores 80% more.
- You pay in storage, embedding calls and near-duplicate results in the top-k.
- You gain: a sentence that straddles a boundary appears whole in at least one chunk.
Compare
Four ways to split
| Strategy | How it cuts | Good for | Watch out |
|---|---|---|---|
| Fixed size | Every N tokens or characters | Quick baseline | Ignores meaning; can cut a sentence or table in half |
| Sentence or paragraph | At natural units | Prose | Units vary a lot in length |
| Semantic | Where the topic changes | Long flowing text | Extra computation at ingest |
| Structure-aware | Along headings, sections, lists, tables | Documents with structure; usually the best default | Needs good parsing first |
- Split on headings first, then paragraphs, and fall back to a size limit only inside a long section.
- Store the heading path (for example “Refunds > Digital goods”) with each chunk.
- Illustrative starting point teams try: a few hundred tokens with 10 to 20 percent overlap. A first experiment, not an answer.
Diagram
Try it: size and overlap on a real passage
Text summary
This tool cuts one short, made-up passage of 83 words (a lending guide for an imaginary library) into chunks of words. You set the chunk size and the overlap, and overlap is always smaller than the size. The question is “How many times can a book be renewed?”, and the answer is one sentence: “Books can be renewed twice, and each renewal adds fourteen days to the loan.” The tool lists the chunks and marks each one that holds the whole answer sentence, or only part of it. At a chunk size of 20 words with no overlap, the cut falls inside the answer sentence, so no chunk holds all of it and the tool warns you. With an overlap of 8 words, the second chunk holds the whole sentence. More overlap means more words stored, because the repeated words are kept in both chunks. Chunks are counted in words here; real systems usually count tokens or characters.
The interactive version needs JavaScript. The text summary above says what it shows.
Worked example
Tables: a row alone has no meaning
A row split naively loses its column names. What the embedder sees depends on how you chunk the row:
| Strategy | Text that gets embedded |
|---|---|
| Row split naively | Gold | 14 days | 5% |
| Caption and header repeated | Refund plans. Plan | Window | Fee. Gold | 14 days | 5% |
| Row turned into a sentence | Gold plan: refund window 14 days, fee 5%. |
- A small table can stay as one chunk.
- A large table needs the caption and header row in every chunk, or each row rewritten as a sentence.
- All of it assumes the parser kept the table’s structure.
Diagram
Give chunks their context back
An isolated chunk says “it” or “this quarter” without naming what. Three fixes, cheapest first:
- The note approach is what Anthropic calls contextual retrieval: the note is prepended to the chunk and used for both the embeddings and the BM25 index.
- The cost is one extra model call per chunk at ingest.
- Small-to-big costs larger prompts, and several children can point to the same parent, so de-duplicate parents.
Concept
What the contextual retrieval write-up reports
Anthropic’s September 2024 post reports results across its own datasets, with a baseline top-20 retrieval failure rate of 5.7%:
| Variant | Failure rate | Reported reduction |
|---|---|---|
| Contextual embeddings | 3.7% | 35% |
| Contextual embeddings + contextual BM25 | 2.9% | 49% |
| Those two, plus reranking | 1.9% | 67% |
- The generated context is typically 50 to 100 tokens per chunk.
- With prompt caching the post estimates a one-time cost of $1.02 per million document tokens, under its stated assumptions (800-token chunks, 8k-token documents, 50-token instructions and 100 tokens of context per chunk).
- These are one team’s numbers on their datasets. Measure on your own questions before you pay for an extra call per chunk.
Concept
Metadata a chunk should carry
Save these at ingest time, so you can filter on them later:
- source (document id or URL): so answers can cite.
- section or heading path.
- date or version: prefer current text, drop superseded text.
- language and document type.
- access control: tenant, group or user permissions.
Access control is the field people forget, and the one with legal consequences. If a user may not read a document, its chunks must never reach the prompt for that user.
Diagram
Filter inside the query, not after it
- Asking the model to “not mention” restricted text is not a control: the text is already in the prompt.
- Scope any cache by identity, or one user’s answer can be served to another.
Worked example
How much does post-filtering lose?
Illustrative: a store holds a mix of documents, and a user may read only a fraction of them. The top-10 is taken first, then filtered.
| Share of the top-10 the user may read | Results left after filtering |
|---|---|
| 100% | 10 |
| 50% | 5 |
| 20% | 2 (10×0.20) |
| 0% | 0, so the system says “no answer” although a permitted document exists |
A real index shows the same effect. The pgvector README says approximate indexes apply filtering after the index is scanned: with HNSW and its default hnsw.ef_search of 40, a condition matching 10% of rows gives about 4 rows on average (40×0.10). It suggests iterative index scans, partial indexes or partitioning to get more.
- Check how your own database applies filters. Behaviour differs between products.
- Take the filter value from the authenticated identity on the server, never from text the user typed.
Source[3] pgvector: open-source vector similarity search for Postgres
Check yourself
Check: a cache and two tenants
An assistant caches final answers using the question text as the key. Tenant A asks “What is our refund window?” and the answer is cached. Tenant B asks the same words. What can go wrong, and what do you change?
Answer
Tenant B may be served Tenant A’s answer, which was built from Tenant A’s documents. The cache is a second path around the retrieval filter. Scope the cache key by identity (tenant and permission group), or skip caching for permissioned content.
Process
Choose chunk size with evidence
Folklore (“512 is standard”) is how teams keep a bad default for years.
- Build a labelled set. Realistic questions, each marked with the passage that answers it. Start with a few dozen (an illustrative size).
- Change one thing. Index the corpus at two or three chunk sizes with the same embedder and overlap.
- Measure retrieval. The fraction of questions with an answering chunk in the top-k is recall@k. Note where in the list it appears.
- Check prompt cost. Bigger chunks mean more tokens per query.
- Spot-check final answers. Retrieval can improve while the answer worsens if big chunks bring noise.
- Pick the smallest size that meets your recall target.
Worked example
A worked experiment (illustrative numbers)
40 labelled questions, top-k=5, same embedder and overlap. Cost is 5 chunks×chunk size tokens of retrieved text per query.
| Chunk size (tokens) | Questions with answer in top-5 | recall@5 | Retrieved tokens per query |
|---|---|---|---|
| 128 | 24 of 40 | 0.60 | 5×128=640 |
| 256 | 32 of 40 | 0.80 | 5×256=1,280 |
| 512 | 34 of 40 | 0.85 | 5×512=2,560 |
| 1024 | 32 of 40 | 0.80 | 5×1,024=5,120 |
- Target: recall@5 of at least 0.80. The smallest size that meets it is 256.
- 512 adds 2 questions (0.05) but doubles the tokens, and 1024 is worse on both counts here.
- Before adopting any size, spot-check end-to-end answers: recall is only half the picture.
Concept
Defaults can hide a cost
Chroma’s 2024 report compared chunkers on token-level metrics, with 5 chunks retrieved per query. Its main results use OpenAI’s text-embedding-3-large; a second round uses all-MiniLM-L6-v2. Two of the main rows:
| Setting | Recall | Precision | IoU |
|---|---|---|---|
| Recursive splitter, 200 tokens, no overlap | 88.1 | 7.0 | 6.9 |
| Token splitter, 800 tokens, 400 overlap (OpenAI Assistants’ default setting, as the report evaluates it) | 87.9 | 1.4 | 1.4 |
- Recall was about the same, but the larger setting retrieved far more text that was not part of the answer.
- The authors call their dataset small and limited in diversity, and say that in the MiniLM round, with smaller context, overlapping chunks looked necessary for high recall. Read it as a reason to measure, not as a rule.
Check yourself
Check: count the chunks
A 3,000-token document is cut into chunks of 300 tokens with 50 tokens of overlap. How many chunks result, and how many tokens are stored in total? (The last chunk may be shorter.)
Answer
Stride =300−50=250. Starts are 0, 250, …, 2,750: 12 chunks. The last starts at 2,750 and has only 250 tokens left, so stored tokens =11×300+250=3,550, against 3,000 without overlap (about 18% more). Without overlap there would be 10 chunks.
Compare
Common mistakes
| Mistake | Why it hurts | Better move |
|---|---|---|
| Pick a size by folklore | Wrong for your corpus, kept for years | Measure recall@k on a labelled set |
| Embed a whole document as one vector | The vector blurs every topic | Cut by structure |
| Split tables row by row without headers | A row like Gold | 14 days | 5% has no meaning | Repeat the header, or rewrite the row as a sentence |
| Filter permissions after retrieval | Few results, and leaks through logs and caches | Filter inside the query |
| One setting for all content | FAQ entries and long contracts differ | Short FAQs need almost no splitting; contracts need clause-aware chunks with section titles |
Summary
Recap
- RAG retrieves chunks and puts them in the prompt. Weights do not change.
- Ingest runs ahead of time. Query runs on every question, with the same embedder.
- Small chunks are precise but context-poor, large chunks are context-rich but blurry, and overlap protects boundaries at a storage cost.
- Split by structure, keep table headers with rows, and restore context with a prefix, a model-written note, or the parent section.
- Store source, section, date and permission metadata, and enforce permissions in the query.
- Choose chunk size by measuring recall@k and prompt cost on a labelled set.
References
References & Sources
Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (opens in a new tab)
Patrick Lewis, Ethan Perez, Aleksandra Piktus, Fabio Petroni, et al.2020NeurIPS 2020Paper
arXiv 2005.11401 (opens in a new tab)https://arxiv.org/abs/2005.11401
Used for The original RAG formulation: combining a model's parametric memory with an external non-parametric memory, and the framing of knowledge updating and provenance as open problems for parametric-only models.
Introducing Contextual Retrieval (opens in a new tab)
Anthropic2024Article
https://www.anthropic.com/news/contextual-retrieval
Used for Contextual retrieval: a short model-written note prepended to each chunk before embedding and BM25 indexing, the reported failure-rate reductions (35%, 49%, 67% against a 5.7% baseline), and the one-time cost estimate.
pgvector: open-source vector similarity search for Postgres (opens in a new tab)
pgvector2026Repository
https://github.com/pgvector/pgvector
Used for Approximate indexes apply filters after the index scan, so a selective condition can return fewer rows than requested (HNSW example with ef_search 40 and a 10% condition).
Evaluating Chunking Strategies for Retrieval (opens in a new tab)
Brandon Smith, Anton Troynikov2024Article
https://www.trychroma.com/research/evaluating-chunking
Used for A 2024 comparison of chunkers on token-level recall, precision and IoU, including the 200-token no-overlap row against the 800/400 default.
Keys: ← → move, Home End first and last, F full screen.