Why bad chunking breaks RAG before embeddings can help

Why bad chunking breaks RAG before embeddings can help

Day 17 — Chunking Is a Structure Decision, Not a String-Splitting Default

Here's the pattern I see on every stuck RAG team: three weeks burned re-tuning embeddings and rerankers, chasing a bug that was already baked in before a single vector got created. The chunk was broken. And once a chunk is broken, nothing downstream — no model, no reranker, no amount of prompt engineering — puts it back together.

The symptom

You know this failure by heart. The retriever hands back a chunk with half a function signature — the docstring landed in a different chunk entirely. Or a config block got sliced so the key sits in one chunk and its value sits in the next. The user asks something precise, the right document is sitting right there in the index, and the retriever still comes back with garbage. So the team runs the usual playbook: swap the embedding model, bolt on a reranker, fiddle with top-k, add BM25 for hybrid search. Three weeks pass. The eval numbers don't move, or they move by a rounding error nobody would bet on. And through all of it, nobody actually opened the chunks and read them.

The actual culprit: chunking destroys information irreversibly

Chunking is the earliest lossy step in the whole pipeline — and the only one you can't undo later. Embed a bad chunk and all you get is an accurate vector representation of broken information. Rerank a bad chunk and you're just re-sorting broken information with more confidence. Once a splitter cuts through a sentence, a function, or a table row, no downstream cleverness puts the severed half back. That's exactly why teams can burn weeks swapping embedding models and see nothing move — they're optimizing the one stage in the pipeline that structurally cannot fix this class of problem. And if your agent is chaining tool calls, editing code, or doing multi-hop reasoning off retrieved context, a severed chunk doesn't just cost you recall. It hands the agent a fact that looks complete and isn't, and the agent acts on it with total confidence.

What fixed-size / recursive-character chunking actually does

LangChain's RecursiveCharacterTextSplitter, and splitters like it — usually configured with something like chunk_size=1000, chunk_overlap=200 — do fine on plain prose, because sentences and paragraphs are roughly uniform in size. Code and structured docs are not prose. Here's what the failure actually looks like on a TypeScript file:

text
BEFORE (source function, 34 lines)

export async function reconcileInventory(
  warehouseId: string,
  items: InventoryDelta[],
  options: ReconcileOptions = defaultOptions,
): Promise<ReconcileResult> {
  const lock = await acquireLock(warehouseId);
  try {
    const current = await loadSnapshot(warehouseId);
    ...
  } finally {
    await lock.release();
  }
}

---

AFTER fixed-size chunking (chunk_size=200 chars, no AST awareness)

Chunk 7: "...export async function reconcileInventory(\n  warehouseId: string,\n  items: InventoryDelta[],\n  options: ReconcileOpt"

Chunk 8: "ions = defaultOptions,\n): Promise<ReconcileResult> {\n  const lock = await acquireLock(warehouseId);\n  try {\n    const current = aw"

The function signature — arguably the most information-dense, most query-relevant part of that whole function — gets sliced across two chunks at an arbitrary character offset. Ask "what does reconcileInventory return" and the query embeds against chunk 7, which has no return type, or chunk 8, which has no function name. Neither chunk can actually answer the question on its own. You get the same failure shape on Markdown docs, where a recursive splitter will happily cut through the middle of a config table or separate a header from the paragraph it introduces — because it's counting characters, not reading structure.

The reframe: chunking is structure-detection, not text-splitting

Your content already has seams — you don't need to invent them. Code has AST nodes: function boundaries, class boundaries, import blocks. Markdown has headers and fenced code blocks. YAML and JSON configs have key boundaries. API docs break cleanly per endpoint. A chunker's real job isn't deciding how many characters make a "good" chunk — it's finding the boundaries the author already drew and cutting along those, while keeping the context that belongs with each piece (the docstring above it, the parent header, the enclosing class name) attached rather than orphaned.

  • Code: use an AST-aware or tree-sitter-based splitter — LlamaIndex's CodeSplitter, or tree-sitter directly — that chunks at function and class boundaries and keeps signatures whole.
  • Markdown and docs: split on headers first (MarkdownHeaderTextSplitter-style) so each chunk carries its section context, then sub-split only if a section is still too big.
  • Config and structured data: chunk per top-level key or per resource block — never mid-object.
  • Attach the parent heading path (something like 'Auth > OAuth > Token Refresh') to the chunk's metadata. It's cheap to add, and it's often the thing that rescues a badly-worded query.

The 10-minute diagnostic

Before you touch your embedding model or reranker again, spend ten minutes checking whether chunking is actually the bottleneck:

  • Pull 15-20 chunks at random from your vector store and just read them. If any of them start or end mid-sentence, mid-signature, or mid-table-row, you have your answer.
  • Take 5 queries you know are failing, find the ground-truth answer in the source doc, and check whether any single chunk in your index actually contains the complete answer. If the answer is split across a chunk boundary, no reranker on earth fixes that — the chunk that should exist simply doesn't.
  • Compare your chunk_size against your content's natural unit size — function length, section length. If most chunks are cutting those natural units in half, that's a structural mismatch, not a ranking problem.
  • If step 1 or step 2 turns up broken chunks, stop tuning embeddings. Fix the splitter, re-index, re-run eval — and only go chasing embedding or reranker gains once this part is clean.

Where this fits in the arc

Chunking is a design decision you own, shaped directly by what your content actually looks like — not preprocessing boilerplate you inherit for free from a library default. Get it wrong, and every stage after it — embeddings, reranking, whatever context your agent assembles — spends its whole budget compensating for damage that already happened upstream. Tomorrow, Day 18, we get into embeddings themselves: once your chunks are structurally sound, how do you actually pick and evaluate an embedding model for your content, instead of defaulting to whatever tops a leaderboard built on data that looks nothing like yours.

Flashcards
Check yourself

Extend your knowledge

  • Try LlamaIndex's CodeSplitter (tree-sitter based) on one of your own source files and diff the resulting chunks against what your current recursive splitter produces.
  • Read the tree-sitter project docs to see how AST parsing actually works across languages — it's the same primitive powering most AST-aware chunkers.
  • Run the 10-minute diagnostic from this lesson against your current production index this week, before any further embedding or reranker tuning.
  • Look at how unstructured.io and LlamaIndex's MarkdownNodeParser handle header-based splitting for docs — solid reference implementations of the seam-based approach.
Test yourself on this lessonquiz →
Discussion

Ask my AI about this article. The chat stays on your device; when you're done you can publish a short summary for other readers.

No questions yet. Try: what's the trade-off here, or how would this fail in practice?