Lesson 4.3: Chunking documents
Learn how to cut documents into pieces for retrieval: chunk size, overlap, structure-aware splitting, parent-child retrieval, costs and how to test choices.
An embedding describes a piece of text, and a search returns pieces. So before anything can be searched, every document has to be cut into pieces, and how you cut them decides much of what your system can find. Cut too small, and each piece loses the context that gave it meaning. Cut too large, and each piece blurs several ideas into one vector, so that none of them is matched well. This step, called chunking, looks like plumbing, yet it is one of the most common reasons that a retrieval system gives poor answers. By the end of this lesson you will be able to explain why documents must be chunked, describe the trade-off between small and large chunks, calculate how many chunks a document produces and how much overlap costs, compare the main ways of splitting text, use headings and other structure to cut at natural boundaries, retrieve small pieces but pass larger ones to the model, add context such as titles and sources to each chunk, work out how many chunks fit in a model's context window, and test chunking choices with real questions. You should have read Lessons 4.1 and 4.2, on embeddings and similarity search, and the earlier lesson on tokens and context windows, because chunk sizes are counted in tokens.
Why we cut documents into pieces
You could embed a whole document as one vector. Three problems make this a poor idea.
1. Embedding models have a limit. Each model reads only up to a maximum number of tokens. Anything beyond it is cut off or rejected. A long report simply does not fit.
2. One vector for a whole document blurs it. A 40-page policy covers leave, expenses, security and travel. A single vector has to represent all of that at once, so it sits in the middle of everything and matches no particular question well. The question "how many days of sick leave do I get?" is about one paragraph, and a vector for the entire document is a poor match for it.
3. You want to hand the model only what is relevant. A language model has a limited context window, and every token you give it costs money and time. Sending a whole 40-page document to answer a question about one paragraph wastes both, and can confuse the model with irrelevant text.
So we cut documents into chunks, embed each chunk and search over chunks. The question becomes: how big should a chunk be, and where should the cuts fall?
The central trade-off: small against large
Think of a chunk of one sentence and a chunk of two pages.
Small chunks of 100 to 200 tokens, about a paragraph, have these properties.
Each is about one idea, so its vector is focused, and a matching question finds it easily.
The retrieved text is short, so you can pass several to the model without filling its context.
But they lose context. A sentence like "This applies only to employees hired after 2020" is meaningless without the preceding sentence that says what "this" is. A chunk that starts mid-argument is hard to match and hard to use.
There are many of them, so storage and search cost more.
Large chunks of 800 to 2,000 tokens, a page or more, have the opposite properties.
They carry context, so the model has what it needs to understand them.
But each blends several ideas, so a question that matches one part of the chunk scores lower than it would against a focused chunk. This is sometimes called dilution.
They use more of the context window, so fewer fit.
If the answer is a single sentence, the model must find it in a long passage.
There is no universally right size. A common starting point is somewhere between 200 and 500 tokens, with some overlap between neighbouring chunks, then adjusted by testing on your own documents and questions. Documents with short, self-contained facts, such as FAQs, suit small chunks. Documents that develop long arguments, such as contracts or research papers, may need larger ones, or a design that brings in the surrounding text.
Predict first: a company's policy documents contain long clauses with many exceptions. A team chooses chunks of 100 tokens because "small is precise". Retrieval keeps returning sentences that begin "However, this does not apply to...". What has gone wrong, and what could they change? Think before you read on.
The small chunks cut clauses off from the sentences that say what they apply to, so the exceptions float free of their rules. The team could use larger chunks, cut at clause boundaries instead of fixed lengths, or retrieve small chunks but pass the surrounding section to the model. Each of these ideas appears below.
How many chunks, and what does overlap cost?
Chunk counts are simple arithmetic, and worth working out before you build, because they drive cost.
Suppose a document is L tokens long. If you cut it into chunks of c tokens with no overlap, you get L ÷ c chunks, rounded up. A 10,000-token document in 500-token chunks gives 20 chunks.
Overlap repeats the last o tokens of each chunk at the start of the next. The reason is to avoid cutting a sentence or an idea in half at the boundary. If the cut falls in the middle of a key sentence, the overlap ensures that the whole sentence appears in at least one chunk. With overlap, each new chunk advances by c − o tokens, called the stride. The number of chunks is the length remaining after the first chunk, divided by the stride, rounded up, plus one for the first chunk.
For the same document with 500-token chunks and 50 tokens of overlap, the stride is 450. The first chunk covers 500 tokens. The remaining 9,500 tokens need 9,500 ÷ 450 = 21.1 strides, so 22 more chunks, a total of 23. The extra cost is the repeated text: every chunk except the first repeats 50 tokens, so the collection holds about c ÷ (c − o) = 500 ÷ 450 = 1.11 times as many tokens as the original. That is 11 per cent more to embed and to store.
Small overlaps, around 10 to 20 per cent of the chunk size, are cheap and catch most boundary problems. Large overlaps, such as half the chunk, nearly double the cost and add many near-duplicate chunks, which can fill your top results with the same text repeated. Use the simulator below to try your own figures.
Notice that the formula treats every chunk as full size, so it slightly overstates the cost when the last chunk is short. For planning, that is a safe direction to be wrong in.
Ways to split text
There are several common methods. They differ in how much they respect the meaning of the text.
Fixed-size splitting. Cut every c tokens, with overlap. It is simple, predictable and fast. But it cuts anywhere: mid-sentence, mid-table, mid-code. It is a sensible baseline to start from, and to beat.
Sentence or paragraph splitting. Split at sentence or paragraph boundaries, then group sentences until the chunk reaches the target size. This never cuts a sentence in half, and it keeps related sentences together more often. It is usually better than fixed-size splitting for prose.
Structure-aware splitting. Use the document's own structure: headings, sections, numbered clauses, list items, table rows. A section titled "Sick leave" becomes a chunk, or a few chunks, that all belong to that heading. This keeps meaning together, and gives you metadata for free: the heading itself. It works best when the source has a reliable structure, such as Markdown, HTML or well-formatted documents.
Recursive splitting. A popular practical method. Try to split on the largest natural boundary first, such as sections, then paragraphs, then sentences, then words, and only descend a level if a piece is still too large. The result respects structure when it can and falls back to simple cuts when it must.
Semantic splitting. Embed sentences and cut where the topic changes, that is, where the similarity between neighbouring sentences drops. It aims to make each chunk about one thing. It is more expensive and can be unstable, and it is not always better than simpler methods, so test it before trusting it.
Special handling for special content. Tables, code, lists and figures need their own treatment.
Tables: do not cut a table in the middle of a row. Keep each table together if it fits, or split by rows while repeating the header, so that every chunk explains its columns.
Code: split by function or class, not by line count.
Lists: keep a list with the sentence that introduces it.
Scanned documents and PDFs: extraction can scramble the reading order, break words and mix headers and footers into the text. Inspect the extracted text before you chunk it. Garbage in, garbage out.
Add context to every chunk
A chunk lifted out of its document often loses its identity. "The limit is 30 days" could be about leave, refunds or notice periods. There are several ways to put the context back.
Attach metadata. Store the document title, section heading, page number, date and source address with each chunk. This lets you show citations to users, filter by date or product, and trace any wrong answer to its source.
Prepend the title or heading to the text that is embedded. For example, embed "Refund policy > Digital goods: The limit is 30 days" and not just "The limit is 30 days". The heading is now part of the vector, and the chunk matches questions about refunds on digital goods.
Write a short context note for each chunk. Some systems ask a language model to produce a one-sentence description of where a chunk sits in its document and add it before embedding. It can help a great deal for documents where chunks depend on context, but it costs an extra model call for every chunk, so work out the cost first.
Keep neighbours linked. Store the identifiers of the previous and next chunk, so that you can fetch them later.
Retrieve small, return large
Here is a design that gets some of the benefit of both sizes. Embed and search small chunks, which match precisely. But when a small chunk is retrieved, hand the model its parent: the surrounding section, or the chunk plus its neighbours. The search is precise, and the model sees the context.
This is often called parent-child or small-to-big retrieval. In practice, you store small child chunks, say 150 tokens, each pointing to a parent, say a whole section of 800 tokens. You search the children, and look up their parents. If several children of the same parent are retrieved, you return the parent once.
The cost is bookkeeping, and a larger payload for the model. If you retrieve the top 5 children and return 5 different parents of 800 tokens, that is 4,000 tokens of context, against 750 for the children alone. You must count that against your context budget, as the next section shows.
The context budget
Chunk size also decides how much you can give the model. A language model's context window must hold the instructions, the question, the retrieved chunks and the answer it writes. If you retrieve k chunks of c tokens each, the retrieved text takes k × c tokens. So the number of chunks you can include is the space left, divided by the chunk size.
For example, a window of 8,000 tokens, with 1,000 reserved for instructions and the question and 1,000 for the answer, leaves 6,000 for retrieved text. With chunks of 500 tokens, you can fit 12. With parent chunks of 2,000 tokens, you can fit only 3. A bigger window helps, but costs more for each call, and giving the model more text does not always improve the answer: long, noisy context can bury the useful part.
Testing your chunking
Rules of thumb get you started. Testing tells you what works for your documents. The method follows from Lesson 4.2.
1. Write 30 to 50 realistic questions and mark the passage that answers each.
2. Chunk the collection two or three different ways, for example 200, 400 and 800 tokens, with and without headings.
3. For each version, embed, search and measure the hit rate at k: the share of questions where a chunk containing the answer is in the top k.
4. Look at the failures. Read the retrieved chunks for the missed questions. Was the answer split across two chunks? Was the matching chunk buried in a large one? Was the heading missing?
5. Change one thing at a time, and re-measure.
The failures teach more than the averages. If answers are being cut in half, increase overlap or use structure-aware splitting. If large chunks are diluted, shrink them or use parent-child retrieval. If chunks have no identity, add titles.
Also look at the cost. A configuration with a slightly better hit rate but three times the chunks may not be worth it.
Three worked examples
Example 1: an FAQ. A bank's FAQ has 400 short question-and-answer pairs of about 80 tokens each. The team makes each pair one chunk, with the question as the heading. There is no overlap, because each pair stands alone. Retrieval is excellent. Cutting these into 500-token windows would have mixed several unrelated questions in each chunk, and hurt matching.
Example 2: a policy handbook. An employee handbook runs to 60,000 tokens, in numbered sections with sub-clauses. The team splits at section headings, then, when a section exceeds 600 tokens, at sub-clause boundaries, with a heading path such as "5. Leave > 5.2 Sick leave" prepended to each chunk. They store the section as a parent and retrieve children of about 250 tokens. In an illustrative test on 40 questions, the hit rate at 5 rises from 68 per cent for fixed 500-token chunks to 85 per cent. Most of the gain comes from keeping exceptions attached to rules, and from the headings.
Example 3: a table-heavy report. A finance report has tables of figures with a header row of years. A fixed-size splitter cuts tables mid-row, so one chunk holds the numbers with no column names. Questions like "what was revenue in 2023?" fail. The team changes to table-aware splitting, keeping tables whole when under 800 tokens and otherwise splitting by rows while repeating the header row in each chunk. The failures disappear for table questions.
Common mistakes
Using one chunk size for everything. FAQs, contracts and tables need different treatment.
Cutting mid-sentence or mid-table with fixed-size splitting and no checks.
Ignoring headings, so chunks lose their identity.
Too much overlap, which inflates cost and fills results with near-duplicates.
Never reading the chunks. Open twenty random chunks and read them. Many problems are visible at once.
Using extracted text without checking it. PDF extraction can scramble order and mix in headers and footers.
Choosing a size by habit, not by testing against questions.
Forgetting the context budget, and then finding that the retrieved text does not fit in the window.
Key takeaways
Documents are chunked because embedding models have limits, one vector for a whole document blurs it and you want to give the model only relevant text.
Small chunks are precise but lose context. Large chunks keep context but dilute meaning and use more of the window. Start around 200 to 500 tokens and test.
With overlap o, the stride is chunk size minus o, and the tokens embedded grow by a factor of chunk size divided by stride. Small overlaps are cheap.
Prefer splitting at natural boundaries: sentences, paragraphs, headings, clauses and table rows. Handle tables, code and lists with care.
Attach metadata and prepend headings to each chunk, so that it keeps its identity and can be cited and filtered.
Retrieve small and return large with parent-child retrieval, count chunks against the context budget and test every choice on real questions.
Check yourself
1. Why not embed a whole 40-page document as a single vector?
The model has a token limit, and one vector would blur many topics together so that it matches no specific question well. You would also send far too much text to the model.
2. A document has 3,000 tokens. Chunks are 500 tokens with 100 tokens of overlap. About how many chunks result?
The stride is 400. After the first chunk, 2,500 tokens remain, which is 6.25 strides, so 7 more. The total is 8 chunks.
3. Why does adding the section heading to each chunk's text before embedding help?
It restores the context that the chunk lost when it was cut out, so the vector matches questions about that topic.
4. What is parent-child retrieval?
You search small chunks for precision, but give the model the larger parent section, so that it has the context it needs.
5. A window of 10,000 tokens reserves 1,500 for instructions and 1,500 for the answer. Chunks are 700 tokens. How many chunks fit?
7,000 tokens remain, and 7,000 ÷ 700 = 10 chunks.
6. How would you find out whether 300-token or 600-token chunks work better for your documents?
Write test questions with known answer passages, run both versions, compare the hit rate at k, read the failures and consider cost.
Try this
Set aside 30 to 45 minutes. You need a handful of real documents, a spreadsheet and, if you like, a short script; the arithmetic steps need only a spreadsheet.
1. Pick a collection you might search, such as a handbook, product manuals or meeting notes. Estimate the number of documents and the average tokens per document. A rough rule is that a token is about three-quarters of a word.
2. Use the first simulator to compute the number of chunks, the tokens to embed and the one-time cost at three chunk sizes: 200, 400 and 800 tokens, each with about 10 per cent overlap. Write the results in a table.
3. Open one real document and mark by hand where you would cut it into chunks at natural boundaries. Count how many chunks that gives, and compare with the fixed-size count.
4. Choose a heading path for three of your chunks, in the form "Document > Section > Subsection". Write what each chunk's embedded text would look like.
5. Use the second simulator with your model's window to find how many chunks of each size fit once you reserve space for instructions and the answer.
6. Write 10 test questions and mark the passage that answers each. Decide how you would measure the hit rate for each chunk size.
7. Optional: if you can run code, chunk the documents with a fixed-size and a structure-aware splitter, embed both and compare the hit rate on your questions.
A good result is a table of chunk counts, tokens and costs at three sizes, a hand-cut example showing where structure-aware splitting differs from fixed-size, three chunks with headings prepended, a context budget for your model and a list of questions ready for testing.
Tags: AI Engineering Chunking Retrieval RAG Embeddings