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.
_10type Chunk = {_10 id: string;_10 source: string; // file path or URL_10 heading: string; // "Billing > Refunds"_10 position: number; // order within the document_10 content: string; // breadcrumb + text, which is what gets embedded_10};
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.
_22type Section = { heading: string; text: string };_22_22function splitByHeading(markdown: string): Section[] {_22 const sections: Section[] = [];_22 let heading = '';_22 let lines: string[] = [];_22 const flush = () => {_22 const text = lines.join('\n').trim();_22 if (text) sections.push({ heading, text });_22 lines = [];_22 };_22 for (const line of markdown.split('\n')) {_22 if (/^#{1,3}\s/.test(line)) {_22 flush();_22 heading = line.replace(/^#+\s*/, '');_22 } else {_22 lines.push(line);_22 }_22 }_22 flush();_22 return sections;_22}
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.
_20const MAX_CHARS = 2400; // about 600 tokens_20_20function packParagraphs(text: string, max = MAX_CHARS): string[] {_20 const paragraphs = text.split(/\n\s*\n/);_20 const chunks: string[] = [];_20 let current: string[] = [];_20 let size = 0;_20 for (const p of paragraphs) {_20 if (current.length && size + p.length > max) {_20 chunks.push(current.join('\n\n'));_20 const last = current[current.length - 1];_20 current = [last]; // overlap: carry the previous paragraph_20 size = last.length;_20 }_20 current.push(p);_20 size += p.length;_20 }_20 if (current.length) chunks.push(current.join('\n\n'));_20 return chunks;_20}
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.
_11function toChunks(source: string, title: string, markdown: string): Chunk[] {_11 return splitByHeading(markdown).flatMap((section) =>_11 packParagraphs(section.text).map((text, i) => ({_11 id: `${source}#${section.heading}#${i}`,_11 source,_11 heading: section.heading,_11 position: i,_11 content: `${title} > ${section.heading}\n\n${text}`,_11 })),_11 );_11}
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.
_10CREATE TABLE chunks (_10 id bigserial PRIMARY KEY,_10 source text NOT NULL,_10 heading text,_10 position int NOT NULL,_10 content text NOT NULL,_10 embedding vector(1024)_10);_10CREATE 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
#quick question
Was this resource helpful?
by Danny