Volume 13 · Chapter 6 — AI-Native Software Architecture & Agentic Engineering Handbook
RAG Systems Design
6.1 Introduction
Retrieval-Augmented Generation is the most important enterprise AI pattern because it solves the LLM’s core weaknesses - hallucination, staleness, and lack of proprietary knowledge - without retraining. But a naive RAG demo and a reliable production RAG system are very different things: answer quality is dominated by retrieval quality, so most of the engineering is in the ingestion and retrieval pipeline, not the model call. This chapter designs RAG for production.
6.2 The Two Phases: Ingestion and Query
RAG has an offline ingestion phase (documents are collected, cleaned, chunked, embedded, and indexed) and an online query phase (the question is embedded, similar chunks are retrieved and injected into the prompt, and the model generates a grounded answer with citations). The quality of the offline phase sets the ceiling on the online phase - garbage in, garbage out.
flowchart TB
subgraph Ingest["Offline: Ingestion"]
Docs["Documents"] --> Clean["Extract + clean"]
Clean --> Chunk["Chunk"]
Chunk --> EmbI["Embed"]
EmbI --> Index[("Vector index + metadata")]
end
subgraph Query["Online: Query"]
Q["User question"] --> EmbQ["Embed"]
EmbQ --> Search["Hybrid search + filter"]
Index --> Search
Search --> Prompt["Grounded prompt"]
Prompt --> LLM["LLM"]
LLM --> Ans["Answer + citations"]
end 6.3 Chunking Strategy
How you split documents is one of the highest-impact RAG decisions. Chunks too large dilute relevance and waste context budget; too small lose meaning. Strategies range from fixed-size (simple, with overlap to avoid cutting mid-thought), to semantic chunking (splitting on meaning boundaries), to structure-aware splitting (by section/heading), enriched with metadata (source, section, date, access level) for filtering. Getting chunking right often matters more than the choice of model.
6.4 Retrieval: Semantic, Keyword, and Hybrid
Vector (semantic) search finds meaning-based matches but can miss exact terms (an account number, a product code); keyword search finds exact terms but misses paraphrases. Hybrid search combines both (often re-ranked) and consistently outperforms either alone. Metadata filtering (by access level, date, source) is applied to enforce security and relevance.
6.5 Security: Access-Trimmed Retrieval
The cardinal RAG security rule is that authorization is enforced at retrieval, not in the prompt. Each chunk carries access metadata, and the search is filtered by the user’s identity and permissions so the model only ever receives context the user is entitled to - because you cannot rely on instructing the model to keep users in their lane (prompt injection defeats that). The model cannot leak what it never received.
// Security trimming: filter the vector search by the user's entitlements.
var filter = _acl.AllowedSourcesFor(user); // groups/roles the user may see
var chunks = await _vectorStore.SearchAsync(queryVector, top: 5,
metadataFilter: c => filter.Contains(c.AccessTag), ct); // model only sees permitted data
6.6 Evaluation
Because RAG quality is not guaranteed, production systems must evaluate it: retrieval accuracy (did we fetch the right chunks?), answer quality and faithfulness (is the answer grounded in the retrieved context, not hallucinated?), and user feedback. Automated evaluation (often LLM-as-judge plus a curated test set) and continuous monitoring are what let you improve the pipeline and catch regressions - RAG is iterated, not shipped once.
How do you design a reliable production RAG system?
I focus the engineering on retrieval quality and security, because in RAG the answer is only as good as what you retrieve, and most of the work is in the pipeline, not the model call. I design two phases well. The offline ingestion phase - collect, extract, and clean documents; chunk them thoughtfully; embed; and index with metadata - sets the ceiling on quality, so I invest heavily in chunking (right-sized, with overlap or semantic/structure-aware splitting so chunks are coherent and self-contained) and in rich metadata (source, section, date, and crucially access level) for filtering. The online query phase embeds the question, retrieves the most relevant chunks, injects them into a grounded prompt that instructs the model to answer only from the provided context and to say it does not know otherwise, and returns the answer with citations so it is verifiable. For retrieval I use hybrid search - combining semantic (vector) search for meaning with keyword search for exact terms like identifiers, often with re-ranking - because it consistently beats either alone, and I apply metadata filtering. Security is non-negotiable: authorization is enforced at retrieval by filtering the search on the user’s entitlements, so the model only ever receives context the user is allowed to see - I never rely on instructing the model to withhold data, because prompt injection defeats that, and the model cannot leak what it never received. I treat retrieved content as untrusted to resist indirect prompt injection. And because RAG quality is not guaranteed, I build evaluation in from the start: measuring retrieval accuracy, answer faithfulness (is it grounded, not hallucinated?), and user feedback, using a curated test set and automated evaluation, with continuous monitoring so I can iterate and catch regressions. Operationally I handle latency, cost (the context budget), and versioning of the index and prompts. The through-line I’d stress is that reliable RAG is an engineering discipline centered on high-quality, secure, evaluated retrieval - chunking, hybrid search, access trimming, grounded prompting with citations, and continuous evaluation - not a one-shot wiring of a vector store to a model.
Why is chunking so important in RAG, and how do you approach it?
Chunking is important because it determines what the retriever can find and what the model gets as context, so it directly bounds answer quality - often more than the choice of model or embedding. If chunks are too large, a single chunk mixes multiple topics, which dilutes its embedding so relevance suffers, and it wastes the limited, paid-for context budget by injecting mostly-irrelevant text; if chunks are too small, they lose the surrounding context needed to be meaningful, so the model gets fragments that do not actually answer the question. The goal is chunks that are coherent, self-contained units of meaning at roughly the granularity of a good answer. My approach: I prefer structure-aware or semantic chunking - splitting on natural boundaries like sections, headings, or paragraphs so each chunk is a complete thought - over naive fixed-size splitting that can cut mid-sentence or mid-idea, though fixed-size with overlap (so context straddling a boundary is not lost) is a reasonable simple baseline. I tune chunk size to the content and the model’s context budget, and I attach rich metadata to each chunk - source, section, date, and access level - which is essential for filtering (both for relevance and for security trimming). I also consider techniques like including a bit of surrounding context or a summary with each chunk, and I evaluate retrieval quality empirically and adjust the chunking, because the right strategy depends on the documents. The key insight I’d convey is that chunking is not a trivial preprocessing detail but a primary design decision in RAG: getting it right is frequently the difference between a system that retrieves the right information and one that retrieves noise, and it is where I spend real effort and iterate based on evaluation.
How do you enforce security and prevent data leakage in a RAG system?
The cardinal rule is that authorization is enforced at retrieval, in code, based on the user’s identity and permissions - never by instructing the model to withhold data, because that approach fails to both prompt injection and ordinary model mistakes. Concretely, every chunk is indexed with access metadata (the roles, groups, or classifications that may see it), and at query time I filter the vector/hybrid search by the current user’s entitlements so the retrieval only ever returns chunks the user is allowed to access. The model therefore only receives context the user could legitimately see, and it cannot leak what it never received - which is the crucial property. This is far safer than the naive approach of indexing everything into a shared store and hoping a prompt instruction keeps users in their lane, which an attacker can bypass with prompt injection and which the model can simply get wrong. Beyond access trimming, I treat retrieved documents themselves as untrusted content, because indirect prompt injection can hide malicious instructions inside a document that then hijack the model - so I do not let retrieved or generated content authorize actions, and I validate outputs. For multi-tenant systems I isolate data strictly (per-tenant partitions or filters) so one tenant can never retrieve another’s data. I also protect sensitive data in the pipeline (classification, masking of PII where appropriate, encryption), log all AI interactions for audit, and ensure the ingestion pipeline itself respects source-system permissions so restricted documents are not over-shared into the index in the first place. The unifying principle is that in RAG, security lives in the retrieval and data layer, applied before anything reaches the model, exactly as it would for any other data-access path - the LLM is untrusted plumbing, and real authorization is enforced around it, per user, at retrieval time.
6.7 Banking RAG Scenario
A bank’s knowledge assistant answers staff and customer questions from approved policies, procedures, and FAQs. Ingestion chunks documents structure-aware, embeds them, and indexes each chunk with source, date, and access-level metadata. Queries use hybrid search (semantic plus keyword for exact policy codes) filtered by the user’s entitlements, so the model never receives content the user cannot see - and customers can never surface internal-only material. Answers are grounded strictly in retrieved context with citations, and the model is told to say it does not know rather than guess. Retrieval accuracy, answer faithfulness, and feedback are continuously evaluated, and every interaction is audited - production-grade, secure, evaluated RAG.
Chapter Revision Notes
- RAG quality is dominated by retrieval quality - most engineering is in the pipeline.
- Ingestion (chunk, embed, index with metadata) sets the ceiling; chunking is a primary decision.
- Hybrid search (semantic + keyword, re-ranked) beats either alone; filter by metadata.
- Enforce authorization at retrieval by trimming to the user’s entitlements - never via the prompt.
- Ground answers in retrieved context with citations; instruct “say you don’t know.”
- Evaluate retrieval accuracy, answer faithfulness, and feedback continuously - RAG is iterated.