Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Retrieval (RAG)AI guideIntermediate#rag#chunking#ingestion#embeddings
Frame · ai-engineering / rag / 03-chunking-strategies.mdGuide 015 / 103

Chunking strategies

Chunking is how you cut documents into the passages that get embedded, retrieved and pasted into the prompt. It feels like a preprocessing detail, but the chunk is the unit of everything downstream: it is what the embedding represents, what the reranker scores, what the model reads and what the citation points to. This doc walks through the main strategies, from a fixed-size splitter to late chunking, and how to choose between them with data instead of folklore.

Why it matters

An embedding is a single summary vector of a passage. If the passage covers three topics, the vector is a blurry average of all three and matches none of them well. If the passage is a lonely sentence like "This limit does not apply to contractors", the vector has no idea what "this limit" was. Good chunks are self-contained enough to be understood alone and focused enough to be about one thing.

Chunk size also sets your token budget. Retrieving five 200-token chunks and five 1,000-token chunks are very different prompts in cost and in how much irrelevant text the model has to ignore.

Chroma's 2024 technical report "Evaluating Chunking Strategies for Retrieval" measured this at the token level (precision, recall and IoU of the retrieved text against the relevant excerpts). Its headline findings are useful: the chunking choice has a large effect on both accuracy and efficiency, some popular splitters perform poorly at their default settings, and a well-tuned recursive character splitter is a strong baseline.

How it works

The common strategies, roughly in order of effort:

  • Fixed-size (token or character) splitting. Cut every N tokens with some overlap. Simple and predictable, but happily cuts mid-sentence and mid-table.
  • Recursive splitting. Try to split on the largest separator first (blank lines, then newlines, then sentences, then words) and only fall back to smaller separators when a piece is still too big. This respects paragraph boundaries most of the time and is the default in LangChain and similar libraries.
  • Structure-aware splitting. Use the parsed document structure: split by headings, keep lists and tables intact, and prepend the heading path to each chunk. For Markdown, HTML and parsed PDFs this is usually the best cheap upgrade.
  • Semantic splitting. Embed sentences, and start a new chunk where similarity between neighbouring sentences drops. Chroma's report also proposes a cluster-based semantic chunker. These can help on long unstructured prose but cost an embedding pass at ingestion.
  • LLM-based splitting. Ask a model to choose split points or write propositions. Highest cost, and not automatically better on precision.
  • Late chunking. Proposed by Jina AI (Günther et al., 2024). Instead of embedding each chunk separately, run a long-context embedding model over the whole document (or a large window), then mean-pool the token embeddings within each chunk's span. Every chunk vector is computed with the full document in view, so "this limit" carries information about the surrounding text. It requires a model that exposes token-level outputs and has a long enough context window.
Rendering diagram…

Size and overlap

There is no universal right size. A few hundred tokens is a common starting point for prose, with an overlap of around 10 to 20 percent so a sentence that straddles a boundary appears whole in at least one chunk. FAQs and ticket data often work best with one item per chunk regardless of length. Legal and technical text with long definitions may need larger chunks or parent-child retrieval (below). Treat all of these as hypotheses to test on your eval set.

Parent-child (small-to-big) retrieval

A useful pattern decouples what you search from what you send. Index small child chunks for precise matching, but store a pointer to a larger parent (the section or page). At query time, retrieve children and pass their parents (deduplicated) to the model. You get precise retrieval and enough surrounding context to answer.

Reference architecture

Rendering diagram…

The key move is "prepend title and heading path". It is cheap, it works with any embedding model, and it addresses the same lost-context problem that late chunking and contextual retrieval solve more expensively.

Code

A structure-first splitter in TypeScript using LangChain's text splitters: split on Markdown headings, then recursively split long sections, and carry the heading path into each chunk.

import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";

type Chunk = { id: string; text: string; headingPath: string };

const splitter = new RecursiveCharacterTextSplitter({
  chunkSize: 1200, // characters, roughly 250-300 tokens of English
  chunkOverlap: 150,
});

export async function chunkMarkdown(docId: string, markdown: string): Promise<Chunk[]> {
  const sections = markdown.split(/\n(?=#{1,3} )/); // split before h1-h3
  const chunks: Chunk[] = [];
  const path: string[] = [];

  for (const section of sections) {
    const match = section.match(/^(#{1,3}) (.+)/);
    if (match) {
      const depth = match[1].length;
      path.splice(depth - 1, path.length, match[2].trim());
    }
    const headingPath = path.join(" > ");
    const pieces = await splitter.splitText(section);
    pieces.forEach((piece, i) => {
      chunks.push({
        id: `${docId}:${chunks.length}`,
        headingPath,
        text: headingPath ? `${headingPath}\n\n${piece}` : piece,
      });
    });
  }
  return chunks;
}

RecursiveCharacterTextSplitter also has a fromLanguage("markdown", ...) factory with Markdown-aware separators if you would rather not hand-roll the heading split.

Trade-offs and pitfalls

  • Characters are not tokens. Splitters often count characters by default. If your embedding model truncates at a token limit, overly long chunks get silently cut. Use a token-based length function or leave headroom.
  • Overlap duplicates results. Neighbouring chunks with heavy overlap can both rank in the top k and waste prompt space. Deduplicate or merge adjacent hits.
  • Semantic chunkers can produce tiny or huge chunks. Enforce minimum and maximum sizes.
  • Tables and code need special handling. Never split a table row or a function in half. Keep them whole or split with the header repeated.
  • Late chunking ties you to a model. It needs token-level embeddings and a long context window, so it is not available with every embedding API.
  • Changing chunking means re-indexing everything. Version your chunking config alongside the index so you know which one produced which vectors.
  • Measure, do not guess. The difference between two splitters is often smaller than the difference between a good and a bad parameter setting for one of them.

Checklist

  • Start with structure-aware splitting plus a recursive fallback, and prepend title and heading path.
  • Count length in tokens that match your embedding model's limit.
  • Use 10 to 20 percent overlap for prose, and none for naturally atomic items like FAQs.
  • Keep tables, lists and code blocks intact.
  • Consider parent-child retrieval when answers need more context than a good search unit holds.
  • Try late chunking or contextual retrieval only after the cheap fixes, and compare on your eval set.
  • Version chunking parameters with the index.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.