---
title: "Chunking Strategies for RAG: Semantic, Heading-Aware & More"
description: "The main chunking strategies compared, why web pages need heading-aware chunking, tested Python for a markdown chunker and semantic chunking, overlap and parent-child chunks, and how to pick a chunk size."
category: "guides"
url: https://keirolabs.cloud/blog/chunking-strategies-rag
published: 2026-11-24
updated: 2026-11-24
---

# Chunking strategies for RAG: fixed, recursive, heading-aware and semantic

## The 60-second version

**Chunking is splitting documents into smaller pieces before you embed and retrieve them.** Retrieval then returns the few chunks that answer a question, instead of whole documents that bury the answer and fill the context window.

| Strategy | How it splits | Best for | Watch out for |
|---|---|---|---|
| Fixed-size | Every N tokens or characters, with overlap | Quick baselines, uniform text | Cuts sentences, tables and code in half |
| Recursive | Paragraphs, then sentences, then words, until chunks fit | General prose | Ignores document structure |
| Heading-aware (markdown) | At headings, then by size within each section | Web pages, docs, anything with headings | Very long sections still need a size split |
| Semantic | Where the topic shifts, measured with embeddings | Long unstructured text, transcripts | Extra embedding calls; uneven sizes |
| Parent-child | Small chunks for matching, larger parent for context | Precise matching that also needs surrounding context | More storage and bookkeeping |

**For web pages, start with heading-aware chunking.** Pages extracted as markdown already mark their own topic boundaries with headings, so use them. A sensible starting size is a few hundred tokens per chunk with a small overlap. Then measure on your own questions.

## Why does chunk size matter?

**Chunk size trades precision for context.**

- **Too large:** one chunk covers several topics, its embedding becomes an average of them, and it matches nothing well. It also costs more context when retrieved.
- **Too small:** a chunk loses the context that makes it meaningful. "It costs $29.99 a month" is useless without the product name from two sentences earlier.

**There is no universal best size.** It depends on your documents, your embedding model and your questions. Pick a starting point, build a small evaluation set, and try two or three sizes. The difference is often bigger than the difference between embedding models.

## What makes web pages different?

**Web pages come with structure you should keep, and noise you should drop.**

- **Extract main content first.** Navigation, footers and cookie banners produce junk chunks that match common queries. In our tests, main-content extraction cut pages by 75% to 99% compared with raw HTML ([context engineering for search agents](/blog/context-engineering-web-search-agents)).
- **Use markdown headings as boundaries.** A section titled "Pricing" is one topic; a split in the middle of it is a bad split.
- **Never split tables or code blocks.** Half a pricing table, or half a function, is worse than no chunk.
- **Prefix each chunk with its page title and heading path.** "Keirolabs › Pricing › Free plan" gives the chunk the context it lost when it was cut out of the page, and it improves embedding matches.
- **Keep the URL on every chunk,** so answers can cite their source.

## Heading-aware chunking in Python

**This chunker splits markdown at headings, keeps code blocks and tables whole, splits oversized sections by paragraph, and prefixes every chunk with its heading path.** It is plain Python and runs as is.

```python
import re

def chunk_markdown(md: str, title: str, max_chars: int = 1500, overlap_paras: int = 1) -> list[dict]:
    # 1) Split into blocks at blank lines and headings; a fenced code block stays one block
    blocks, buf, in_code = [], [], False
    def end_block():
        if any(l.strip() for l in buf):
            blocks.append("\n".join(buf).strip())
        buf.clear()
    for line in md.splitlines():
        if line.strip().startswith("`" * 3):     # a code fence opens or closes
            in_code = not in_code
        if not in_code and re.match(r"#{1,6}\s", line):
            end_block(); blocks.append(line.strip())   # each heading is its own block
        elif not in_code and not line.strip():
            end_block()
        else:
            buf.append(line)
    end_block()

    # 2) Walk blocks, tracking the heading path, and pack them into chunks under max_chars
    chunks, path, cur = [], [], []
    def flush():
        if cur:
            prefix = " › ".join([title] + path)
            chunks.append({"heading": prefix, "text": prefix + "\n\n" + "\n\n".join(cur)})
    for b in blocks:
        m = re.match(r"^(#{1,6})\s+(.*)", b)
        if m:                                    # a heading starts a new section
            flush(); cur = []
            level = len(m.group(1))
            path[:] = path[: level - 1] + [m.group(2).strip()]
            continue
        if cur and sum(len(x) for x in cur) + len(b) > max_chars:
            flush(); cur = cur[-overlap_paras:] if overlap_paras else []   # carry overlap
        cur.append(b)
    flush()
    return chunks

page = """# Pricing
## Free plan
1,000 credits a month. No card needed.

## Paid plans
| Plan | Price |
|---|---|
| Essential | $29.99 |
| Startup | $99.99 |
| Business | $299.99 |
"""
for c in chunk_markdown(page, title="Example API", max_chars=200):
    print(repr(c["heading"]), len(c["text"]))
# 'Example API › Pricing › Free plan' 73
# 'Example API › Pricing › Paid plans' 129
```

**What it does with the sample page:**

- Each section becomes its own chunk, labeled with its full heading path.
- The table stays in one piece. Fenced code blocks are kept whole the same way, even when they contain blank lines or lines starting with `#`.
- A section longer than `max_chars` is split between paragraphs, and the last paragraph is repeated at the start of the next chunk as overlap.

**Tune `max_chars` for your embedding model.** A rough rule for English is about 4 characters per token, so 1,500 characters is around 375 tokens.

## How does semantic chunking work?

**Semantic chunking puts boundaries where the meaning shifts.** It embeds each sentence, measures the similarity between neighbors, and cuts where similarity drops sharply. It suits long text without headings, like transcripts, emails and scraped forum threads.

```python
import math, re

def cosine(a: list[float], b: list[float]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))

def semantic_chunks(text: str, embed, threshold: float = 0.5) -> list[str]:
    """embed: function list[str] -> list[vector]. Cuts where neighbor similarity falls below threshold."""
    sents = [s for s in re.split(r"(?<=[.!?])\s+", text.strip()) if s]
    vecs = embed(sents)
    chunks, cur = [], [sents[0]]
    for i in range(1, len(sents)):
        if cosine(vecs[i - 1], vecs[i]) < threshold:
            chunks.append(" ".join(cur)); cur = []
        cur.append(sents[i])
    chunks.append(" ".join(cur))
    return chunks

# Toy embedding so the example runs without a model: topic words -> axes
def toy_embed(sents):
    topics = [("price", "cost", "plan"), ("latency", "fast", "speed")]
    return [[sum(w in s.lower() for w in t) + 0.01 for t in topics] for s in sents]

text = "The plan costs $30. Each price tier adds credits. Latency is about one second. Fast mode cuts speed further."
print(semantic_chunks(text, toy_embed))
# ['The plan costs $30. Each price tier adds credits.', 'Latency is about one second. Fast mode cuts speed further.']
```

**In production, pass a real embedding function and tune `threshold` on your data.** A common variant cuts at a percentile, such as the largest 10% of similarity drops, instead of a fixed threshold. Add a maximum size too, since semantic chunks can grow large on a single-topic document.

## What about overlap and parent-child chunks?

**Overlap** repeats the end of one chunk at the start of the next, so a fact that straddles a boundary still appears whole somewhere. The chunker above carries the last paragraph forward. Keep overlap small: a paragraph, or 10% to 15% of the chunk.

**Parent-child chunking** indexes small chunks for precise matching, but returns the larger parent (the whole section) to the model. You get sharp retrieval and enough context to answer. Store a `parent_id` on each small chunk and look up the parent after retrieval.

## How do I pick the right chunking strategy?

**Test two or three settings on 50 real questions, and measure whether the right chunk comes back.**

| Measure | How |
|---|---|
| Recall@5 | Does a chunk containing the answer appear in the top 5? |
| Answer accuracy | Does the final answer match the known answer? |
| Context size | Total tokens of the retrieved chunks per question |

Pick the smallest setup that keeps recall high. If recall is fine but answers are wrong, retrieved chunks may lack context: add heading prefixes, or try parent-child.

**After chunking, two retrieval upgrades usually pay off:** run keyword and semantic search together ([BM25 and hybrid search](/blog/bm25-hybrid-search-reciprocal-rank-fusion)), and rerank the top candidates ([reranking search results](/blog/reranking-search-results)).

## Chunking web search results without the pipeline

**Fetching, extracting, chunking and embedding pages yourself is four steps.** Keirolabs `/search/content` (ours) does them in one call. It returns each result's full page text as markdown, and with `embeddings.enabled: true` it also returns chunks with their embedding vectors. You choose `embeddings.chunkSize` (100 to 2,000) and the vector size (384, 512, 768 or 1,024 dimensions).

```python
import os, requests

r = requests.post(
    "https://api.keirolabs.cloud/api/v2/search/content",
    headers={"Authorization": f"Bearer {os.environ['KEIRO_API_KEY']}"},
    json={"query": "postgres connection pooling best practices", "maxResults": 3,
          "embeddings": {"enabled": True, "chunkSize": 500, "dimensions": 768}},
    timeout=60,
)
r.raise_for_status()
for res in r.json()["results"]:
    print(res["url"], len(res.get("chunks", [])), "chunks")
```

That is 1.5 credits a call on paid plans, well under a cent, and new accounts get up to 2,000 free credits with no card ([get a key](https://platform.keirolabs.cloud/register)).

## Checklist

- **Extract main content before chunking web pages.**
- **Split at headings first, then by size.**
- **Never split tables or code blocks.**
- **Prefix chunks with the page title and heading path, and keep the URL.**
- **Use a small overlap: about one paragraph.**
- **Use semantic chunking for long text without headings.**
- **Test 2 or 3 chunk sizes on real questions, and measure recall@5.**
