4.2 Document Chunking Strategies: Fixed, Recursive & Contextual
80% of 'bad RAG answers' are actually chunking bugs! Experiment with a live RAG Chunker Lab and learn Recursive Splitting, Table/Code preservation, Parent-Child retrieval, and Contextual Chunk Headers.
1. Why Chunking Makes or Breaks Every RAG System
Ask ten AI engineers why their RAG bot gave a wrong answer, and nine will blame the LLM or the vector database. When you actually inspect the retrieved chunks, the real culprit is almost always broken chunking:
- A Markdown pricing table got sawed in half: Chunk #14 has the column headers, while Chunk #15 has
| $49 | Unlimited |with no plan name attached! - A pronoun (
"It expires after 24 hours.") got separated from the heading"## Password Reset Links"three paragraphs earlier — turning the chunk into an orphan sentence that neither embeddings norBM25can match!
The Goldilocks Chunk-Size Tradeoff
| Chunk Size | Retrieval Precision (Embedding Sharpness) | Context Completeness for LLM | Sweet Spot Use Case |
|---|---|---|---|
Tiny (64 – 128 tokens) | Very sharp single-fact vector | ❌ Loses surrounding caveats & pronouns | FAQ one-liners, glossary definitions |
Balanced (250 – 512 tokens) (10–15% overlap) | ✅ Crisp topical focus | ✅ Preserves full paragraph + local context | Default Production Sweet Spot! |
Large (1,024 – 2,048 tokens) | ⚠️ Diluted "vector soup" | Rich multi-paragraph context | Parent-Child retrieval (embed small child, return big parent!) |
2. Hands-On Lab: Watch Naive Slicing Break SQL vs. Recursive Splitting
Toggle between ❌ Naive Fixed-Size Slicing and ✅ Structure-Aware Recursive below, and drag the Target Size and Overlap sliders to see when the SQL code fence gets torn apart:
# Refund Policy (v2.4) Enterprise plans include a 30-day full refund guarantee if SLA uptime drops below 99.9%. ``
me drops below 99.9%. ```sql SELECT account_id, refund_cents FROM sla_credits WHERE uptime_pct < 99.9 AND plan = '
e_pct < 99.9 AND plan = 'enterprise'; ``` Starter plans are billed monthly and can be cancelled anytime before ren
celled anytime before renewal.
3. The 4 Production Chunking Strategies (In Order of Power)
Strategy 1: Recursive Separator Splitting (Your Clean Baseline)
Instead of slicing blindly every 500 characters mid-word, split hierarchically down a priority list of natural boundaries until chunks fit under your token budget:
"\n## "/"\n### "(Markdown section headings)"\n\n"(Paragraph breaks)"\n"(Line breaks)". "(Sentence boundaries)" "(Word fallback)
Strategy 2: Format-Specific AST / Table-Aware Chunking
- Source Code (
.py,.ts,.go): Never split mid-function! Parse withtree-sitteror Python'sastmodule so every chunk is a completeclassordefalongside its imports and docstring. - Markdown / HTML / PDF Tables: Never split a table without repeating the
<thead>header row at the top of every table chunk — otherwise rows 51–100 become meaningless floating numbers!
Strategy 3: Parent–Child (Small-to-Big) Retrieval
Want both laser-sharp 150-token embeddings and rich 1,000-token LLM context?
- Index
150-token Child chunks in your vector index, each storing aparent_section_idforeign key. - At query time, match the top Child vectors — then fetch and deduplicate their full
1,000-token Parent sections from PostgreSQL to hand to the LLM!
Strategy 4: Contextual Retrieval (Breadcrumb + LLM Context Header — -49% Retrieval Failures!)
Popularized by Anthropic's Contextual Retrieval research: before embedding or indexing a chunk in BM25, prepend its document breadcrumb + a 1–2 sentence situating header!
❌ RAW ORPHAN CHUNK (Fails search for "Acme Q3 revenue"):
"Revenue grew by 14% over the prior quarter to $312M, driven by cloud renewals."
✅ CONTEXTUALIZED CHUNK (Nails BOTH Vector & BM25 search!):
"[Doc: Acme Corp 10-Q | Period: Q3 2026 | Section: Financial Results]
This chunk reports Acme Corp's Q3 2026 revenue growth compared to Q2 2026.
---
Revenue grew by 14% over the prior quarter to $312M, driven by cloud renewals."
Cost Tip: Because every chunk in a 50-page PDF uses the same 50-page document as context when generating its 1-sentence header, Prompt Caching (Lesson 1.2) cuts contextualization cost by ~90% (~
$1per million document tokens)! Even without an LLM call, simply prepending deterministic[Doc Title > H1 > H2]Markdown breadcrumbs gives you 70% of the win for$0.00!
4. Wire-Level Trace: Orphan Chunk Failure vs. Breadcrumb Contextualization
"They are rotated automatically every 90 days and stored in AWS KMS."
5. Production Code: Framework-Free Markdown Breadcrumb Chunker
Zero heavy dependencies — clean, deterministic Python & TypeScript that keeps Markdown headings attached to every single chunk and never splits fenced code blocks:
import re
from dataclasses import dataclass
@dataclass
class DocChunk:
breadcrumb: str
content: str
@property
def text_for_embedding(self) -> str:
return f"[{self.breadcrumb}]\n{self.content}"
def chunk_markdown_with_breadcrumbs(md: str, doc_title: str, max_chars: int = 1400) -> list[DocChunk]:
h1, h2 = doc_title, "Overview"
chunks: list[DocChunk] = []
# Split on blank lines outside fenced code blocks
FENCE = chr(96) * 3
in_code = False
blocks: list[str] = []
cur_lines: list[str] = []
for line in md.splitlines():
if line.strip().startswith(FENCE):
in_code = not in_code
if not in_code and line.strip() == "":
if cur_lines:
blocks.append("\n".join(cur_lines))
cur_lines = []
else:
cur_lines.append(line)
if cur_lines:
blocks.append("\n".join(cur_lines))
buf = ""
def flush():
nonlocal buf
if buf.strip():
chunks.append(DocChunk(breadcrumb=f"{h1} > {h2}", content=buf.strip()))
buf = ""
for b in blocks:
if b.startswith("# "):
flush(); h1 = b[2:].strip()
elif b.startswith("## "):
flush(); h2 = b[3:].strip()
elif len(buf) + len(b) + 2 <= max_chars:
buf = f"{buf}\n\n{b}".strip()
else:
flush(); buf = b
flush()
return chunks6. What Breaks in Production (War Stories)
- Chunking by Characters Instead of Tokens on Code/CJK:
1,500characters of English is~375tokens, whereas1,500characters of dense JSON/minified JS or Japanese can exceed1,200tokens — blowing past small embedding limits or bloating prompts! Measure chunk caps in tokens (tiktoken). - Naive PDF Text Extraction Destroying Two-Column Layouts & Tables: Running
pypdfon a two-column financial PDF reads straight across columns horizontally — gluing Column 1 sentence halves onto Column 2! Use layout-aware parsers (Docling,Marker, or Vision-LLM PDF-to-Markdown OCR) before chunking. - Zero Deterministic Chunk IDs (
UUIDv4Duplicate Bloat): Re-running your ingestion cron job with randomuuid4()IDs inserts duplicate copies of every chunk, filling Top-5 results with 5 identical copies of the same paragraph! Compute deterministic IDs (sha256(doc_id + ":" + chunk_index + ":" + content_hash)).
Module 4.2 Mastery Check — Document Chunking Strategies
Keep Exploring: Related Lessons & Tools
All Courses →Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.