Sub topic 13
Choosing a Strategy and Avoiding Common Pitfalls
This chapter assumes you can read basic Python, know how embeddings and vector similarity search work, and know what a token is. It also assumes you have met the chunkers from earlier chapters: fixed-size with overlap, recursive splitting, sentence-based, structure-aware, semantic, and parent-child. Here you decide which to use and learn which mistakes to watch for.
Start with the corpus, not the technique
No chunking strategy wins everywhere. The right choice depends on three things you can inspect before writing code:
- Document shape. Does the text have reliable structure, such as headings, tables, or code, or is it flat prose?
- Question shape. Do users ask for a single fact ("What is the refund window?") or for an explanation that spans several paragraphs?
- Limits. What is the embedding model's maximum input in tokens, and how many retrieved chunks fit in the generation prompt?
The diagram shows one way to turn those answers into a starting point. Treat the result as a first candidate to measure, not a final answer.
Starting points by content type
| Content | First candidate | Why |
|---|---|---|
| Long-form prose (articles, reports) | Recursive splitting, 200 to 400 tokens, 10 to 15% overlap | Paragraph breaks are natural boundaries, and the splitter degrades gracefully when they are missing. |
| Markdown or HTML documentation | Structure-aware, split at headings, with the heading path as metadata | Sections are the unit people write and search by. |
| Source code | Split by function or class, never by raw character count | A function cut in half is hard to retrieve or read. |
| Tables and spreadsheets | One row or row group per chunk, with the header repeated | A row without its column names is meaningless. |
| FAQ or short records | One record per chunk, no overlap | The record is already the right size. |
| Chat or transcripts | Group by speaker turns or time windows, with overlap | Meaning depends on the preceding turns. |
| Dense legal or technical text with cross-references | Small chunks for search plus parent-child retrieval | Precise matching needs small units, but answers need the surrounding clauses. |
Sentence-based and semantic chunking appear less often in this table on purpose. Sentence-based chunking works well for clean prose but adds little over recursive splitting. Semantic chunking requires embedding every sentence at ingest time and tuning a similarity threshold. Reach for it only if measurement shows boundary errors that cheaper methods cannot fix.
A sensible default recipe
If you have no strong signal yet, begin here:
- Split with a recursive splitter, or at headings if the documents are structured.
- Target 256 to 512 tokens per chunk, comfortably below the embedding model's limit.
- Use 10 to 15% overlap for prose, and none for records that are already self-contained.
- Store the source ID, the heading path, and the position of each chunk as metadata.
- Build a small evaluation set and measure recall@k before changing anything else.
Step 5 matters most. A default is only a hypothesis.
Comparing configurations with a harness
The script below chunks a tiny corpus under several settings and scores each one with recall@k. It uses a deliberately crude word-overlap ranker so it runs with no dependencies. In a real project, replace retrieve with your embedding search.
Relevance is labeled by document ID, not chunk ID. Chunk IDs change whenever you change the chunking settings, so labels tied to them would be useless for comparing configurations.
import re
def chunk_words(text, size=200, overlap=40):
if overlap >= size:
raise ValueError("overlap must be smaller than size")
words = text.split()
step = size - overlap
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break
return chunks
def recall_at_k(retrieved_ids, relevant_ids, k=5):
if not relevant_ids:
return 0.0
hits = len(set(retrieved_ids[:k]) & set(relevant_ids))
return hits / len(relevant_ids)
def tokenize(text):
return set(re.findall(r"[a-z0-9]+", text.lower()))
def retrieve(question, chunks, k):
q = tokenize(question)
ranked = sorted(chunks, key=lambda c: len(q & tokenize(c["text"])), reverse=True)
return [c["doc"] for c in ranked[:k]]
docs = {
"refunds": (
"Refunds are issued to the original payment method within five "
"business days of approval. Gift cards are not refundable. "
"Customers must request a refund within thirty days of purchase."
),
"shipping": (
"Standard shipping covers all countries in Europe and North America. "
"Delivery takes between three and seven business days. Express "
"shipping is available for an additional fee."
),
}
questions = [
("How long do refunds take to arrive?", "refunds"),
("Which countries does standard shipping cover?", "shipping"),
]
configs = [(8, 0), (8, 3), (20, 5)]
for size, overlap in configs:
chunks = [
{"doc": doc_id, "text": piece}
for doc_id, text in docs.items()
for piece in chunk_words(text, size, overlap)
]
scores = [
recall_at_k(retrieve(q, chunks, k=2), [relevant], k=2)
for q, relevant in questions
]
print(f"size={size} overlap={overlap} chunks={len(chunks)} "
f"recall@2={sum(scores) / len(scores):.2f}")The script prints one line per configuration, showing the chunk count and the mean recall@2. With only two questions the numbers are not meaningful. The point is the shape of the loop: fix the questions, vary one setting, and compare.
Common pitfalls
The table lists the mistakes that cause the most trouble, followed by detail on the less obvious ones.
| Pitfall | Symptom | Fix |
|---|---|---|
| Sizing by characters or words only | Embedding truncation, or chunks far larger than expected | Count tokens with the embedding model's own tokenizer. |
| Overlap equal to or above size | Infinite loops or an error | Validate that overlap is smaller than size. |
| Chunks too small | High recall on keywords, but answers lack context | Increase size, or add parent-child retrieval. |
| Chunks too large | Vague matches, with irrelevant text filling the prompt | Reduce size, or split at headings. |
| Splitting inside code fences or tables | Broken code, orphaned table rows | Detect fences and tables before splitting. |
| Missing metadata | Chunks that say "it" or "the above" with no referent | Attach heading path, title, and source. |
| Changing chunking without re-indexing | Old and new chunks mixed in one index | Version the index and rebuild it fully. |
| Judging by a few examples | A config that looks good on one query and fails elsewhere | Use a labeled evaluation set. |
Token limits are silent
Most embedding endpoints either truncate or reject input above their maximum length. Truncation is the dangerous case. The tail of the chunk is simply never embedded, so retrieval cannot match anything stated there. Words are a rough proxy for tokens, and the ratio varies by language and content. Code and non-English text usually produce many more tokens per word than English prose. Measure with the real tokenizer and leave a margin.
Overlap creates duplicates
Overlap helps when a sentence straddles a boundary, but it also means the same text appears in two chunks. At retrieval time, the top results may contain near-duplicates that waste prompt space. Deduplicate retrieved chunks by source position, or merge adjacent hits from the same document before building the prompt.
Heading detection can be fooled
The simple Markdown splitter from the structure-aware chapter treats any line beginning with # as a heading. Inside a fenced code block, that same pattern is a comment, so the splitter will start a new section in the middle of the code. Track whether you are inside a fence and skip heading detection while you are.
import re
def split_markdown_safe(text):
sections, path, buf = [], [], []
in_fence = False
def flush():
body = "\n".join(buf).strip()
if body:
sections.append({"headings": list(path), "text": body})
buf.clear()
for line in text.splitlines():
if line.lstrip().startswith("```"):
in_fence = not in_fence
buf.append(line)
continue
m = None if in_fence else re.match(r"^(#{1,6})\s+(.*)$", line)
if m:
flush()
level = len(m.group(1))
path[:] = path[:level - 1]
path.append(m.group(2).strip())
else:
buf.append(line)
flush()
return sectionsOne more limit remains. A single section can still exceed your size limit, so pass oversized sections through a recursive splitter that keeps the heading path in the metadata.
Evaluation sets that mislead
An evaluation set built from questions you wrote while reading the chunks will favor the current chunking. Write questions from the documents' content, or collect real user queries, before you chunk. Include questions whose answers span two paragraphs, because these expose boundary problems. Also keep a few questions that have no answer in the corpus, so you notice when retrieval returns confident nonsense.
When to add complexity
Add features in order of cost and evidence:
- Metadata and heading paths. Cheap, and almost always helpful for structured documents.
- Parent-child retrieval. Worth it when small chunks match well but the answers need surrounding text. It costs extra storage and a lookup step.
- Semantic chunking. Worth it only when your measurements show that fixed boundaries cut ideas apart and that cleaner boundaries improve recall. It adds ingest cost and a threshold to tune.
If a simpler method already meets your recall target, stop there. Every extra stage is another thing to rebuild when the corpus or the embedding model changes.
Operating the choice
Chunking is part of your index schema. Record the splitter name, size, overlap, and tokenizer alongside the index so you can reproduce it. When you switch embedding models, re-check the size limit and re-measure, because the best chunk size for one model is not guaranteed for another. When documents change, re-chunk and re-embed only the changed documents, keyed by a stable document ID, so stale chunks do not linger.
Exercise
A team splits a technical manual into fixed 120-word chunks with no overlap. Recall@5 on their evaluation set is 0.55, and failures often involve answers that begin at the end of one chunk and finish at the start of the next. Name two changes they could try, and say how they should compare them.
Show answer
They could add overlap (for example 20 to 30 words) so boundary-straddling sentences appear whole in one chunk, or switch to recursive or heading-based splitting so boundaries fall on paragraphs or sections. They should change one setting at a time, rebuild the index for each, and run the same labeled questions through each version. They should compare recall@5 labeled by document ID, since chunk IDs change between configurations.
Exercise
Your Markdown splitter produces a section titled "install dependencies" that contains only the text "pip install -r requirements.txt", and the section is followed by a new section for each comment line in the code block. What went wrong, and how do you fix it?
Show answer
The splitter treats # comment lines inside the fenced code block as headings. Fix it by tracking whether the current line is inside a fence (toggle on each line starting with three backticks) and skipping heading detection while inside one.