Skip to content
Skip to lesson
Back to Topics
MediumRAG & Retrieval13 min read

Chunking Strategies

Turn clean documents into retrieval units that preserve answers, citations, and measurable search quality.

On this page

The API specification made it out of the Markdown parser intact:

inference-api-spec-v2.md, section 4.2: Streaming timeout: close idle SSE connections after 90 seconds without heartbeat frames.

Then the chunking step runs, and it does something that looks harmless. One chunk ends with Streaming timeout: close idle SSE connections after, and the next begins with 90 seconds without heartbeat frames. A developer asks, "Why did my idle SSE connection close, and how do I keep it alive?" The second chunk matches seconds and heartbeat cleanly and ranks first. The model receives a timeout and an exception with nothing stating which protocol or condition they belong to.

Nothing crashed. Extraction succeeded, the vector index returned a high-scoring hit, and the answer still failed because the boundary landed right across the one sentence that mattered.

Two stages decide whether the trigger (idle SSE connections), the threshold (90 seconds), and the exception (without heartbeat frames) reach the generator intact: document ingestion (extracting clean structure from raw PDFs, HTML, scans, and Markdown) and (dividing normalized documents into the units a retriever indexes and returns in ).[1] Every embedding model also enforces a hard token ceiling while compressing an entire chunk into one vector; all-MiniLM-L6-v2, for example, outputs 384 dimensions and truncates inputs past 256 word pieces by default.[2]

A 12-word specification rule from inference-api-spec-v2.md section 4.2 reads: Streaming timeout: close idle SSE connections after 90 seconds without heartbeat frames. On the left, fixed 8-word windows with 2-word overlap cut directly between 90 and seconds, leaving Chunk 1 without the unit or heartbeat exception and Chunk 2 without the SSE trigger. On the right, heading-aware section chunking keeps the trigger, numeric threshold, exception, and section 4.2 locator together in one chunk.
Fixed windows split a rule right between its numeric threshold and its qualifying clause. A heading-aware section keeps the condition, value, and source locator together.

Ingestion first: PDFs, HTML, OCR, and normalized records

Even the sharpest chunker cannot repair text corrupted during extraction. Normalize every incoming file format into a single structured record carrying source_id, locator (page number, section heading, or anchor), version, a SHA-256 , extracted text blocks, and caller-permission metadata before any splitter runs:

Source formatDominant failure modePractical defense
Digital PDFsPDFs store positioned glyphs rather than logical paragraphs; multi-column layouts scramble reading order, running headers/footers break sentences, and tables flatten into unaligned text[3][4]Use layout-aware parsers (such as Docling or bounding-box column sorters) that reconstruct reading order and emit structured tables[5]
Scanned PDFs & images (OCR)Character confusions (1S vs. 15, O vs. 0, dropped decimal points) silently alter numeric limits[6]Record OCR confidence scores and route low-confidence pages to vision-language OCR (such as olmOCR) or human review; never silently regex-rewrite uncertain digits[7]
HTML web pagesNavigation bars, sidebars, cookie banners, and footers flood chunks with repeated boilerplateParse the DOM (for example with BeautifulSoup or readability extractors) to keep <main> / <article> headings, lists, and tables while stripping page chrome[8]
Markdown & docsFlattening files to plain text throws away headings, tables, and code fences you already hadParse into an AST or preserve heading hierarchy, fenced code blocks, and pipe tables verbatim[9]

When documents are dominated by dense charts, multi-column financial tables, or engineering schematics that resist text extraction, visual page retrieval (such as ColPali, which embeds rendered page images with a vision-language encoder and matches queries via ColBERT-style late interaction) lets retrieval skip fragile OCR altogether.[10][11] Finally, treat external HTML and PDF text as untrusted input: keep extraction quality, quarantine checks against embedded prompt injections, and document access permissions as three independent gates before writing records into the index.[12]

Define answerability before choosing a chunk size

It is tempting to treat chunk size as a tuning dial and ask whether 512 tokens beats 256. Start instead with what a complete passage must hold for a real query: "Why did my idle streaming connection close, and how do I keep it open?"

Candidate chunkSearchable?Answerable?Defect
Streaming timeout: close idle SSE connections afteryesnoDrops the 90-second limit and heartbeat exception
90 seconds without heartbeat frames. Batch retention: expire JSONL outputs after 14 days.yesnoDrops the SSE trigger and mixes in an unrelated retention rule
Streaming timeout: close idle SSE connections after 90 seconds without heartbeat frames.yesyesKeeps trigger, threshold, and exception intact

Small chunks still work well as sharp search targets when a downstream step reliably expands them into their parent section before generation. Always evaluate the complete assembled text that actually enters the generator under your context budget.

Fixed windows and the real cost of overlap

The simplest splitter walks across text in fixed windows of NN with overlap OO, advancing by stride N−ON - O. The script below splits on whitespace so cut boundaries stay easy to inspect; in production, always count lengths with your model's tokenizer (including prepended headings and special tokens) so oversized inputs are never silently truncated.

What does increasing overlap actually buy? Our streaming-timeout rule is 12 words long. Inside a 7-word window, ramping overlap from 0 to 4 doubles the total indexed words while keeping complete coverage of the 12-word rule at zero:

fixed-windows-and-overlap-cost.py
import numpy as np

def fixed_windows(text: str, size: int, overlap: int) -> list[str]:
    if not 0 <= overlap < size:
        raise ValueError("require size > overlap >= 0")
    words = text.split()
    chunks = []
    for start in range(0, len(words), size - overlap):
        end = min(start + size, len(words))
        chunks.append(" ".join(words[start:end]))
        if end == len(words):
            break
    return chunks

spec = (
    "Streaming timeout: close idle SSE connections after 90 seconds without heartbeat frames. "
    "Batch retention: expire JSONL outputs after 14 days."
)
for i, chunk in enumerate(fixed_windows(spec, size=6, overlap=2)):
    print(f"win[{i}]: {chunk}")

full_rule = ("streaming timeout", "90 seconds", "heartbeat frames")
short_fact = ("connections after 90 seconds",)

for overlap in (0, 2, 4):
    chunks = fixed_windows(spec, size=7, overlap=overlap)
    indexed_words = sum(len(c.split()) for c in chunks)
    has_rule = sum(all(p in c.lower() for p in full_rule) for c in chunks)
    has_short = sum(all(p in c.lower() for p in short_fact) for c in chunks)
    print(f"size=7 overlap={overlap}: chunks={len(chunks)} words={indexed_words:2d} full_rule={has_rule} short_fact={has_short}")
    assert has_rule == 0
Output
win[0]: Streaming timeout: close idle SSE connections
win[1]: SSE connections after 90 seconds without
win[2]: seconds without heartbeat frames. Batch retention:
win[3]: Batch retention: expire JSONL outputs after
win[4]: outputs after 14 days.
size=7 overlap=0: chunks=3 words=20 full_rule=0 short_fact=0
size=7 overlap=2: chunks=4 words=26 full_rule=0 short_fact=1
size=7 overlap=4: chunks=6 words=40 full_rule=0 short_fact=1

Look at win[4] (outputs after 14 days.): a trailing fragment drops its subject (Batch retention: expire JSONL) so the 14-day window floats without context. Meanwhile, overlap 2 rescues the 4-word phrase "connections after 90 seconds" (short_fact=0 -> 1) at the cost of 6 extra words, yet no amount of overlap can ever fit a 12-word rule inside a 7-word window.

Three interval maps show size-7 windows over the same 17 runbook words. Overlap 0, 2, and 4 store 17, 21, and 33 words in 3, 3, and 5 chunks. A strip under each map darkens where words repeat across windows. The rollback rule spans words 1 to 10, so no seven-word window holds the whole rule at any overlap.
Higher overlap multiplies indexed tokens (roughly 1 / (1 - O/N)), giving short facts a second chance across boundaries while never fitting a fact longer than the window itself.

Bennani and Moslonka found no measurable answer-quality gain from up to 20% overlap on Natural Questions with sentence-aware splitting and SPLADE retrieval.[13] Measure overlap on your own labeled queries before paying the storage and latency tax.

Split on document structure first

Technical documentation, API references, and research papers already mark logical boundaries with headings, tables, paragraphs, and fenced code blocks. Throwing away Markdown structure only to patch broken boundaries with overlap solves a problem you created yourself.

For plain prose or oversized sections without subheadings, LangChain's RecursiveCharacterTextSplitter tries paragraph breaks ("\n\n"), line breaks ("\n"), spaces (" "), and characters ("") in sequence.[14] Watch two defaults: it counts Python characters (len) unless you pass a tokenizer-backed length_function, and its default separators do not detect sentence boundaries.

Keep three structural rules intact when splitting technical docs:

  1. Prepend headings to body text: Attach each Markdown heading (or heading hierarchy) to the embedded string while storing raw text and source locators separately so citations stay verbatim.
  2. Keep table headers with every row group: Detaching | /v1/batches | 100 MB | 24h | from | Endpoint | Max Payload | Timeout | strips every cell of its role. Repeat column headers (and table-wide units or footnotes) on every split group.
  3. Keep fenced code blocks intact, and distribute oversized tails evenly: Treat each fenced code block as atomic unless it alone exceeds the encoder cap. When an oversized paragraph must be split under a hard cap (for example, 15 words at max size 7), you need at least 3 chunks so you cannot enforce a 6-word minimum (3×6=18>153 \times 6 = 18 > 15); distribute evenly (5, 5, 5) rather than gluing a 1-word tail into an 8-word overflow that silently truncates inside the embedder.
structure-aware-spec-splitting.py
@dataclass(frozen=True)
class SpecChunk:
    heading: str
    body: str
    indexed_text: str
    locator: str

def split_markdown_sections(markdown: str, source: str) -> list[SpecChunk]:
    chunks, heading, buf = [], "Document", []

    def flush() -> None:
        text = "\n".join(buf).strip()
        if text:
            chunks.append(SpecChunk(heading, text, f"{heading}\n{text}", f"{source}#sec={len(chunks)}"))
        buf.clear()

    for line in markdown.strip().splitlines():
        if line.startswith("## "):
            flush()
            heading = line[3:].strip()
        else:
            buf.append(line)
    flush()
    return chunks

def split_table_with_headers(lines: list[str], heading: str, max_rows: int = 2) -> list[str]:
    header, sep, rows = lines[0], lines[1], lines[2:]
    return [
        f"{heading}\n{header}\n{sep}\n" + "\n".join(rows[i:i + max_rows])
        for i in range(0, len(rows), max_rows)
    ]

def balanced_cap_split(text: str, max_words: int) -> list[tuple[str, tuple[int, int]]]:
    spans = list(re.finditer(r"\S+", text))
    count = math.ceil(len(spans) / max_words)
    base, extra = divmod(len(spans), count)
    out, cursor = [], 0
    for i in range(count):
        n = base + int(i < extra)
        s, e = spans[cursor].start(), spans[cursor + n - 1].end()
        out.append((text[s:e], (s, e)))
        cursor += n
    return out

doc = """## Streaming timeout
Close idle SSE connections after 90 seconds without heartbeat frames.
## Batch retention
Expire completed JSONL output files after 14 days."""

for ch in split_markdown_sections(doc, "inference-api-spec-v2.md"):
    print(ch.locator, "|", ch.indexed_text.replace("\n", " :: "))

table = [
    "| Endpoint | Max Payload | Timeout |",
    "| --- | --- | --- |",
    "| /v1/embeddings | 16 MB | 30s |",
    "| /v1/chat/completions | 32 MB | 90s |",
    "| /v1/batches | 100 MB | 24h |",
]
table_chunks = split_table_with_headers(table, "API Endpoint Limits", max_rows=2)
print("Table groups:", len(table_chunks), "| all carry header:", all("| Endpoint |" in g for g in table_chunks))

balanced = balanced_cap_split(
    "Close idle SSE connections after 90 seconds unless clients send periodic keepalive heartbeat frames over HTTP.",
    max_words=7,
)
print("Balanced spans:", [(len(t.split()), span) for t, span in balanced])
assert all(len(t.split()) <= 7 for t, _ in balanced)
Output
inference-api-spec-v2.md#sec=0 | Streaming timeout :: Close idle SSE connections after 90 seconds without heartbeat frames.
inference-api-spec-v2.md#sec=1 | Batch retention :: Expire completed JSONL output files after 14 days.
Table groups: 2 | all carry header: True
Balanced spans: [(6, (0, 35)), (5, (36, 72)), (5, (73, 110))]

Parent-child retrieval: search small, answer big

Often the sharpest embedding target is a single sentence, while the generator needs the entire surrounding section (including caveats and parameter tables). Parent-child retrieval indexes narrow child spans for matching and expands each hit to its parent section before generation.[15]

A query about a failed rollback on deploy pay-742 matches the short indexed child 15 minutes with deploy ID. After checks that the link is current, the caller may read the parent, and the section fits the budget, its pointer returns the complete rollback section from page 7 of incident-runbook-v3.pdf.
The retriever matches a compact child excerpt, then follows its pointer to assemble the complete cited parent section for generation.

Expansion introduces three serving-time invariants:

  1. Deduplicate parents when two matched children point to the same parent section.
  2. Verify version agreement and caller permissions on the parent itself.
  3. Reject budget overflows (or drop lower-ranked parents) rather than silently truncating a parent mid-clause.
parent-child-expansion.py
parents = {
    "sec-4-2": {
        "text": "Streaming timeout: close idle SSE connections after 90 seconds without heartbeat frames. Send `: ping` every 30 seconds.",
        "source": "inference-api-spec-v2.md",
        "version": 2,
    },
}
hits = [
    {"text": "90 seconds without heartbeat frames", "parent_id": "sec-4-2", "version": 2},
    {"text": "Send `: ping` every 30 seconds", "parent_id": "sec-4-2", "version": 2},
]

def expand_parents(matches: list[dict], allowed: set[str], word_budget: int) -> list[dict]:
    selected = {}
    for m in matches:
        pid = m["parent_id"]
        if pid not in allowed:
            raise PermissionError("parent access denied")
        parent = parents[pid]
        if m["version"] != parent["version"]:
            raise ValueError("stale child-to-parent version")
        selected[pid] = parent
    if sum(len(p["text"].split()) for p in selected.values()) > word_budget:
        raise ValueError("context budget exceeded")
    return list(selected.values())

expanded = expand_parents(hits, allowed={"sec-4-2"}, word_budget=25)
print(f"child_hits={len(hits)} -> deduplicated_parents={len(expanded)}")
print("expanded:", expanded[0]["text"])

for label, args in [
    ("stale", ([{**hits[0], "version": 1}], {"sec-4-2"}, 25)),
    ("denied", (hits, set(), 25)),
    ("overflow", (hits, {"sec-4-2"}, 10)),
]:
Output
child_hits=2 -> deduplicated_parents=1
expanded: Streaming timeout: close idle SSE connections after 90 seconds without heartbeat frames. Send `: ping` every 30 seconds.
stale: stale child-to-parent version
denied: parent access denied
overflow: context budget exceeded

Semantic chunking and late chunking

Structure-aware splitting plus parent expansion handles most technical corpora cleanly. Reach for heavier splitters only when labeled errors reveal a specific failure:

Observed failureTechniqueWhat to verify
Long unstructured prose drifts across topicsSemantic boundary detectionHard size cap and labeled recall vs. sentence splits
Short matched span misses caveatsParent-child expansionDeduplication, version match, and token budget
Pronouns depend on earlier paragraphsLate chunkingEncoder token-state access and permission isolation

Bennani and Moslonka observed that sentence-preserving splits matched semantic chunking up to ~5,000 tokens of retrieved context on Natural Questions.[13] Always benchmark the simpler structural baseline first.

Semantic chunking embeds adjacent sentences and proposes a split wherever cosine similarity drops below a tuned threshold (watch out for poorly calibrated thresholds that sever an exception from its rule). Late chunking solves cross-sentence coreference (such as a paper introducing "Rotary Position Embeddings (RoPE)" and later saying "the method"): Günther et al. run the full document through the encoder first, then mean-pool contextual token states inside each chunk span.[16]

Side-by-side comparison of early and late chunking on an eight-word sentence split into spans of three, three, and two tokens. On the left (early), self-attention is restricted to block-diagonal chunk spans so pooled states h4 to h6 see only words 4 to 6. On the right (late), full bidirectional attention runs across all 8 tokens before pooling h4 to h6 into a contextual chunk vector.
Early chunking restricts self-attention to isolated spans. Late chunking encodes the full sequence first and pools token hidden states afterward, letting each vector absorb surrounding document context.

Keep three constraints in mind for late chunking:

  1. Vectors gain context, raw text does not: The stored chunk still reads "the method", so the generator still needs parent expansion to name RoPE clearly.
  2. Encoder requirements: You need access to token-level hidden states plus exact character-to-token offset alignment (unlike ColBERT late interaction, late chunking still stores a single pooled vector per chunk).[16]
  3. Permission isolation: Never encode public and restricted sections in the same transformer forward pass, because cross-token attention lets restricted text shape the public chunk's vector even if the restricted chunk is filtered out later.

Evaluate splitters at a fixed generation budget

The script below compares broken fixed windows against heading-aware sections using TfidfVectorizer cosine retrieval and a semantic-boundary check over technical paper sentences:

evaluate-splitters-and-semantic-cuts.py
query = "idle SSE connection timeout seconds heartbeat"
required_phrases = ("sse connections", "90 seconds", "heartbeat")

configs = {
    "broken_fixed": [
        "Streaming timeout: close idle SSE connections after",
        "90 seconds without heartbeat frames. Batch retention: expire JSONL outputs after 14 days.",
    ],
    "heading_aware": [
        "Streaming timeout\nClose idle SSE connections after 90 seconds without heartbeat frames.",
        "Batch retention\nExpire completed JSONL output files after 14 days.",
    ],
}

for name, chunks in configs.items():
    vec = TfidfVectorizer(stop_words="english")
    mat = vec.fit_transform(chunks)
    top_hit = chunks[int(np.argmax(cosine_similarity(vec.transform([query]), mat)[0]))]
    answerable = all(p in top_hit.lower() for p in required_phrases)
    print(f"{name:14} | answerable={answerable} | hit={top_hit.splitlines()[0]}")

# Semantic similarity drop between topic-coherent vs topic-shifted sentences
sentences = [
    "Rotary position embeddings rotate query and key pairs by token index.",
    "Rotary position embeddings preserve relative position inside query-key dot-product attention.",
    "KV cache paging allocates fixed blocks to eliminate external memory fragmentation.",
]
s_vec = TfidfVectorizer(stop_words="english").fit_transform(sentences).toarray()
for i in range(len(sentences) - 1):
    sim = float(cosine_similarity(s_vec[i:i + 1], s_vec[i + 1:i + 2])[0, 0])
    action = "split" if sim < 0.15 else "keep"
    print(f"boundary {i}->{i + 1}: cosine={sim:.2f} -> {action}")

assert not all(p in configs["broken_fixed"][0].lower() for p in required_phrases)
assert all(p in configs["heading_aware"][0].lower() for p in required_phrases)
Output
broken_fixed   | answerable=False | hit=Streaming timeout: close idle SSE connections after
heading_aware  | answerable=True | hit=Streaming timeout
boundary 0->1: cosine=0.41 -> keep
boundary 1->2: cosine=0.00 -> split

Production chunking checklist

DecisionDefault starting pointWhat to check
Primary splitterHeading- and table-aware splitting with recursive fallbackAnswerable-chunk rate on labeled queries
Token budgetMeasure full embedded string (heading + body + special tokens) with embedder tokenizerZero silent truncation
Tables & codeRepeat column headers on row splits; keep fenced blocks intactExact-value and API-parameter queries
OverlapOff for complete sections; benchmark on prose fallbacksToken inflation 1/(1−O/N)1/(1 - O/N) vs. recall lift
Metadatasource_id, locator, heading, version, SHA-256 Verbatim citations back to normalized spans
Advanced splittersParent expansion first; semantic/late chunking only on measured missesFair comparison at a fixed generation token budget
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 5 answered
1.A fixed splitter processes 20 words with window size 8 and overlap 3, stopping once a window reaches the end. What are the zero-based start offsets and total indexed word occurrences?
2.An API spec contains a 12-word constraint. A splitter uses 9-word windows with overlaps of 0, 3, and 6. What holds for single-chunk coverage versus assembled multi-chunk context?
3.An embedding tokenizer counts 47 body tokens, 4 prepended heading tokens, and 2 special tokens, while the encoder limit is 48 tokens. What happens if you embed without resplitting?
4.Two matched child chunks point to parent P (18 generator tokens), and a third points to parent Q (11 tokens). Both parents are permitted and current, and the evidence budget is 25 tokens. Under deduplicated whole-parent packing, what is the cost and decision?
5.During late chunking, a public API guide and an internal restricted architecture note are encoded in one shared transformer forward pass before mean-pooling each span. Filtering removes the restricted chunk at query time. What security flaw remains?

5 questions remaining.

References

Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks.

Lewis, P., et al. · 2020 · NeurIPS 2020

https://arxiv.org/abs/2005.11401

sentence-transformers/all-MiniLM-L6-v2

Sentence Transformers · 2026 · Hugging Face model card

https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2

pypdf Documentation.

pypdf Contributors · 2026 · Official documentation

https://pypdf.readthedocs.io/

PDF3: Ensuring Correct Tab and Reading Order in PDF Documents

World Wide Web Consortium · 2026

https://www.w3.org/WAI/WCAG22/Techniques/pdf/PDF3

Docling document

Docling project · 2026

https://docling-project.github.io/docling/concepts/docling_document/

Tesseract OCR Documentation.

Tesseract OCR Project · 2026 · Official documentation

https://tesseract-ocr.github.io/tessdoc/

olmOCR

Allen Institute for AI · 2026 · GitHub

https://github.com/allenai/olmocr

Beautiful Soup Documentation.

Richardson, L. · 2026 · Official documentation

https://beautiful-soup.readthedocs.io/

Using markdown-it-py

markdown-it-py Contributors · 2026

https://markdown-it-py.readthedocs.io/en/latest/using.html

ColPali: Efficient Document Retrieval with Vision Language Models

Faysse, M., Sibille, H., Wu, T., Omrani, B., Viaud, G., Hudelot, C., & Colombo, P. · 2024

https://arxiv.org/abs/2407.01449

ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT.

Khattab, O., & Zaharia, M. · 2020 · SIGIR 2020

https://arxiv.org/abs/2004.12832

OWASP GenAI LLM Top 10 2026

OWASP GenAI Security Project · 2026

https://genai.owasp.org/resource/owasp-genai-llm-top-10-2026/

A Systematic Analysis of Chunking Strategies for Reliable Question Answering.

Bennani, S., & Moslonka, C. · 2026 · arXiv preprint

https://arxiv.org/abs/2601.14123

RecursiveCharacterTextSplitter

LangChain · 2023

https://docs.langchain.com/oss/python/integrations/splitters/recursive_text_splitter

ParentDocumentRetriever

LangChain · 2024

https://reference.langchain.com/python/langchain-classic/retrievers/parent_document_retriever/ParentDocumentRetriever

Late Chunking: Contextual Chunk Embeddings Using Long-Context Embedding Models.

Günther, M., et al. · 2024 · arXiv preprint

https://arxiv.org/abs/2409.04701

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.