Recursive Chunking
Recursive chunking splits text using a sequence of separators, starting with larger structural boundaries and moving to smaller ones only when a chunk is still too large. It is a practical strategy for keeping document structure while controlling chunk size.
By the end of this lesson, you will be able to:
- Explain how recursive chunking works and why separator order matters.
- Understand how paragraphs, lines, sentences, and words can become fallback boundaries.
- Build a simple recursive chunker with Python.
- Choose chunk size and overlap settings for a RAG pipeline.
- Understand how recursive chunking differs from fixed-size and sentence chunking.
- Recognize cases where recursive chunking needs structure-aware or semantic strategies.
What Is Recursive Chunking?
Recursive chunking tries to split text at the largest useful boundary first. If the resulting piece is still too large, it moves to the next smaller separator and splits again.
A common sequence is paragraph β line β sentence β word β character. The exact separators depend on the document type and the chunking library.
Why Use a Hierarchy of Separators?
Consider a technical document containing several paragraphs. A fixed-size splitter may cut through a paragraph even when a clean paragraph boundary is available.
Length first
A chunk reaches its limit in the middle of a paragraph, so the next chunk starts with a continuation.
Structure first
The splitter first tries a paragraph boundary and only goes smaller when the paragraph itself is too large.
This often produces chunks that are easier to interpret because the splitter tries to preserve natural document structure before making finer cuts.
How Recursive Splitting Works
Separator Order Matters
The order of separators expresses your preference for what should stay together. Put larger structural boundaries first and smaller boundaries later.
separators = [
"\\n\\n", # paragraph
"\\n", # line
". ", # sentence
" " # word
]
for separator in separators:
print(repr(separator))With this order, the algorithm prefers paragraph boundaries. It only considers smaller boundaries when a larger piece cannot fit the target size.
Simple Recursive Chunker in Python
The following learning implementation demonstrates the core idea without depending on an external framework.
def recursive_split(text, max_words, separators):
if len(text.split()) <= max_words:
return [text.strip()]
separator = separators[0]
parts = [part.strip() for part in text.split(separator) if part.strip()]
if len(parts) == 1 and len(separators) > 1:
return recursive_split(text, max_words, separators[1:])
chunks = []
current = []
current_words = 0
for part in parts:
part_words = len(part.split())
if current and current_words + part_words > max_words:
chunks.append(" ".join(current))
current = []
current_words = 0
if part_words > max_words and len(separators) > 1:
chunks.extend(recursive_split(part, max_words, separators[1:]))
else:
current.append(part)
current_words += part_words
if current:
chunks.append(" ".join(current))
return chunks
text = "Paragraph one has useful context. It contains several sentences.\\n\\nParagraph two explains the next idea. It also contains supporting detail."
chunks = recursive_split(text, max_words=12, separators=["\\n\\n", "\\n", ". ", " "])
for i, chunk in enumerate(chunks, start=1):
print(f"Chunk {i}: {chunk}")Chunk Size Still Matters
Recursive chunking does not remove the need for a target size. You still need a maximum word or token budget so retrieval remains focused and the LLM receives manageable context.
Fragmented context
Chunks may contain too little information to answer a question.
Useful context
Chunks preserve structure while remaining focused enough for retrieval.
More noise
Large chunks can dilute relevance and consume more context tokens.
Recursive Chunking and Overlap
Overlap can repeat part of the previous chunk so information near a boundary remains available in the next chunk.
Python: Adding Simple Overlap
A simple post-processing approach can carry the final part of one chunk into the next. Production implementations should account for token budgets and avoid creating tiny duplicate fragments.
def add_word_overlap(chunks, overlap_words):
result = []
for index, chunk in enumerate(chunks):
if index == 0:
result.append(chunk)
continue
previous_words = chunks[index - 1].split()
prefix = " ".join(previous_words[-overlap_words:])
result.append((prefix + " " + chunk).strip())
return result
chunks = [
"RAG retrieves relevant documents for a query.",
"The retriever sends useful context to the language model.",
"The model uses that context to generate an answer."
]
for chunk in add_word_overlap(chunks, overlap_words=4):
print(chunk)Recursive vs Fixed-size Chunking
Length-driven
Splits around a fixed number of characters, words, or tokens. It is simple and predictable but may cut through structure.
Hierarchy-driven
Tries larger structural boundaries before falling back to smaller ones when the content remains too large.
Recursive chunking adds structure awareness without requiring a full semantic model. That makes it a strong general-purpose baseline for many RAG applications.
Recursive vs Sentence Chunking
Recursive Chunking in RAG
Read the document
Extract the source text and preserve useful structural information when possible.
Apply separators
Try larger boundaries first and recursively fall back when content is too large.
Create vectors
Generate embeddings for the final chunks.
Search relevant chunks
Use vector similarity and metadata filters to find useful context.
The retrieved chunks become context for the generation step. Better chunk boundaries can improve the chance that the retrieved text contains a complete, useful explanation.
Preserve Metadata
Keep metadata with every recursive chunk so retrieval results can be traced back to the original document and section.
Original document identifier.
Structural context for the chunk.
Where the chunk came from.
Useful when comparing chunking strategies.
Where Recursive Chunking Works Well
Paragraph and line boundaries often preserve explanations and examples.
Large sections can fall back to smaller boundaries without immediately cutting every block at a fixed length.
Paragraph-first splitting is a natural fit for many articles and knowledge bases.
Variable-length sections can be reduced to manageable retrieval units.
Where Recursive Chunking Can Struggle
Plain text separators may not preserve row and column relationships.
Natural-language separators may not match programming structure.
Columns, headers, footers, and reading order can be wrong before chunking even begins.
Two nearby paragraphs can be structurally close but semantically unrelated.
Very large blocks may require many recursive levels before reaching a useful size.
An unsuitable separator list can produce awkward chunks even when the algorithm is correct.
Common Mistakes
That removes the main advantage of recursive fallback.
Word counts are only an approximation of the model's actual token budget.
Large overlap can create expensive and repetitive retrieval results.
A separator list for prose may be inappropriate for code, tables, or structured records.
Without source and position information, debugging retrieval becomes harder.
A clean chunking algorithm still needs retrieval and answer-quality evaluation.
How to Evaluate Recursive Chunking
Measure whether relevant source information appears among the retrieved results.
Check whether the retrieved chunk contains the information needed to answer.
Large or poorly grouped chunks can introduce distracting content.
Track embedding and generation costs as chunk size and overlap change.
Use a small evaluation set of realistic questions and compare recursive chunking against your current strategy. The goal is not the prettiest chunks; it is better retrieval and better final answers.
Build a Recursive Chunker
Create a Python function that receives a multi-paragraph document and recursively splits it using paragraph, sentence, and word boundaries.
- Start with a maximum chunk size such as 50 words.
- Try paragraph breaks first.
- For oversized pieces, fall back to sentence boundaries.
- Use words as a final fallback for very long sentences.
- Print each chunk with its index and word count.
- Try 0 and 1-sentence overlap and compare five retrieval questions.
source, section, chunk_index, word_count, and chunking_strategy with every chunk.Quick Quiz
It tries a larger, preferred separator before falling back to smaller separators.
It determines which document boundaries the chunker prefers to preserve.
No. A target size is still needed to keep retrieval focused and context manageable.
Fixed-size splitting is mainly length-driven, while recursive splitting tries a hierarchy of structural boundaries.
Retrieval relevance, context completeness, noise, token cost, and final answer quality.
30-Second Recap
Key Takeaways
- Recursive chunking uses a hierarchy of separators rather than one hard boundary.
- It tries to preserve larger document structure before falling back to smaller units.
- Separator order is a design decision and should match your document type.
- Chunk size and overlap still affect retrieval quality, cost, and context.
- Recursive chunking is a strong general-purpose baseline for many RAG systems.
- Tables, code, complex PDFs, and semantic topic shifts may need specialized strategies.
- The best chunking configuration is the one that performs well on your real retrieval evaluation set.