IamBishal
AI Engineering

RAG Chunking Strategies: How to Choose, and How to Measure the Choice

No chunk size is right for every corpus, so treat chunking as a retrieval-design decision and settle it with recall@k on your own labelled queries.

Bishal Saha

20 min read

Shrinking chunks is a database decision with storage and latency costs.
Bishal Saha

Someone asks your support assistant how many export requests per minute the Enterprise plan allows. It answers with the Pro plan's number, or says it doesn't know. Then a colleague opens the docs and points to the table row that answers the question. The model didn't fail. The passage never reached it.

When retrieval misses like this, people suspect chunking first, and most advice comes down to a number. Firecrawl recommends recursive splitting at 400–512 tokens with 10–20% overlap as a default; MachineLearningMastery lists 512 or 1024 tokens with 10–20% overlap as common settings. Neither knows your documents or queries.

I treat chunking as a retrieval-design decision, closer to choosing an index or a primary key than to tuning a parameter. My work centres on RAG and LLM applications, and my background includes PostgreSQL, so I look at chunks the way I look at rows: what is the unit of lookup, what does it cost to store, and which queries does it serve badly?

The short answer: no chunk size is right for every corpus. For structured documents, start with structure-aware splitting that carries the heading path into every chunk, add document context where a chunk's meaning depends on text outside it, and choose between options by measuring recall@k on queries you labelled yourself.

1. Two units that rarely line up

Every chunker makes two decisions at once. It sets the unit of retrieval, the thing the index scores and returns, and the unit of meaning, the span a reader needs to answer the question. The unit of retrieval works best small and focused. The unit of meaning is often bigger than it looks, because it depends on a heading three paragraphs up or a table's header row.

Small chunks have a real advantage: dense retrieval often works better on shorter segments, because a short passage is less likely to have its meaning over-compressed into one vector. That pushes chunks smaller, and every step smaller separates a chunk from more of its context. Size isn't the only lever either; Anthropic notes that chunk size, boundaries and overlap can all affect retrieval performance.

The running example is an API documentation page with an H2 called "Rate limits", an H3 for each plan, and under each H3 a Markdown table of endpoints against requests per minute. The query is "What is the rate limit on the export endpoint for the Enterprise plan?" One table row answers it, and that row means nothing without its header row and the "Enterprise" heading.

docs/api/rate-limits.md (illustrative excerpt)
## Rate limits

Limits apply per API key. Requests over the limit receive HTTP 429.

### Pro

| Endpoint         | Requests per minute |
|------------------|---------------------|
| GET /v1/orders   | 300                 |
| POST /v1/exports | 10                  |

### Enterprise

| Endpoint         | Requests per minute |
|------------------|---------------------|
| GET /v1/orders   | 3000                |
| POST /v1/exports | 120                 |

This pipeline marks where chunking decisions take effect:

flowchart LR
  D["Document"] --> C["Chunker"]
  C --> E["Embed"]
  E --> I["Index (pgvector HNSW)"]
  I --> R["Retrieve top-N"]
  R --> RR["Rerank to top-k"]
  RR --> L["LLM"]
  C -.- n1["Boundaries, size, overlap, context prefix"]
  E -.- n2["Model token limit: possible truncation"]
  I -.- n3["Chunk count drives rows, index size, build time"]
  R -.- n4["hnsw.ef_search caps candidates"]
  RR -.- n5["Candidate pool size N vs final k"]

2. Fixed-size and recursive splitting: cheap, predictable, blind to structure

Fixed-size chunking cuts the text every N tokens and can repeat some tokens across each cut. It is deterministic and cheap, so re-indexing and backfills stay predictable. It ignores sentence, section and table ends.

Overlap is insurance for answers that straddle a boundary. In Chroma's evaluation, TokenTextSplitter reached its highest recall, 0.824, at a chunk size of 250 with an overlap of 125, and dropped to 0.771 with no overlap. Overlap can matter; that isn't a setting to copy.

Overlap has a cost too. Overlapping each chunk by half its length roughly doubles the chunk count, so you store twice the embeddings and rows. Adjacent chunks also become near-duplicates that crowd top-k slots another relevant passage could have used, so deduplicate near-identical hits, or reduce overlap once structure-aware boundaries make it less necessary.

Recursive character splitting is the usual upgrade. It works through a prioritised list of separators, paragraph breaks before line breaks, and recurses until each piece fits under the limit. Prose comes out better, but the splitter still treats a table row, or a line of code, as just another line. Shrink the window and the Enterprise export row lands in a chunk with neither "Enterprise" nor the full column header.

3. Structure-aware chunking: let the document draw the boundaries

Documentation already has boundaries, because its authors wrote them. Structure-aware chunking splits on Markdown or HTML headings, keeps lists and code fences intact, and falls back to recursive splitting only inside a section that exceeds the size limit.

The change I'd make first is to carry the heading path into every chunk: store Rate limits > Enterprise as metadata for filtering and display, and prefix it to the text that gets embedded. A short chunk then still says what it's about, which is exactly what the Enterprise row was missing.

Fixed windows ignore the table; structure-aware chunks keep it whole and carry their heading path.

Tables need explicit rules. Keep a table whole if it fits; otherwise split it by rows and repeat the header row in every piece, because without column names | POST /v1/exports | 120 | is just a string with a number in it. To find tables that got split anyway, sample chunks that contain pipe or <td> syntax but no header line. Code needs different rules: split at function or class boundaries, and keep the sentence that introduces a code block attached to it, since that sentence is often what matches the query.

Headings cause a problem of their own: a heading stranded at the end of one chunk, or a heading-only chunk that matches many queries and answers none. The LangChain Markdown header splitter docs suggest strip_headers=True when a header becomes a tiny first chunk. If you strip headers, put the heading path back into the embedded text yourself.

Section sizes come out uneven, long sections still need a secondary split, and the approach needs clean input: a badly converted PDF has lost the headings and table markup, so fix the conversion before tuning the chunker.

4. Semantic chunking finds topic shifts, at a price

Semantic chunking embeds sentences or small windows, then starts a new chunk wherever similarity between neighbours drops below a threshold; some variants cluster sentences instead. Every sentence is embedded at index time, changing the model or threshold can move boundaries across the whole corpus and force a re-index, and a similarity signal has no notion of a table header or a code fence.

The evidence points two ways. In Chroma's evaluation, ClusterSemanticChunker scored highest on precision but slightly below average on recall, which Chroma suggests is likely due to its small chunks. My reading is that semantic chunking may suit long, unstructured prose such as transcripts. On documentation, the headings already mark most topic shifts, and finding them costs no embeddings.

5. Giving chunks back their document

Three techniques restore a small chunk's context without enlarging the unit the index scores.

Contextual retrieval. As Anthropic describes it, an LLM is given the whole document and writes a short context for each chunk, which is prepended before the chunk is embedded and indexed for BM25. In Anthropic's tests, Contextual Embeddings reduced the top-20-chunk retrieval failure rate by 35% (5.7% → 3.7%), and combining them with Contextual BM25 reduced it by 49% (5.7% → 2.9%). It improved every embedding model Anthropic tested, on Anthropic's data rather than yours. The cost lands at index time: one LLM call per chunk, repeated whenever the chunker changes.

Parent-document (small-to-big) retrieval. Index small child chunks so matching stays sharp, then return the enclosing section to the LLM. In PostgreSQL that is ordinary relational modelling: a child table with a foreign key to its parent, and the vector index on the child.

schema.sql (illustrative)
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE doc_section (
  id           bigserial PRIMARY KEY,
  doc_id       text NOT NULL,
  heading_path text NOT NULL,
  body         text NOT NULL
);

CREATE TABLE doc_chunk (
  id         bigserial PRIMARY KEY,
  section_id bigint NOT NULL REFERENCES doc_section(id),
  start_char int    NOT NULL,  -- offsets into the source document
  end_char   int    NOT NULL,
  content    text   NOT NULL,
  embedding  vector(1024) NOT NULL  -- set to your embedding model's dimension
);

CREATE INDEX ON doc_chunk USING hnsw (embedding vector_cosine_ops);

Small-to-big costs context tokens, since each hit sends a whole section. When several children of one parent match, deduplicate the parents before building the prompt.

Small children keep matching precise; deduplicated parents give the LLM the whole section.

Late chunking. Günther and colleagues reverse the usual order: embed all tokens of the long text with a long-context embedder, then apply chunking after the transformer and just before mean pooling, with no additional training. Because every token has already attended to its surroundings, the Enterprise row's vector can carry some of the "Enterprise" heading.

You need an embedder that pools per chunk rather than per input. Some hosted APIs offer this: Jina's embeddings API has a late_chunking flag that concatenates the inputs and processes them as one sequence before splitting. Otherwise you run a model that exposes token-level outputs, such as the Apache-2.0 jina-ai/late-chunking reference implementation. Documents longer than the model's window still need splitting first.

6. Where each strategy breaks

StrategyGood forFails onCost
Fixed-size + overlapUniform text, predictable re-indexingTables, code, anything where a boundary splits meaningLow compute; overlap adds storage and duplicate hits
Recursive characterGeneral proseTable rows and code lines treated as plain linesLow compute
Structure-awareDocs, wikis, specs with clean markupBadly converted PDFs; uneven section sizesLow compute; per-format rules to maintain
SemanticLong unstructured prose, transcriptsTables, code; boundaries shift when model or threshold changesEmbedding every sentence; re-index on change
Contextual retrievalChunks that depend on document-level contextCorpora where index-time LLM cost is unacceptableOne LLM call per chunk, repeated when the chunker changes
Parent-documentAnswers that need the whole sectionTight context budgetsMore context tokens per hit; parent deduplication
Late chunkingContext-dependent chunks without LLM callsDocuments beyond the model windowAn embedder with per-chunk pooling, hosted or self-run

7. Chunk size against embedding limits, top-k, reranking and the index

Start with the embedder. Pinecone notes that a chunk exceeding the embedding model's context window may have its excess tokens truncated, so check what yours does, and measure chunk lengths with the tokenizer that model actually uses; character counts and another model's tokenizer both mislead.

Chunk size times k is roughly what reaches the LLM, so smaller chunks let you retrieve more of them. Anthropic compared 5, 10 and 20 chunks and found 20 the most performant of those, but advises testing on your own use case.

Reranking widens the funnel: retrieve a large candidate set cheaply, then let a reranker choose the final k. In Anthropic's tests, adding reranking on top of contextual embeddings and contextual BM25 cut the top-20-chunk failure rate by 67% (5.7% → 1.9%), using the Cohere reranker. That figure is for the stacked pipeline on Anthropic's data, not a reranker on its own.

This is where pgvector can quietly undermine the funnel. The pgvector README notes that HNSW results are limited by hnsw.ef_search, 40 by default, so a request for 100 candidates can return fewer rows. Raise it for that query:

candidates.sql (illustrative)
BEGIN;
SET LOCAL hnsw.ef_search = 200;  -- at least the number of candidates you request
SELECT id, section_id, content
FROM doc_chunk
ORDER BY embedding <=> $1        -- $1: query embedding, bound by your driver
LIMIT 100;
COMMIT;

SET LOCAL keeps the change inside the transaction, so other queries on a pooled connection keep the default. If the candidate query also filters, say by product or document type, turn on iterative index scans (pgvector 0.8.0 or later) with SET LOCAL hnsw.iterative_scan = strict_order. They then scan further, up to a cap set by hnsw.max_scan_tuples.

Smaller chunks also mean more rows: a bigger index, longer builds and an ef_search setting to retune. Shrinking chunks is a database decision with storage and latency costs, and it deserves the same review as any other schema change.

8. Measuring a chunking choice

The labelled set comes first. Collect real user queries, pair each with the passage that answers it, and record that passage as a document ID plus a character span, not a chunk ID. Chunk IDs change whenever the chunker changes; spans are anchored to the source, so any chunker can be scored against the same labels.

Use two metrics. Recall@k is the fraction of queries where at least one top-k chunk overlaps the gold span by a minimum amount. Precision is the share of retrieved text inside the gold span, which penalises bloated chunks and duplicated text outside the gold span. Report both, because a strategy can win on one and lose on the other, as Chroma's semantic chunker did.

Hold everything else fixed: corpus, embedding model and index settings, or use exact search so the approximate index isn't a second variable.

k is the awkward one: ten small chunks and ten section-sized chunks are different amounts of text, so either choose k per chunker to equalise retrieved text, or report text returned per query beside recall. Any-overlap recall also flatters large chunks, so raise the minimum overlap when the whole answer has to arrive in one chunk.

The harness scores two chunkers by recall@k, character-level precision and characters returned per query, using exact cosine search. You supply embed, which maps a list of strings to an L2-normalised NumPy array from your production model. The fixed-size chunker counts characters rather than tokens, and the header chunker neither splits long sections nor repeats table headers; fix both before trusting the numbers. The header chunker also prefixes the heading path, so it changes two variables; add a variant without the prefix to separate them.

chunk_eval.py
import re
import numpy as np

def fixed_chunks(doc_id, text, size=1500, overlap=200):
    step, out = size - overlap, []
    for s in range(0, len(text), step):
        if s > 0 and s + overlap >= len(text):
            break  # this window would sit entirely inside the previous chunk
        e = min(s + size, len(text))
        out.append((doc_id, s, e, text[s:e]))
    return out

def header_chunks(doc_id, text):
    fences = [m.span() for m in re.finditer(r"^```.*?^```", text, re.M | re.S)]
    starts = [m.start() for m in re.finditer(r"^#{1,6} ", text, re.M)
              if not any(a <= m.start() < b for a, b in fences)]
    bounds = sorted({0, *starts, len(text)})
    out, path = [], {}
    for s, e in zip(bounds, bounds[1:]):
        body = text[s:e]
        m = re.match(r"(#{1,6}) (.*)\n?", body)
        if m:  # the heading moves into the path prefix, e.g. "Rate limits > Enterprise"
            level = len(m.group(1))
            path = {k: v for k, v in path.items() if k < level}
            path[level] = m.group(2).strip()
            body = body[m.end():]
        prefix = " > ".join(path[k] for k in sorted(path))
        out.append((doc_id, s, e, f"{prefix}\n{body.strip()}"))  # offsets stay in source
    return out

def evaluate(chunks, queries, embed, k=10, min_frac=0.0):
    # queries: (query_text, doc_id, gold_start, gold_end); characters stand in for tokens
    C = embed([c[3] for c in chunks])
    Q = embed([q[0] for q in queries])
    top_k = np.argsort(-(Q @ C.T), axis=1)[:, :k]  # exact cosine search
    hits, precision, returned = 0, 0.0, 0
    for qi, (_, doc, gs, ge) in enumerate(queries):
        top = [chunks[i] for i in top_k[qi]]
        ov = [max(0, min(e, ge) - max(s, gs)) if d == doc else 0 for d, s, e, _ in top]
        size = sum(e - s for _, s, e, _ in top)
        hits += any(o >= max(1, min_frac * (ge - gs)) for o in ov)
        precision += sum(ov) / size
        returned += size
    n = len(queries)
    return {"recall@k": hits / n, "precision": precision / n, "chars_per_query": returned / n}

def compare(docs, queries, embed, k=10, min_frac=0.0):
    for name, chunker in [("fixed", fixed_chunks), ("headers", header_chunks)]:
        chunks = [c for d, t in docs.items() for c in chunker(d, t)]
        print(name, len(chunks), evaluate(chunks, queries, embed, k, min_frac))

Against pgvector, load each chunker's output with its offsets and replace the NumPy ranking with ORDER BY embedding <=> $1 LIMIT k.

Before spending anything on embeddings, look at the chunks; the output is deterministic. A 200-character window with 40 characters of overlap stands in for a long page, and the gold span is the Enterprise POST /v1/exports row, characters 412–454 of the excerpt saved exactly as shown, with a trailing newline.

show_chunks.py
from chunk_eval import fixed_chunks, header_chunks

text = open("docs/api/rate-limits.md").read()
gold = (412, 454)  # the Enterprise "POST /v1/exports" row
for name, chunks in [("fixed", fixed_chunks("rl", text, size=200, overlap=40)),
                     ("headers", header_chunks("rl", text))]:
    for _, s, e, body in chunks:
        if s < gold[1] and gold[0] < e:
            print(f"--- {name} [{s}:{e}]\n{body}\n")

It prints:

output
--- fixed [320:455]
ute |
|------------------|---------------------|
| GET /v1/orders   | 3000                |
| POST /v1/exports | 120                 |

--- headers [267:455]
Rate limits > Enterprise
| Endpoint         | Requests per minute |
|------------------|---------------------|
| GET /v1/orders   | 3000                |
| POST /v1/exports | 120                 |

The fixed chunk holding the answer starts partway through the word "minute", with no "Enterprise" and no "rate limit", only an endpoint path and numbers. The window before it, [160:360], is worse in a quieter way: it has the "### Enterprise" heading and the column header, but its only export row is Pro's, with a value of 10. A chunk like that can match the query well and carry the wrong number, one plausible route to the Pro answer in the opening. The header-aware chunk keeps heading path, column names and row together.

That is chunk text, not a retrieval result; whether the header chunk ranks higher depends on your embedding model, and evaluate on your labelled set tells you. When it runs, list the queries that flipped between chunkers in both directions. Each points to a structure, a table, a code block or a heading, where one chunker loses meaning. On a small labelled set a difference of one or two queries is noise, so grow it from production misses.

9. Where to start, and the 30 queries that decide it

For a corpus of mostly structured text such as documentation, wikis or specs, I would start with structure-aware splitting and a recursive fallback for long sections, with heading paths in the embedded text and tables kept whole with their headers. The document's writers have already marked the units of meaning, so using them costs little.

Add context where meaning depends on the rest of the document: parent-document retrieval if your context budget absorbs whole sections, contextual retrieval if index-time LLM cost is acceptable, late chunking if your embedder can pool per chunk. Keep semantic chunking mainly for long, unstructured prose. Whether retrieval is the right lever at all is the subject of fine-tuning vs RAG vs prompt engineering; what happens to chunks once they reach the window is context engineering.

Then label 30 real queries, each with the passage that answers it recorded as a document span, and compare your current chunker against one alternative by recall@k, with the embedding model, index settings and retrieved-text budget held fixed. Keep the queries that flipped. They tell you which chunker to choose, and why.

View All Articles

Bishal SahaLet's build together

Have a system to design, or an AI feature to get right?

Tell me about the problem. You'll get a clear, honest view of the best way forward.

  • Reply within 24 hoursOn business days, with my honest view and a next step.
  • Accepting select engagementsArchitecture, AI features and full builds.
  • Remote, worldwideWorking with startups, SMEs and enterprises.