Chunking strategies
Split documents into retrievable pieces that are each about one thing yet carry enough context to answer; chunk size is a precision-vs-context trade-off you settle with evals, not defaults.
Analogy: Cutting a textbook into index cards: one card per sentence loses the context, one card per chapter hides the fact you need. You want one idea per card, with the chapter title written on top.
How it works
- Each chunk gets one vector, so a chunk that mixes several topics matches none of them well.
- Small chunks (~100–200 tokens) match precisely but may lack context; large ones (1,000+) blur topics and burn tokens.
- Default to recursive splitting at ~300–800 tokens with 10–20% overlap: paragraphs first, sentences only if needed.
- Structure-aware chunking splits on headings and tables and prepends the heading path, like "Policies > On-call > Mexico".
- Parent-child gets both: match on small chunks, then hand the LLM their whole parent section.
Check yourself
Answer to mark it learned; your answers aren't scored.
You re-chunked a policy wiki from 2,000 to ~400 tokens. Factoid questions improved a lot, but "Summarize the on-call policy" now gets disconnected fragments. Best next step?
Go deeper
Full explanation
Chunking splits parsed documents into the units you embed, retrieve and paste into the prompt. Each chunk gets one vector, so size is a trade-off:
- Small (~100–200 tokens): sharp embeddings and precise matches, but the chunk may lack the context to answer ("it grew 4%" — what did?).
- Large (1,000+ tokens): rich context, but the vector averages several topics and matches none of them well, and it burns prompt tokens.
Strategies, in the order I'd try them:
- Fixed-size with overlap: e.g. 300–800 tokens, 10–20% overlap so a sentence cut at a boundary survives whole in one chunk. Baseline.
- Recursive: split on paragraphs, then lines, sentences, words, only as far as needed to fit. The sensible default.
- Structure-aware: split on headings, sections and table boundaries; prepend the heading path ("Policies > On-call > Mexico"). Needs good Document ingestion & parsing.
- Semantic: cut where similarity between adjacent sentences drops. More compute; reported gains over fixed-size are inconsistent.
- Parent-child (small-to-big): match on small chunks, hand the LLM their parent section.
- Late chunking: embed the whole document with a long-context model, then pool token vectors per chunk, so each chunk keeps its surroundings.
Pick with Evaluating RAG on your own questions; Contextual retrieval attacks the same lost-context problem.
Code A recursive, token-aware splitter with overlap
import tiktoken
enc = tiktoken.get_encoding("cl100k_base") # use your embedding model's tokenizer
SEPARATORS = ["\n\n", "\n", ". ", " "] # paragraphs -> lines -> sentences -> words
# Production equivalent: langchain_text_splitters.RecursiveCharacterTextSplitter
def ntok(text: str) -> int:
return len(enc.encode(text))
def split(text: str, max_tokens: int = 500, seps=SEPARATORS) -> list[str]:
if ntok(text) <= max_tokens:
return [text]
if not seps: # nothing left to split on: hard cut by tokens
ids = enc.encode(text)
return [enc.decode(ids[i:i + max_tokens]) for i in range(0, len(ids), max_tokens)]
sep, finer = seps[0], seps[1:]
chunks, buf = [], ""
for piece in text.split(sep):
merged = buf + sep + piece if buf else piece
if ntok(merged) <= max_tokens:
buf = merged # greedily pack small pieces up to the limit
continue
if buf:
chunks.append(buf)
if ntok(piece) <= max_tokens:
buf = piece
else: # one piece is still too big: recurse with finer separators
chunks += split(piece, max_tokens, finer)
buf = ""
return chunks + [buf] if buf else chunks
def add_overlap(chunks: list[str], overlap: int = 75) -> list[str]:
# Prefix each chunk with the previous one's tail so boundary sentences survive
tails = [enc.decode(enc.encode(c)[-overlap:]) for c in chunks[:-1]]
return chunks[:1] + [t + " " + c for t, c in zip(tails, chunks[1:])]Real example
An internal wiki chunked at 2,000 tokens returns the right page for "What's the on-call pay in Mexico?", but the answer is one line in a table covering eight countries, so the vector is dominated by the others and the chunk ranks #12. Re-chunking at ~400 tokens with the heading path prepended ("Compensation > On-call > Mexico") moves it to #1. Now "Summarize the on-call policy" gets fragments, so the team switches to parent-child: match on 400-token children, send the 2,000-token parent section.
Trade-offs +3 · −3
+ You gain
- Cheap lever: re-chunking costs a re-embed, often a few dollars, and can move recall a lot.
- Structure-aware chunks give clean citations (section, page) and self-explanatory context.
- Parent-child gets precise matching and full context at the same time.
− You pay
- No universal size: the optimum depends on documents, queries and embedding model.
- Every change means re-embedding and re-indexing the whole corpus.
- Semantic and late chunking add compute and complexity for gains you must prove on your data.
Use it when
Whenever documents are longer than what you want to retrieve, which is nearly always. Invest more when documents are long, structured (manuals, policies, contracts) or mix many topics per page.
Avoid it when
Short self-contained items — FAQ entries, product records, tickets, chat messages — are already natural chunks: index each one whole instead of splitting it.
Numbers to know 4
- Common starting point: 300–800 tokens per chunk with 10–20% overlap.
- Parent-child: children ~100–400 tokens, parents ~1,000–2,000 tokens or a whole section.
- Many open embedding models cap input at 512 tokens (some at 256); longer text is silently truncated.
- Anthropic's contextual retrieval prepends ~50–100 tokens of generated context to each chunk.
Common pitfalls 4
- Splitting mid-table or mid-list so neither half can answer the question.
- Sizing in characters while the embedding model's limit is in tokens, then losing the tail to truncation.
- Orphan chunks like "The limit is 30 days" with no product or policy named: prepend title and headings.
- Copying a size from a blog post instead of sweeping 2–3 sizes on your eval set.
Interview questions 2
Answer out loud first, then reveal.
How do you pick a chunk size?Show answer
Empirically. I start with recursive, structure-aware splitting around 400–500 tokens, ~15% overlap and the heading path prepended. Then I sweep two or three sizes, say 250, 500 and 1,000, on a labelled set of real questions and compare recall@k and answer quality. Small chunks usually win on factoid questions, large ones on summaries and how-tos; if I need both, I use parent-child: retrieve small, return the parent. The trade-off I'm watching is match precision versus context in the prompt, and token cost.
What is late chunking, and when would it help?Show answer
Normal chunking embeds each chunk in isolation, so a chunk saying "its revenue grew 20%" has lost who "it" is. Late chunking runs the whole document, up to the model's window (e.g. 8k tokens), through a long-context embedding model first, then mean-pools the token embeddings inside each chunk's span. Each vector is conditioned on its surroundings. It helps on documents full of back-references. The catch: you need token-level outputs, which most embedding APIs don't expose. Contextual retrieval gets a similar effect with an LLM-written prefix, at higher indexing cost.