Skip to main content
Back to all articles
AI Engineering 10 min read

Chunking for Production RAG: Strategies, Trade-offs, Retrieval Quality, and What Actually Works

A practical guide to chunking in production RAG: how to choose boundaries, preserve context, handle different document types, and evaluate what actually improves retrieval.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#rag#chunking#retrieval#embeddings#semantic-search#hybrid-search#reranking#typescript#python#evaluation
On this page

Chunking sounds simple until a RAG system starts missing answers that are clearly sitting inside the source documents.

At first, it is tempting to blame the model. Maybe the prompt is weak. Maybe the embedding model is not good enough. Maybe we need a larger context window.

Sometimes the real problem is much earlier.

The document was split badly.

That matters because retrieval can only find the pieces we put into the index. If an important fact gets cut in half, buried inside a huge block of unrelated text, or stripped away from its heading, the LLM never gets a fair chance to answer correctly.

This is how I think about chunking in production RAG systems: not as a text utility, but as part of the retrieval design.

If you want the next stage after chunking, I covered that in Hybrid Retrieval Before Bigger Models.

What chunking actually does

A document is usually too large to retrieve as one useful unit.

Take a long API guide. It may contain authentication, rate limits, webhooks, errors, pagination, and code examples. If we embed the whole thing as one chunk, the embedding has to represent too many ideas at once.

Now go too far in the other direction and split every sentence separately. Retrieval becomes very specific, but the chunks often lose meaning.

For example:

The limit is 500 requests per minute.

That sentence is technically complete, but it is weak retrieval context. Which API? Which plan? Which client type?

This is much better:

Payments API Documentation API > Rate Limits

>

Standard clients may make 500 requests per minute.

The actual rule did not change. The chunk simply carries enough context to stand on its own.

That is the main idea behind good chunking.

Boundaries matter more than chasing a perfect size

A lot of chunking discussions start with numbers.

Should we use 500 tokens? 800? 1,000 characters?

Those numbers matter, but bad boundaries usually hurt more than an imperfect size.

This is a bad split:

Chunk 1: Employees receive 25 paid

>

Chunk 2: vacation days every year.

Now neither chunk contains the full fact.

A slightly larger chunk with a complete idea is usually better than a perfectly sized chunk that cuts through a sentence, a policy rule, a table row, or a code block.

In practice, I treat chunk size as a guardrail. I do not let it decide every boundary.

Too large and too small both cause problems

Large chunks preserve context, but they become noisy.

If one chunk contains six different topics, vector search has a harder time representing what that chunk is really about. Rerankers also have more irrelevant text to score, and every retrieved chunk consumes more prompt space.

Small chunks have the opposite problem.

They may retrieve well but make little sense by themselves.

For example:

It expires after 30 minutes.

What expires? A password reset link? A session? A checkout reservation?

Small chunks also create more index rows, more duplicates, and more cases where we need to pull neighboring chunks back in later.

So the goal is not “small chunks” or “large chunks.”

The goal is useful chunks.

The chunking strategies I actually care about

There are many names for chunking techniques, but only a few patterns come up repeatedly in production.

Fixed-size chunking

Split every N characters or tokens.

It is simple, cheap, and predictable. It is also blind to document structure.

I use it as a fallback for plain text or messy content where better boundaries do not exist. I would not use one fixed size for every source in a mixed knowledge base.

Recursive chunking

Recursive chunking is a good default for normal prose.

Instead of cutting text immediately at a fixed limit, it tries better boundaries first: sections, paragraphs, line breaks, sentences, then smaller separators if needed.

It is deterministic and cheap, and in many projects it gets surprisingly far.

Structure-aware chunking

This is the approach I prefer whenever the source already has useful structure.

For Markdown, keep headings with their content.

For HTML, preserve sections and heading hierarchy.

For API docs, keep an endpoint with its parameters, errors, and examples where possible.

For legal documents, preserve clauses and definitions.

The author already gave us meaningful boundaries. Throwing them away and splitting everything every 500 tokens does not make much sense.

Semantic chunking

Semantic chunking tries to place boundaries where the topic changes.

It can help with long unstructured text, transcripts, and documents where paragraphs do not reflect real topic boundaries.

It is more expensive, though, because it usually needs extra embedding or model work during ingestion.

I do not start with it automatically. I try simpler structural approaches first and move to semantic chunking when retrieval tests show a real problem.

LLM-based chunking

An LLM can help understand messy documents, infer sections, add context, or repair poor extraction.

That can be useful, but it makes ingestion slower, more expensive, and less deterministic.

For me, LLM chunking is a targeted tool, not the default answer.

Different document types need different treatment

This is where one global splitter usually falls apart.

Markdown and HTML already contain structure.

PDFs need good parsing before chunking even begins.

Source code should respect functions, methods, classes, and modules.

Tables need headers attached to the values they describe.

Support conversations need speaker and turn context.

API documentation often works best when each operation stays together with its description, parameters, examples, and errors.

A rough starting point looks like this:

SourceGood starting strategy
MarkdownHeading-aware + recursive fallback
HTMLDOM/section-aware
PDFLayout-aware parsing first
API docsEndpoint/operation-aware
Source codeAST or symbol-aware
FAQsQuestion + full answer
Legal docsClause/section-aware
TablesTable-aware
ConversationsTurn/topic-aware

The important part is not the exact label. It is that the splitter should understand the shape of the source.

PDFs are usually a parsing problem first

A lot of “chunking problems” in PDFs are really extraction problems.

If a parser mixes two columns together, drops headings, flattens tables into nonsense, or inserts headers and footers into every page, the chunks are already damaged before they reach the embedding model.

For example, imagine a pricing table extracted like this:

Plan Basic Pro Enterprise Price 20 50 Contact Limit 5 20 Unlimited

Changing the chunk size will not fix that.

For PDFs, I care more about layout-aware parsing than fancy splitting logic. Good chunking starts with good structure.

Code needs code-aware boundaries

Source code is another place where generic fixed-size splitting performs badly.

I would rather retrieve a complete function or method than half a method plus the beginning of the next one.

For code, useful metadata includes file path, language, symbol name, class name, and line range.

A code assistant often works well with small symbol-level chunks for retrieval, then expands to the enclosing class or nearby methods when more context is needed.

That leads to one of the most useful patterns in RAG.

Retrieve small, then expand context

The best chunk for retrieval does not always have to be the same chunk we send to the LLM.

Suppose this sentence is highly relevant:

Password reset links expire after 30 minutes.

That small chunk may be perfect for retrieval.

But if the user asks what happens after expiry, whether the link can be reused, or whether support can extend it, the model probably needs the surrounding section too.

This is where parent-child retrieval helps.

We retrieve the smaller child chunk first, then fetch its parent or nearby chunks before building the final prompt.

That gives us precision during retrieval and more context during generation.

type Chunk = {  id: string;  parentId: string | null;  previousChunkId: string | null;  nextChunkId: string | null;  text: string;};​async function expandContext(  chunk: Chunk,  getChunk: (id: string) => Promise<Chunk | null>,): Promise<Chunk[]> {  const ids = [    chunk.parentId,    chunk.previousChunkId,    chunk.id,    chunk.nextChunkId,  ].filter((id): id is string => Boolean(id));​  const result = await Promise.all(ids.map(getChunk));  return result.filter((item): item is Chunk => item !== null);}

I would not expand every result blindly, but the pattern is very useful when small chunks retrieve well but do not contain enough context to answer fully.

Keep headings and metadata with the chunk

A chunk usually needs more than plain text.

At minimum, I want enough metadata to answer questions like:

  • which document did this come from?
  • which section?
  • which tenant?
  • which version?
  • which page?
  • is the user allowed to see it?

I also like keeping heading hierarchy separate from the visible chunk text.

For example, instead of embedding only:

Standard clients may make 500 requests per minute.

I might build the retrieval text like this:

function buildRetrievalText(  title: string,  headings: string[],  text: string,): string {  const path = [title, ...headings].filter(Boolean).join(" > ");  return path ? `${path}\n\n${text}` : text;}

Now the chunk carries the context that a human reader would naturally get from the page around it.

This often improves both semantic and lexical retrieval without needing anything fancy.

Overlap is useful, but more is not always better

Overlap exists because some ideas cross boundaries.

A little overlap can make two neighboring chunks more self-contained.

The problem starts when overlap becomes large enough that many chunks are almost copies of each other.

Then topK = 5 may return five versions of the same paragraph.

That looks good in similarity scores but is bad for retrieval diversity.

When duplicate results become a problem, I use content hashes, section-level deduplication, reranking, or MMR-style diversity instead of simply increasing topK again.

Good boundaries usually reduce how much overlap you need in the first place.

Chunking changes how the whole retrieval pipeline behaves.

Vector search needs semantically focused chunks.

BM25 benefits when exact identifiers and their explanations live in the same useful unit.

Hybrid retrieval works better when both lexical and semantic search can find the same chunk cleanly.

Reranking works better when candidates are focused instead of bloated with unrelated text.

And the LLM works better when the final context contains a few strong pieces of evidence instead of a pile of repetitive chunks.

This is why chunking should be evaluated as part of retrieval, not in isolation.

What chunk size should you start with?

There is no universal number.

For normal prose, something around 300 to 800 tokens can be a reasonable place to start testing.

But it is only a starting point.

An FAQ answer might be 100 tokens and already complete.

An API endpoint section might need 600.

A legal clause with its exception might be larger.

I prefer soft limits instead of forcing every chunk into exactly the same size.

Keep a useful section intact when possible. If it becomes too large, split it recursively while preserving the same heading and metadata.

That gives you consistency without destroying structure.

A production ingestion flow

A real ingestion pipeline usually looks more like this:

Text
Document   ↓File-Type Detection   ↓Parser   ↓Structure Extraction   ↓Document-Specific Chunker   ↓Context Enrichment   ↓Metadata   ↓Embedding   ↓Vector Index   ↓Hybrid Retrieval   ↓Reranking   ↓Context Assembly   ↓LLM

The main thing I would avoid is one global splitText(document, 1000) function handling every file type.

A better design is to route each source to the chunker that understands it.

The easiest way to settle chunking debates: evaluate it

People can argue for a long time about 400-token versus 700-token chunks.

It is much easier to test both.

Create a small set of real questions and label the evidence that should be retrieved for each one.

Then compare chunking strategies with metrics such as:

  • Recall@K
  • Precision@K
  • MRR
  • answer correctness
  • faithfulness
  • context relevance

The test set should include the messy questions people actually ask: exact error codes, vague wording, misspellings, table lookups, questions requiring an exception, and questions where the answer lives across nearby sections.

If one strategy gets better retrieval on your corpus, that matters more than a generic rule from a blog post.

Separate retrieval failures from generation failures

This is one of the most important debugging habits in RAG.

If the answer is wrong, first check whether the correct evidence was actually retrieved.

If it was not, look at parsing, chunk boundaries, metadata, filters, embeddings, ranking, and context assembly.

If the correct evidence was present but the model still answered badly, then you have a generation problem.

Those are different failures.

A better prompt cannot reliably recover a fact that never made it into the context.

What I would use as a practical default

For a mixed company knowledge base, I would start with:

Text
Structure-aware chunking+Recursive fallback+Contextual headings+Rich metadata+Parent-child retrieval+Hybrid retrieval+Reranking+Evaluation

Then I would add more complexity only when the failures justify it.

If PDF tables are broken, fix parsing.

If small chunks lose context, add parent or neighbor expansion.

If exact identifiers are missed, add lexical retrieval.

If long unstructured documents split badly, test semantic chunking.

If candidates are relevant but badly ordered, add reranking.

That is a much healthier progression than starting with every advanced technique at once.

Final thought

Chunking is not really about finding a magic number.

It is about deciding what the retriever should treat as one meaningful piece of evidence.

So instead of asking:

What is the best chunk size?

I think the better question is:

What is the smallest self-contained unit that can be retrieved precisely, and how much surrounding context does the model need to answer correctly?

Once you think about chunking that way, the rest of the design becomes much easier.

KEEP READING

Related engineering notes