---
title: "How do I chunk documents for retrieval?"
description: "Split on structure (headings, paragraphs, code blocks), aim for 300 to 800 tokens with 10 to 20 percent overlap, prefix each chunk with its title, and store metadata."
url: https://www.danny.engineering/answer/ai/how-do-i-chunk-documents-for-retrieval
author: Danny
published: 2026-12-03T00:00:00.000Z
updated: 2026-12-03T15:35:00.000Z
tags: ["AI"]
---

# How do I chunk documents for retrieval?

## The short answer


A chunk needs to be small enough that one embedding represents one idea, and large enough that the passage still makes sense on its own. Start at 300 to 800 tokens (roughly 1,200 to 3,200 characters) with 10 to 20 percent overlap between neighbours. Split along the document's own structure, headings first, then paragraphs, never through the middle of a code block, rather than every N characters. Prepend a short breadcrumb such as "Billing > Refunds" to each chunk so it carries its context, and store the source, heading and position next to the text.


```typescript
type Chunk = {
  id: string;
  source: string;   // file path or URL
  heading: string;  // "Billing > Refunds"
  position: number; // order within the document
  content: string;  // breadcrumb + text, which is what gets embedded
};
```


## Why it matters


An embedding is a single vector for the whole chunk, so it averages the meaning of everything in it. Make the chunk too big and it covers several topics at once: the vector points nowhere in particular, retrieval gets vaguer, and when the chunk is retrieved it drags three irrelevant paragraphs into the prompt with the one you wanted. Make it too small and a sentence like "This setting defaults to 30 days" loses whatever "this setting" referred to. The embedding is vague for a different reason, and even when the chunk is retrieved the model cannot use it.


Overlap is insurance against bad boundaries. A sentence that straddles two chunks appears in both, so a question about it will match one of them. It costs a little storage and some duplicate results, which you dedupe.


Remember that the chunk is also what ends up in the prompt. Five chunks of 600 tokens is 3,000 tokens of context, which is cheap and easy for the model to read. Chunk size is about retrieval quality and prompt quality at once.


For sizing you do not need an exact token count. One token is about four characters of English, so a character budget is close enough; code tokenises less efficiently, so give it more room.


## How to do it


### Split on structure first


Documents already tell you where ideas begin and end. Markdown has headings; HTML has `h1` to `h3`, `p` and `pre`; source code has functions. Use those boundaries before you fall back to anything mechanical. This sketch splits Markdown into sections by heading and remembers the heading for each.


```typescript
type Section = { heading: string; text: string };

function splitByHeading(markdown: string): Section[] {
  const sections: Section[] = [];
  let heading = '';
  let lines: string[] = [];
  const flush = () => {
    const text = lines.join('\n').trim();
    if (text) sections.push({ heading, text });
    lines = [];
  };
  for (const line of markdown.split('\n')) {
    if (/^#{1,3}\s/.test(line)) {
      flush();
      heading = line.replace(/^#+\s*/, '');
    } else {
      lines.push(line);
    }
  }
  flush();
  return sections;
}
```


A fenced code block should stay whole. If one is longer than your limit, let it be an oversized chunk on its own rather than cutting it; half a function is useless to both the embedding and the model.


### Pack paragraphs when a section is too long


A section under a heading can still run to thousands of words. Split it on blank lines and pack paragraphs into chunks up to your budget, carrying the last paragraph forward as the overlap.


```typescript
const MAX_CHARS = 2400; // about 600 tokens

function packParagraphs(text: string, max = MAX_CHARS): string[] {
  const paragraphs = text.split(/\n\s*\n/);
  const chunks: string[] = [];
  let current: string[] = [];
  let size = 0;
  for (const p of paragraphs) {
    if (current.length && size + p.length > max) {
      chunks.push(current.join('\n\n'));
      const last = current[current.length - 1];
      current = [last]; // overlap: carry the previous paragraph
      size = last.length;
    }
    current.push(p);
    size += p.length;
  }
  if (current.length) chunks.push(current.join('\n\n'));
  return chunks;
}
```


### Prepend a breadcrumb


"Refunds are processed within five working days" means something quite different under "Billing" than under "Returns of faulty hardware". Put the document title and heading path at the top of each chunk before embedding it, and store the same string so what you compare is what you embedded.


```typescript
function toChunks(source: string, title: string, markdown: string): Chunk[] {
  return splitByHeading(markdown).flatMap((section) =>
    packParagraphs(section.text).map((text, i) => ({
      id: `${source}#${section.heading}#${i}`,
      source,
      heading: section.heading,
      position: i,
      content: `${title} > ${section.heading}\n\n${text}`,
    })),
  );
}
```


Keep the breadcrumb short. A hundred characters of path on a 300-token chunk starts to skew the embedding towards the path.


### Store metadata with each chunk


The text alone is not enough. Store where it came from and where it sits.


```sql
CREATE TABLE chunks (
  id bigserial PRIMARY KEY,
  source text NOT NULL,
  heading text,
  position int NOT NULL,
  content text NOT NULL,
  embedding vector(1024)
);
CREATE INDEX ON chunks (source);
```


With `source` you can show a citation and, when a document changes, delete its chunks and re-insert them in one transaction. With `position` you can fetch the neighbours of a retrieved chunk at answer time to widen the context without making every chunk bigger.


### Evaluate with real questions


Chunking is the cheapest part of a retrieval pipeline to change and often the biggest lever. Collect twenty to fifty questions real users asked, note which passage answers each, and measure how often that passage appears in the top five results. Change one variable at a time (size, overlap, breadcrumb on or off) and keep what improves the number. Guessing at a chunk size without this is just guessing.


## Common pitfalls

- **Splitting every N characters.** It cuts sentences, code and tables in half and ignores the structure the author gave you. Use it only as the last fallback for a paragraph that is itself too long.
- **Chunks with no context.** A paragraph that says "it" and "this option" with no heading is hard to retrieve and hard to use. The breadcrumb fixes most of this.
- **Cutting through code blocks and tables.** Keep them whole, even if that means an oversized chunk. Half a table is noise.
- **Too much overlap.** At 50 percent overlap every passage is stored twice and your top five results contain the same text three times. Stay around 10 to 20 percent and dedupe by source and position.
- **Forgetting re-indexing.** When a document changes, its old chunks must go. Delete by `source`, re-chunk, re-embed and re-insert; do not append.
- **Embedding page furniture.** Navigation menus, footers and cookie banners scraped from HTML become chunks that match everything. Strip them before chunking.

## Related reading

- [Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting)
- [pgvector](https://github.com/pgvector/pgvector)
- [String.prototype.split() on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)
