How-To Guide

Sizing RAG Document Chunks and Overlap Windows

Choose chunk size, overlap windows, and structural markdown splitters to balance retrieval recall, precision, and embedding latency in RAG pipelines.

On this page

  1. Why Chunk Geometry Dictates Retrieval Quality
  2. Choosing Chunk Size and Overlap Ratio
  3. Implementing Structure-Aware Recursive Splitting
  4. Parent-Document Retrieval and Deduplication
  5. Boundary Pitfalls: Tables, Code Blocks, and Multilingual Text
  6. Benchmarking and Verifying Chunk Windows

Why Chunk Geometry Dictates Retrieval Quality

When a Retrieval-Augmented Generation (RAG) system hallucinates or misses an answer that clearly sits inside your knowledge base, teams often blame the generator LLM or rewrite the system prompt. In practice, poor retrieval recall caused by naive text chunking accounts for a larger share of failures. Every embedding model maps a variable-length passage into one fixed-dimension vector. If a chunk spans three unrelated sections—authentication, rate limits, and billing webhooks—its single vector sits halfway between all three topics and ranks poorly for queries targeting any one of them.

Conversely, slicing text into tiny 50-token fragments produces sharp topic matching at the cost of severing reasoning chains. A sentence reading "Do not enable this flag in multi-region clusters" loses all value if the preceding paragraph naming the flag sits in chunk 41 while the warning lands in chunk 42. Designing chunk geometry is therefore an engineering trade-off across semantic focus, boundary continuity, vector index footprint, and prompt context budget.

Choosing Chunk Size and Overlap Ratio

Two dimensions define any sliding splitter: target chunkSize and overlap. Larger chunks (600–1,000 tokens) retain local narrative and code examples intact, making them effective for broad conceptual questions or legal clauses where context surrounds every rule. Smaller chunks (200–400 tokens) excel at factoid lookup, error-code matching, and FAQ retrieval where diluting a specific detail inside surrounding prose weakens cosine ranking.

Overlap repeats a trailing slice of chunk N at the start of chunk N + 1 so facts spanning a split boundary appear intact in at least one vector. Setting overlap between 10% and 20% protects boundary continuity without exploding storage costs. Pushing overlap to 50% doubles embedding API bills, doubles vector index memory, and crowds top-K retrieval slots with near-duplicate slices of the exact same paragraph unless you run parent-document deduplication. You can inspect exact split indices, boundary cuts, and overlap character counts interactively in the Interactive RAG Chunk Visualizer.

Do not forget hybrid search metadata filtering when designing your chunk schema. Store docId, headingPath, updatedAt, and tenant access-control tags alongside every chunk vector rather than stuffing metadata strings into the raw prose blindly. While prepending the heading breadcrumb improves semantic embeddings for short paragraphs, stuffing 20 JSON tags into every chunk wastes embedding context and tilts similarity scores toward boilerplate labels. Keep access filters and freshness timestamps as structured database columns indexed separately from the vector column so pre-filtering and post-filtering stay exact.

Implementing Structure-Aware Recursive Splitting

Fixed character slicing (text.slice(i, i + 1500)) routinely slices right through the middle of words, inline URLs, and fenced code blocks. A production chunker applies hierarchical separators first: split by ## / ### markdown headings, then double newlines (paragraphs), then sentences, and only split raw characters if a single monolithic token sequence (like minified JSON or a huge log line) exceeds chunkSize. Prepending the active heading breadcrumb (# Auth > ## Token Rotation) to each chunk ensures the embedding encodes section context even when the body paragraph uses pronouns.

export interface RagChunk {
  index: number;
  headingPath: string;
  text: string;
  startOffset: number;
  endOffset: number;
  approxTokens: number;
}

interface ChunkConfig {
  maxChars: number;
  overlapChars: number;
}

function estimateTokens(text: string): number {
  const cjk = (text.match(/[\u4e00-\u9fff]/g) ?? []).length;
  const nonCjk = text.length - cjk;
  return Math.ceil(nonCjk / 4 + cjk * 1.4);
}

function splitParagraphsWithOffsets(sectionText: string, baseOffset: number) {
  const units: Array<{ text: string; start: number; end: number }> = [];
  const regex = /[^\n]+(?:\n(?!\n)[^\n]+)*/g;
  let match: RegExpExecArray | null;
  while ((match = regex.exec(sectionText)) !== null) {
    units.push({
      text: match[0].trim(),
      start: baseOffset + match.index,
      end: baseOffset + match.index + match[0].length,
    });
  }
  return units;
}

export function chunkMarkdownDocument(
  markdown: string,
  config: ChunkConfig = { maxChars: 1400, overlapChars: 200 },
): RagChunk[] {
  if (config.overlapChars >= config.maxChars) {
    throw new Error("overlapChars must be strictly smaller than maxChars");
  }

  const lines = markdown.split(/\r?\n/);
  const blocks: Array<{ headingPath: string; body: string; offset: number }> = [];
  const headingStack: string[] = [];
  let currentLines: string[] = [];
  let blockOffset = 0;
  let runningOffset = 0;

  const flushBlock = () => {
    const body = currentLines.join("\n").trim();
    if (body.length > 0) {
      blocks.push({
        headingPath: headingStack.join(" > ") || "Document Root",
        body,
        offset: blockOffset,
      });
    }
    currentLines = [];
  };

  for (const line of lines) {
    const headingMatch = line.match(/^(#{1,3})\s+(.+)$/);
    if (headingMatch) {
      flushBlock();
      const depth = headingMatch[1].length;
      headingStack.splice(depth - 1);
      headingStack[depth - 1] = headingMatch[2].trim();
      blockOffset = runningOffset + line.length + 1;
    } else {
      currentLines.push(line);
    }
    runningOffset += line.length + 1;
  }
  flushBlock();

  const chunks: RagChunk[] = [];
  for (const block of blocks) {
    const units = splitParagraphsWithOffsets(block.body, block.offset);
    let buffer: typeof units = [];
    let bufferLen = 0;

    const emitBuffer = () => {
      if (buffer.length === 0) return;
      const bodyText = buffer.map((u) => u.text).join("\n\n");
      const content = `[${block.headingPath}]\n${bodyText}`;
      chunks.push({
        index: chunks.length,
        headingPath: block.headingPath,
        text: content,
        startOffset: buffer[0].start,
        endOffset: buffer[buffer.length - 1].end,
        approxTokens: estimateTokens(content),
      });
    };

    for (const unit of units) {
      if (bufferLen + unit.text.length > config.maxChars && buffer.length > 0) {
        emitBuffer();
        // Retain trailing units up to overlapChars
        const carry: typeof units = [];
        let carryLen = 0;
        for (let i = buffer.length - 1; i >= 0; i--) {
          if (carryLen + buffer[i].text.length > config.overlapChars && carry.length > 0) break;
          carry.unshift(buffer[i]);
          carryLen += buffer[i].text.length + 2;
        }
        buffer = carry;
        bufferLen = carryLen;
      }
      buffer.push(unit);
      bufferLen += unit.text.length + 2;
    }
    emitBuffer();
  }

  return chunks;
}

Parent-Document Retrieval and Deduplication

A powerful extension once basic chunking works is parent-child retrieval: index compact 300-token child chunks for razor-sharp semantic search, then fetch the surrounding 1,200-token parent section (or sibling chunks index - 1 and index + 1) from PostgreSQL before assembling the prompt. This pattern separates the retrieval unit from the generation unit so you never sacrifice context completeness to get sharp vector similarity. Whenever two top-K hits overlap across the same documentId, merge their [startOffset, endOffset] ranges before sending the prompt so the LLM does not read repeated paragraphs or waste context tokens.

export function mergeOverlappingChunks(
  hits: Array<{ docId: string; startOffset: number; endOffset: number; text: string }>,
) {
  const sorted = [...hits].sort((a, b) =>
    a.docId === b.docId ? a.startOffset - b.startOffset : a.docId.localeCompare(b.docId),
  );
  const merged: typeof sorted = [];
  for (const hit of sorted) {
    const prev = merged[merged.length - 1];
    if (prev && prev.docId === hit.docId && hit.startOffset <= prev.endOffset) {
      prev.endOffset = Math.max(prev.endOffset, hit.endOffset);
      if (!prev.text.includes(hit.text)) {
        prev.text = `${prev.text}\n...\n${hit.text}`;
      }
    } else {
      merged.push({ ...hit });
    }
  }
  return merged;
}

Boundary Pitfalls: Tables, Code Blocks, and Multilingual Text

Real enterprise corpora routinely break naive splitters in four ways:

  • Fenced code blocks and Markdown tables: Splitting inside a 40-line SQL migration or Markdown pricing table strips column headers from lower rows, making retrieved fragments unintelligible. Treat fenced code blocks and tables as atomic units up to an emergency max threshold, or duplicate the Markdown table header row into every split piece.
  • Character limits vs CJK token density: A 1,500-character limit equals roughly 375 English tokens, yet 1,500 Chinese or Japanese characters can exceed 2,000 tokens depending on the tokenizer. Always calibrate chunk sizing against your embedding model’s tokenizer for every language in your corpus.
  • Zero-progress infinite loops: If a caller passes overlapChars >= maxChars or an unsplittable 5,000-character URL fails to shrink across recursive steps, naive loop splitters either enter an infinite loop or emit thousands of shifted duplicates. Enforce overlapChars < maxChars and monotonic forward index progression.
  • Stale orphaned chunks on re-index: Updating a document from 12 chunks down to 9 leaves stale vectors 9..11 in the vector table unless you delete all existing rows for doc_id inside the same transaction before inserting the new chunks.

Benchmarking and Verifying Chunk Windows

Avoid tuning chunk sizes purely by visual inspection. Test candidate sizes (256, 512, 768 tokens) and overlap percentages (0%, 10%, 20%) systematically:

  1. Preview sample documents inside the Interactive RAG Chunk Visualizer to verify headings, paragraphs, and code samples are not severed awkwardly.
  2. Build an evaluation set of 40–100 real user questions paired with the exact document ID and character spans containing the answers.
  3. Measure recall@5, MRR (Mean Reciprocal Rank), and total prompt tokens consumed per query across your candidate split configurations.
  4. Assert in automated unit tests that every generated chunk satisfies approxTokens <= modelLimit, startOffset < endOffset, and overlapChars >= maxChars throws immediately. Also verify re-indexing a shortened document deletes orphaned trailing chunks inside the same database transaction before inserting replacements.

FAQ

What is a good starting chunk size and overlap for technical documentation?
For English API docs and engineering manuals, 350 to 500 tokens (roughly 1,400 to 2,000 characters) with 10 to 15 percent overlap (40 to 75 tokens) usually balances precision and context continuity well before domain tuning.
Why can oversized chunks hurt RAG accuracy even when the embedding model supports 8,192 tokens?
Compressing an entire multi-topic page into a single dense vector averages unrelated concepts together, lowering cosine similarity against specific user queries and pulling noisy context into the LLM prompt.
Should I count chunk lengths in characters, words, or model tokens?
Count in tokens (or token-calibrated characters per script, since CJK characters carry far more tokens per character than English) so chunks never get silently truncated by the embedding API.

Related Examples

Interactive Tools for This Topic