esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
Let’s talk

I’ll build the agent for it.

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.

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

  1. 1A plain cut at word 18 splits the fee rule.
  2. 2Neither half holds the whole rule, so the bot answers from the wrong part.
  3. 3Six words are shared, so the next chunk starts earlier.
  4. 4Chunk 2 holds the 24-hour condition whole, so the bot finds it and answers.
Top: a plain cut at word 18 splits the fee rule, so neither half holds it whole and the bot misses it. Bottom: six words are shared, so chunk 2 holds the 24-hour condition whole and the bot can answer from it. The price is a few repeated words.

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. 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. 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. 3

    Cut a window

    Take the words from the start up to start plus size. That is one chunk.

  4. 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.

Python
# 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

1 / 6

What will they ask next?

  1. Q113What is chunking, and why does size matter?13 min
  2. Q114Fixed vs recursive vs semantic chunking?12 min
  3. Q115What is chunk overlap?10 min
  4. Q155Build a minimal RAG pipeline.13 min
  5. Q475Implement cosine similarity and brute-force top-k search.13 min

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.