5.1 End-to-End RAG Architecture, Grounding & ACL Filtering
Master how Retrieval-Augmented Generation works in real companies: decide between RAG, Fine-Tuning, and Long Context, enforce multi-tenant ACL security before vector search, and keep indexes fresh.
1. RAG vs. Fine-Tuning vs. Long Context (The #1 Architecture Decision)
Every week, a product manager asks: "Should we fine-tune a custom model on our company Confluence wiki so it knows our internal docs?"
Almost always, the answer is NO — use RAG! Fine-tuning adjusts model weights to teach style, tone, or narrow task format; it is a terrible database for fast-changing facts!
| Requirement | RAG (Retrieval-Augmented Generation) | Long Context Stuffing (100k+ Prompt) | Fine-Tuning (LoRA / SFT) |
|---|---|---|---|
| Teach new / hourly-changing facts? | 🏆 Instant (INSERT / UPDATE chunk) | ✅ Instant (if whole corpus < 150k tok) | ❌ Stale immediately; forgets/hallucinates |
Per-User Access Control (ACL)? | 🏆 Enforced per query in WHERE! | ✅ Filter files per request | ❌ Impossible — weights leak across users! |
| Exact Verifiable Citations? | 🏆 Direct [doc_id] source links | ✅ Supported | ❌ Model cannot cite training weights |
| Teach strict domain tone / DSL syntax? | ⚠️ Limited to few-shot window | ⚠️ Expensive per call | 🏆 Ideal use case for Fine-Tuning! |
When DOES Long Context Stuffing beat RAG? If your entire knowledge base for a task is under
40,000tokens (e.g., a 35-page product manual shared across all users) and you turn on KV Prompt Caching (Lesson 1.2), stuffing the whole manual into the cached prefix requires zero chunking or vector DB infrastructure! Once your corpus grows past100ktokens or varies per tenant, RAG wins decisively.
2. Anatomy of a Production RAG System (Two Decoupled Pipelines)
Production RAG is never one script — it is two decoupled pipelines sharing one strict contract (identical embedding model, dimensionality, and ACL schema):
- Offline / Event-Driven Indexing Pipeline: Triggered by webhooks (Notion page saved, GitHub PR merged, S3 PDF uploaded) → Parses clean Markdown → Splits into breadcrumb-enriched chunks → Computes content hash (
SHA-256) to skip unchanged chunks → Embeds changed chunks in batches → Upserts into PostgreSQLpgvectorinside an ACID transaction. - Online Real-Time Query Pipeline (
< 800 msTTFT): Authenticates caller's JWT → Resolves permittedorg_id/team_ids→ Runs ACL-filtered retrieval → Formats top chunks into XML<source>blocks → Streams a grounded, cited response!
3. The Cardinal Rule of Enterprise RAG: ACL Filtering Happens BEFORE Retrieval!
Suppose Alice (Marketing) asks your company AI assistant: "What is the CEO's Q4 layoff plan?"
- Catastrophic Bug: Retrieve global Top-5 chunks first, see that Chunk #1 is
ceo-confidential.pdf, and ask the LLM in the system prompt "Don't mention confidential HR files to Marketing users." (Trivial prompt injection leaks it in 10 seconds!) - Production Architecture: Query-time SQL MUST bind Alice's verified permissions directly in
WHERE:
WHERE org_id = $auth_org_id
AND access_group_id = ANY($alice_verified_groups)
If Alice doesn't have read access to ceo-confidential.pdf, that vector never even enters the LLM context window!
4. Wire-Level Trace: Grounded Prompt Construction & Incremental Sync
BEGIN; DELETE FROM doc_chunks WHERE doc_id = $1; INSERT INTO doc_chunks ... (new v2.5 pricing chunks); COMMIT;
5. Production SDK Code: Grounded RAG Prompt Assembly Across Providers
(Tip: Anthropic Claude even includes a native first-party Citations API (citations={"enabled": True}) that automatically maps every generated sentence back to exact character offsets in your source documents!)
from openai import OpenAI
from pydantic import BaseModel
client = OpenAI()
class CitedRagAnswer(BaseModel):
answer_markdown: str
cited_source_ids: list[str]
found_in_sources: bool
def generate_rag_answer(question: str, chunks: list[dict]) -> CitedRagAnswer:
sources_xml = "\n".join(
f'<source id="{c["id"]}" title="{c["title"]}">\n{c["text"]}\n</source>'
for c in chunks
)
resp = client.responses.parse(
model="gpt-4o-mini",
temperature=0.0,
instructions=(
"Answer ONLY using facts inside <sources>. Cite source IDs inline like [doc_1]. "
"If <sources> lacks the answer, set found_in_sources=False and say you don't have that info."
),
input=f"<sources>\n{sources_xml}\n</sources>\n\nQuestion: {question}",
text_format=CitedRagAnswer,
)
return resp.output_parsed6. What Breaks in Production (War Stories)
- Zombie Chunks After Document Edits: Updating
refund-policy.mdby upsertingchunk_0..chunk_4when the old version hadchunk_0..chunk_6leaveschunk_5andchunk_6orphaned in your index — causing the bot to contradict itself! Always delete old chunks fordoc_idinside the same transaction as inserting new ones. - Temporal Blindness (
2022Doc Outranking2026Doc): Two quarterly reports ("Q1 2022 Pricing" and "Q1 2026 Pricing") have near-identical cosine similarity (0.91vs0.90). Always storepublished_atmetadata, pass dates inside<source updated="2026-03-01">, and apply a slight recency boost when queries ask for current state! - Dumping
top_k = 30Unfiltered Chunks Into the Prompt: Stuffing 30 mediocre chunks increases latency 4×, triggers "Lost in the Middle" distraction, and explodes cost. Retrieve25–50candidates cheaply, then Rerank down to the Top5–8(Lesson 5.2)!
Module 5.1 Mastery Check — RAG Architecture & ACL Security
Keep Exploring: Related Lessons & Tools
All Courses →Paste LeetCode-style level-order tree arrays, graph edge lists, or 2D matrices to render clean vector SVG diagrams and DFS traversals.
Compute MD5, SHA-1, SHA-256, SHA-384, and SHA-512 hashes or keyed HMAC signatures directly in your browser using Web Crypto.