Chunking: how to split documents for RAG
Chunking decides what the model can see. Split a document badly and the right answer is never retrieved, however good the model is.
1. Why it matters
- Retrieval works on chunks, not documents. The model only sees the chunks you retrieve.
- Most RAG quality problems are retrieval problems, and most retrieval problems start with chunking.
- Chunk size also sets cost: three chunks of 800 words cost about ten times more input tokens than three chunks of 80 words.
2. Key ideas
3. How it works, step by step
- Collect 20 to 50 real questions and, for each, the sentence in the document that answers it. This is your retrieval test set.
- Start with recursive chunking at 200 to 400 tokens (about 150 to 300 words) and 10 to 15 percent overlap.
- Store file, page and section with every chunk so you can cite sources and filter.
- Measure recall@3 and recall@5 on your test set.
- Try two or three alternatives (smaller chunks, heading-based chunks, more overlap) and keep the one with the best recall at an acceptable token cost.
- Inspect failures by hand: print the question, the expected sentence and the chunks that were retrieved instead.
- Re-run the test whenever the documents, the chunker or the embedding model change.
4. Code you can run
Run it from the starter project folder: python examples/l1_chunking.py. It runs offline for free; add an API key in .env to use Claude.
"""Lesson 1: compare chunking strategies on the sample PDF by retrieval recall at 3.
Run: python examples/l1_chunking.py"""
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from starter.chunking import by_heading, fixed_size, recursive
from starter.pdf_loader import load_pdf
from starter.store import VectorStore
PDF = os.path.join(os.path.dirname(__file__), "..", "data", "sample_policy.pdf")
GOLDEN = [ # question, a phrase that must be inside a retrieved chunk
("How many days of paid leave do I get each year?", "20 days of paid leave"),
("How much unused leave can I carry forward?", "carried forward up to 5 days"),
("When must expense claims be submitted?", "within 30 days"),
("What is the daily meal limit when travelling?", "1,500 rupees per day"),
("How many days a week can I work remotely?", "up to 3 days a week"),
("How long must a laptop password be?", "at least 14 characters"),
("What is the yearly learning budget?", "40,000 rupees"),
("When do I need a doctor's note for sick leave?", "longer than 2 days"),
]
text = "\n\n".join(p["text"] for p in load_pdf(PDF))
strategies = {
"fixed 40 words, overlap 0": fixed_size(text, 40, 0),
"fixed 40 words, overlap 10": fixed_size(text, 40, 10),
"recursive, max 60 words": recursive(text, 60),
"by heading": by_heading(text),
}
for name, chunks in strategies.items():
store = VectorStore(); store.add(chunks)
found = sum(any(phrase in hit["text"].replace("\n", " ") for hit in store.search(q, k=3)) for q, phrase in GOLDEN)
avg = sum(len(c.text.split()) for c in chunks) / len(chunks)
print(f"{name:<28} chunks={len(chunks):>3} avg words={avg:5.1f} recall@3={found}/{len(GOLDEN)}")
print("\nExample chunk with metadata (by heading):")
c = strategies["by heading"][2]
print(c.meta, "|", c.text[:90] + "...")fixed 40 words, overlap 0 chunks= 9 avg words= 36.1 recall@3=7/8
fixed 40 words, overlap 10 chunks= 11 avg words= 38.6 recall@3=7/8
recursive, max 60 words chunks= 6 avg words= 54.2 recall@3=7/8
by heading chunks= 8 avg words= 38.6 recall@3=7/8
Example chunk with metadata (by heading):
{'section': 'Sick Leave'} | Employees get 10 days of sick leave each year, separate from paid leave. A doctor's note i...5. What the code does
- load_pdf returns one item per page; the text of all pages is joined for the comparison.
- Each strategy produces a list of Chunk objects (id, text, meta). by_heading keeps the section title as metadata.
- GOLDEN pairs a question with a phrase that must appear in a retrieved chunk. That is a retrieval test, separate from the answer test.
- recall@3 counts how many questions have the answer phrase inside one of the top three chunks.
- On this small, well-structured document all four strategies find 7 of 8. On long, messy documents the differences are much larger, which is why you measure instead of guessing.
6. Common mistakes and fixes
| Problem | Fix |
|---|---|
| Chunks are huge (whole pages) | Retrieval returns mostly irrelevant text and costs rise. Split pages into paragraphs or sections. |
| Chunks are tiny (one line) | Answers lose their subject: "It must be approved within 7 days." Use bigger chunks or add the heading to each chunk. |
| Tables are flattened into one long line | Keep a table row with its header, or convert each row to a sentence such as "Plan: Gold. Price: 499." |
| No page or section stored | You cannot cite or filter. Add metadata at chunking time; it is hard to add later. |
| Scanned PDF returns empty text | The PDF is an image. Run OCR first, then chunk. |
| Chunker changed but nothing was re-tested | Treat chunking as code: version it and re-run the retrieval test set. |
7. Product manager view
- Ask the team for recall@k on a real question set, not a demo. If recall is low, no prompt change will fix the answers.
- Chunk size is a cost lever: smaller chunks mean fewer input tokens per answer.
- Metadata decides what features are possible: citations, 'search only my department', 'only documents updated this year'.
8. Assignment
Check your work against the model answer for Subject 6.
9. Interview questions
How do you choose a chunk size?
Start from the content and the questions: one idea per chunk, usually 200 to 400 tokens with 10 to 15 percent overlap. Then measure recall@k on real questions and pick the smallest size that keeps recall high, because smaller chunks also cut cost.
Why use overlap?
So a fact that falls on a chunk boundary still appears whole in at least one chunk. Too much overlap wastes storage and returns near-duplicate chunks.
What metadata would you store with each chunk and why?
Source file, page, section, date and access level: for citations, filtering, freshness and permission checks.
Retrieval misses answers in tables. What do you do?
Chunk tables row by row with the header repeated, or turn each row into a sentence, then re-measure recall on table questions.