Why chunk at all when the window is 32K
The naive reading of a 32K window is that you can paste in whole documents and skip retrieval engineering. It works for a demo with one short document and fails on four fronts. Cost scales with every token on every call: a 25,000-token prompt at fifty cents per million input tokens is about a cent and a half per query, roughly fifty times a well-scoped 500-token context. Prefill of 25,000 tokens also adds hundreds of milliseconds before the first output token.
Precision matters more. A model answering from 25,000 tokens of which 400 are relevant is doing needle-in-a-haystack work, and it is measurably worse at that than at reading eight focused passages. Irrelevant context is not neutral: it supplies plausible distractors to synthesize across, and lost in the middle means material buried mid-prompt gets less attention than material at the edges.
The third is attribution: if the prompt is a whole document, a citation points at 40 pages and audits nothing, while chunk-level citations point at a paragraph. The fourth is access control, since retrieval enforces per-user permissions on what enters the prompt and document stuffing is all or nothing. Chunking makes all four tractable; a 32K window changes the budget arithmetic, not the logic.
The 32K budget, counted
Start from 32,768 and subtract before planning anything. Reserve 1,500 to 2,500 tokens of output for a substantive answer, 300 to 600 for the system instruction and formatting rules, and 800 to 1,500 for conversation history if the product is multi-turn. That leaves roughly 28,000 tokens for context — which sounds enormous and is a trap.
Do not fill the window. Retrieval quality per token falls as you add marginal chunks, so the useful target is 40 to 60 percent of the budget — 12,000 to 17,000 tokens. At 450 tokens per chunk that is 27 to 38 chunks; after reranking you typically keep 8 to 15 and still have headroom for a long answer. Treat the budget as a ceiling, and every extra chunk as something that must justify its tokens against the ones already there.
Do the arithmetic per model, because tokenisers differ. English runs about four characters per token, while code, JSON, non-Latin scripts and tables run higher: a 2,000-word document is roughly 2,700 tokens in English and can be 5,000 in Japanese. Never budget in words when the constraint is tokens; measure with the tokeniser you will deploy.
Chunk size is a trade you cannot avoid
Small chunks retrieve precisely and answer poorly. A 150-token chunk about one clause matches a specific query sharply but may omit the condition that makes the clause apply, so the model fills the gap. Large chunks answer well and retrieve fuzzily: a 1,500-token chunk about six topics has a vector averaging six topics and matching all of them weakly. For general prose the sweet spot sits around 300 to 600 tokens, with 400 to 500 a reasonable default.
Size depends on question shape. Factoid lookup — what is the notice period — wants 200 to 350 tokens. Procedural questions want 600 to 900, because steps are useless without their prerequisites. Comparative questions want larger units still, which argues for parent-child retrieval rather than one global chunk size.
Resist tuning chunk size by intuition. It is one of the few parameters you can ablate cheaply: index the corpus at 250, 500 and 900 tokens, run the same 100-question evaluation, compare recall@10 and faithfulness. The curve is usually flat between 400 and 700 and falls off either side, which says precision within that band is not where your remaining errors live.
Split on structure, not on character count
The single largest quality gain in most chunking work is respecting document structure. Markdown has headings; HTML has sections; DOCX has styles; PDFs have a layout that a good extractor can recover into headings and blocks. Split first at the highest-level boundary that fits the size budget, then descend: document, chapter, section, subsection, paragraph. A chunk that begins mid-sentence in the middle of a subordinate clause is a chunk whose embedding is about the wrong thing.
Carry the structural path into the chunk. One starting with Accounts Payable > Invoicing > Credit notes is self-describing, and both the embedding and the generator benefit. It costs 10 to 20 tokens and fixes the common failure where a chunk says the deadline is 30 days without saying what for.
For code, split on syntax — functions, classes, methods — with the enclosing module and imports as a short preamble. For transcripts, split on speaker turns and topic shifts, and attach timestamps, since a meeting chunk without one is hard to cite. For slide decks, keep each slide's title with its bullets and note the deck and slide number. A generic recursive character splitter destroys all of these.
Overlap, boundaries and the cost of duplication
Overlap stops an answer being severed by a boundary. Ten to fifteen percent — 50 to 80 tokens on a 500-token chunk — is the usual range. More overlap raises the chance the answer appears whole somewhere and also raises index size, embedding cost and duplicate results. Retrieve ten chunks where four are near-duplicates and 40 percent of the context budget went on repetition.
Prefer sentence or paragraph boundaries to fixed counts, and never split inside a table row, a code block or a list. When a unit exceeds the maximum, split at the largest internal boundary that fits and record the parent id for reassembly. When a unit falls far below the minimum, merge it with its sibling rather than indexing a 40-token fragment no query will match well.
Deduplicate at retrieval time as well as at index time. Near-duplicate chunks — the same policy paragraph repeated in twelve documents — crowd out diversity in the top k. A cheap minhash or shingle similarity filter over the candidate set, keeping the highest-scoring representative, is often worth more than another point of recall.
Parent-child retrieval: small to search, large to read
The tension between precise matching and sufficient context has a clean solution: index small units, return large ones. Embed 200-token children for sharp matching, store a pointer to a 1,000-token parent section, and expand a retrieved child to its parent before it reaches the prompt. Search runs at the resolution where specificity helps; generation reads at the resolution where coherence helps.
Implementations vary in ambition. The simplest keeps a parent id on every chunk and expands after reranking, deduplicating so three matching children from one section produce one section in the prompt. A more elaborate version embeds each sentence with one or two neighbours and widens the window at read time. Both are cheap and both usually beat a single mid-sized chunk size.
Watch the budget when you expand. Twenty children expanding to twenty 1,000-token parents is 20,000 tokens, blowing the allocation. Cap the parents, rank them by their best child's score, and expand only the top few.
Contextual headers and contextual retrieval
A chunk lifted out of a document loses the referents that made it make sense. The pronoun it, the table it refers to and the section's subject all vanish. The fix is to prepend a short generated context to each chunk before embedding: a sentence or two describing where the chunk sits in the document and what it is about. Something like, this passage is from the 2024 enterprise agreement, section 4, describing renewal terms and the notice period for non-renewal.
Generating it costs one small-model call per chunk — a few dollars and an hour for 10,000 chunks. Anthropic's published results reported roughly a third fewer retrieval failures, rising to about two thirds with BM25 and reranking. The mechanism is simple: the prepended context supplies vocabulary the query uses and the chunk omits.
The cheaper variant is a deterministic header: document title, section path, date and document type, concatenated in front of the chunk text. It captures most of the benefit when your documents have clean structure, costs nothing beyond the tokens, and never hallucinates. Start there, and spend model calls on generated context only for documents whose structure is weak.
Late chunking and document-level context
Standard chunking embeds each chunk in isolation, so it never sees its neighbours. Late chunking inverts the order: run the whole document through a long-context embedding model, then pool token embeddings over each chunk's span. Every chunk vector is informed by its surroundings, which helps exactly where isolated embedding fails — ambiguous pronouns, section jargon, a table referenced two paragraphs earlier.
It requires an embedding model with a long enough context and token-level output, plus care at chunk boundaries. Not every store or hosted API supports it, and the gain is corpus-dependent: documents with strong internal references benefit, standalone FAQ entries do not. Measure before committing, and note that late chunking makes incremental indexing harder because a new chunk technically depends on the whole document.
A pragmatic middle ground: embed the chunk with its header plus a one-line document summary, approximating document-level context at a fraction of the complexity.
Tables, code and other awkward content
Tables break naive chunkers predictably: the header row stays in the first chunk and rows scatter, so Q3 41,200 arrives with no column names. Serialise tables as markdown with the header repeated in every chunk, or keep the whole table as one chunk up to a size limit, plus a sentence describing what it shows. For wide tables, a flattened per-row sentence often retrieves better than the grid.
Code needs its imports, its class signature and its docstring to be interpretable. Split on function boundaries, prepend the module path and the imports, and never split inside a string literal or a multi-line expression. For configuration files, key paths matter more than the value: a chunk containing timeout: 30 is meaningless without the service and environment it belongs to.
Charts and images are a separate pipeline. Either caption them with a vision model and index the caption as text, or extract the underlying data table and index that. Indexing an image without a textual description makes it invisible to a text retriever, which is a common and quiet gap in documentation corpora.
Metadata every chunk should carry
Retrieval quality depends as much on filters as vectors, and filters depend on metadata recorded at ingest. Minimum set: document id, chunk index, section path, source URI, title, last-modified date, document type, language, permission principal or tenant id. Add domain fields — product, version, jurisdiction, effective date — because those are the filters users actually apply.
Effective dates deserve special mention in any corpus with superseded documents. A policy that changed in March has two versions, and a query about current rules must not retrieve the old one. Store valid_from and valid_to and filter on them at query time rather than deleting history, which you will want for audits and for answering questions about what the policy said last year.
Store the parser and chunker version too. When a parsing bug is fixed you must re-ingest every chunk the old parser produced, and without a version field that becomes a full rebuild.
Assembling the window
Filling a 32K window is an optimisation problem under a token budget. After reranking you may have 40 candidates and room for 15. Greedy top-k wastes budget on redundancy, since the five best chunks are often variations of one paragraph. Maximal marginal relevance penalises candidates similar to ones already chosen; a simpler and usually sufficient fix is capping chunks per document at two or three.
Order matters. Put the strongest evidence first, the next strongest last, and the middle filled with supporting material. Number every chunk and require the answer to cite by number. If you have a long conversation history, put it before the retrieved context rather than after, so the context sits adjacent to the question.
Leave headroom. A prompt that exactly fills the window leaves no room for the answer, and truncation at the provider's limit errors or silently drops the tail — usually the question. Compute the assembled count before the call and assert it is under the limit minus the output reservation.
How to tell whether a chunking change helped
Chunking changes are easy to feel good about and hard to verify. Build the evaluation before the change: 100 to 200 questions, each annotated with the document and character span that answers it. Then compute whether any retrieved chunk overlaps that span — span-level recall — rather than whether the chunk id matches, because ids change whenever you re-chunk. That gives a stable metric across chunking variants.
Run the ablation in one pass: 250, 500 and 900 tokens, with and without overlap, with and without headers. Four to six configurations show the shape, and the sweep costs a few dollars in embeddings. Report recall@10, recall@20 and faithfulness separately, since a change can improve retrieval while hurting answers by returning larger, noisier passages.
Finally, inspect failures by hand. Retrieve for twenty failing questions and read the top five chunks. The pattern is usually obvious within ten minutes — the answer split across two chunks, the table lost its header, the section title left behind. That finds more than another parameter sweep.
A recipe that works
- Parse with structure preserved; keep headings, tables and lists as typed blocks rather than flattening to plain text.
- Split at the deepest structural boundary that fits 400 to 600 tokens; never split a table row, code block or list item.
- Add a deterministic header with document title, section path and date; add a generated one-line context for documents with weak structure.
- Overlap 10 to 15 percent on sentence boundaries, and deduplicate near-identical chunks before indexing.
- Index children of 200 to 300 tokens with pointers to 800 to 1,200-token parents, and expand only the top few parents into the prompt.
- Retrieve 50 per retriever, fuse, rerank to 15, deduplicate by parent, and cap the assembled context at 40 to 60 percent of the window.
Common mistakes
- Filling the 32K window because it is there, raising cost, adding distractors and pushing the answer into the low-attention middle.
- Splitting on character count with a fixed overlap, which cuts sentences, tables and code blocks at arbitrary points.
- Indexing 1,500-token chunks for factoid questions, where the vector is an average of everything the chunk discusses.
- Indexing 100-token fragments with no header, so the chunk cannot say what its subject is.
- Setting overlap to 50 percent, then retrieving six near-duplicates of the same paragraph into a ten-slot context.
- Forgetting to record an effective date, then answering current-policy questions with a superseded document.
- Expanding every retrieved child to its full parent, which turns a 6,000-token context into a 25,000-token one.
- Judging a chunking change by reading three examples instead of running a span-level recall ablation.