Sub topic 5
Fixed-size chunking with overlap
This chapter covers the simplest chunking strategy: cut a document into pieces of roughly equal length, and let neighboring pieces share some text. It is the baseline that the later strategies in this tutorial are compared against.
I assume you know basic Python, what an embedding is, how vector similarity search works, and what a token is. The chapter before this one covered how to choose chunk size and overlap in general terms. Here you implement the strategy and look at where it breaks.
What fixed-size chunking does
Fixed-size chunking ignores the meaning and layout of the text. It picks a size, such as 200 words or 800 characters, and cuts the document every time it reaches that size. The size can be counted in characters, words, or tokens.
Overlap is the amount of text that each chunk repeats from the end of the previous chunk. Without overlap, a sentence that falls on a boundary is cut in two, and neither half carries the full idea. With overlap, the boundary region appears at the end of one chunk and again at the start of the next. At least one of them then holds the sentence whole, as long as the sentence is shorter than the overlap.
The relationship between the three numbers is:
sizeis the maximum length of a chunk.overlapis how much of the previous chunk is repeated.step = size - overlapis how far the window moves each time.
With size=200 and overlap=40, the window moves 160 words per step. Each chunk shares 40 words with its predecessor, so about 20% of the stored text is duplicated.
A working implementation
The function below chunks by word count. It splits the text on whitespace, walks a window across the word list, and rejoins each window into a string.
def chunk_words(text, size=200, overlap=40):
if overlap >= size:
raise ValueError("overlap must be smaller than size")
words = text.split()
step = size - overlap
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break
return chunksThree details are worth understanding.
- The overlap check. If
overlap >= size, thenstepis zero or negative.rangewould raise an error or never advance, so the function fails early with a clear message. - The early break. Once a chunk reaches the end of the word list, the next window would contain only words that are already in this chunk. The
breakstops the loop and avoids a trailing chunk that is entirely duplicated text. - Whitespace normalization.
text.split()followed by" ".join(...)collapses newlines, tabs, and repeated spaces into single spaces. This is fine for plain prose. It destroys line breaks in code, tables, and lists, which matters later in this chapter.
Trying it
sample = " ".join(f"w{i}" for i in range(500))
pieces = chunk_words(sample, size=200, overlap=40)
for i, piece in enumerate(pieces):
ws = piece.split()
print(i, len(ws), ws[0], ws[-1])Assuming chunk_words from above is defined in the same file, the output is:
0 200 w0 w199
1 200 w160 w359
2 180 w320 w499Chunk 1 begins at w160, which is the last 40 words of chunk 0 (w160 to w199). The final chunk is shorter because the document ran out of words.
Counting in the right unit
Words are easy to count but are only a rough proxy for what an embedding model sees. Embedding models have a maximum input length measured in tokens, and a token is often a fragment of a word. English prose averages roughly 1.3 tokens per word. Code, URLs, and text in some other languages can produce many more tokens per word.
This leads to a common failure. A chunk of 200 words may be 260 tokens in plain English but 500 tokens in a dense technical document. If the embedding model accepts 512 tokens, the second case is close to the limit, and some models silently truncate input beyond it. The truncated tail is then missing from the vector, so the chunk cannot be found by a question about that tail.
The options, from least to most accurate, are:
| Unit | How you count | Strength | Weakness |
|---|---|---|---|
| Characters | `len(text)` | Fast, no dependencies | Loose link to tokens, varies by language |
| Words | `text.split()` | Easy to reason about | Token count still varies |
| Tokens | The embedding model's own tokenizer | Matches the model's limit exactly | Needs the tokenizer, slower |
If your model's limit is close to your chunk size, count in tokens using the tokenizer that belongs to the embedding model. The loop is the same; only the list you slide over changes. Here is a generic version that works on any list of items, including token IDs:
def window(items, size, overlap):
if size <= 0:
raise ValueError("size must be positive")
if not 0 <= overlap < size:
raise ValueError("overlap must be in [0, size)")
step = size - overlap
out = []
for start in range(0, len(items), step):
out.append(items[start:start + size])
if start + size >= len(items):
break
return out
tokens = list(range(1000))
windows = window(tokens, size=256, overlap=32)
print(len(windows), [len(w) for w in windows])Running it prints 5 [256, 256, 256, 256, 104]. To use it with a real tokenizer, encode the text into token IDs, call window, and decode each window back into a string. Check that decoding keeps the characters you expect, because a window boundary can fall in the middle of a multi-byte character with some tokenizers.
What overlap buys and what it costs
Overlap is not free. Each choice has an effect on storage, retrieval, and answer quality.
Benefits
- A sentence or fact near a boundary is more likely to appear intact in at least one chunk.
- Context that bridges two chunks, such as a pronoun that refers back to the previous sentence, is partly preserved.
Costs
- Index size grows. With 20% overlap, you store about 25% more text than you would with none, since each chunk's unique content is
stepwords out ofsize. The ratio issize / step, so 200/160 = 1.25. - Search results can contain near-duplicates. When a relevant passage sits in an overlap zone, two adjacent chunks both match, and they take two slots in your top-k results.
- The generator receives repeated text in its prompt, which wastes part of the context budget.
A common starting range is 10% to 20% of the chunk size. Going above about 30% rarely helps, because the extra duplication raises cost and near-duplicate results faster than it improves recall.
Edge cases
Test these inputs before relying on a chunker.
- Empty text.
"".split()returns[].range(0, 0, step)yields nothing, sochunk_wordsreturns an empty list. Your pipeline must handle a document that produces zero chunks. - Text shorter than
size. The first window covers everything, thebreaktriggers, and you get one chunk. - Text exactly
sizewords long. The first window ends exactly at the end, so thebreaktriggers and no extra chunk appears. - Zero overlap.
overlap=0is valid. The step equals the size and chunks do not share text. - Negative overlap. The
overlap >= sizecheck does not catch it.overlap=-10makessteplarger thansize, so words between windows are dropped. The genericwindowfunction above rejects it. If you keepchunk_words, add the same lower-bound check. - Very long single "words". A base64 string or a long URL counts as one word but may be many tokens. Word-based sizes cannot see this.
A quick check of the first three:
assert chunk_words("") == []
assert len(chunk_words("a b c", size=10, overlap=2)) == 1
exact = " ".join(["x"] * 200)
assert len(chunk_words(exact, size=200, overlap=40)) == 1
print("edge cases pass")Where fixed-size chunking fails
Fixed-size chunking is predictable, which is a real advantage. You can compute how many chunks a corpus will produce and how large the index will be. It is also fast and has no dependencies. Its weakness is that it is blind to structure.
- Mid-sentence cuts. Window boundaries land wherever the count lands. A chunk can begin with the second half of a sentence, which makes it harder to embed meaningfully.
- Broken structures. A heading can end up at the bottom of one chunk while its section body starts the next. A table row can be split from its header.
- Mixed topics. A fixed window may contain the end of one topic and the start of another. The embedding then blends the two, and the vector matches neither topic well.
- Lost formatting. Because the word-based version rejoins with single spaces, line breaks and indentation are gone.
These are the reasons the next chapters introduce recursive splitting, sentence-based chunking, and structure-aware chunking. Each one keeps the same size limit but chooses cut points more carefully.
When fixed-size is the right choice
Use it when:
- The text is fairly uniform prose, such as transcripts, articles, or logs without much structure.
- You need a quick baseline to measure other strategies against.
- Speed and a predictable index size matter more than boundary quality.
Move to another strategy when your documents have headings, code, tables, or lists that carry meaning through their layout.
Summary of the key settings
| Setting | Typical starting point | What to watch |
|---|---|---|
| Unit | Tokens when near the model limit, otherwise words | Truncation by the embedding model |
| Size | 200 to 500 tokens | Too large blends topics, too small loses context |
| Overlap | 10% to 20% of size | Duplicate results and larger index |
| Step | `size - overlap` | Must be greater than zero |
These are starting points, not rules. The final chapters show how to test them against your own questions.
Exercise
You chunk a document of 1,000 words with chunk_words(text, size=250, overlap=50). How many chunks are produced, and what are the first and last words of the second chunk (by index, where the first word has index 0)?
Show answer
The step is 250 - 50 = 200. Window starts are 0, 200, 400, 600, 800. The window at start 600 covers words 600 to 849, which does not reach the end, so the loop continues. The window at start 800 covers words 800 to 999, and 800 + 250 >= 1000, so the loop breaks after adding it. That gives 5 chunks. The second chunk starts at index 200 and ends at index 449.
Exercise
A teammate sets overlap=-20 with size=100 in chunk_words, expecting "a little gap between chunks to save space." What happens, and how would you fix the function?
Show answer
The check overlap >= size passes, so no error is raised. The step becomes 100 - (-20) = 120, which is larger than the size, so 20 words between each pair of windows are never included in any chunk. That text becomes unsearchable. Fix it by also rejecting negative values, for example if not 0 <= overlap < size: raise ValueError(...).
Exercise
Your embedding model accepts 512 tokens. You chunk with size=400 words and overlap=60 words on a corpus of API documentation full of code identifiers and URLs. Retrieval misses facts that appear near the end of chunks. What is the likely cause, and what change would you make?
Show answer
Technical text produces many more tokens per word than plain prose, so a 400-word chunk can exceed 512 tokens. The model truncates the input, and the tail of the chunk is not represented in its vector. Count size in tokens using the embedding model's own tokenizer and choose a size comfortably below 512, for example 300 tokens with an overlap of 40 to 60 tokens.