Chunking Strategies for Embedding Pipelines
Choose chunk sizes, overlaps and boundaries that keep retrieved passages meaningful, then measure how each strategy affects recall before committing to one.
On this page
Introduction
Chunking is the least glamorous and most consequential step in a retrieval pipeline. The embedding model can only see what you give it, so a chunk that mixes two unrelated topics matches both poorly, and a chunk that cuts a sentence in half loses the very fact you needed. There is no universally correct chunk size; the right answer depends on how your documents are structured and how questions are asked. What matters is that you choose the boundary rule deliberately and measure its effect on retrieval recall, because getting it wrong is expensive to discover late.
Why Fixed Size Splitting Fails
Splitting every N characters ignores structure and produces arbitrary cuts through sentences, tables and code. A table split across two chunks is useless to both, and a heading stranded at the end of a chunk loses its section. Fixed size is easy to implement and therefore tempting, but it optimizes for the tokenizer rather than the reader. Use it only as a fallback for text with no detectable structure.
import tiktoken
ENC = tiktoken.get_encoding("cl100k_base")
def split_sentences(text: str) -> list[str]:
# Keep terminators; simple but predictable for prose.
import re
parts = re.split(r"(?<=[.!?])\s+", text.strip())
return [p for p in parts if p]
def chunk_by_tokens(text: str, max_tokens: int = 400, overlap: int = 50) -> list[str]:
sentences = split_sentences(text)
chunks, cur, cur_tokens = [], [], 0
for s in sentences:
n = len(ENC.encode(s))
if cur_tokens + n > max_tokens and cur:
chunks.append(" ".join(cur))
# carry trailing sentences for overlap
back, back_tokens = [], 0
for prev in reversed(cur):
pn = len(ENC.encode(prev))
if back_tokens + pn > overlap:
break
back.insert(0, prev)
back_tokens += pn
cur, cur_tokens = back, back_tokens
cur.append(s)
cur_tokens += n
if cur:
chunks.append(" ".join(cur))
return chunks
Split on Structure First
Markdown headings, HTML section tags, source code functions and PDF paragraphs are natural semantic boundaries. Splitting on them keeps a section, a function or a list together so the embedding represents one idea. When a natural unit exceeds your maximum size, fall back to sentence-aware splitting within that unit rather than cutting mid-sentence. Preserving the heading path as metadata lets you prepend the section title to the chunk before embedding, which sharpens similarity for questions that mention the topic.
def assert_chunks_valid(chunks: list[str], max_tokens: int = 400) -> None:
for i, c in enumerate(chunks):
assert c.strip(), f"chunk {i} is empty"
n = len(ENC.encode(c))
assert n <= max_tokens, f"chunk {i} has {n} tokens (> {max_tokens})"
# Neighbouring chunks should share some overlap text.
for i in range(len(chunks) - 1):
tail = chunks[i].split()[-5:]
head = chunks[i + 1].split()[:15]
assert set(tail) & set(head), f"no overlap between chunks {i} and {i + 1}"
Choosing Size and Overlap
Measure size in tokens, not characters, because the embedding model truncates by token. A common starting range is 256 to 512 tokens with 10 to 20 percent overlap so a fact spanning a boundary appears whole in at least one chunk. Overlap costs storage and duplicates near-identical text in results, so keep it modest. Above roughly 800 tokens the embedding starts averaging distinct ideas and similarity scores flatten, which hides the single best chunk among many mediocre ones.
Keeping Metadata Attached
Every chunk should carry the document id, the position, the section path, the source URL and any access control labels. Metadata enables citation, lets you filter by tenant or permission at query time, and allows you to reassemble neighbouring chunks when a retrieved passage needs surrounding context. Without metadata a retrieved passage is an orphan string that you cannot verify or display responsibly. Propagating access labels from the source document keeps a chunk from surfacing for a tenant who should never see it.
Validating the Chunking Output
Treat chunking as data transformation that needs tests. Assert that no chunk exceeds the token limit, that overlap regions actually duplicate text, that concatenating chunks reproduces the source with only expected overlap, and that no chunk is empty or pure whitespace. Run these checks in the ingestion job so a schema change in the source cannot silently produce broken chunks that degrade retrieval for weeks.
Measuring the Effect on Recall
Chunk size is a retrieval hyperparameter, so evaluate it like one. Build a question set with known answer passages, re-ingest the corpus under each candidate strategy, and compare recall at K and mean reciprocal rank. Choose the strategy that wins on your data rather than the value that sounded reasonable in a blog post. Because changing chunking invalidates every stored vector, decide the strategy before you index at scale and freeze it once measured.
Tables, Code and Multilingual Text
Structured content needs special handling. A wide table loses its meaning when split by character count, so serialize each row as a self-contained line that repeats the column headers, or summarize the table once and embed the summary. Source code should be split on function and class boundaries so a signature stays with its body. Multilingual corpora must use an embedding model trained across the relevant languages, because a model tuned only on English maps translated queries and native text to different regions of the space. Record the language on every chunk so retrieval can filter or route by it.
The Cost of Splitting Too Finely
Aggressive splitting feels safe because smaller chunks match more precisely, but it multiplies the number of vectors, the storage bill and the query cost while fragmenting context until each chunk answers half a question. It also floods the top K results with overlapping neighbours of the same passage, crowding out other relevant material. Track vectors per document and mean chunks returned per query as operational metrics; a sudden rise usually means a source format changed and the parser split on the wrong boundary. Balance precision against these costs rather than minimizing chunk size by default.
Sources
Sources: tiktoken, OpenAI embeddings guide, LangChain text splitters.
FAQ
- Should I chunk by tokens or characters?
- Always by tokens. The embedding model enforces a token limit, and character counts vary with language and content, so a character budget can silently overflow and truncate the chunk.
- What overlap should I use?
- Start with ten to twenty percent of the chunk size, enough to keep a fact that spans a boundary whole in one chunk. More overlap raises storage cost and duplicate results without much recall gain.
Report a problem with this articleOpens a pre-filled issue on GitHub.