# Chunking

> The Chunking is a technique of splitting documents into smaller pieces for indexing and retrieval.

## What chunk size should I use for RAG?

The technique of splitting documents into fragments, for example by headings, paragraphs or a fixed number of tokens, before creating embeddings. The size and boundaries of chunks strongly affect the quality of RAG.

- Topic: Retrieval
- Type: technique

## Example

Wrong:

```js
const chunks = [];
for (let i = 0; i < text.length; i += 500) {
  chunks.push(text.slice(i, i + 500));
}
```

Right:

```js
const paragraphs = text.split(/\n\s*\n/);
const chunks = paragraphs.map((p, i) => ({
  text: [paragraphs[i - 1] ?? '', p].join('\n\n').trim(),
  source: doc.url,
  position: i,
}));
```

Splitting on paragraphs avoids cutting sentences, the previous paragraph adds overlap, and metadata enables citations.

## Common mistakes

- Chunks are so small that they lose the context needed to answer.
- Splitting tables or code blocks in half.

## Key points

- Chunks split on structure such as headings or paragraphs, not mid-sentence.
- Chunks have some overlap so facts at a boundary are not lost.
- Each chunk keeps metadata: source, title and position, for citations.
- Chunk size fits the embedding model's input limit.

## Interview questions

### How much overlap should chunks have?

A common start is about 10 to 20 percent of the chunk size, enough to keep a fact at a boundary whole in at least one chunk.

### Should I chunk code differently from text?

Yes. Split code by functions or classes, not by character count, so each chunk is a complete unit.

### Small chunks vs large chunks?

Small chunks match queries more precisely but lose context. Large chunks keep context but dilute the match. Test both on real questions.

## Related cards

- [RAG](https://wonderium.dev/ai/rag.md)
- [Embeddings](https://wonderium.dev/ai/embeddings.md)
- [Vector Database](https://wonderium.dev/ai/vector-database.md)
- [Tokenizer](https://wonderium.dev/ai/tokenizer.md)

---

- Level: [Artificial Intelligence](https://wonderium.dev/ai.md)
- HTML version: https://wonderium.dev/ai/chunking
- Last updated: 2026-11-25
