Sub topic 4
Choosing chunk size and overlap
This chapter assumes you know basic Python, what an embedding is, how vector similarity search ranks results, and what a token is. Earlier chapters covered where chunking sits in a RAG pipeline, why we chunk, and the token limits that apply. Here you will decide how big chunks should be and how much neighboring chunks should share.
Two numbers, many consequences
Every chunker has two settings you must pick before you write any real logic:
- Chunk size is the maximum length of one chunk, measured in tokens, words, or characters.
- Overlap is the amount of text that the end of one chunk shares with the start of the next.
No universal best pair exists. The right values depend on the questions users ask, the structure of your documents, the embedding model, and how much text the generator can read. This chapter gives you a starting point, a way to reason about each direction you can move, and a way to check the cost of your choice.
What chunk size controls
An embedding model turns a chunk into one vector. That vector is a summary of everything in the chunk, so size controls how specific the summary is.
Small chunks (roughly 64 to 200 tokens) usually hold one idea. A query that targets that idea matches strongly, so precision is high. The costs are:
- A chunk can lose the context it needs. "It was raised to 15%" is useless if the sentence naming the subject sits in the previous chunk.
- An answer that spans several sentences may be split across chunks, and only some of them may rank in the top results.
- You get more vectors to store and search.
Large chunks (roughly 500 to 1,500 tokens) keep context together and rarely cut an answer in half. The costs are:
- The vector averages several topics, so a query about one of them matches weakly. This is often called dilution.
- Each retrieved chunk carries more irrelevant text into the prompt, which uses context budget and can distract the generator.
- You may exceed the embedding model's input limit, in which case the model silently truncates the tail, or rejects the input, depending on the provider.
A practical starting range
When you have no data yet, start from these defaults and then adjust:
| Content type | Starting size (tokens) | Starting overlap |
|---|---|---|
| Short FAQ entries, chat messages | 100 to 200 | 0 to 10% |
| Documentation, articles, help pages | 256 to 512 | 10 to 15% |
| Long reports, legal text, papers | 400 to 800 | 10 to 20% |
| Source code | By function or class, not by size | Rarely needed |
These are starting points, not rules. The ranges come from common practice, and your corpus may behave differently. A question-answering system whose answers are one fact each favors the small end. A system that must explain a process across several paragraphs favors the large end.
Two limits cap your choice from above:
- The embedding model's input limit. If the model accepts 512 tokens, a 700-token chunk is partly ignored. Keep chunks safely below the limit, because your chunker's token count and the model's tokenizer may disagree slightly.
- The context budget. If you retrieve
kchunks and each hassizetokens, the retrieved text costs aboutk × sizetokens. That must fit in the prompt alongside the question, instructions, and room for the answer.
What overlap does
Overlap exists because boundaries are arbitrary. A fixed-size splitter can cut a sentence, or a definition and its example, into two chunks. With overlap, the end of chunk N is repeated at the start of chunk N+1. A passage cut at the boundary then appears whole in at least one chunk.
Overlap helps when:
- Answers often sit near paragraph or sentence boundaries.
- Your splitter ignores structure, as plain fixed-size splitting does.
- Small chunks make it likely that one idea spans a cut.
Overlap has a cost, and it grows with the ratio of overlap to size:
- Storage and embedding cost. Repeated text is embedded and stored twice.
- Duplicate retrieval. A query that matches the shared text may return both neighboring chunks, so two of your
kslots hold nearly the same words. - No fix for bad boundaries. Overlap hides a bad cut. It does not choose a good one. Splitters that respect sentences, paragraphs, and headings (covered in later chapters) need less overlap.
A common range is 10% to 20% of the chunk size. Going above about 25% rarely pays for itself, because you store a lot of duplicate text for a small gain in boundary coverage. The overlap must also stay smaller than the size, or the chunker can never advance. The chunker below rejects that case.
Measuring the cost of a configuration
Before you embed a corpus, you can compute how many chunks a setting produces and how many tokens you will store. The function below mirrors the fixed-size chunker you will build in the next chapter: each chunk starts size - overlap tokens after the previous one, and the last chunk may be shorter.
def chunk_stats(total_tokens, size, overlap):
if overlap >= size:
raise ValueError("overlap must be smaller than size")
step = size - overlap
count = 0
stored = 0
for start in range(0, total_tokens, step):
count += 1
stored += min(size, total_tokens - start)
if start + size >= total_tokens:
break
return {
"chunks": count,
"stored_tokens": stored,
"overhead": stored / total_tokens - 1,
}
if __name__ == "__main__":
corpus_tokens = 100_000
for size, overlap in [(256, 0), (256, 50), (1024, 200)]:
stats = chunk_stats(corpus_tokens, size, overlap)
print(
f"size={size:>4} overlap={overlap:>3} "
f"chunks={stats['chunks']:>4} "
f"stored={stats['stored_tokens']:>6} "
f"overhead={stats['overhead']:.1%}"
)For a 100,000-token corpus, this prints:
size= 256 overlap= 0 chunks= 391 stored=100000 overhead=0.0%
size= 256 overlap= 50 chunks= 486 stored=124250 overhead=24.2%
size=1024 overlap=200 chunks= 122 stored=124200 overhead=24.2%The table shows two effects. First, 50 tokens of overlap on 256-token chunks adds about 24% more stored text, because overlap is 20% of the size and the step shrinks to 206 tokens. Second, the same overlap ratio gives the same overhead whatever the size, but small chunks produce about four times as many vectors. That matters for index size and search latency on large corpora.
Interactions to watch
Size and top-k. If you shrink chunks, raise k or the generator may see too little. If you grow chunks, lower k or the prompt may fill with noise. Change these together and compare results, not one at a time.
Size and query type. Short keyword-style queries match small chunks well. Long, descriptive questions often match larger chunks better, because the question itself carries context.
Overlap and deduplication. If overlap is high, consider merging adjacent retrieved chunks before building the prompt. Otherwise the generator reads the same sentences twice.
Size and metadata. Titles and heading paths added to each chunk (a later chapter) use tokens. A 256-token budget with a 30-token header leaves 226 tokens of body text. Account for this in the size you choose.
A repeatable way to choose
- Find the hard limits. Note the embedding model's maximum input tokens and the prompt budget you can spend on retrieved text.
- Look at your documents and questions. Are answers one sentence or several paragraphs? Is the text prose, tables, or code?
- Pick a starting pair from the table above, such as size 400 and overlap 60 for documentation.
- Compute the cost with a function like
chunk_statsto see chunk count and storage overhead. - Try two or three neighbors of your starting point, for example sizes 256, 400, and 800 with overlap at about 15%.
- Compare on a fixed question set and keep the best configuration. Re-run the comparison whenever you change the embedding model or the document mix, because the best size moves with both.
Common mistakes
- Using characters as if they were tokens. A 1,000-character limit is about 250 tokens in English prose, but can be far more in code or other languages.
- Setting overlap to a large fraction of size. This inflates the index and fills results with near-duplicates.
- Ignoring the embedding model's limit. Text beyond the limit may be dropped without an error, so the end of a long chunk never influences its vector.
- Using one setting for every document type. A corpus of FAQs and long contracts rarely wants a single size. Consider separate settings per source.
- Changing size without re-indexing. Chunk settings define what is in the index. After changing them, you must re-chunk and re-embed everything, or you will compare mixed results.
Exercise
You index a 200,000-token corpus with chunk size 500 and overlap 100. About how many chunks do you get, and how many tokens do you store in total? Your embedding model accepts at most 256 tokens. What do you change, and why?
Show answer
The step is 500 - 100 = 400 tokens, so the chunker starts a new chunk every 400 tokens. The number of chunks is 1 + ceil((200,000 - 500) / 400) = 1 + 499 = 500. Of these, 499 are full 500-token chunks, and the last starts at token 199,600 and holds 400 tokens. Stored tokens are 499 × 500 + 400 = 249,900, about 25% more than the corpus. The chunk size of 500 exceeds the model's 256-token limit, so the model would truncate or reject the text and about half of each chunk would not shape its vector. Reduce the size below 256 (for example 200, leaving room for a metadata header) and keep overlap near 10% to 20% of the new size, such as 30. Then re-chunk and re-embed everything and compare the new setup against the old one on a fixed question set.