How to Chunk Documents for RAG: Size, Overlap and Common Mistakes

By ayush-rag27 / October 7, 2026

How to Chunk Documents for RAG: Size, Overlap and Common Mistakes

If you’ve built a RAG system, you’ve probably had this experience. The demo works beautifully on three hand-picked questions. Then a real user asks something slightly off-script, and the system confidently returns a paragraph that is technically from your documents but has nothing to do with the question.

Most people’s first instinct is to blame the model, or the embeddings, or the vector database. Sometimes that’s right. But in my experience, the culprit is far more often something much less glamorous: how the documents were chopped up before they were ever indexed.

Chunking is the step everyone rushes through. You find a tutorial, copy chunk_size=1000, chunk_overlap=200, and move on to the exciting parts. Then you spend three weeks tuning prompts to compensate for retrieval that was broken from day one.

This post is the guide I wish I’d had. We’ll cover why chunking matters, how to pick a chunk size, what overlap actually does (and doesn’t do), the main chunking strategies, and the mistakes that quietly wreck retrieval quality.

Why chunking matters more than you think

A RAG pipeline has one job at retrieval time: given a question, find the pieces of text most likely to contain the answer, and hand them to the language model. Everything downstream depends on those pieces being good.

We chunk documents for two practical reasons:

  1. Embedding models have limits. Most can only process a few hundred to a few thousand tokens, and they perform best well below their maximum.
  2. Retrieval needs precision. If you embed an entire 40-page PDF as one vector, that vector is a blurry average of everything in it. A question about one specific clause will never match it strongly.

But chunking creates its own problem. Every time you cut a document, you risk separating things that belong together: a claim from its evidence, a table from its header, a pronoun from the noun it refers to.

So the whole game is balancing two forces:

  • Small chunks give you precise matching but lose context.
  • Large chunks keep context but dilute the signal and cost more tokens.

There is no universally correct answer. There is only the right answer for your documents and your questions.

Understanding chunk size

Let’s start with the number everybody asks about first: how big should a chunk be?

What happens when chunks are too small

Imagine a chunk that says:

“This applies only to customers on the legacy plan, and the deadline has been extended to March 31.”

What applies? Which deadline? Taken alone, this sentence is nearly useless, yet it might be embedded and retrieved on its own. The embedding captures only a fuzzy idea of “deadline extension,” so it may match many unrelated queries and fail to match the one that matters.

Very small chunks (say, under 100 tokens) tend to produce:

  • Fragments that are meaningless without their neighbours
  • A huge number of vectors, which means higher storage and slower search
  • Retrieved results that look relevant but can’t actually answer anything

What happens when chunks are too large

Now the opposite. Suppose a chunk is 2,000 tokens and covers refund policy, shipping times, and warranty terms. A user asks about shipping. The chunk does contain the answer, but the embedding represents all three topics at once, so its similarity score for a shipping question is mediocre. A more focused chunk from a different document might outrank it.

Even when large chunks do get retrieved, you pay for it: more tokens in the prompt, higher cost, and a language model that has to find a needle in a bigger haystack. Models are also known to pay less attention to information buried in the middle of long contexts.

Starting points that actually work

Here’s a rough guide. Treat these as starting points to test, not rules.

Content typeTypical chunk size (tokens)Why
FAQs, short support articles100–250Each answer is already self-contained
General documentation, wikis250–500Enough room for a concept and a short example
Long-form articles, reports400–800Arguments need space to develop
Legal and contracts300–600, split by clauseClauses are the natural unit of meaning
Source codePer function or classSplitting mid-function destroys meaning
Chat logs, transcripts5–15 turns, groupedA single message rarely stands alone

If you want one default to begin with, around 400–512 tokens with a bit of overlap is a sensible place to start for prose. It’s not magic. It just sits comfortably between the two failure modes above.

The real answer, though, is that chunk size should be driven by the shape of your questions. If users ask for specific facts (“What is the notice period?”), smaller chunks usually win. If they ask for explanations (“Why did the architecture change?”), larger chunks usually win. Look at your real queries before choosing.

Overlap: what it does and what it doesn’t

Overlap means that consecutive chunks share some text. If you use 500-token chunks with 50 tokens of overlap, the last 50 tokens of chunk one are repeated at the start of chunk two.

The reasoning is simple: if a sentence gets cut at a chunk boundary, the overlap gives both chunks a chance to contain it intact.

Chunk 1: [........................................|overlap|]
Chunk 2:                                     [|overlap|........................................]

How much overlap is reasonable?

A common rule of thumb is 10–20% of the chunk size. For 500-token chunks, that’s 50–100 tokens.

Going higher than that usually isn’t worth it. Here’s what happens as you crank overlap up:

OverlapEffect
0%Cleanest index, but boundary information can be lost
10–20%Good balance for most prose
30–50%Lots of duplicate content; index size balloons; retrieval often returns near-identical chunks
50%+Mostly wasted storage and compute

The part people get wrong

Overlap is a patch, not a fix. It helps when a sentence or two straddles a boundary. It does nothing if the real problem is that your chunk boundaries ignore the structure of the document.

If your splitter cuts a table in half, 15% overlap won’t save you. If it separates a heading from the section below it, overlap probably won’t help either. The better solution is to split on meaningful boundaries in the first place, which brings us to strategies.

One more thing: heavy overlap has a sneaky side effect. When you retrieve the top five results and three of them are near-duplicates of each other, you’ve effectively retrieved only three distinct pieces of information while paying for five. That wastes context window space that could have held something useful.

Chunking strategies, from simple to smart

There are several approaches, and they sit on a spectrum from “fast and dumb” to “slow and clever.” Don’t assume the clever ones are always better. Often they aren’t, at least not by enough to justify the complexity.

1. Fixed-size chunking

You split every N characters or tokens, no matter what’s in the text.

def fixed_chunks(text, size=500, overlap=50):
    chunks = []
    start = 0
    while start < len(text):
        end = start + size
        chunks.append(text[start:end])
        start = end - overlap
    return chunks

Pros: Trivial to implement, predictable, fast.

Cons: Cuts mid-sentence and mid-word. Ignores all structure.

It’s a perfectly reasonable baseline, and you should honestly build it first so you have something to beat. But I wouldn’t ship it for anything with real structure.

2. Recursive character splitting

This is the workhorse, and it’s what most libraries default to. The idea is to try splitting on the largest natural separator first (paragraph breaks), and only fall back to smaller ones (line breaks, then sentences, then words) when a piece is still too big.

from langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=60,
    separators=["\n\n", "\n", ". ", " ", ""],
)

chunks = splitter.split_text(document_text)

This respects paragraph and sentence boundaries wherever it can, which makes chunks far more coherent than fixed-size splitting. For a lot of projects, this is where you can stop.

3. Structure-aware chunking

If your documents have structure, use it. Markdown headings, HTML tags, and PDF sections all tell you where ideas begin and end.

from langchain_text_splitters import MarkdownHeaderTextSplitter

headers = [("#", "h1"), ("##", "h2"), ("###", "h3")]
splitter = MarkdownHeaderTextSplitter(headers_to_split_on=headers)

docs = splitter.split_text(markdown_text)
# Each doc carries its heading path in doc.metadata

The big win here isn’t just cleaner boundaries. It’s that each chunk can carry its heading trail as metadata, something like Billing > Refunds > Annual plans. That context is gold, and we’ll come back to it.

4. Semantic chunking

Instead of using length or punctuation, semantic chunking embeds each sentence and starts a new chunk when the topic appears to shift (when similarity between adjacent sentences drops below a threshold).

In theory, this produces chunks that match the actual flow of ideas. In practice, results are mixed. It’s slower and more expensive, the threshold needs tuning, and it can produce wildly uneven chunk sizes. Some benchmarks show only modest gains over recursive splitting, and sometimes none.

I’d reach for it only after simpler methods have clearly hit a ceiling.

5. Parent-child (small-to-big) retrieval

This one is worth understanding because it sidesteps the size dilemma rather than compromising on it.

You index small chunks (say, 150 tokens) for precise matching, but when one matches, you return its larger parent (say, 800 tokens, or the whole section) to the language model.

Parent section (800 tokens)
 ├── child chunk A (150 tokens)  ← indexed
 ├── child chunk B (150 tokens)  ← indexed
 └── child chunk C (150 tokens)  ← indexed

Match on child B  →  send the parent section to the LLM

You get the precision of small chunks and the context of large ones. The cost is a slightly more complex pipeline, since you need to store the relationship between children and parents.

Quick comparison

StrategyComplexityChunk qualityBest for
Fixed-sizeVery lowLowQuick baselines
RecursiveLowGoodMost prose-heavy projects
Structure-awareMediumVery goodDocs with headings, HTML, Markdown
SemanticMedium–highVariableUnstructured text where topics drift
Parent-childMedium–highVery goodWhen you need both precision and context

Add context to your chunks

Here’s a trick that gives a surprising amount of lift for very little effort.

A chunk pulled from the middle of a document has lost its surroundings. It might say “The limit is 500 requests per minute,” with no hint of which product, which plan, or which endpoint that limit belongs to.

The fix is to attach context to each chunk before embedding it. The simplest version is to prepend the document title and heading path:

def contextualize(chunk_text, doc_title, heading_path):
    header = f"Document: {doc_title}\nSection: {' > '.join(heading_path)}\n\n"
    return header + chunk_text

# Embed this string, not the raw chunk
text_to_embed = contextualize(
    "The limit is 500 requests per minute.",
    "API Reference",
    ["Rate limits", "Pro plan"],
)

Now the embedding knows this limit is about the Pro plan’s rate limits. Retrieval for “What’s the Pro plan rate limit?” gets a lot better.

A more advanced version uses a language model to write a one- or two-sentence summary situating each chunk within its document, then prepends that. It’s more expensive at indexing time, but it can noticeably reduce failed retrievals on large, repetitive corpora.

Also store useful metadata alongside each chunk: source file, page number, section, date, document type. You’ll use it for filtering (“only search 2025 policies”) and for showing citations to users.

Common mistakes (and how to avoid them)

These are the ones I see most often.

Mistake 1: Using the same settings for everything

A 1,000-character chunk with 200 overlap might be fine for blog posts and terrible for a spreadsheet, a legal contract, or a codebase. Different content needs different treatment.

Fix: Route documents by type. It’s completely normal to have three or four different chunking configurations in one system.

Mistake 2: Measuring chunk size in characters when your model thinks in tokens

Characters and tokens are not the same thing. 500 characters is roughly 125 tokens of English, but it can be quite different for code, other languages, or text with lots of numbers. If your embedding model has a token limit and you only count characters, you can silently exceed it and get truncated embeddings.

Fix: Count tokens using the same tokenizer family as your embedding model.

import tiktoken

enc = tiktoken.get_encoding("cl100k_base")

def token_len(text):
    return len(enc.encode(text))

print(token_len("How should I chunk this document?"))

Mistake 3: Destroying tables, lists, and code blocks

This is the big one. A table split across two chunks becomes two meaningless pieces: one with column headers and no data, another with data and no headers. Same story for numbered steps split in the middle, or a code example separated from the explanation above it.

Fix: Treat these as atomic units. Keep tables whole (or repeat the header row in each chunk if you must split). Keep code blocks together with the sentence that introduces them. Many parsing libraries can detect tables and code blocks if you ask them to.

Mistake 4: Garbage in, garbage out

Chunking can’t rescue badly extracted text. PDFs are the usual offender: two-column layouts read straight across, page headers and footers repeated in every chunk, hyphenated words broken in half, scanned pages with OCR noise.

If every chunk begins with “Confidential – Page 14 of 62 – Acme Corp,” your embeddings are partly encoding that boilerplate, and retrieval suffers.

Fix: Inspect your extracted text before chunking. Open ten random chunks and read them. Strip repeated headers and footers, fix the reading order, and clean obvious junk.

Mistake 5: Never actually looking at the chunks

I’m repeating myself on purpose, because it’s the highest-leverage habit there is. Print out fifty random chunks and read them like a user would. Ask: could I answer a question from this alone? Does it start mid-sentence? Is it mostly boilerplate?

You’ll find problems in ten minutes that no metric would have told you about.

Mistake 6: Overlap as a substitute for thinking

Bumping overlap to 40% because “it seems safer” usually just fills your index with near-duplicates. Pick a modest overlap, and fix boundary problems at the source by splitting along natural structure.

Mistake 7: Ignoring the retrieval side

Chunking doesn’t live in isolation. If you retrieve only the top 3 chunks and your chunks are tiny, you may not be giving the model enough. If you retrieve the top 10 with huge chunks, you may be flooding it. Chunk size and top_k should be tuned together.

Mistake 8: Never re-chunking

People treat chunking as a one-time setup decision. But as your document set grows and your users’ questions become clearer, your original settings may stop being the best ones. Build your pipeline so re-indexing is cheap and repeatable.

How to actually evaluate your chunking

Opinions about chunk size are cheap. Measurements are better.

Build a small evaluation set: 30 to 100 realistic questions, each paired with the document or passage that contains the answer. You can write these by hand, pull them from real user logs, or generate candidates with an LLM and then review them manually. Hand review matters, because synthetic questions tend to be easier than real ones.

Then, for each chunking configuration you want to compare, measure:

  • Hit rate / recall@k: How often does the correct passage appear in the top k results?
  • MRR (mean reciprocal rank): How high up does the correct passage rank?
  • Answer quality: Given the retrieved chunks, does the final answer come out right? This is what ultimately matters, and you can grade it by hand or with an LLM judge.

Here’s a bare-bones loop to compare configurations:

configs = [
    {"size": 256, "overlap": 30},
    {"size": 512, "overlap": 60},
    {"size": 1024, "overlap": 100},
]

for cfg in configs:
    index = build_index(docs, chunk_size=cfg["size"], overlap=cfg["overlap"])
    hits = 0
    for question, expected_source in eval_set:
        results = index.search(question, top_k=5)
        if any(r.source == expected_source for r in results):
            hits += 1
    print(cfg, f"recall@5 = {hits / len(eval_set):.2%}")

Change one thing at a time. If you adjust size, overlap, and strategy all at once, you’ll have no idea which change helped.

And a note of caution: don’t overfit to your eval set. If you tune obsessively against 40 questions, you’ll end up with settings that are brilliant at those 40 questions and mediocre at everything else. Refresh the set periodically with real queries.

A practical starting recipe

If you want a sensible path rather than a philosophy lecture, here’s what I’d do for a new project:

  1. Clean your text first. Fix extraction problems, strip boilerplate, preserve structure (headings, tables, code).
  2. Start with recursive splitting at roughly 400–512 tokens with 10–15% overlap, measured in tokens.
  3. Prepend the title and heading path to every chunk before embedding, and store metadata.
  4. Keep tables and code blocks intact.
  5. Build a small eval set and measure recall@k as your baseline.
  6. Run a few experiments: try smaller and larger sizes, and try parent-child retrieval if your answers need more context than your matches provide.
  7. Read your chunks. Again. Seriously.
  8. Only then consider fancier techniques like semantic chunking or LLM-generated context.

Most of the gains come from steps 1 through 4. The exotic techniques are usually the last 5%.

Final thoughts

Chunking feels like plumbing, and it is. But plumbing determines whether anything useful comes out of the tap.

The pattern I keep seeing is that teams who treat chunking as a first-class design decision, who look at their data, test a few configurations, and keep structure intact, end up with RAG systems that feel dramatically more reliable than teams who copy default settings and hope. And it rarely requires anything sophisticated. It requires attention.

So before you switch embedding models or rewrite your prompts for the fifth time, go look at your chunks. Read them out loud if you have to. If a chunk doesn’t make sense to you, it won’t make sense to your retriever either.

Good luck, and happy chunking.

Frequently asked questions

What is the best chunk size for RAG?

There isn’t one. For general prose, 400 to 512 tokens is a solid starting point. Go smaller (100 to 250 tokens) for FAQs and fact-heavy content, and larger (500 to 800 tokens) for long-form reports where ideas need room to develop. Then test against your own questions, because that’s the only thing that settles it.

How much overlap should I use?

Around 10 to 20 percent of your chunk size. Anything above 30 percent mostly fills your index with near-duplicates. If you feel tempted to raise overlap to fix boundary problems, fix the boundaries instead by splitting on headings, paragraphs and other natural structure.

Should I measure chunk size in tokens or characters?

Tokens, ideally using a tokenizer close to your embedding model’s. Characters are easier to count, but the token-to-character ratio shifts with language, code and numbers, so you can accidentally exceed your model’s input limit without noticing.

Is semantic chunking worth it?

Sometimes, but not usually as a first move. It’s slower, needs threshold tuning, and often produces uneven chunk sizes. Recursive or structure-aware splitting gets you most of the benefit for far less effort. Try semantic chunking once simpler methods have clearly plateaued on your eval set.

How do I chunk PDFs, tables and code?

Clean the extracted text first: remove repeated headers and footers, fix column reading order, and repair broken words. Keep tables whole, or repeat the header row if you have to split them. For code, split per function or class, and keep each snippet together with the explanation that introduces it.

What is parent-child (small-to-big) retrieval?

You index small chunks for precise matching, but when one matches, you send its larger parent section to the language model. It gives you the precision of small chunks and the context of big ones, at the cost of storing the relationship between them.

Do I need to re-chunk when I change my embedding model?

Not always, but it’s worth checking. Different models have different token limits and different sweet spots for input length. If you switch, re-run your evaluation set with a couple of chunk sizes before assuming your old settings still hold.

How do I know my chunking is actually working?

Build a small set of 30 to 100 realistic questions with known answer sources, and track recall@k and answer quality as you change settings. Alongside the numbers, read a few dozen random chunks by eye. Between the two, you’ll catch nearly every serious problem.

Can I use different chunking settings for different document types?

Yes, and you probably should. Policies, support articles, source code and transcripts all have different natural units of meaning. Routing each type to its own configuration is normal and usually a clear win over one-size-fits-all settings.

See the full walkthrough in Build a RAG Chatbot with LangChain.

Scroll to Top