Slides · Retrieval-augmented generation

RAG architecture and chunking

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:

  1. Describe the two phases of a RAG pipeline.
  2. Choose a chunking strategy and justify the trade-offs.
  3. Say which metadata a chunk needs and why permissions live inside retrieval.
  4. Pick a chunk size from evidence, not habit.

Source1 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

Diagram: Ingest runs ahead of time and turns documents into embedded chunks in a vector store.

Query (every question)

Ingest (offline)

Raw documents

Parse and clean

Chunk

Embed chunks

Vector store

User question

Embed question

Retrieve top-k

Build prompt

LLM answers

Diagram summary: Ingest runs ahead of time and turns documents into embedded chunks in a vector store. At query time the question is embedded with the same model, the nearest chunks are fetched from the store, they are placed in a prompt with the question, and the model generates the answer.

Process

Ingest, step by step

  1. 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.
  2. Chunk. Split the text into pieces. Most of this lesson is about this step.
  3. Embed. Turn each chunk into a vector with an embedding model.
  4. 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

  1. Embed the question with the same model used for the chunks.
  2. Fetch the top-k nearest chunks (an optional rerank step can reorder them).
  3. Build a prompt from the question and the chunks.
  4. 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:

ChoiceBenefitCost
Small chunksPrecise matchesA chunk may lose the context that gives it meaning
Large chunksMore context per hitThe embedding blurs several topics; more irrelevant tokens in the prompt
Overlap between neighboursA fact on a boundary survives whole in at least one chunkMore 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)\text{previous start} + (\text{size} - \text{overlap}).

OverlapStrideChunk starts (tokens)ChunksTokens stored
02000, 200, 400, 600, 80055×200=1,0005 \times 200 = 1{,}000
40 (20%)1600, 160, 320, 480, 640, 80066×200=1,2006 \times 200 = 1{,}200
100 (50%)1000, 100, … , 80099×200=1,8009 \times 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

StrategyHow it cutsGood forWatch out
Fixed sizeEvery N tokens or charactersQuick baselineIgnores meaning; can cut a sentence or table in half
Sentence or paragraphAt natural unitsProseUnits vary a lot in length
SemanticWhere the topic changesLong flowing textExtra computation at ingest
Structure-awareAlong headings, sections, lists, tablesDocuments with structure; usually the best defaultNeeds 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

Cutting a passage into chunks

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:

StrategyText that gets embedded
Row split naivelyGold | 14 days | 5%
Caption and header repeatedRefund plans. Plan | Window | Fee. Gold | 14 days | 5%
Row turned into a sentenceGold 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:

Diagram: A bare chunk can be enriched in two ways before embedding: a cheap prefix of the document title and section heading, or a short note...

Bare chunk:
It rose 3% in Q2

Cheap prefix:
title + section

LLM note:
situate chunk
in its document

Embed enriched text

Index

Small-to-big (separate technique):
match small chunk

Return parent section
to the model

Diagram summary: A bare chunk can be enriched in two ways before embedding: a cheap prefix of the document title and section heading, or a short note written by a model that situates the chunk in its whole document. Separately, small-to-big works at read time: match on the small chunk, then hand the model its larger parent section. The “It rose 3% in Q2” chunk is an invented example.
  • 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.

Source2 Introducing Contextual Retrieval

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%:

VariantFailure rateReported reduction
Contextual embeddings3.7%35%
Contextual embeddings + contextual BM252.9%49%
Those two, plus reranking1.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.

Source2 Introducing Contextual Retrieval

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

Diagram: The block titled “Post-filtering: unsafe and lossy” fetches the best matches from the whole store and then removes the ones the user may...

Filter in the query

Apply user's tenant and group

Top-k from allowed chunks

Full k results

Post-filtering: unsafe and lossy

Top-k from everything

Drop forbidden chunks

Few or zero left

Diagram summary: The block titled “Post-filtering: unsafe and lossy” fetches the best matches from the whole store and then removes the ones the user may not read, which can leave nothing and lets restricted text touch scores, logs and caches. The block titled “Filter in the query” applies the user’s tenant and group inside the search, so only chunks the user may read are ever candidates.
  • 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 readResults left after filtering
100%10
50%5
20%2 (10×0.2010 \times 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.1040 \times 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.

Source3 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.

  1. Build a labelled set. Realistic questions, each marked with the passage that answers it. Start with a few dozen (an illustrative size).
  2. Change one thing. Index the corpus at two or three chunk sizes with the same embedder and overlap.
  3. Measure retrieval. The fraction of questions with an answering chunk in the top-k is recall@k. Note where in the list it appears.
  4. Check prompt cost. Bigger chunks mean more tokens per query.
  5. Spot-check final answers. Retrieval can improve while the answer worsens if big chunks bring noise.
  6. Pick the smallest size that meets your recall target.

Worked example

A worked experiment (illustrative numbers)

40 labelled questions, top-k=5k = 5, same embedder and overlap. Cost is 5 chunks×chunk size5 \text{ chunks} \times \text{chunk size} tokens of retrieved text per query.

Chunk size (tokens)Questions with answer in top-5recall@5Retrieved tokens per query
12824 of 400.605×128=6405 \times 128 = 640
25632 of 400.805×256=1,2805 \times 256 = 1{,}280
51234 of 400.855×512=2,5605 \times 512 = 2{,}560
102432 of 400.805×1,024=5,1205 \times 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:

SettingRecallPrecisionIoU
Recursive splitter, 200 tokens, no overlap88.17.06.9
Token splitter, 800 tokens, 400 overlap (OpenAI Assistants’ default setting, as the report evaluates it)87.91.41.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.

Source4 Evaluating Chunking Strategies for Retrieval

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= 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= 11 \times 300 + 250 = 3{,}550, against 3,000 without overlap (about 18% more). Without overlap there would be 10 chunks.

Compare

Common mistakes

MistakeWhy it hurtsBetter move
Pick a size by folkloreWrong for your corpus, kept for yearsMeasure recall@k on a labelled set
Embed a whole document as one vectorThe vector blurs every topicCut by structure
Split tables row by row without headersA row like Gold | 14 days | 5% has no meaningRepeat the header, or rewrite the row as a sentence
Filter permissions after retrievalFew results, and leaks through logs and cachesFilter inside the query
One setting for all contentFAQ entries and long contracts differShort 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

  1. 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

    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.

  2. Introducing Contextual Retrieval (opens in a new tab)

    Anthropic2024Article

    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.

  3. pgvector: open-source vector similarity search for Postgres (opens in a new tab)

    pgvector2026Repository

    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).

  4. Evaluating Chunking Strategies for Retrieval (opens in a new tab)

    Brandon Smith, Anton Troynikov2024Article

    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.