LESSON 40 Β· CHUNKING

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.

35 min readβ€’Intermediateβ€’Generative AI

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

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.

Large textDocument content
β†’
Try paragraphKeep structure
β†’
Too large?Use smaller boundary
β†’
Final chunksWithin target size
Key idea:recursive chunking is not simply β€œsplit every N characters.” It uses a hierarchy of boundaries and only becomes more aggressive when necessary.
2

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.

FIXED CUT

Length first

A chunk reaches its limit in the middle of a paragraph, so the next chunk starts with a continuation.

β†’
RECURSIVE CUT

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.

3

How Recursive Splitting Works

LEVEL 1ParagraphFirst choice for normal prose.
LEVEL 2Line breakUsed when larger blocks remain too large.
LEVEL 3SentenceCreates smaller natural-language units.
LEVEL 4Word / characterLast-resort boundaries for very large pieces.
Important: recursive means the algorithm can apply the next separator to an oversized piece again. It does not mean that every document must use exactly the same separator list.
4

Separator Order Matters

The order of separators expresses your preference for what should stay together. Put larger structural boundaries first and smaller boundaries later.

</> Python
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.

5

Simple Recursive Chunker in Python

The following learning implementation demonstrates the core idea without depending on an external framework.

</> Python
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}")
Learning point:the function first tries the largest separator. Oversized pieces are passed to a smaller separator until they can be assembled into chunks under the target.
6

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.

TOO SMALL

Fragmented context

Chunks may contain too little information to answer a question.

BALANCED

Useful context

Chunks preserve structure while remaining focused enough for retrieval.

TOO LARGE

More noise

Large chunks can dilute relevance and consume more context tokens.

Practical rule:choose a measurable starting size, then test retrieval quality on representative questions instead of assuming one number works for every dataset.
7

Recursive Chunking and Overlap

Overlap can repeat part of the previous chunk so information near a boundary remains available in the next chunk.

Chunk 1Paragraph A + B
β†’
OverlapRepeat B
β†’
Chunk 2B + C
Trade-off: overlap may improve continuity but increases duplicate text, storage, embedding work, and potentially repetitive retrieval results.
8

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.

</> Python
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)
9

Recursive vs Fixed-size Chunking

FIXED-SIZE

Length-driven

Splits around a fixed number of characters, words, or tokens. It is simple and predictable but may cut through structure.

VS
RECURSIVE

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.

10

Recursive vs Sentence Chunking

SENTENCESentence-firstFinds sentence boundaries and groups them into chunks.
RECURSIVEHierarchy-firstTries paragraph and line boundaries before smaller ones.
BEST FITClean proseSentence chunking is easy to reason about for ordinary text.
GENERAL BASELINEMixed proseRecursive splitting can adapt when sections vary in length.
11

Recursive Chunking in RAG

1 Β· LOAD

Read the document

Extract the source text and preserve useful structural information when possible.

2 Β· SPLIT

Apply separators

Try larger boundaries first and recursively fall back when content is too large.

3 Β· EMBED

Create vectors

Generate embeddings for the final chunks.

4 Β· RETRIEVE

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.

12

Preserve Metadata

Keep metadata with every recursive chunk so retrieval results can be traced back to the original document and section.

SOURCEproduct-guide.pdf

Original document identifier.

SECTIONInstallation

Structural context for the chunk.

POSITIONChunk 14

Where the chunk came from.

CHUNKERrecursive

Useful when comparing chunking strategies.

Why it matters: metadata supports filtering, citations, debugging, evaluation, and reconstruction of nearby context.
13

Where Recursive Chunking Works Well

DOCUMENTATIONTechnical guides

Paragraph and line boundaries often preserve explanations and examples.

POLICIESLong business documents

Large sections can fall back to smaller boundaries without immediately cutting every block at a fixed length.

ARTICLESStructured prose

Paragraph-first splitting is a natural fit for many articles and knowledge bases.

SUPPORTHelp content

Variable-length sections can be reduced to manageable retrieval units.

14

Where Recursive Chunking Can Struggle

TABLESStructure is lost

Plain text separators may not preserve row and column relationships.

CODEWrong boundaries

Natural-language separators may not match programming structure.

PDFSExtraction issues

Columns, headers, footers, and reading order can be wrong before chunking even begins.

TOPIC SHIFTSMeaning changes

Two nearby paragraphs can be structurally close but semantically unrelated.

HUGE SECTIONSDeep fallback

Very large blocks may require many recursive levels before reaching a useful size.

BAD SEPARATORSPoor boundaries

An unsuitable separator list can produce awkward chunks even when the algorithm is correct.

15

Common Mistakes

MISTAKE 1Using only one separator

That removes the main advantage of recursive fallback.

MISTAKE 2Ignoring token size

Word counts are only an approximation of the model's actual token budget.

MISTAKE 3Too much overlap

Large overlap can create expensive and repetitive retrieval results.

MISTAKE 4Ignoring document type

A separator list for prose may be inappropriate for code, tables, or structured records.

MISTAKE 5Dropping metadata

Without source and position information, debugging retrieval becomes harder.

MISTAKE 6Never evaluating

A clean chunking algorithm still needs retrieval and answer-quality evaluation.

16

How to Evaluate Recursive Chunking

RELEVANCEDid retrieval find the right chunk?

Measure whether relevant source information appears among the retrieved results.

COMPLETENESSIs enough context present?

Check whether the retrieved chunk contains the information needed to answer.

NOISEHow much unrelated text?

Large or poorly grouped chunks can introduce distracting content.

COSTHow many tokens?

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.

PRACTICE

Build a Recursive Chunker

Create a Python function that receives a multi-paragraph document and recursively splits it using paragraph, sentence, and word boundaries.

  1. Start with a maximum chunk size such as 50 words.
  2. Try paragraph breaks first.
  3. For oversized pieces, fall back to sentence boundaries.
  4. Use words as a final fallback for very long sentences.
  5. Print each chunk with its index and word count.
  6. Try 0 and 1-sentence overlap and compare five retrieval questions.
Challenge: store source, section, chunk_index, word_count, and chunking_strategy with every chunk.

Quick Quiz

1. What does recursive chunking do first?

It tries a larger, preferred separator before falling back to smaller separators.

2. Why is separator order important?

It determines which document boundaries the chunker prefers to preserve.

3. Does recursive chunking remove the need for a chunk-size limit?

No. A target size is still needed to keep retrieval focused and context manageable.

4. How is recursive chunking different from fixed-size chunking?

Fixed-size splitting is mainly length-driven, while recursive splitting tries a hierarchy of structural boundaries.

5. What should you evaluate?

Retrieval relevance, context completeness, noise, token cost, and final answer quality.

30-Second Recap

1 Β· ORDERPrefer larger separators first.
2 Β· FALLBACKMove to smaller boundaries when needed.
3 Β· SIZEKeep chunks within a practical budget.
4 Β· OVERLAPRepeat context only when useful.
5 Β· EVALUATEMeasure retrieval and answer quality.

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.