RAG Document Chunking: Fixed-Overlap, Sentence-Boundary & Contextual
Why bad chunking ruins even the best LLM: sliding-window overlap math (stride = size − overlap), sentence-boundary & recursive markdown splitters, Parent-Document retrieval, and Anthropic's Contextual Retrieval.
Document Chunking splits long PDFs and articles into retrieval-sized passages using fixed-size overlap, sentence boundaries, or contextual headers before embedding.
Embedding an entire 40-page PDF blurs its vector into mush, while slicing mid-sentence cuts facts in half; smart chunking is the #1 lever for RAG recall.
80% of 'LLM hallucination' bugs in RAG are actually chunking bugs — if the retriever chops a negation or drops the company name, no 400B LLM can guess the missing half!
Picking the right chunk size (~256–512 tokens), 10%–20% overlap, and structure-aware splitting (Markdown headers, AST code blocks, PDF tables) is the highest-ROI lever in RAG engineering.
Anthropic showed that simply prepending a 1-sentence LLM-generated document context header to every chunk before indexing cuts failed retrievals by 49% (and 67% with Reranking!).
Hands-on RAG interview favorite: 'Implement both a Fixed-Overlap Chunker and a Sentence-Boundary Chunker, and explain how you would chunk a 200-page financial PDF with tables!'
What happens to a single 1536-dim embedding vector if you embed an entire 5,000-word chapter as ONE giant chunk?
- Implement fixed-size sliding-window chunking cleanly using stride = chunk_size − overlap
- Explain the Chunk-Size Goldilocks trade-off: too small loses surrounding context; too large dilutes the embedding vector
- Implement sentence-boundary chunking so propositions and negations ('NOT 30 days') are never sliced in half
- Apply Contextual Retrieval (prepending document summaries) and Small-to-Big (Parent Document) retrieval in production RAG
Chunking is like making index cards for an open-book exam. If you write only 3 words per card, you lose the meaning ('is NOT'); if you staple an entire 20-page chapter onto 1 card, you can never find the one formula you need! The sweet spot is 1 clean paragraph per card with a short header at the top ([ACME Q3 2026 — Refunds]) and a 1-sentence overlap bridge!
1. Fixed-Size Sliding Window Chunking & Overlap Math
Adjust the Overlap slider in the mini-lab below to see how stride = size − overlap creates overlapping bridges across chunk edges.
Sliding Window Loop Invariants
Given token/word list tokens, chunk size , and overlap :
- Stride:
stride = S - O - Slices:
tokens[i : i + S]fori = 0, stride, 2*stride, ... - Crucial Tail Guard: Break as soon as
i + S >= len(tokens)so you don't emit tiny redundant tail fragments already 100% covered by the previous chunk!
Chunk Size (5 words) + Sliding Overlap Slicer
2. Sentence-Boundary & Recursive Structure-Aware Splitting
Never chop right through 'NOT | 30 days'! Sentence-boundary and Recursive splitters respect natural text hierarchy.
The Recursive Separator Hierarchy
Production splitters try coarse boundaries first, falling back only if a block exceeds max_tokens:
- Markdown headings (
##,###) & Code AST function boundaries - Double newlines (
\n\n— paragraphs) - Sentence boundaries (
.,?,!) - Whitespace / tokens (last resort for giant unpunctuated strings)
3. Contextual Retrieval & Parent-Document (Small-to-Big) RAG
Even a perfect sentence chunk like 'Revenue grew 14% YoY.' is an orphan once separated from its document title — Contextual Retrieval fixes this completely!
Two Modern Upgrades Over Basic Chunking
- Contextual Retrieval: Use a cheap fast LLM (with Prompt Caching on the full document!) to prepend a 1–2 sentence context header to every chunk before embedding & BM25 indexing.
- Small-to-Big (Parent Document): Embed small 200-token child chunks for razor-sharp retrieval, store
parent_idin metadata, and hand the full 1,000-token parent section to the generator LLM!
Worked Example: Fixed-Overlap Chunking Edge Case
10 words, chunk_size = 4, overlap = 2 (stride = 2).
[0:4], [2:6], [4:8], [6:10] — stop at i = 6 because 6 + 4 >= 10!
i + S >= N, i = 8 would emit [8:10], which is 100% redundant with [6:10]!In fixed-size chunking with chunk_size = 500 and overlap = 100, what is the stride (step size) between consecutive chunk starts?
Why do Markdown tables and Python functions break badly under naive 500-character chunking?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Start with 256–512 tokens and 10%–15% overlap using a recursive paragraph/sentence splitter — then measure Recall@5 on your own eval set before tuning!
Chunk-Boundary Context Preservation Animator
Toggle Overlap ON vs. OFF to see how sliding overlap prevents chopping facts right across a chunk boundary.
Codebase RAG (AST-Aware Chunking)
Uses Tree-sitter to chunk by complete functions/classes with file path & class signature prepended.
Enterprise Legal & Finance RAG
Combines Contextual Retrieval headers + Parent-Document expansion so clause numbers and parties are never lost.
import re
# Sentence-Boundary Chunking with Overlap (preserves complete ideas for RAG)
def sentence_chunk(text: str, max_chars: int = 90, overlap_sentences: int = 1) -> list[str]:
sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+", text.strip()) if s.strip()]
chunks, cur = [], []
for sent in sentences:
if cur and sum(len(x) for x in cur) + len(sent) > max_chars:
chunks.append(" ".join(cur))
cur = cur[-overlap_sentences:] if overlap_sentences > 0 else []
cur.append(sent)
if cur:
chunks.append(" ".join(cur))
return chunks
doc = "RAG grounds LLMs in private data. Good chunking avoids cutting sentences in half. Overlap keeps cross-boundary context intact."
for i, ch in enumerate(sentence_chunk(doc, max_chars=80, overlap_sentences=1), 1):
print(f"Chunk {i}: {ch}")
overlap >= chunk_size (infinite loop) or emitting redundant tiny trailing chunks.0 <= overlap < chunk_size and break when start + chunk_size >= len(tokens)!