Learn AI · Foundations
Chunking Strategies for RAG
Chunking is the highest-leverage decision in any RAG system. Get it wrong and no embedding model or vector DB will save you. Here's how to chunk by document type.
Key takeaways
- 1Chunking is an indexing decision, not a preprocessing afterthought — it determines what the retriever can ever find.
- 2400–800 tokens with 10–15% overlap is a reasonable default for prose; specialized content needs specialized rules.
- 3Parent-child chunking (small chunks for search, large chunks for context) is the most common upgrade path.
- 4Always attach metadata: source URL, section header, page number, doc type. Metadata filtering beats bigger embeddings.
- 5Evaluate chunking with retrieval recall, not vibes — if the right chunk isn't in top-5, fix chunking before touching the LLM.
Why chunking matters more than your embedding model
RAG has two phases: index time and query time. At index time, you split documents into chunks, embed each chunk, and store the vectors. At query time, you retrieve the top-k chunks and paste them into the prompt.
The retriever can only return what you chunked. If the answer spans two chunks and you split in the middle, neither chunk will rank highly. If you chunk a pricing table row-by-row, the retriever finds individual prices but loses the column headers. Chunking is the ceiling on retrieval quality — everything downstream (embeddings, vector DB, reranking, LLM) operates within that ceiling.
Most teams spend weeks tuning embedding models while their chunks are broken. Don't be that team.
The core tradeoff
Every chunking decision balances two forces:
| Force | Small chunks (128–256 tokens) | Large chunks (1000+ tokens) |
|---|---|---|
| Retrieval precision | High — tight match to query | Low — lots of irrelevant text |
| Context completeness | Low — missing surrounding info | High — full section preserved |
| Top-k noise | Less noise per chunk | More noise per chunk |
| Embedding cost | More chunks = more $ | Fewer chunks = cheaper |
There's no universal optimum. The right size depends on your documents and your users' questions.
Strategy 1: Fixed-size with overlap
The simplest approach: split every N tokens, with M tokens of overlap between consecutive chunks.
Chunk 1: tokens 0–512
Chunk 2: tokens 448–960 ← 64-token overlap
Chunk 3: tokens 896–1408
Defaults: 512 tokens, 64-token overlap (~12%).
Pros: Fast, predictable, works for homogeneous prose. Cons: Splits mid-sentence, mid-paragraph, mid-table. Ignores document structure.
When to use: Blog posts, articles, general documentation. Your first implementation.
Implementation tip: Split on sentence boundaries when possible. Libraries like LangChain's RecursiveCharacterTextSplitter try \n\n → \n → . → before falling back to character count.
Strategy 2: Structure-aware chunking
Respect the document's own hierarchy — headers, sections, list items, code blocks.
Markdown / HTML docs:
- Split on
##or###headers. - Each section becomes one chunk (or sub-split if a section exceeds your max).
- Store the header trail as metadata:
["Getting Started", "Authentication", "API Keys"].
Code:
- Split on function, class, or module boundaries.
- Include the file path, function signature, and imports in metadata.
- Keep related tests in the same chunk when possible.
Q&A / FAQ docs:
- Each question-answer pair is exactly one chunk.
- Don't merge multiple Q&As — users ask one question at a time.
Tables:
- Never split a table across chunks.
- If the table is too large, include column headers in every sub-chunk or store the full table as a single chunk regardless of size.
Strategy 3: Semantic chunking
Use an embedding model to detect topic boundaries. Embed sentences sequentially; when the similarity between consecutive sentences drops below a threshold, start a new chunk.
Pros: Chunks align with natural topic shifts. Great for long unstructured prose (research papers, transcripts). Cons: Slow at index time (one embedding per sentence). Produces uneven chunk sizes. Threshold tuning is finicky.
When to use: Podcast transcripts, research papers, long-form reports where structure-aware splitting fails.
Strategy 4: Parent-child chunking
The most impactful upgrade for production RAG:
- Child chunks (128–256 tokens) — embedded and searched. Tight match to queries.
- Parent chunks (full section, 1000–2000 tokens) — not embedded. Retrieved by association when a child matches.
Query: "How do I rotate API keys?"
→ Child chunk matched: "...click Settings > API Keys > Rotate..."
→ Parent chunk passed to LLM: full "API Keys" section with setup, rotation, and revocation
You get precise retrieval and rich context. This is what most mature RAG systems converge on.
Metadata is half the chunking strategy
Every chunk should carry:
- Source — file path, URL, or document ID
- Position — page number, section header, line range
- Type —
prose,code,table,faq - Timestamp — when the source was last updated
Metadata enables pre-filtering at query time: "only search API docs from the last 6 months" beats hoping the embedding model figures it out.
How to evaluate chunking
Don't guess. Measure.
- Build a retrieval eval set — 20–50 questions with known gold-source passages. See Evals Explained for the framework.
- Measure recall@k — for each question, is the gold passage in the top-k retrieved chunks?
- Target 80%+ recall@5 before touching the LLM prompt or switching embedding models.
- Inspect failures — when recall is low, read the missed chunks. You'll find split boundaries, missing context, or metadata gaps.
Run this eval every time you change chunk size, overlap, or strategy. Chunking regressions are silent and expensive.
Chunking by content type — quick reference
| Content type | Strategy | Chunk size | Key metadata |
|---|---|---|---|
| Prose / docs | Fixed-size + overlap | 512 tokens, 64 overlap | Section header, URL |
| API reference | One endpoint per chunk | Full endpoint block | Method, path, version |
| Code | Function/class boundary | Full function + imports | File path, symbol name |
| Tables | Whole table | As large as needed | Table title, column headers |
| FAQ | One Q+A per chunk | Full Q+A | Category, tags |
| PDFs | Page-aware + structure | 512 tokens, respect pages | Page number, section |
| Slack / chat | Thread or time window | Full thread or 1-hour window | Channel, author, timestamp |
Common failure modes
- Splitting tables row-by-row — retriever finds a cell value but the LLM has no column context.
- No overlap on procedural docs — step 4 is in chunk 2, step 5 is in chunk 3, and neither chunk makes sense alone.
- Chunking code without imports — the function body is retrieved but the LLM doesn't know what types or modules are in scope.
- Stale chunks after doc updates — you re-embed changed docs but forget to delete old chunks, so the retriever serves outdated passages.
- Ignoring document updates — chunking once at deploy and never re-indexing. Pair chunking with a change-detection pipeline.
The decision tree
Is your content structured (headers, sections, endpoints)?
→ Yes: structure-aware chunking
→ No: fixed-size with overlap
Is recall@5 below 80%?
→ Yes: try parent-child chunking
→ No: you're probably fine
Do you have tables or code?
→ Yes: specialized rules (whole table, function boundaries)
→ No: defaults work
Still failing?
→ Build a retrieval eval and inspect the misses
Chunking isn't glamorous. It's the unsexy infrastructure decision that determines whether your docs chatbot actually works. Invest here first.
Common misconceptions
The wrong-but-common takes worth correcting.
Myth
There's one optimal chunk size for every corpus.
Reality
Chunk size is a tradeoff between precision (small chunks match queries tightly) and context (large chunks preserve meaning). Legal contracts, API docs, and Slack threads need different strategies.
Myth
Semantic chunking always beats fixed-size splitting.
Reality
Semantic chunking (split on topic boundaries detected by an embedding model) is better for long prose but slower at index time and can produce wildly uneven chunk sizes. Fixed-size with overlap is often good enough.
Myth
Re-chunking is cheap — just re-run the pipeline.
Reality
Re-chunking means re-embedding everything, invalidating your eval baselines, and potentially breaking citations. Get chunking right early or version your index.
Real-world use cases
Internal knowledge bases
Chunk Confluence pages by heading hierarchy so each section is independently retrievable.
API documentation
One endpoint = one chunk, with the full request/response schema included.
Open
Legal and compliance docs
Chunk by clause number with parent-document metadata for full-context generation.
Codebase Q&A
Split on function/class boundaries and keep file path + symbol name in metadata.
Frequently asked questions
Watch
Hand-picked videos from official + trusted channels. Opens in a new tab.
Related on AIKnowHub
Concept
RAG Explained
Retrieval-Augmented Generation is how you give LLMs access to your own data without retraining them. Here's how it actually works.
Concept
Embeddings Explained
Embeddings turn text into numbers that capture meaning. They power search, RAG, recommendations, and clustering — here's how.
Concept
Vector Databases Explained
What vector databases actually do, when you need one, and what the real tradeoffs between Pinecone, Weaviate, Qdrant, and pgvector look like.
Workflow
Build an AI Docs Chatbot
A RAG-powered chatbot that answers questions from your documentation with citations — the kind every SaaS site needs in 2026.
Comparison
Best Embedding Model
OpenAI vs Voyage vs Cohere vs open-source — which embedding model wins on quality, cost, and ecosystem in 2026?
Tool Guide
Dify Guide
The definitive guide to Dify for low-code AI apps — RAG chatbots, agent workflows, MCP import, self-host vs cloud, and when to pick it over Flowise or n8n.