Katkat

Chunking Documents for Retrieval

By the Katkat team · Updated · 10 min read

Quick overview

Learn how to chunk documents for RAG: fixed, structural and semantic splitting, overlap, metadata and parent-child retrieval, with a worked example.

Lesson 19 of 88 · AI Engineering Interview Course

After this lesson you will be able to explain how a document gets split into retrievable pieces, why those splits decide whether a RAG system finds the right evidence, and what each strategy costs. You will be able to compare fixed-size, structural and semantic chunking, work out the cost of overlap with real numbers, and describe how metadata and parent-child retrieval fix the weaknesses of small chunks.

Why we chunk at all

A retrieval system does not search whole documents. It embeds pieces of text into vectors, finds the pieces nearest to the query, and puts them in the prompt. Three constraints force the splitting.

  • Embedding quality. One vector summarises a whole piece of text. A 20-page report embedded as one vector becomes a blurry average of many topics, and a specific question matches it poorly. See Embeddings.
  • Model input limits. Embedding models accept a maximum number of tokens, and text beyond that limit is truncated or rejected.
  • Context budget and cost. Every retrieved token is paid for, and it competes with instructions and conversation history for space. See Context Windows. Very long contexts also tend to use evidence unevenly, as the "Lost in the Middle" paper explores.

Chunking is therefore a trade-off between two failure modes. Chunks that are too small lose the surrounding context needed to interpret them. Chunks that are too large dilute the embedding and waste prompt tokens. Every technique below is a way to manage that trade-off. Chunking is one stage of the pipeline in Retrieval-Augmented Generation, End to End, and the text it receives comes from the step described in Document Ingestion for RAG.

Fixed-size chunking

The simplest approach cuts text into windows of a fixed length, measured in tokens or characters, optionally with overlap.

Mechanism. Tokenize the document, take tokens 0 to N-1 as chunk 1, then step forward by a stride and repeat. Measure length in the tokens of your embedding model rather than in characters or words, because the model's input limit is in tokens. See Tokenization.

Strengths. It is trivial to implement, fast, deterministic, and gives predictable chunk sizes, which makes cost and index size easy to estimate. It works on any text, including messy text with no markup.

Weaknesses. It ignores meaning. A cut can land in the middle of a sentence, split a table from its header, or separate a definition from the sentence that uses it. A chunk that begins "However, this does not apply when..." is nearly useless without the sentence before it.

A common refinement is recursive splitting. Try to split on the largest natural separator first (blank lines between paragraphs), and only fall back to smaller separators (single newlines, then sentences, then words) when a piece is still over the limit. It stays size-bounded but cuts at natural boundaries far more often than a blind window does. A concrete implementation exercise is in Implement a Text Chunker with Overlap.

Structural chunking

Structural chunking uses the document's own organisation as the split points.

  • Markdown and HTML. Split at headings, so each chunk is a section or subsection. Keep the heading path (for example "Billing > Refunds > Late requests") with the chunk.
  • Code. Split by function, class or module, ideally using a parser, so a function is never cut in half.
  • Tables. Keep a table together, or repeat the header row in every chunk that holds part of it. A row of numbers without its column names is meaningless to an embedding model.
  • Legal and policy text. Split by clause or numbered article.
  • FAQs and support tickets. One question-answer pair or one ticket per chunk.
  • Transcripts and chat logs. Group by speaker turns or by time window.

Trade-offs. Structural chunks are coherent, because the author already grouped related ideas. The cost is variable size. One section may be 40 tokens and another 4,000, so you still need a maximum size and a fallback (usually recursive splitting) for oversized sections, and you may want to merge tiny neighbouring sections. It also depends on good parsing. PDFs with columns, headers, footers and scanned pages can produce scrambled text, and then no chunking strategy can save the result.

Semantic chunking

Semantic chunking places boundaries where the topic changes instead of where a length counter runs out.

Mechanism. One common design is as follows.

  1. Split the text into sentences.
  2. Embed each sentence, or a small sliding window of sentences.
  3. Compute the similarity between each adjacent pair.
  4. Start a new chunk wherever similarity drops below a threshold, for example below a chosen percentile of all adjacent similarities in the document.
  5. Enforce a minimum and maximum chunk size.

A variant asks an LLM to propose the boundaries or to rewrite each passage so that it stands alone.

Trade-offs. Chunks follow topics, which can help on long, loosely structured prose. The costs are real. You embed every sentence at ingestion, which adds compute and time. Results depend on a threshold you must tune. Chunk sizes vary a lot, which complicates budgeting. And the benefit over well-tuned recursive or structural splitting is not guaranteed, so you should measure it on your own data with a retrieval evaluation (see Evaluating a RAG System) before paying for it.

Comparing the strategies

StrategySplit ruleChunk sizeIngestion costBest forMain risk
Fixed-sizeToken countUniformVery lowUnstructured text, a first baselineCuts mid-thought
RecursiveLargest natural separator under a size capRoughly boundedVery lowGeneral-purpose defaultStill blind to topic
StructuralHeadings, clauses, functions, rowsVariableLow, but needs good parsingDocs, code, policies, FAQsOversized or tiny sections
SemanticSimilarity drop between sentencesVariableHigher (embeds every sentence)Long prose with weak structureThreshold tuning, uncertain gain
LLM-guidedA model chooses boundariesVariableHighestSmall, high-value corporaCost, inconsistency

Overlap, with a worked example

Overlap means consecutive chunks share some tokens. If a key fact straddles a boundary, at least one chunk contains the whole of it, and the start of each chunk gets some lead-in context.

The stride is the chunk size minus the overlap. Suppose a document has 10,000 tokens, the chunk size is 500 and the overlap is 100.

  • Stride = 500 - 100 = 400 tokens.
  • Chunk starts are at 0, 400, 800, and so on. The chunk starting at 9,200 ends at 9,700, so tokens 9,700 to 10,000 are not yet covered and one more chunk is needed.
  • The number of chunks is ceil((10,000 - 500) / 400) + 1 = ceil(23.75) + 1 = 24 + 1 = 25. The last chunk starts at 9,600 and holds only 400 tokens.
  • Without overlap the same document gives 10,000 / 500 = 20 chunks.
  • Tokens stored with overlap: 24 x 500 + 400 = 12,400, which is 24% more than the original 10,000. You also store 25% more vectors (25 versus 20).

So 20% overlap costs roughly a quarter more storage and embedding work. It also creates near-duplicate results. If two adjacent chunks both rank in the top 5, they waste prompt space by repeating the same 100 tokens. Deduplicate or merge adjacent hits before building the prompt. Overlap helps most for fixed-size splitting. With clean structural boundaries, little or no overlap is often enough.

There is no universally correct size. Many teams start with a few hundred tokens and 10% to 20% overlap, then tune against measured retrieval quality. Treat that as a starting point, not a rule.

Metadata

Each chunk should carry more than its text. Metadata is stored next to the vector and used at query time and in the answer.

  • Provenance. Document ID, title, URL or file path, page number, section path, and chunk index. This enables citations and lets you fetch neighbouring chunks.
  • Filters. Product, language, document type, author, date, version. Filtering before or during the vector search narrows candidates cheaply and avoids returning outdated or irrelevant material.
  • Access control. Tenant ID or permission groups. Apply the filter at retrieval time, so text a user may not see never reaches the prompt. Filtering after generation is too late.
  • Lifecycle. Content hash and ingestion timestamp. When a document changes, you can find and delete exactly its old chunks and re-embed only what changed, and you can detect duplicates.

A related technique is contextual prefixing. Before embedding, prepend the document title and section path to the chunk text, for example "Employee handbook > Leave > Parental leave:". The vector then carries context the chunk body lacks. You can store the unprefixed text separately for display. Metadata fields are also what make exact-match filters and keyword search possible, which pairs well with Hybrid Search and Reranking.

Parent-child retrieval

Small chunks match queries precisely but give the model too little to reason with. Large chunks give the model context but match poorly. Parent-child retrieval (also called small-to-big retrieval) uses both.

Mechanism.

  1. Split documents into parents, such as sections of about 1,000 tokens.
  2. Split each parent into children of about 250 tokens.
  3. Embed and index only the children, each with a pointer to its parent ID.
  4. At query time, search the children, then map the top hits to their parents, deduplicate, and put the parents in the prompt.

Worked numbers. A 10,000-token document gives 10 parents and 40 child vectors (4 per parent). Suppose the top 5 children come from 3 distinct parents. You send 3 x 1,000 = 3,000 tokens instead of 5 x 250 = 1,250 tokens of child text. The model gets about 2.4 times the context, and the match was still decided by precise 250-token vectors. The index holds 40 vectors instead of the 10 you would have with parents alone, a 4x increase in vector count.

Variants. Instead of a fixed parent, return the matched chunk plus its immediate neighbours (a window around the hit), or return the whole section identified by the section-path metadata.

Trade-offs. You spend more prompt tokens per hit, so fewer distinct sources fit in the budget, and a large parent may contain a lot of irrelevant text. You also maintain two levels of storage. A reranker over the retrieved parents can help trim what you send. Parent-child is most valuable when answers depend on surrounding text, such as exceptions, definitions and conditions, which is common in policies and technical documentation.

How does this come up in interviews?

1. How would you choose a chunk size for a new corpus? Start with the embedding model's input limit and the typical answer length, pick a baseline such as a few hundred tokens with modest overlap, then evaluate a few settings on a labelled set of questions. Compare retrieval metrics such as recall at k, and check end-to-end answer quality. Corpus type matters, so structured documents may need section-based chunks while chat logs need turn-based ones.

2. Why use overlap, and what does it cost? Overlap prevents a fact that straddles a boundary from being split across two chunks that each look incomplete. It costs storage, embedding compute and duplicate hits. For example, 100 tokens of overlap on 500-token chunks adds about 24% more stored tokens. I would deduplicate adjacent hits and reduce overlap if the splits already follow document structure.

3. Explain parent-child retrieval and when you would use it. Embed small child chunks for precise matching, but return the larger parent section to the model for context. Use it when queries match narrow passages but the answer depends on surrounding conditions. The trade-offs are more prompt tokens per hit and a larger index, so I would cap the number of parents sent and deduplicate them.

4. Retrieval returns the right document, but the answer misses a condition stated in the previous paragraph. What do you change? This is a context-loss problem from chunks that are too small or cut in the wrong place. I would split on structure, add the section heading as a prefix, retrieve neighbouring chunks or the parent section, and check the failure against the debugging steps in Your RAG System Gives Wrong Answers. Then I would re-run the retrieval evaluation to confirm the fix.

5. How would you chunk a table-heavy PDF or a code repository? For tables, I would extract them with a layout-aware parser and keep each table whole, or repeat the header row in every piece, and store a short text summary alongside it. For code, I would split by function or class using a parser and store file path and symbol name as metadata. In both cases the goal is to keep each chunk self-explanatory.

Common mistakes

  • Measuring chunk size in characters or words while the embedding model limit is in tokens.
  • Using one chunk size and strategy for every document type in the corpus.
  • Cutting tables, code blocks or numbered lists in the middle, and losing header rows.
  • Adding large overlap everywhere and then sending near-duplicate chunks to the model.
  • Storing only the text and no source, section or version metadata, which makes citations, filtering and updates impossible.
  • Applying access-control filters after retrieval or generation instead of during retrieval.
  • Choosing semantic chunking because it sounds advanced, without measuring it against a simple recursive baseline.
  • Tuning chunking by eyeballing a few examples instead of running a retrieval evaluation.
  • Re-ingesting a changed document without deleting its old chunks, leaving stale and conflicting evidence in the index.
  • Treating chunking as a one-off decision instead of something to revisit when the corpus, embedding model or query types change.