Course
AI · Module 04: Embeddings, Chunking & Vector SearchTutorial 11 of 21
AI Course·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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 nor BM25 can match!

The Goldilocks Chunk-Size Tradeoff

Chunk SizeRetrieval Precision (Embedding Sharpness)Context Completeness for LLMSweet Spot Use Case
Tiny (64 – 128 tokens)Very sharp single-fact vector❌ Loses surrounding caveats & pronounsFAQ one-liners, glossary definitions
Balanced (250 – 512 tokens) (10–15% overlap)✅ Crisp topical focus✅ Preserves full paragraph + local contextDefault Production Sweet Spot!
Large (1,024 – 2,048 tokens)⚠️ Diluted "vector soup"Rich multi-paragraph contextParent-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:

Interactive RAG Chunker: Naive Fixed-Char vs Structure-Aware Recursive
Watch how naive character slicing saws SQL code blocks in half — and how Recursive Splitting preserves semantic units!
🚨 SQL CODE BLOCK TORN IN HALF!
Chunk #1 (115 chars)
# Refund Policy (v2.4)
Enterprise plans include a 30-day full refund guarantee if SLA uptime drops below 99.9%.

``
Chunk #2 (115 chars)Unclosed ```!
me drops below 99.9%.

```sql
SELECT account_id, refund_cents
FROM sla_credits
WHERE uptime_pct < 99.9 AND plan = '
Chunk #3 (115 chars)Unclosed ```!
e_pct < 99.9 AND plan = 'enterprise';
```

Starter plans are billed monthly and can be cancelled anytime before ren
Chunk #4 (30 chars)
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:

  1. "\n## " / "\n### " (Markdown section headings)
  2. "\n\n" (Paragraph breaks)
  3. "\n" (Line breaks)
  4. ". " (Sentence boundaries)
  5. " " (Word fallback)

Strategy 2: Format-Specific AST / Table-Aware Chunking

  • Source Code (.py, .ts, .go): Never split mid-function! Parse with tree-sitter or Python's ast module so every chunk is a complete class or def alongside 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 a parent_section_id foreign 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!

TEXT
❌ 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% (~$1 per 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

Tracing Why Orphan Chunks Fail & How Contextual Headers Fix Them
Interactive LLM Pipeline Tracer · Step 1 of 2 (1. Raw Chunk Loses Its Section Heading)
1→doc = parse_markdown("enterprise-security-whitepaper.md")
2→# Step 1: Split on H2/H3 + paragraphs while keeping code blocks atomic
3→raw_chunks = split_markdown_sections(doc, max_tokens=400)
4# Step 2: Prepend [Doc > H1 > H2] breadcrumb before embedding!
5enriched = [f"[{c.doc_title} > {c.h1} > {c.h2}]\n{c.body}" for c in raw_chunks]
Raw Chunk #19 BodyORPHAN PRONOUN!
"They are rotated automatically every 90 days and stored in AWS KMS."
What's Happening: What is 'They'?! Customer API keys? TLS certificates? Database master keys? Separated from its H2 heading ('### Customer Master Keys'), this chunk fails retrieval!

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:

SDK:
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 chunks

6. What Breaks in Production (War Stories)

  1. Chunking by Characters Instead of Tokens on Code/CJK: 1,500 characters of English is ~375 tokens, whereas 1,500 characters of dense JSON/minified JS or Japanese can exceed 1,200 tokens — blowing past small embedding limits or bloating prompts! Measure chunk caps in tokens (tiktoken).
  2. Naive PDF Text Extraction Destroying Two-Column Layouts & Tables: Running pypdf on 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.
  3. Zero Deterministic Chunk IDs (UUIDv4 Duplicate Bloat): Re-running your ingestion cron job with random uuid4() 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

Q1.Why does naive fixed-character chunking fail badly on technical docs with tables and SQL/Python code blocks?
Q2.What problem does prepending a `[Doc Title > H1 > H2]` breadcrumb (or Contextual Retrieval header) solve?
Q3.How does Parent-Child ('Small-to-Big') Retrieval get the best of both small and large chunks?
Q4.How can you run LLM-generated Contextual Retrieval headers across a 100-chunk PDF without paying 100× for the full document tokens?

Keep Exploring: Related Lessons & Tools

All Courses →