How to Write a Chunker With Overlap
How to cut a long document into overlapping pieces in plain Python, and how to pick the size and overlap, for your AI interview.
In short
A chunker cuts a long text into pieces of set size, and overlap makes each piece repeat the end of the one before, so an idea split at a boundary still appears whole. The step is size minus overlap, and overlap must stay smaller than size.
11 min readBeginnerCommon · estimateFacts checked 27 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
A chunker cuts a long document into pieces of a set size. Overlap means each piece starts with the last few words of the piece before, so a sentence cut at the edge still appears whole in one piece. In code, the step is size minus overlap. I always check that overlap is smaller than size, because if they are equal the step is zero and the loop never moves on, or Python raises an error. I tune both numbers by testing how well search finds the right chunk, not by guessing.
A language model reads only a limited amount of text at once, and a search index works better on short pieces. So before we embed a long document, which means turning it into numbers a search can compare, we cut it into chunks. A chunker is the small piece of code that does the cutting. Its two settings are the chunk size, how big each piece is, and the overlap, how much of the previous piece is repeated at the start of the next.
Why repeat text? Because a cut can land in the middle of a rule. Imagine a bank policy that waives a card fee when the card was reported lost within 24 hours. Without overlap, one chunk holds the first half of that rule and the next holds the rest. Neither chunk gives the full rule. With overlap, the 24-hour condition sits whole in at least one chunk, and the search can find it.
The code is short. Set the step to size minus overlap, cut a window of the given size, and stop when a window reaches the end. I also refuse an overlap as big as the size, because the step would be zero. Words stand in for tokens here, since the standard library has no tokenizer. In production I would count tokens, because embedding models have token limits.
Then I say what the numbers cost and what they cannot fix. More overlap means more chunks to embed and store, and more near-duplicate hits in the results. Overlap also does not give a chunk its missing context, such as which card or which year the policy covers. That needs a different technique, so I would test a few settings on real questions and keep the one that finds the right chunk best.
What is a chunker with overlap, in plain words?
A chunker cuts a long text into pieces. Each piece is a chunk, and the chunks are what you embed (turn into a list of numbers a search can compare) and search. Overlap means neighbouring chunks share a few words at their edges, so each piece repeats the end of the piece before it.
Think of a relay of claims clerks, each given one page of a 400-page loan agreement. Each clerk starts with the last two lines of the page before, so no clause is read without its opening. The copying costs a little extra reading, and it saves the clause that a hard page break would otherwise split.
The case in this answer is a bank's support assistant that searches its policy handbook. A rule about card fees is cut across two chunks, and the assistant quotes the wrong fee.
Key words
- Chunk
- A piece of a document, small enough to embed and search.
- Overlap
- Words repeated at the edge of the next chunk.
- Step
- How far the next chunk starts: size minus overlap.
- Token
- The unit a model reads, roughly a word or part of one.
Why does overlap matter at a cut?
A plain cut can break a rule in half, and neither half then gives the answer. The chart shows the same rule cut two ways.
Overlap keeps a rule whole at a cut
Plain cut, no overlap
Cut at word 18
the fee rule is split in two
Two halves
neither half holds the whole rule
Cut with 6 words shared
Cut at word 18
the next chunk starts 6 words back
Condition stays whole
chunk 2 holds the 24-hour condition
Bot misses the fee
answers from the wrong part
Bot answers right
the condition is found and used
- 1A plain cut at word 18 splits the fee rule.
- 2Neither half holds the whole rule, so the bot answers from the wrong part.
- 3Six words are shared, so the next chunk starts earlier.
- 4Chunk 2 holds the 24-hour condition whole, so the bot finds it and answers.
Tip
Asked why overlap helps? Say it protects an idea that a cut would split, and that it costs some repeated text.
How do you write the chunker in code?
- 1
Check the settings
Overlap must be zero or more and smaller than size. Otherwise the step is zero or negative and the chunker never moves on.
- 2
Set the step
The step is size minus overlap. With 18-word chunks and 6 shared words, each new chunk starts 12 words after the last.
- 3
Cut a window
Take the words from the start up to start plus size. That is one chunk.
- 4
Stop at the end
Once a window reaches the last word, stop. Without this stop, the final chunk is only a repeat of the tail before it.
Here it is in plain Python, run as printed. Words stand in for tokens.
# A made-up bank policy, cut into 18-word chunks. Words stand in for tokens. Standard library only.
text = (
"A replacement debit card costs 150 rupees. The fee is waived if the card was "
"reported lost within 24 hours of the last transaction. Otherwise the customer pays "
"the fee and the card is posted in five working days."
)
PHRASE = "the card was reported lost within 24 hours"
def chunk(words, size, overlap):
if not 0 <= overlap < size:
raise ValueError("overlap must be at least 0 and smaller than size")
step = size - overlap # how far each new chunk starts
chunks = []
for start in range(0, len(words), step):
chunks.append(words[start:start + size])
if start + size >= len(words): # the last window reached the end
break
return chunks
words = text.split()
for overlap in (0, 6):
parts = chunk(words, 18, overlap)
whole = [i + 1 for i, c in enumerate(parts) if PHRASE in " ".join(c)]
print(f"overlap {overlap}: {len(parts)} chunks, phrase whole in chunk {whole}")
for i, c in enumerate(chunk(words, 18, 6), 1):
print(i, " ".join(c))Output
overlap 0: 3 chunks, phrase whole in chunk [] overlap 6: 3 chunks, phrase whole in chunk [2] 1 A replacement debit card costs 150 rupees. The fee is waived if the card was reported lost within 2 the card was reported lost within 24 hours of the last transaction. Otherwise the customer pays the fee 3 Otherwise the customer pays the fee and the card is posted in five working days.
The run shows the rescue. With no overlap, no chunk holds the 24-hour condition whole. With 6 words shared, chunk 2 does.
How do you choose the chunk size and overlap?
There is no universal answer. LangChain's guide says: "Chunk size trades precision against context, and there is no universal best value." Small chunks match questions precisely but may lack context. Big chunks carry context but dilute the match and cost more to read.
“Chunk overlap repeats a portion of text between adjacent chunks so that an idea split at a boundary still appears whole in at least one chunk.”
LangChain
“A common starting point is an overlap of 10% to 20% of the chunk size.”
LangChain
“While this approach works well for many applications, it can lead to problems when individual chunks lack sufficient context.”
Anthropic
- Too small
Chunks lose the context
A chunk can be too short to answer on its own, and the bot then guesses.
- Too big
Matches get blurred
Long chunks hold many topics, so they match questions less precisely and the model reads noise.
- Tested
Keep what retrieves best
Try a few sizes and overlaps on real questions, then keep the setting that finds the right chunk most often.
Measure in tokens, not characters, because embedding models have token limits and bill by the token. Anthropic's contextual retrieval post says that in RAG, chunks are usually no more than a few hundred tokens, and it notes that chunk size, boundary and overlap can affect how well search finds the right chunk.
What can overlap not fix?
Overlap keeps a cut from splitting an idea. It does not tell a chunk what it is about. A chunk that says the fee is waived may not name the card or the policy year. Microsoft's guide warns that relevant context spread across chunks might not be captured.
Tip
Asked how to fix missing context? Name a separate step, such as adding a short context line to each chunk before embedding it, rather than more overlap.
How would you chunk a 400-page loan agreement for a bank's assistant?
Start with the structure. Clauses have numbers and headings, so I cut on clause boundaries first. Then I apply the size and overlap only to a clause that is still too long.
I keep the clause number and heading as labels stored with every chunk (metadata), so the assistant can cite the clause even when the chunk is a middle slice.
Then I test. I keep a fixed set of real questions, such as what the late-payment charge is, and check which chunk comes back for each. I change the size or overlap only when that set gets worse.
What does the interviewer want to hear?
A strong answer covers
- What a chunk is, and why documents get split before they are embedded.
- The step is size minus overlap, and overlap must be smaller than size.
- A plain cut can split a rule, and overlap keeps it whole in one chunk.
- Size and overlap are tuned by testing, not guessed.
- Overlap costs storage and near-duplicate hits, and it does not add context.
- The loop stops at the last full window, so the final chunk is not a repeat.
Common traps
Trap"Overlap is just extra text, so bigger is always safer."
BetterBigger overlap means more chunks to store and more near-duplicate hits. Test a range.
Trap"Overlap fixes missing context."
BetterIt keeps an idea whole across a cut. A chunk still needs its document context, which is a separate fix.
Trap"Split by characters and you are done."
BetterModels count tokens, so measure in tokens, and prefer cuts at sentences or headings where you can.
Can you spot the bug?
Spot the bug
A teammate's chunker keeps losing words between chunks in the policy handbook. Which line causes it?
Quick check
A chunker is set to size 512 tokens and overlap 512 tokens. What should it do?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
Learn it in depth
Last updated on 27 November 2026
Building a search over your own documents?
Venkat designs and builds AI products and agents, the UI and the system behind them. Book a short call and say which documents you need searched.