Early-bird price on the GenAI & Agentic AI Engineer Bootcamp batch. Grab a seat →

Chunking is how you split documents into passages before embedding them, and it sets a ceiling on everything that follows: a retriever can only return passages that exist. Start by splitting along the document's own structure (headings, paragraphs, table rows), fall back to fixed-size pieces with a small overlap where there is no structure, and choose sizes by measuring retrieval on real questions, not by copying a number from a tutorial.

Key takeaways

  • A good chunk covers one idea and makes sense when read alone. That matters more than hitting an exact size.
  • Fixed-size splitting with overlap is the baseline. Structure-aware splitting usually beats it on documents that have headings, lists or tables.
  • Different document types need different treatment. PDFs, tables, code and transcripts each break in their own way.
  • Keep metadata with every chunk: source, section heading, page, date. It powers filtering, citations and debugging.
  • There is no universally right chunk size. Test two or three settings against the same question set and keep the one with the best recall.

This article is part of our complete guide to retrieval-augmented generation, which covers the full pipeline.

Why does chunking matter so much?

In a RAG system each chunk is turned into one vector by an embedding model, and search compares the question's vector with each chunk's vector. Two things follow.

A chunk that mixes several topics gets a vector that represents none of them well, so it matches no question strongly. And a chunk cut in the wrong place loses meaning. "It must be renewed every 12 months" is useless if the sentence naming what "it" refers to landed in the previous chunk.

Anthropic's write-up on retrieval notes that chunk size, chunk boundary and chunk overlap can all affect retrieval performance, and that chunks are usually no more than a few hundred tokens. Treat that as a starting region, not a rule.

How does fixed-size chunking with overlap work?

You cut the text every N characters or tokens, and let each chunk repeat the last part of the previous one. The overlap means a sentence that straddles a boundary appears whole in at least one chunk.

Cutting at an exact character count slices through words and sentences. A better baseline tries natural boundaries first. LangChain's RecursiveCharacterTextSplitter does this: according to its documentation it tries larger units first and moves to smaller ones only when a unit exceeds the chunk size.

# pip install -U langchain-text-splitters
from langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
chunks = splitter.split_text(document_text)

Fixed-size splitting works on any text and takes minutes to set up. But it knows nothing about meaning, so a heading can be separated from its section. Overlap helps at the edges, at the price of storing and embedding the same text twice and of near-duplicate passages in the prompt.

What is structure-aware chunking?

Most business documents already tell you where the ideas begin and end: headings, numbered clauses, list items, question-and-answer pairs. Structure-aware chunking splits on those marks and keeps the heading path with each piece.

For Markdown, LangChain's MarkdownHeaderTextSplitter splits on the heading levels you name and records the headings as metadata:

from langchain_text_splitters import MarkdownHeaderTextSplitter

headers_to_split_on = [("#", "Header 1"), ("##", "Header 2"), ("###", "Header 3")]
splitter = MarkdownHeaderTextSplitter(headers_to_split_on, strip_headers=False)
sections = splitter.split_text(markdown_text)

for section in sections:
    print(section.metadata, len(section.page_content))

Each result is a document object with page_content and a metadata dictionary such as {'Header 1': 'Leave policy', 'Header 2': 'Carry-over'}. By default the splitter removes the heading lines from the text. Passing strip_headers=False keeps them, which is usually what you want, because the heading often holds the very words a person will search for.

Sections vary in length, so combine the two methods: split by structure first, then apply the recursive splitter to any section that is still too long.

One more inexpensive improvement: put the document title and heading path at the top of each chunk before embedding it. Anthropic describes a stronger version, in which a model writes a short context for every chunk, and reports fewer retrieval failures in its own tests.

Structure-aware chunking extracts text, splits on headings, splits oversized sections again, then attaches context and metadata to each chunk.

How should you chunk different document types?

Document typeWhat goes wrongWhat to do
PDFs with a text layerColumns read straight across, headers and footers repeated in every chunk, words broken by hyphens at line endsUse a layout-aware extractor, strip repeated headers and footers, keep the page number as metadata for citations
Scanned PDFsNo text at all, only imagesRun OCR first and spot-check its output. Errors here cannot be fixed later
TablesFixed-size cuts separate values from their column namesKeep a small table whole. For a large one, make each row a chunk and repeat the header row, or write each row as a sentence
FAQs and support ticketsA question and its answer land in different chunksOne chunk per question-and-answer pair or per ticket
Transcripts and chat logsNo headings. Topics driftSplit on speaker turns or time windows, with overlap

Tables deserve extra care. A row such as "Gold, 20, 5, Yes" means nothing without its column names. Rewriting it as "Gold plan: 20 users, 5 projects, priority support included" gives the embedding model real words to work with.

How do you test chunk settings instead of guessing?

Treat chunking like any other parameter: change it, measure, compare.

  1. Collect real questions. Thirty to fifty taken from support tickets, search logs or colleagues is enough to see large differences.
  2. Label the evidence, not the chunk. For each question record the source document and a short quotation that contains the answer. Chunk IDs change every time you re-chunk. A quotation does not.
  3. Build one index per setting. For example 400, 800 and 1,600 characters, and heading-based splitting.
  4. Measure recall@k for each. A question counts as a hit if any of the top k chunks comes from the right document and contains the quotation.
  5. Read the misses. Ten minutes spent reading failed questions tells you more than the score does.

The hit test is a few lines, where each test case is a dictionary with question, source and evidence keys:

def recall_at_k(test_set, retrieve, k=5):
    hits = 0
    for case in test_set:
        chunks = retrieve(case["question"], k)  # list of (source, text) pairs
        if any(src == case["source"] and case["evidence"] in text for src, text in chunks):
            hits += 1
    return hits / len(test_set)

Be fair when comparing sizes. Five chunks of 1,600 characters put four times as much text in front of the model as five chunks of 400. Compare at a similar total amount of text, for example the top 5 large chunks against the top 20 small ones. Otherwise large chunks win simply by containing more.

With a small test set, small differences are noise. On 40 questions, one question is 2.5 percentage points. Act on gaps of several questions, not one. The companion article on how to evaluate a RAG system explains recall, precision and mean reciprocal rank in full.

Testing chunk settings is a loop of choosing a setting, re-indexing, measuring recall on fixed questions and reading the misses.

What are the common chunking mistakes?

  • Dropping metadata. Without the source, page and section you cannot cite, filter or debug.
  • Blaming chunking for search problems. If the missed questions contain product codes or exact phrases, the fix may be keyword search, not a new chunk size. See hybrid search and reranking.
  • Forgetting the re-index cost. Every change to chunking means embedding the whole corpus again. On a large corpus that takes time and money, so run experiments on a representative sample first.

Common questions

What chunk size should I start with?

A few hundred tokens, split on headings where they exist, is a reasonable first attempt. Then test one smaller and one larger setting on your own questions. Nobody can give you the right number without seeing your documents.

How much overlap do I need?

Enough to keep a sentence whole across a boundary, so a sentence or two. With heading-based splitting you often need none between sections. More overlap means more duplicate text to store, embed and retrieve.

Do very long context windows make chunking unnecessary?

Only when the whole corpus fits in the prompt, in which case you do not need retrieval at all. Once you are retrieving, you are choosing which passages to send, and their boundaries still matter.

Free download: RAG evaluation checklist and test-set template

A checklist for measuring a RAG system properly, retrieval first and answers second, plus a blank test-set spreadsheet you can fill in today. See what’s inside.