RAG chunk size is the setting most teams copy from a tutorial and never test. Guides say "use 512 tokens" or "use 1,000 characters", but published studies disagree with each other, and the right number depends on your documents and your questions. So I did two things. I read four published chunking studies and pulled out their actual numbers. Then I built a small test harness and ran it on something real: my own project runbooks.

The short version: chunk size matters less than most advice suggests, chunk boundaries matter more, and 30 questions is enough to see a real difference only if you measure the noise. This guide gives you the research summary, the full code, my results with confidence intervals, and a checklist you can run on your own documents. If retrieval is new to you, read What Is RAG? Retrieval-Augmented Generation first.

Quick answer: RAG chunk size tradeoffs on runbooks

  • There is no universal best RAG chunk size. Studies on different datasets find different winners: small chunks for short factual answers, larger chunks for long or scattered answers.
  • A solid default is 200 to 400 tokens with little or no overlap, or sections that follow the document's own headings. Treat it as a starting point and test it.
  • Where you cut matters as much as how long the chunk is. In my test, chunks that follow headings and paragraphs ranked the right answer clearly higher than fixed windows of the same size.
  • Adding the file name and heading path to each chunk is nearly free and raised top-1 hits in my test from 19 to 22 of 32 at the 200-word size.
  • Large chunks hide cost. An 800-word chunk matched structured chunking on ranking quality, but sent about 6.7 times more words to the model.
  • Measure noise. With 32 questions, many setups are statistically tied. Report confidence intervals, not just a score.

What chunk size actually trades off

A chunk is the unit your retriever indexes and your model reads. Four things change when you make it bigger:

  1. Recall goes up. A larger chunk is more likely to contain the whole answer, including the sentence before and after it.
  2. Precision goes down. More of the text you send is unrelated to the question. The model has to ignore it, and you pay for the tokens.
  3. Embeddings blur. A vector for 1,000 tokens averages many ideas. A vector for 100 tokens is sharper but may lack context.
  4. Split answers disappear or duplicate. A small chunk can cut an answer in half. Overlap repeats text to avoid that, at the price of more chunks.

Chunk size is also tied to your context budget. If you pass the top 5 chunks to a model, the chunk size times five is the floor of your input per question.

One practical note on units. Many studies count tokens, while it is easier to experiment in words. In English, one word is roughly 1.3 tokens, so 200 words is close to 260 tokens. The ratio changes with code, URLs and other languages, so use your own tokenizer when you budget cost.

What four published studies found

I read these primary sources and kept only claims I could find in them.

Chroma: token-level recall and precision

Chroma's research team compared chunkers by measuring how many relevant tokens were retrieved (recall), how many retrieved tokens were relevant (precision) and an intersection-over-union score, using text-embedding-3-large and the top 5 results. Averaged across their corpora:

ChunkerSize (tokens)OverlapRecallPrecision
Recursive80040085.41.5
Recursive400089.53.6
Recursive200088.17.0
Cluster semantic400091.34.5
LLM basedabout 240091.93.9

Three takeaways. Halving a recursive chunker from 400 to 200 tokens cost about 1.4 points of recall but roughly doubled precision. A default setting of 800 tokens with 400 overlap scored worst on most precision metrics. And with a smaller embedding model, overlap mattered more: one token-based setup at 250 tokens had recall 82.4 with overlap versus 77.1 without. Chroma's suggestion is that a recursive splitter at 200 tokens with no overlap is a strong default.

Vectara and collaborators: is semantic chunking worth it?

Qu, Tu and Bao compared fixed-size chunking with two semantic chunkers across document retrieval, evidence retrieval and answer generation. Semantic chunkers helped mainly on synthetic documents made by stitching unrelated texts together. On evidence retrieval, fixed-size chunking was best on three of five datasets, and the gaps were often tiny (for example 47.11 versus 46.87 on one dataset). Answer-generation scores were nearly identical. Their conclusion is that the benefit of semantic chunking is inconsistent and does not justify the extra compute. The paper first appeared as an arXiv preprint in October 2024.

NVIDIA: page-level and token-size comparison

NVIDIA compared token chunks of 128, 256, 512, 1,024 and 2,048 tokens (15 percent overlap), page-level chunks and section-level chunks on five datasets, scored by an LLM judge. Page-level chunking had the best average accuracy (0.648) and the lowest variance, while token-based averages ranged from 0.603 to 0.645. Medium sizes usually did best, and very small (128) and very large (2,048) chunks usually did worse. Factoid-heavy datasets did well at 256 to 512 tokens. Analytical datasets did better at 1,024 tokens or page-level chunks.

Fraunhofer IAIS: chunk size depends on the dataset

Bhat and colleagues tested chunk sizes from 64 to 1,024 tokens on six datasets. Short factual answers (SQuAD) were best at 64 tokens. Technical explanation text (TechQA) improved from about 5 percent recall at 64 tokens to about 62 to 72 percent at 1,024 tokens, depending on the embedding model. They also report that the best size depends on the embedding model. The authors note limits, including string-match evaluation and synthetic document stitching.

What these studies agree on

  • No single size wins everywhere. The best size follows the type of question.
  • Medium sizes (about 200 to 512 tokens) are a safe place to start.
  • Fancy chunkers are not a guaranteed win. Gains are small or inconsistent next to a well-configured simple splitter.
  • Overlap helps weak or small-context setups and can hurt precision.
  • Evaluation design is fragile. String-match scoring, synthetic data and few questions all limit what you can conclude. That includes my test below.

My test: 18 chunking setups on 16,000 words of runbooks

Setup

  • Corpus: 18 Markdown files from my own project (deployment, process manager, backups, privacy operations, developer guide). 16,282 words, 216 sections. The median section is 55 words, the 90th percentile 156 words, the longest 737.
  • Questions: 32 questions with a known answer. For each I recorded a short phrase that must appear in the correct chunk, such as pm2 startup or GET /api/health. I checked that every phrase exists in the corpus. Some questions reuse words from the docs; others are phrased loosely.
  • Retriever: BM25 with the rank_bm25 package. No embeddings. This isolates the effect of chunking on keyword retrieval.
  • Metrics: hit@1, hit@3, hit@5 (is the answer phrase in a top-k chunk), mean reciprocal rank (MRR), and the average number of words in the top 3 chunks, which is your context cost.
  • Noise: a bootstrap over the 32 questions (2,000 resamples) gives a 95 percent interval for hit@3.

The code

The full library is under 100 lines. First, loading documents and a word counter:

python
import re, glob, random
from rank_bm25 import BM25Okapi

def load_docs(root):
    files = sorted(f for f in glob.glob(root + "/**/*.md", recursive=True)
                   if "node_modules" not in f and "/.git/" not in f)
    return {f.replace(root + "/", ""): open(f, encoding="utf-8", errors="ignore").read()
            for f in files}

def wc(s):
    return len(s.split())

Chunker 1: fixed windows with optional overlap. This is the baseline every tutorial shows.

python
def fixed_words(docs, size, overlap=0.0):
    step = max(1, int(size * (1 - overlap)))
    out = []
    for name, text in docs.items():
        w = text.split()
        for i in range(0, max(1, len(w)), step):
            out.append((" ".join(w[i:i + size]), {"doc": name}))
            if i + size >= len(w):
                break
    return out

It is fast and simple, and it cuts through tables, lists and code blocks without noticing.

Chunker 2: Markdown sections that never break a code fence. It tracks the heading path (such as Server Setup > Restart) as it goes.

python
HEAD = re.compile(r"^(#{1,6})\s+(.*)$")

def sections(text):
    stack, buf, in_code, out = [], [], False, []
    def flush():
        body = "\n".join(buf).strip()
        if body:
            out.append((" > ".join(h for _, h in stack), body))
        buf.clear()
    for line in text.splitlines():
        if line.strip().startswith("```"):
 in_code = not in_code
 m = HEAD.match(line) if not in_code else None
 if m:
 flush()
 level = len(m.group(1))
 while stack and stack[-1][0] >= level:
 stack.pop()
 stack.append((level, m.group(2).strip()))
 buf.append(line)
 flush()
 return out

Chunker 3: pack paragraphs up to a limit. Blank-line separated blocks are packed together until the limit. Oversize blocks are split by line, then by words as a last resort.

python
def pack_blocks(body, max_words):
 blocks = [b for b in re.split(r"\n\s*\n", body) if b.strip()]
 pieces, cur, cur_w = [], [], 0
 def emit():
 nonlocal cur, cur_w
 if cur:
 pieces.append("\n\n".join(cur))
 cur, cur_w = [], 0
 for b in blocks:
 bw = wc(b)
 if bw > max_words:
 emit()
 acc, accw = [], 0
 for ln in b.splitlines():
 lw = wc(ln)
 if lw > max_words:
 if acc:
 pieces.append("\n".join(acc)); acc, accw = [], 0
 w = ln.split()
 for i in range(0, len(w), max_words):
 pieces.append(" ".join(w[i:i + max_words]))
 continue
 if accw + lw > max_words and acc:
 pieces.append("\n".join(acc)); acc, accw = [], 0
 acc.append(ln); accw += lw
 if acc:
 pieces.append("\n".join(acc))
 elif cur_w + bw > max_words:
 emit(); cur, cur_w = [b], bw
 else:
 cur.append(b); cur_w += bw
 emit()
 return pieces

def by_heading(docs, max_words=400, prefix=False):
 out = []
 for name, text in docs.items():
 for hpath, body in sections(text):
 for piece in pack_blocks(body, max_words):
 t = f"{name} | {hpath}\n{piece}" if prefix else piece
 out.append((t, {"doc": name, "heading": hpath}))
 return out

With prefix=True, each chunk starts with its file name and heading path. This is a manual, free version of the idea Anthropic describes as contextual retrieval: give every chunk a short piece of context so it still makes sense when read alone. Anthropic uses a model to write that context, while I only used the file name and heading path.

Evaluation and noise.

python
tok = lambda s: re.findall(r"[a-z0-9_\-\.]+", s.lower())

def evaluate(chunks, questions, k_max=10):
 bm = BM25Okapi([tok(c[0]) for c in chunks])
 per_q = []
 for q, ans in questions:
 sc = bm.get_scores(tok(q))
 top = sorted(range(len(chunks)), key=lambda i: -sc[i])[:k_max]
 rank = next((r for r, i in enumerate(top, 1) if ans in chunks[i][0]), None)
 ctx3 = sum(wc(chunks[i][0]) for i in top[:3])
 per_q.append({"rank": rank, "ctx3": ctx3})
 return per_q

def bootstrap_ci(values, reps=2000, seed=0):
 rnd, n, ms = random.Random(seed), len(values), []
 for _ in range(reps):
 ms.append(sum(values[rnd.randrange(n)] for _ in range(n)) / n)
 ms.sort()
 return ms[int(.025 * reps)], ms[int(.975 * reps)]

Run it like this on your own folder of Markdown files:

python
docs = load_docs("path/to/your/docs")
questions = [("how do I restart the api", "systemctl restart"), ...]
for name, chunks in [("fixed 200", fixed_words(docs, 200)),
 ("headings 400 + path", by_heading(docs, 400, prefix=True))]:
 per_q = evaluate(chunks, questions)
 hits3 = [1 if p["rank"] and p["rank"] <= 3 else 0 for p in per_q]
 print(name, sum(hits3), bootstrap_ci(hits3))

I ran every line of this on my corpus. The full scripts, including the question list, are in the code pack that goes with this article.

Results

All scores are out of 32 questions. "Ctx3" is the average number of words in the top 3 chunks.

SetupChunkshit@1hit@3hit@5MRRCtx3
Fixed 100 words, no overlap1731324290.607291
Fixed 100 words, 15% overlap1961524290.624294
Fixed 200 words, no overlap911324280.597550
Fixed 200 words, 15% overlap1001725270.669593
Fixed 400 words, no overlap511727280.6981,051
Fixed 400 words, 15% overlap531824270.6951,103
Fixed 800 words, no overlap292224270.7581,958
Fixed 800 words, 15% overlap312025260.7272,002
Paragraph blocks, up to 200 words1081927290.729500
Paragraph blocks, 200 words + file name1082028290.742508
Paragraph blocks, up to 400 words541725270.6801,019
Headings, up to 200 words2331926280.708240
Headings, 200 words + path2332226280.773288
Headings, up to 400 words2192026280.726243
Headings, 400 words + path2192126280.760294
Headings, up to 800 words + path2162126280.755294

(Two paragraph-block variants with the file name at 400 words are omitted; they matched the plain 400-word row.)

What the results say

1. Top-3 recall is nearly flat, and the intervals prove it. Hit@3 ranges from 24 to 28 across every setup. The bootstrap intervals overlap heavily, for example 19 to 29 for fixed 100 words and 22 to 30 for headings. Anyone who reads "27 beats 24" here is reading noise.

2. Ranking quality does separate the strategies. Mean reciprocal rank moves more, from about 0.60 for small fixed windows to about 0.77 for heading-based chunks with a path. To check that it is not luck, I resampled the questions in pairs. Moving from fixed 200 words to headings up to 400 words with a path raised MRR by 0.163, with a 95 percent interval of 0.058 to 0.271. Moving from fixed 200 words to fixed 800 words gave +0.161 (0.055 to 0.275). Both intervals exclude zero.

3. Big chunks win on ranking, but you pay in context. Fixed 800-word chunks and heading-based chunks with a path reached almost the same MRR. The difference was +0.002 with an interval from -0.138 to 0.145, so they are statistically tied. The costs are not tied: the 800-word setup sent an average of 1,958 words to the model, and the heading-based setup sent 294. That is about 6.7 times more input for the same ranking quality. If you pay per token, this is the finding that matters.

4. Adding the heading path or file name was cheap and helped the top spot. At 200 words, adding the heading path raised hit@1 from 19 to 22 and MRR from 0.708 to 0.773, at a cost of about 48 extra words in the top 3 (240 to 288). Adding only the file name to paragraph blocks raised hit@3 from 27 to 28 and MRR from 0.729 to 0.742. These are small effects on a small test, but the cost is close to zero.

5. Fixed windows cut through code and tables. I counted chunks with an unclosed code fence. Fixed 200-word windows produced 16 of them out of 91 chunks, fixed 400-word windows 8 of 51, paragraph blocks 6 of 108 and heading-based chunks 0 of 219. In a runbook, a command split from its explanation is a broken answer, even if the keyword is present in the half you retrieved.

6. Overlap is not a free fix. It helped the 200-word fixed windows (hit@1 13 to 17) and did little or hurt elsewhere (hit@3 27 to 24 at 400 words). Chroma reports the same pattern: overlap lowers precision and matters most for small or weak setups.

7. Small-to-big retrieval did not help here. I also tested indexing small chunks (50, 100 or 200 words) and returning the whole parent section. Results were the same across child sizes: hit@1 22, hit@3 26, MRR 0.76 to 0.77, around 250 to 295 words of context. The reason is the corpus: the median section is only 55 words, so most sections are already small. On long narrative documents, this technique may behave differently. I have not tested that.

The questions that failed

Across the structure-aware setups, the same six questions missed the top 3 each time. Looking at them shows what chunk size cannot fix:

  • Vague questions. "Where is the project directory on the production server" has no unique word. The path appears in several documents, and chunks from other files scored about the same.
  • Competing sections. "Which endpoint shows whether Redis is connected" has the answer ranked 10th for a heading-based setup. The top four chunks came from four other documents that mention Redis more often.
  • Answers in a short parent section. For "which file manages the Redis client", the second-ranked chunk came from the right document, the "Health & Fallback" subsection, which mentions Redis often. The file path sits in the short intro paragraph under the parent heading, which ranked 14th. Splitting a section into subsections can separate the answer from the words that score highly.
  • Answers in a code block. For "make pm2 processes come back after a server reboot", the answer pm2 startup sits inside a command block under a heading that does not use the question's words.

These are retrieval problems, not chunk size problems. A reranker, hybrid search or query rewriting is the right tool. I cover the first two in Hybrid Search vs Vector Search for RAG.

Limits of this test

  • 32 questions is small. One question moves hit@3 by about 3 points, and the bootstrap only captures question-sampling noise, not corpus differences.
  • I wrote the questions after reading the documents, which can favor setups that match my wording.
  • BM25 only. A neural embedding model, as the Fraunhofer study shows, can prefer different sizes.
  • A hit means the answer phrase is present in a retrieved chunk. It does not prove a model could answer correctly from it.
  • The corpus is short technical documentation with many small sections. Long reports, legal text, PDFs or tables may need larger chunks.
  • Words are not tokens.

How to choose RAG chunk size for your own data

Follow this process and you will learn more than any tutorial can tell you.

  1. Classify your questions. Are they short facts (a setting, a number, a command) or explanations that need surrounding text? Facts favor 100 to 300 tokens. Explanations favor 500 to 1,000 tokens or whole sections.
  2. Look at the structure of your documents. If you have headings, use them. Fall back to a size limit inside long sections. If you have PDFs with pages, test page-level chunks as NVIDIA did.
  3. Write 30 to 50 real questions from support tickets, chat logs or search logs. Include vague ones. Record the file and a phrase that must appear in a correct chunk.
  4. Run three setups first: a recursive or paragraph-based splitter at about 200 tokens, the same at about 400 tokens, and heading-based chunks with the heading path added. Add overlap only if the first results show answers cut in half.
  5. Report four numbers: hit@1, hit@5, MRR and average words sent to the model. Add a bootstrap interval. If two setups overlap, pick the cheaper one.
  6. Read the failures. List every missed question and decide whether it is a chunking problem (answer split), a retrieval problem (needs hybrid or rerank) or a data problem (answer not in the docs).
  7. Repeat the test with your real embedding model. BM25 results do not transfer exactly.
  8. Freeze the test. Keep the questions in your repository and run them after every change to your parser, chunker or embedding model.

A practical default

If you need a starting point today and do not have time for a test:

Content typeChunkingNotes
Markdown or HTML docs with headingsBy heading, up to about 300 to 400 tokens, heading path added to each chunkNever split inside a code block or table
FAQs and support answersOne question and answer per chunkNatural unit, no overlap needed
Long articles and reports400 to 600 tokens, 10 percent overlapTest 1,000 if questions need wide context
PDFs with pagesTest page-level against 512 and 1,024 tokensPage boundaries often match topics
Source codeBy function or classKeep the file path in each chunk
Chat logs and transcriptsBy speaker turn or topic windowAdd timestamps and speaker as metadata

Store the file name, section title, URL and position with each chunk. You will need them for citations, filtering and debugging.

Beyond chunk size: what else moves the needle

  • Contextual headers. Prepend the document title and heading path. It is free, and my test showed a small gain in top-1 hits. For a stronger version, Anthropic describes using a model to write a short situating context for each chunk before indexing.
  • Hybrid retrieval. Combine keyword and vector search so exact terms and paraphrases both work.
  • Reranking. Rerank the top 20 to 50 results and send fewer, better chunks. That attacks the cost problem directly.
  • Query rewriting. Expand vague questions with the missing context, such as the product or file the user means.
  • Metadata filters. Filter by product, version or date before ranking, which fixes the "same words in many documents" failure above.
  • Parent-child retrieval. Index small pieces and return the parent section. My corpus did not benefit, but long documents may.

For a complete pipeline around these steps, including retries and evaluation, read the production RAG pipeline guide. If you are ingesting a website, the RAG FAQ pipeline with sitemap, GPT-4o and Pinecone shows an ingestion flow you can pair with the chunker above. And if your question is about remembering a user rather than finding a document, see AI Memory vs RAG: Which Should You Build?.

Common mistakes

  • Copying a default chunk size from a library without testing it. One study found a popular 800 token, 400 overlap default scoring worst on most precision measures.
  • Judging a change on five hand-picked questions.
  • Reporting hit@3 only. It hides ranking differences and context cost.
  • Splitting code blocks, tables and lists in the middle.
  • Using the same chunk size for every document type.
  • Adding overlap everywhere. It costs storage and precision.
  • Choosing a semantic chunker without comparing it to a simple recursive splitter on your own data. The Vectara study suggests the gain is often small.
  • Forgetting to re-run the test after switching the embedding model.

Frequently asked questions

What is the best chunk size for RAG? There is no single best value. A good starting range is 200 to 400 tokens, or structure-based chunks that follow your headings. Confirm it with a labeled set of your own questions.

Should I use tokens or words? Use tokens to budget cost, since models charge per token. Words are fine for experiments. In English, one word is about 1.3 tokens, but code and other languages differ.

How much overlap should I use? Start with none. Add 10 to 15 percent if you see answers cut across chunk boundaries or if you use a small embedding model. In my test overlap helped 200-word windows and hurt others, and Chroma found it lowers precision.

Are semantic chunkers worth it? Often not by themselves. A Vectara study found fixed-size chunking was best on three of five evidence retrieval datasets, with tiny gaps elsewhere. Test a simple recursive splitter first.

Does chunk size matter if I use a reranker? Yes. A reranker can only reorder what the first stage retrieves, so the answer must be in the candidate chunks. Smaller, cleaner chunks also reduce what you send to the final model.

How many test questions do I need? At least 30 to 50 for a rough comparison, and more to detect small differences. Always report an interval, since with 32 questions I could separate ranking quality but not top-3 recall.

Does this work for Hindi or Gujarati documents? The method does, but chunk size in words or tokens changes by language, and tokenizers split Indic scripts into more tokens. Test with a tokenizer and an embedding model that supports the language.

Key takeaways

  • Published studies disagree on the best chunk size because question types and models differ. Match chunking to your questions.
  • In my 32-question BM25 test, top-3 recall was flat, but ranking quality separated structure-aware chunking from fixed windows with a clear margin (MRR +0.16, 95 percent interval 0.06 to 0.27).
  • Large chunks matched structured chunking on ranking but cost about 6.7 times more context.
  • Adding the heading path to each chunk is nearly free and gave a small gain.
  • Fixed windows cut code blocks and tables. Respect structure where you have it.
  • Overlap is a targeted fix, not a default.
  • Failures were mostly vague questions and competing sections, which need hybrid search, reranking or filters, not a new chunk size.
  • Keep a frozen question set and rerun it whenever anything in the pipeline changes.
SOURCES & REFERENCES
NEXT IN SERIES

Production RAG Pipeline Architecture: A Practical Guide

Most RAG demos work and most RAG products fail. Here is the full production architecture, the six stages that matter, how to measure quality, and the mistakes that quietly ruin answers.

Continue Reading