Chunking Strategies: Fixed vs Sentence vs Recursive
Implement and compare fixed-size, sentence-boundary, and recursive character text splitters, and understand how chunk size and overlap affect retrieval quality.
Chunking Strategies: Fixed vs Sentence vs Recursive is a free AI Engineering Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Engineering Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Chunking Quality Matters
Chunking is the process of splitting loaded documents into smaller pieces that fit within the LLM's context window and can be individually indexed and retrieved. The way you chunk determines retrieval quality more than almost any other factor. A chunk that splits an answer across two pieces means neither chunk alone is sufficient to answer the question. A chunk that mixes two unrelated topics gets retrieved for questions about both but is useful for neither.
Fixed-Size Chunking
Fixed-size chunking splits text into chunks of exactly N characters or N tokens, regardless of sentence or paragraph boundaries. It is the simplest strategy and fast to implement. The major drawback is that it often cuts sentences in half, creating chunks that start or end mid-thought. This is acceptable for dense, uniformly formatted text like database export dumps, but produces poor retrieval quality on narrative prose or technical documentation.
def fixed_size_chunks(text, chunk_size=500, overlap=50):
'''Split text into fixed-size character chunks with overlap'''
chunks = []
start = 0
while start < len(text):
end = start + chunk_size
chunk = text[start:end]
chunks.append(chunk)
start += chunk_size - overlap # overlap keeps context at boundaries
return chunks
example = 'This is a long document. ' * 100
chunks = fixed_size_chunks(example, chunk_size=200, overlap=20)
print(f'Produced {len(chunks)} chunks, first: {chunks[0][:80]}...')Adding Overlap to Fixed Chunks
The key improvement to fixed-size chunking is overlap: each chunk shares N characters with the previous chunk. This ensures that information near a chunk boundary appears in both adjacent chunks. With 50-100 token overlap, a sentence that crosses a boundary will be fully captured in at least one of the two chunks. More overlap means better coverage but larger index size and redundant content in retrieval results.
# Overlap example with a sentence at the boundary
text = 'A B C D E F G H I J'
chunk_size = 6 # characters
overlap = 2
i = 0
while i < len(text):
print(repr(text[i:i+chunk_size]))
i += chunk_size - overlap
# Output shows overlapping content:
# 'A B C D'
# 'C D E F'
# 'E F G H'
# Each adjacent pair shares 2 charsSentence-Boundary Chunking
Sentence-boundary chunking uses NLP libraries like nltk or spacy to detect sentence ends before splitting. This guarantees that no sentence is cut in half. You accumulate sentences until adding the next one would exceed the target size, then start a new chunk. The result is chunks that always contain complete thoughts, which produces significantly better embedding quality than fixed-character splitting.
import nltk
nltk.download('punkt', quiet=True)
def sentence_chunks(text, max_tokens=300):
sentences = nltk.sent_tokenize(text)
chunks = []
current = []
current_len = 0
for sent in sentences:
sent_tokens = len(sent.split())
if current_len + sent_tokens > max_tokens and current:
chunks.append(' '.join(current))
current = []
current_len = 0
current.append(sent)
current_len += sent_tokens
if current:
chunks.append(' '.join(current))
return chunksRecursive Character Text Splitting
Recursive character splitting is the most widely used strategy in production RAG systems. It tries a hierarchy of separators in order: first paragraph breaks (\n\n), then newlines (\n), then sentence-ending periods, then spaces, and finally individual characters. It splits at the largest meaningful boundary that keeps the chunk under the target size, resulting in chunks that respect document structure as much as possible.
from langchain_text_splitters import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000, # target size in characters
chunk_overlap=200, # overlap between consecutive chunks
separators=['\n\n', '\n', '. ', '! ', '? ', ' ', ''],
length_function=len
)
with open('document.txt') as f:
text = f.read()
chunks = splitter.split_text(text)
print(f'Split into {len(chunks)} chunks')
for i, chunk in enumerate(chunks[:3]):
print(f'Chunk {i}: {len(chunk)} chars — {chunk[:60]}...')Token-Aware Splitting
Character counts are an imprecise proxy for token counts. A 1000-character chunk might be 200 tokens or 400 tokens depending on word length and language. For precise control, split by token count using tiktoken. This matters for fitting chunks to the model's context window and for accurate cost estimation. LangChain's TokenTextSplitter wraps tiktoken for token-aware chunking.
from langchain_text_splitters import TokenTextSplitter
import tiktoken
# Split by actual token count, not characters
splitter = TokenTextSplitter(
encoding_name='cl100k_base', # GPT-4 tokenizer
chunk_size=256, # target tokens per chunk
chunk_overlap=32 # overlap in tokens
)
chunks = splitter.split_text(text)
# Verify token count
enc = tiktoken.get_encoding('cl100k_base')
for chunk in chunks[:3]:
tokens = len(enc.encode(chunk))
print(f'Chunk: {tokens} tokens')Choosing the Right Chunk Size
Chunk size is a critical hyperparameter. Small chunks (100-200 tokens) are precise — they contain tightly focused information that embeds well. But they lose surrounding context, so the LLM may not have enough information to answer. Large chunks (500-1000 tokens) provide more context but their embeddings average over a broader topic, making them harder to retrieve for specific queries. Most production systems use 256-512 tokens with empirical testing on their data.
Adding Context to Chunks
A powerful enhancement is contextual chunk headers: prepend the document title and section heading to each chunk's text before embedding. This means the embedding captures not just the chunk's content but also where it came from in the document. A chunk reading Benefits and Vacation Policy: Employees accrue 15 days annually... retrieves much more accurately for questions about vacation policy than the same text without the header.
def create_contextual_chunks(doc, splitter):
title = doc['metadata'].get('title', '')
section = doc['metadata'].get('section', '')
text = doc['text']
raw_chunks = splitter.split_text(text)
contextual_chunks = []
for chunk in raw_chunks:
# Prepend document context to each chunk
context_header = f'{title}\n{section}\n\n' if title else ''
contextual_chunks.append({
'text': context_header + chunk,
'metadata': doc['metadata']
})
return contextual_chunksComparing Strategies on Your Data
No single chunking strategy is universally best. Build a quick evaluation: take 20 questions you know the answers to, run retrieval with each chunking strategy, and measure how often the correct chunk ranks in the top 5 results (hit rate@5). This takes an hour to set up and saves weeks of guessing. You will often find that your specific document format (dense legal prose vs. structured technical docs) strongly favors one strategy over others.
def evaluate_chunking_strategy(questions_and_answers, retriever):
hits = 0
for qa in questions_and_answers:
results = retriever.retrieve(qa['question'], top_k=5)
result_texts = [r['text'] for r in results]
# Check if answer text appears in any retrieved chunk
if any(qa['answer'] in text for text in result_texts):
hits += 1
hit_rate = hits / len(questions_and_answers)
print(f'Hit rate@5: {hit_rate:.1%} ({hits}/{len(questions_and_answers)})')
return hit_rateHandling Special Document Types
Some document types need special-purpose chunking. Code files should be split by function or class boundaries, not character count. Markdown files should be split at heading boundaries so each chunk corresponds to one section. Tables should be kept intact as a single chunk (splitting mid-table makes the content uninterpretable). Plan your chunking strategy based on the document types in your corpus rather than applying a one-size-fits-all splitter.
from langchain_text_splitters import MarkdownHeaderTextSplitter
# Split Markdown by header hierarchy
md_splitter = MarkdownHeaderTextSplitter(
headers_to_split_on=[
('#', 'h1'),
('##', 'h2'),
('###', 'h3')
]
)
with open('documentation.md') as f:
md_text = f.read()
# Each chunk gets metadata from its heading hierarchy
chunks = md_splitter.split_text(md_text)
for chunk in chunks[:3]:
print('Section:', chunk.metadata)
print('Text:', chunk.page_content[:80])
print()Tracking Chunk Lineage
Every chunk needs a stable, unique ID derived from its source document and position. Use this ID to update specific chunks when documents change without re-indexing the entire corpus. A deterministic hash of the source path plus chunk index works well. Also record chunk position (chunk 3 of 12 from document X) in metadata — this helps re-assemble full sections when multiple adjacent chunks are retrieved together.
import hashlib
def assign_chunk_ids(chunks, source_path):
for i, chunk in enumerate(chunks):
key = f'{source_path}::chunk_{i}'
chunk_id = hashlib.sha256(key.encode()).hexdigest()[:16]
chunk['id'] = chunk_id
chunk['metadata']['chunk_index'] = i
chunk['metadata']['total_chunks'] = len(chunks)
return chunks
# IDs are stable across re-runs if source and position match
chunks = sentence_chunks(text)
chunks = [{'text': c, 'metadata': {}} for c in chunks]
assign_chunk_ids(chunks, 'docs/policy_v3.pdf')Quick Check
Test your understanding of AI Engineering concepts from this lesson.
Lesson Recap
In this lesson you learned: fixed-size chunking is simple but cuts sentences in half, sentence-boundary chunking preserves complete thoughts, recursive character splitting respects document structure and is the most common production choice, and advanced techniques including token-aware splitting, contextual headers, special-purpose splitters for Markdown and code, and stable chunk IDs for incremental updates. Next up we embed and store these chunks in a vector database.
Frequently asked questions
Is the “Chunking Strategies: Fixed vs Sentence vs Recursive” lesson free?
Yes — the full text of “Chunking Strategies: Fixed vs Sentence vs Recursive” is free to read here on the web, and the AI Engineering Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Engineering Academy course, upgrade to CoddyKit PRO.
What will I learn in “Chunking Strategies: Fixed vs Sentence vs Recursive”?
Implement and compare fixed-size, sentence-boundary, and recursive character text splitters, and understand how chunk size and overlap affect retrieval quality. You practise AI Engineering Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Engineering Academy?
No prior experience is required. AI Engineering Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Chunking Strategies: Fixed vs Sentence vs Recursive” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Engineering Academy lesson?
Yes. Every AI Engineering Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Document Loading and Text Extraction
- Chunking Strategies: Fixed vs Sentence vs Recursive
- Indexing: Embedding and Storing Chunks
- Query, Retrieve, and Generate