Course
AI · Module 05: Production RAG SystemsTutorial 13 of 21
AI Course·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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!

RequirementRAG (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,000 tokens (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 past 100k tokens 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 INDEXING PIPELINE (ASYNC WORKER)1. Parse PDF/MD/HTML2. Recursive Chunk + Meta3. Embedding Model4. pgvector / HNSW DBONLINE QUERY PIPELINE (REAL-TIME < 800ms)1. User Query + Auth ACL2. Metadata Filter + Search3. Rerank Top-5 Chunks4. Grounded Cited Reply
Figure: Critical Rule — ALWAYS use the exact same embedding model + dimensionality in both Offline Indexing and Online Querying!
  1. 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 PostgreSQL pgvector inside an ACID transaction.
  2. Online Real-Time Query Pipeline (< 800 ms TTFT): Authenticates caller's JWT → Resolves permitted org_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:
SQL
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

Tracing Secure Multi-Tenant RAG From Webhook to Cited Answer
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. Transactional Re-Indexing Prevents Stale 'Ghost Chunks')
1→# 1. Incremental Sync: Hash check avoids re-embedding unchanged chunks!
2→if db.get_doc_hash(doc_id) != sha256(new_md): reindex_transactional(doc_id, new_md)
3# 2. Query Time: Hard ACL filter + Top-K retrieval
4sources = search_chunks(q_vec, org_id=jwt.org_id, groups=jwt.groups, k=5)
5# 3. Grounded Synthesis with strict citation & abstention rules
6answer = llm_grounded_reply(question, sources)
ACID Upsert + Orphan CleanupZERO STALE PRICING
BEGIN;
DELETE FROM doc_chunks WHERE doc_id = $1;
INSERT INTO doc_chunks ... (new v2.5 pricing chunks);
COMMIT;
What's Happening: If Pricing.md shrinks from 12 chunks to 9 chunks and you only UPSERT chunks 1..9 by index, old chunks 10..12 stay alive forever quoting 2024 prices! Delete-and-replace inside a transaction prevents ghost chunks.

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!)

SDK:
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_parsed

6. What Breaks in Production (War Stories)

  1. Zombie Chunks After Document Edits: Updating refund-policy.md by upserting chunk_0..chunk_4 when the old version had chunk_0..chunk_6 leaves chunk_5 and chunk_6 orphaned in your index — causing the bot to contradict itself! Always delete old chunks for doc_id inside the same transaction as inserting new ones.
  2. Temporal Blindness (2022 Doc Outranking 2026 Doc): Two quarterly reports ("Q1 2022 Pricing" and "Q1 2026 Pricing") have near-identical cosine similarity (0.91 vs 0.90). Always store published_at metadata, pass dates inside <source updated="2026-03-01">, and apply a slight recency boost when queries ask for current state!
  3. Dumping top_k = 30 Unfiltered Chunks Into the Prompt: Stuffing 30 mediocre chunks increases latency 4×, triggers "Lost in the Middle" distraction, and explodes cost. Retrieve 25–50 candidates cheaply, then Rerank down to the Top 5–8 (Lesson 5.2)!

Module 5.1 Mastery Check — RAG Architecture & ACL Security

Q1.When a company wants an internal assistant to answer questions over Confluence pages that change 50 times a day and have per-team permissions, why does RAG beat Fine-Tuning?
Q2.Where MUST multi-tenant / team-level permission checks (`ACL`) be enforced in an enterprise RAG pipeline?
Q3.Why does updating an edited document by only `UPSERT`ing chunks `0..N` (without deleting prior chunks for `doc_id`) cause subtle production hallucinations?
Q4.When IS stuffing the full document into the prompt (without vector search) actually simpler and better than RAG?

Keep Exploring: Related Lessons & Tools

All Courses →