Forward Deployed EngineeringAI EngineeringRAG Chunking

How would you chunk documents for retrieval, and how do you know your chunking is good?

Question 14 of 73 · Updated

On this page

Interview-ready answer#

I would treat chunking as a retrieval optimization problem, not simply a text-splitting problem. The goal is to create passages that are small enough to retrieve precisely but complete enough to answer the question without losing important context.

I would first inspect the document types and representative customer queries. For ordinary prose, I would start with structure-aware splitting at headings, paragraphs and sentence boundaries, using roughly 256–512 tokens as an experimental baseline and a small overlap where it helps. For contracts, policies, tables and code, I would preserve the logical units that carry meaning. If small chunks retrieve well but lack context, I would retrieve child chunks and expand them to their parent sections or neighboring passages.

To know whether chunking is good, I would compare alternative configurations on labeled customer questions. I would measure whether the required evidence reaches the model within the same retrieval and token budgets, then evaluate answer correctness, groundedness, citation quality, latency and cost. I would choose the smallest and simplest configuration that meets the customer's requirements, not a universally prescribed chunk size.

1. Why chunking matters#

A chunk is a unit of content that can be indexed, retrieved and supplied to a model. Chunking determines how precisely a search system can locate evidence and how much surrounding information accompanies it.

Chunks that are too small may separate a rule from its exceptions, detach a table cell from its headers, or omit the entity that a pronoun refers to. Chunks that are too large may mix unrelated topics, dilute embedding relevance, and consume too much of the generation context.

The best retrieval unit and the best generation-context unit do not necessarily have the same size.

2. Choose the strategy based on the source#

StrategyHow it worksBest use and trade-off
Fixed-size token windowsSplit into equal-sized token ranges, optionally overlappingSimple reproducible baseline; can break semantic boundaries
Recursive splittingSplit at coarse boundaries first, then finer boundaries until a size target is metGeneral-purpose prose; depends on useful separators and parsing
Structure-aware splittingPreserve headings, paragraphs, clauses, tables or code symbolsPolicies, manuals, contracts and code; requires good document parsing
Semantic chunkingDetect topic changes using sentence or passage similarityContent with irregular topic boundaries; adds compute and threshold tuning
Parent-child retrievalIndex smaller passages but expand retrieved evidence to a larger enclosing sectionPrecise search with richer context; expansion must respect token and access limits

These approaches can be combined. For example, split a manual by section, then divide oversized sections into smaller token-bounded chunks. Keep section titles as metadata or include them in the searchable representation when useful. Measure the extra token cost rather than assuming more metadata always improves retrieval.

3. Practical example: a customer travel policy#

Suppose a document contains the following hypothetical policy:

International travel reimbursement

Employees may claim approved international travel expenses.

Contractor exception

Contractors require written approval from the project sponsor before booking international travel.

A naive split might index the second paragraph without its heading. A query such as "Can contractors expense overseas travel?" could retrieve only the general employee rule and generate an incorrect answer.

A structure-aware approach preserves the contractor heading, the exception, its parent section, and document version. If the exception and the general rule are both needed, retrieve the specific exception and expand to the relevant parent context. Do not indiscriminately include the entire handbook.

For tables, preserve row and column headers alongside values. For code, consider functions, classes, and relevant signatures. For contracts, keep clause identifiers, definitions, and exceptions linked. For scanned documents, fix OCR and layout extraction before tuning the splitter.

4. A practical token-window baseline#

The following implementation operates on integer token IDs already produced by the chosen tokenizer. It returns half-open token offsets and overlapping chunks without inventing a tokenizer or depending on an external API.

PYTHON
def chunk_windows(token_ids: list[int], size: int, overlap: int): if size <= 0 or not 0 <= overlap < size: raise ValueError('Require size > 0 and 0 <= overlap < size') start = 0 while start < len(token_ids): end = min(start + size, len(token_ids)) yield start, end, token_ids[start:end] if end == len(token_ids): break start = end - overlap print(list(chunk_windows([0, 1, 2, 3, 4, 5], 4, 1))) # [(0, 4, [0, 1, 2, 3]), (3, 6, [3, 4, 5])]

Use the embedding model's actual tokenizer and input limits. Reserve capacity for headings, metadata and special tokens that will be added later. Token offsets alone are not original-document character offsets; maintain a source mapping for citation and highlighting. When converting chunks back into text, handle tokenizer-specific boundaries and verify the resulting text and token counts.

Local verification: 8,302 checks passed: 8,296 combinations of document length, positive chunk size and valid overlap; five invalid-parameter checks; and one explicit output example. The tests checked coverage, size bounds, exact slices, progress and expected overlap. They validate the windowing implementation, not semantic quality or retrieval effectiveness.

5. What metadata should every chunk retain?#

A production index should preserve stable source identifiers, document version, section hierarchy, page or source offsets where available, tenant and authorization metadata, and chunking/embedding configuration versions. Store parent and neighbor identifiers if the system supports context expansion.

Use deterministic IDs within a source version and make ingestion idempotent. When a source changes, update affected chunks and remove superseded entries. When access is revoked or content is deleted, propagate that change to indexes and caches. Enforce access control during retrieval and parent expansion using trusted application and storage policies. An authorized child does not automatically authorize every sibling or parent passage.

6. How to evaluate chunk quality#

Build an evidence-labeled evaluation set. Collect representative questions from actual customer workflows, including exact identifier lookup, paraphrases, multi-passage questions, policy exceptions, and unanswerable cases. Label the supporting document spans and expected answers with domain experts.

Use source spans or stable evidence units as labels instead of chunk IDs because chunk IDs change when the splitting strategy changes.

MetricWhat it tells you
Evidence Recall@kFraction of required labeled evidence units covered by the top k retrieved chunks, using a consistent span-coverage rule
All-evidence successWhether every required evidence unit reaches the selected context
MRR / nDCGWhether relevant results appear near the top; nDCG can account for graded relevance
Context precisionHow much selected context is useful under a consistent relevance definition
Answer correctness and groundednessWhether the final answer is correct and supported by evidence
Citation accuracy and abstentionWhether sources actually support claims and missing evidence triggers appropriate uncertainty
Operational metricsIndex size, ingestion cost, retrieval latency, context tokens and end-to-end latency

A chunk-level relevance metric alone can be misleading because splitting changes the number and boundaries of chunks. For fair comparisons, keep evidence labels stable across configurations and deduplicate overlapping evidence before measuring coverage.

7. Run a controlled chunking experiment#

Start with a small grid, for example token targets of 256, 512 and 1,024, with no overlap and a modest overlap such as 10%. These are experiment settings, not universal recommendations. Include a structure-aware baseline and a parent-child variant if the documents benefit from hierarchy.

Keep the corpus snapshot, embedding model, query set, retrieval settings and generation model fixed while testing one change at a time. Compare both a fixed candidate budget and a fixed final context-token budget: top 5 results of 1,024 tokens are not directly equivalent to top 5 results of 256 tokens. Retune retrieval and reranking for shortlisted configurations if needed, then validate on held-out questions.

For a hypothetical question requiring three evidence spans, a configuration that retrieves two of them has evidence recall of 2/3, but fails the all-evidence test. That distinction is important for questions about exceptions, dependencies and multi-step policies.

Inspect failures manually. A higher retrieval score does not necessarily mean a better answer if evidence is incomplete, duplicated or truncated before reaching the model.

8. Common production failures and fixes#

SymptomLikely causeWhat I would inspect or change
Answer cites the wrong policyExceptions or scope detached from rulesSource parsing, headings, parent links and version metadata
Relevant facts are not retrievedChunks too broad, poorly embedded, or missingIndex completeness, query ranking, hybrid search and alternative boundaries
Retrieved passages are repetitiveExcessive overlap or near-duplicate chunksDeduplicate candidates and reduce overlap; measure evidence coverage
Correct chunk retrieved but answer is wrongContext expansion, truncation or generation errorFinal prompt, supporting evidence and gold-context generation test
Tables yield wrong numbersLost headers, units or row relationshipsLayout-aware parsing and structured table representation
Index grows rapidlyVery small chunks or excessive overlapChunk count, storage, re-embedding costs and retrieval latency
Old or unauthorized content appearsVersion, deletion or permission synchronization failureSource lifecycle, permission filters and cache invalidation

9. Engineering judgment for an FDE#

I would not optimize chunking in isolation. The strategy interacts with parsing, embedding model limits, keyword search, reranking, context construction and the customer's question distribution.

For a policy assistant, preserving complete clauses and exceptions may matter more than maximizing retrieval similarity. For a technical support assistant, short searchable passages with neighboring expansion may offer a better balance. For structured financial facts, querying an authorized database or preserving table structure may outperform ordinary text chunking.

I would agree on measurable customer acceptance criteria, maintain reproducible index versions, deploy the new configuration gradually, and compare it against the existing baseline. If retrieval recall improves but answer quality does not, I would trace the final evidence and generation stages before changing the splitter again.

Likely interviewer follow-ups#

  • Is overlap always helpful? No. It reduces boundary loss but duplicates content and increases indexing and context costs. Test it against a no-overlap baseline.
  • Would you use one chunk size for every document? Not necessarily. Source structure and query intent should drive the strategy.
  • What if the embedding model truncates chunks? Enforce its actual token limit, including added context and metadata, and verify that important evidence is not silently lost.
  • How do you evaluate semantic chunking? Compare it against simpler strategies using stable evidence labels, equal context budgets, downstream answer quality and ingestion cost.
  • How do you know whether chunking or the LLM is responsible? Check whether the correct evidence exists in the index, is retrieved, and appears in the final prompt. Supply gold evidence directly to the generator to isolate downstream failures.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models