6.1 RAG Ingestion, Chunking & Multi-Tenant Indexing
Key Takeaways
Layout-aware parsing and heading-aware chunking help preserve clauses, table headers, footnotes and other structural context; evaluate against representative questions.
Contextual Retrieval prepends chunk-specific context (often 50–100 tokens) before embedding and lexical indexing; retain the original evidence and validate enrichment.
Use stable document identity, version/effective-date checks, current permissions, change/deletion tracking and reconciliation to keep retrieval current.
Compare dedicated deployments, namespaces and shared filtering by verified provider isolation, cost, key handling, residency, and deletion guarantees; enforce caller scope before retrieval reaches the model.
6.1 RAG Ingestion, Chunking & Multi-Tenant Indexing
Core Principle: Grounded answer quality depends on retrieving current, authorized evidence. Reranking cannot recover evidence that was never indexed or selected, and prompting cannot establish access control.
Document Parsing & Chunking Strategies
Enterprise knowledge lives in heterogeneous formats: multi-column PDFs, scanned invoices, Confluence HTML, Markdown runbooks, and Excel spreadsheets. Before chunking begins, layout-aware parsing can preserve reading order, tables, and footnotes and remove repeated boilerplate when safe. Avoid discarding headers needed to identify a rule or page. A naive PDF text extractor that linearizes a two-column compliance table row-by-row can corrupt column relationships in the extracted representation.
Once clean text and structured blocks are extracted, architects select a chunking strategy based on corpus structure, latency budget, and ingestion cost:
These sizes are illustrative starting points, not universal requirements.
| Strategy | Example Size & Overlap | Strengths | Failure Modes & Cost |
|---|---|---|---|
| Fixed-Size Token | 400–512 tokens; 50–64 token overlap | Fast, deterministic, no contextual LLM cost (embedding still costs) | Splits mid-sentence, breaks Markdown tables, severs clause headers from rules |
| Recursive Structural / Heading-Aware | 400–800 tokens bounded by headings/paragraphs | Keeps tables and code intact; injects section breadcrumbs | Uneven chunk lengths; short sibling sections may still lack document-level context |
| Contextual enrichment after chunking | 300–600 tokens + 50–100 token LLM prefix | Resolves pronouns ("the limit above"); can improve retrieval of otherwise ambiguous chunks | Higher ingestion cost and latency evaluate low-cost model/caching and eligible batching |
Preserving Tables, Code Blocks, and Clause Boundaries
Production pipelines combine recursive structural chunking with atomic block rules:
- Header Breadcrumbs: Prepend the document title and full heading path (for example,
Policy HR-402 > Travel > International Per Diem) to every child chunk so standalone fragments retain scope. - Atomic Tables & Code: Preserve table relationships and relevant footnotes. If a long table must be split, repeat identifying headers and retain source references. Keep fenced code blocks atomic up to a hard ceiling (such as 1,024 tokens) rather than breaking a function signature away from its error handling.
- Targeted Sliding Overlap: Apply a 10–15% overlap (about 51–77 tokens on a 512-token target) strictly between narrative prose paragraphs. Overlap can help keep conditional qualifiers like "except for Tier-1 EU accounts" stay attached to the numeric SLA they modify.
- Contextual Enrichment Economics: Using Anthropic's Contextual Retrieval pattern with prompt caching on the parent document, generate a short chunk-specific description using its parent document. Anthropic’s 2024 experiments used about 50–100 contextual tokens before embedding and lexical indexing; benchmark the improvement on your corpus. A lower-cost model and eligible caching or batching may save ingestion charges, but contextual summaries are generated aids, not authoritative evidence. Test their quality and cite original source content.
Exam Trap: Shrinking fixed chunks without evaluating the loss of context can be counterproductive. Tiny chunks sever governing exceptions from their rules, causing Claude to state an absolute policy when an adjacent paragraph contained a critical carve-out.
Metadata Enrichment & Freshness Pipelines
Semantic similarity alone cannot distinguish a draft 2027 budget proposal from the binding 2026 policy. Maintain trusted, versioned metadata independently of the document’s prose, with suitable authorization and effective-date checks at query time:
- Provenance & Versioning:
doc_id,chunk_id,doc_version,source_uri, andcontent_hash(SHA-256). - Temporal Validity:
effective_date,expiration_date, andlifecycle_status(draft,active,superseded,deleted). - Governance & Access:
jurisdiction(e.g.,US-CA,EU-GDPR),owner_group,security_classification(public,internal,confidential,restricted), andacl_principals.
Incremental CDC, Re-Indexing & Tombstoning
When full re-indexing cannot meet the cost or freshness SLA, use incremental change tracking (such as change data capture or source events) with reconciliation. Connector support differs:
- Hash Diffing: Compute a SHA-256 hash per normalized document (or section) to avoid re-embedding identical content when safe. Changes to access rights, dates or other metadata still require synchronization even if the content hash matches.
- Atomic Version Swap: Write new version chunks (
v4) withlifecycle_status = pending, then switch the authoritative active-version pointer only after the new records are validated and available. Design retrieval to consult that pointer or equivalent consistency mechanism; different search indexes may update asynchronously. - Tombstoning & Hard Purge: When a document is deleted or revoked, immediately set
is_deleted = true(a tombstone or deny state used by enforced retrieval controls as soon as revocation is known) and remove obsolete vectors, lexical records and other copies according to the deletion/retention policy. Test stale cache and backup handling. - Reconciliation Sweeps: Run a daily manifest diff against source repositories to catch dropped webhooks to detect missed deletions and permissions changes.
Set freshness goals according to business risk and source capability. For example, a business may choose a five-minute p95 update target for rapidly changing policy, but old permissions must not grant continued access after revocation. Measure lag from source update to authorized searchable version and fail closed when validity cannot be established.
Multi-Tenant Index Isolation
When serving multiple business units or external B2B SaaS customers, architects must choose how tenant vectors and lexical postings are physically separated:
| Isolation model | Potential benefit | Trade-off and checks |
|---|---|---|
| Dedicated deployment or index per tenant | Can support stricter isolation, separate keys and region if the provider implements them | More operational overhead and possible higher minimum cost; verify physical vs logical isolation and all replicas |
| Namespace or partition per tenant | May reduce shared-query exposure and simplify tenant-specific storage | Exact storage/compute isolation, performance and key support are provider-specific; application must bind the namespace to verified tenant identity |
| Shared index with enforced document-level access controls | Can reduce infrastructure duplication and support shared documents | A filtering or permission-ingestion defect has broader scope; ensure unauthorized results never reach model, reranker outputs or user |
Architectural Trade-Offs in Practice
A mid-market SaaS platform with 2,500 customers might evaluate a tiered architecture instead of assuming every tenant needs a separate cluster. For example, if a dedicated environment costs an assumed $150/month, 2,500 such deployments would cost $375,000/month before usage. A namespace-based option may be more cost-effective for customers whose isolation requirements permit it, while a separate deployment may suit those requiring approved regional and key controls. Do not infer that the choice of index alone guarantees encryption or deletion timing. Verify key scope, replicas, snapshots, source copies, caches and deletion receipts. Cryptographic erase has prerequisites and validation requirements; deleting an index is not proof of cryptographic sanitization.
Primary references
A company indexes multi-page travel reimbursement PDFs. An audit finds that answers omit policy exceptions in table footnotes and tables spanning page breaks, even when the rule’s main paragraph is retrieved. Which ingestion change addresses this observed failure?
Reduce fixed-size chunk length from 512 tokens to 128 tokens with zero overlap so embeddings stay tightly focused on individual sentences
Switch to layout-aware PDF parsing with heading-aware structural chunking that keeps tables atomic, repeats column headers, and injects section breadcrumbs
Increase sampling variation so the model guesses the missing footnotes
Keep only first-page summaries and infer the missing reimbursement exceptions from general knowledge
An e-commerce company updated its return policy from 30 days to 14 days in Confluence two weeks ago, yet its customer-facing RAG agent still quotes the old 30-day rule on 20% of queries. Investigation shows the nightly ingestion script only upserts chunks whose IDs match newly generated UUIDs. What pipeline fix prevents stale policies from remaining retrievable?
Add a system prompt instruction telling Claude to prefer shorter return windows whenever two policies conflict
Lower the top-k retrieval count from 10 to 2 so older chunks are statistically less likely to appear
Re-embed every unchanged document across the entire company every 15 minutes without tracking document versions
Implement an incremental CDC pipeline with deterministic doc_id mapping, atomic version swaps, immediate soft-delete tombstoning of superseded chunks, and asynchronous hard purge
A B2B legal-tech service has 1,800 standard tenants with a tight budget and four regulated organizations requiring customer-managed keys, EU-only processing, and documented erasure within a contractual deadline. A vendor confirms namespaces meet standard-tenant requirements but only dedicated deployments support the latter customers’ key and location controls. Which design should the architect pursue, subject to testing the deletion commitments?
Use verified tenant namespaces for standard customers and separate approved deployments for regulated customers; validate key scope, residency and deletion evidence.
A single shared vector index across all 1,804 customers using post-query application filtering on tenant_id
Dedicated physical vector clusters for all 1,804 customers regardless of monthly infrastructure budget
A single shared index with no tenant metadata where Claude separates firm records inside the system prompt
A team wants contextual prefixes for 500,000 chunks from approved internal documents. Baseline Opus ingestion exceeds the budget. What is the best candidate to evaluate for lower cost while preserving retrieval quality?
Skip contextual summaries entirely and double the vector embedding dimensions from 1,024 to 2,048
Truncate every document to its first 500 tokens before chunking so fewer chunks need prefixes
Evaluate a lower-cost model for contextual enrichment, cache eligible parent-document prefixes, and use eligible asynchronous batches where retention and deadline permit.
Run contextual summarization dynamically on all 500,000 chunks at query time for every incoming user request
Sections you finish are checked off in the contents.