🧩 Dedicated Prep Track

AI Threat Modeling & Data Flow Architecture

Enterprise architectural blueprint for threat modeling modern Artificial Intelligence (AI), Retrieval-Augmented Generation (RAG), and agentic pipelines. Master the 7-component Data Flow Diagram (DFD), 6 critical Trust Boundaries (TB0 to TB5), STRIDE (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege) tailored for generative AI, DREAD risk scoring, and a production threat register.

← All Prep Tracks
7-Component AI DFD6 Trust Boundaries (TB0–TB5)STRIDE Adapted for GenAISTRIDE × Boundary Heat MapDREAD Risk QuantificationRAG Support Agent RegisterSTAR Interview Masterclass

AI System Data Flow & Trust Boundaries

Interactive 7-component data flow diagram with return paths and trust zones

Modern AI systems operate across distributed environments: user interfaces, API gateways, LLMs (Large Language Models), vector databases, and external tool execution servers. Establishing explicit trust boundaries at every seam ensures that untrusted data is sanitized, decisions are governed by code, and actions require verified authorization.

Core Data Flow Architecture
  • 7-component end-to-end AI data flow pipeline
  • 6 distinct trust boundary crossings (TB0 through TB6)
  • Explicit separation between data, model context, and execution
Critical Return Path Defense
  • Return paths: retrieved documents and tool responses re-enter the model context
  • The LLM is never an authorization enforcement point; checks live in application code
  • TB0 supply chain controls for base models, weights, and third-party tools
Quick Jump:1. Data Flow Pipeline2. LLM ↔ RAG Systems Map3. 5 Core RAG Types & Matrix4. LLM vs RAG vs Agents5. 7 Build Patterns × 8 Sources6. LangGraph vs CrewAI7. Trust Boundaries (TB0–TB6)

AI System Data Flow: Runtime Path & Offline Ingestion Path

Complete architectural data flow showing the online request-response chain (with trust boundaries TB1–TB6), MCP server placement, the offline batch ingestion pipeline, and return paths

Runtime + Offline Architecture

Runtime Path: User → Input → LLM → RAG & MCP → Memory → Output → Users

User / External Input
Humans, apps, other agents
Untrusted by default
Prompt / Input Layer
AuthN + rate limits
Input guardrails
Context assembly
LLM (Model)
Interprets context
Plans tool calls
Generates response
RAG & MCP Tools
Hybrid retrieval
In-host MCP Client
Isolated MCP Servers
Zod schema + ACL filter
▲ fed by ingestion
Memory / Storage
Vector + BM25 index
Session memory
User data
▲ fed by ingestion
Output / Action Layer
Output guardrails
Citations
Triggers actions
Users / External Systems
Answer to user
Email, DBs, APIs, SaaS
TB1 Identity + quotasTB2 Instructions vs dataTB3 Tool authZ + return pathTB4 Tenant isolationTB5 DLP on the way outTB6 Egress + approval
Architecture Zoom-In

MCP (Model Context Protocol) Server Placement & Trust Boundary (TB3)

Where MCP Servers physically live, how they decouple model reasoning from system execution, and how data returns across TB3.

Open JSON-RPC 2.0 Standard
1. MCP Host & Client
Host application runtime (Claude, Cursor, LangGraph agent)
🧠 LLM Agent Loop: plans and emits tools/call
🔌 MCP Client (In-Process): discovers tools (tools/list) & validates schemas
TB32. Transport & Boundary
Strict bidirectional JSON-RPC 2.0 communication
⚙️ Local stdio: Spawned child process in gVisor sandbox. Zero sockets, credentials stay local.
🌐 Remote mTLS SSE: Server-Sent Events over HTTPS + OAuth 2.0 Bearer token (SSRF safe).
3. Standard MCP Servers
Decoupled execution processes with scoped credentials
🗄️ Postgres MCP: Read-only AST SQL
🐙 GitHub MCP: PRs & scoped repos
🏢 ServiceNow: Tickets & workflows
💻 Shell / Code: Ephemeral microVM
4. Targets & Return Path
Enterprise backends & untrusted return payload
🎯 Enterprise Backends: Databases, Git repos, internal REST APIs, cloud infra
🛡️ Delimited Return: Payloads enclosed in <mcp_output> to stop Indirect Prompt Injection
📍 Physical Placement: MCP Servers run outside the LLM orchestrator. Local servers run as sandboxed child processes (stdio); enterprise servers run as containerized microservices (SSE).
🔑 Zero Secret Leakage: Database passwords and OAuth tokens reside strictly inside the MCP Server process. The LLM only receives sanitized query outputs, never raw credentials.
↩️ Bidirectional TB3 Hop: Tool outputs returning from the MCP Server are treated as untrusted external data — parsed with schema checks and logged to SIEM with OpenTelemetry (OTel).
Runtime path (online, per request): triggered by a user, runs in seconds, reads the indexes and answers. Main risk: direct prompt injection, data leakage in the output.
Offline path (batch, ahead of time): triggered by new or changed source data, runs in minutes to hours, writes the indexes. Main risk: data poisoning, missing ACL (Access Control List) metadata.
▲ The link is the index. Offline writes chunks, embeddings and ACL metadata into the vector, BM25 (Best Matching 25) and graph indexes; at runtime RAG (Retrieval-Augmented Generation) and Memory / Storage only read from them. So runtime answers can only be as fresh, clean and correctly permissioned as the last ingestion run, and a poisoned document ingested offline becomes indirect prompt injection at runtime.

Offline Path: Ingestion and Indexing

1. Sources
Docs, wikis, tickets
Databases, APIs
Code repositories
2. Extract
Parse PDF / HTML
OCR (Optical Character Recognition)
Capture ACL metadata
3. Clean
PII (Personally Identifiable Information) redaction
Dedupe
Secret + injection scan
4. Chunk
Semantic chunking
Overlap windows
Tag source + owner
5. Embed
Embedding model
Version the model
Batch + retry
6. Index
Vector DB (Database)
BM25 (Best Matching 25) index
Knowledge Graph
⟲ Re-index on source change (CDC: Change Data Capture) and re-embed whenever the embedding model version changes
The arrows also run backwards. Retrieved chunks and tool responses flow from RAG & Tools back into the LLM (Large Language Model) across TB3. That return path carries indirect prompt injection, so retrieved content is untrusted input, the same as a user prompt.

How an LLM Connects to Different RAG Systems

An LLM (Large Language Model) does not query data stores directly. A retrieval orchestrator sends each question to one or more RAG (Retrieval-Augmented Generation) backends, merges what comes back, and grounds the prompt in that context before the model writes an answer.

Vector RAG
Connects via: Query is turned into an embedding, then an ANN (Approximate Nearest Neighbor) similarity search returns the top-k chunks.
Best for: Unstructured docs, policies, wikis, runbooks.
pgvectorPineconeWeaviateFAISS
Hybrid Search RAG
Connects via: BM25 (Best Matching 25) keyword search plus dense vectors, merged with RRF (Reciprocal Rank Fusion) and a cross-encoder reranker.
Best for: Exact IDs, error codes, product names and jargon.
ElasticsearchOpenSearchCohere Rerank
GraphRAG
Connects via: LLM pulls out entities, then walks the KG (Knowledge Graph) with Cypher or community summaries.
Best for: Multi-hop questions, how things relate, root cause.
Neo4jMS GraphRAGNeptune
Structured / Text-to-SQL RAG
Connects via: LLM writes SQL (Structured Query Language) against a semantic layer. The query runs read-only and the result rows go back into the prompt.
Best for: Metrics, KPIs (Key Performance Indicators), finance and ops data.
SnowflakePostgresdbt Semantic Layer
LLM + Retrieval Orchestrator
Routes, fuses and grounds context
Query Router / Intent Classifier
Query Rewrite (HyDE: Hypothetical Document Embeddings)
Context Fusion + Reranking
Prompt Assembly (token budget)
LLM Generation + Citations
Agentic RAG (Tools / MCP)
Connects via: LLM plans its own retrieval steps and calls tools through MCP (Model Context Protocol) servers or function calling.
Best for: Questions that need several sources and multiple steps.
MCP serversLangGraphFunction calling
Web / Live Search RAG
Connects via: Calls a search API, scrapes and cleans the pages, then grounds the answer with citations to each URL (Uniform Resource Locator).
Best for: Fresh facts, news, anything newer than the model training cutoff.
TavilyBing APIGoogle Grounding
Multimodal RAG
Connects via: Images, PDF (Portable Document Format) pages and audio are embedded with CLIP (Contrastive Language-Image Pre-training) or a VLM (Vision-Language Model).
Best for: Diagrams, scanned forms, slides, screenshots.
ColPaliCLIPWhisper
Memory RAG
Connects via: Past conversation summaries and user facts are stored, then pulled back by user ID (Identifier) and relevance on each turn.
Best for: Personalization and long-running agent sessions.
Mem0RedisZep

Request Lifecycle: Query to Grounded Answer

1. Query
User question
Chat history
User / tenant ID
2. Route
Intent classify
Pick RAG backends
Run in parallel
3. Retrieve
Vector / BM25
Graph / SQL
Web / Tools (MCP)
4. Fuse
RRF merge
Cross-encoder rerank
Dedupe + ACL filter
5. Generate
Grounded prompt
LLM answer
Inline citations
6. Guard
PII redaction
Faithfulness check
Output guardrails
⟲ Evaluate continuously with RAGAS (RAG Assessment): context precision, recall and faithfulness, fed back into chunking and routing
ACL (Access Control List) filter: apply document permissions during retrieval, before the LLM sees anything. Filtering after generation is too late, because the data has already leaked into the answer.
PII (Personally Identifiable Information): redact it at ingestion and again on output. Treat retrieved chunks as untrusted input, since they can carry indirect prompt injection.
Interview line: "Start with hybrid search plus a reranker. Add GraphRAG or Text-to-SQL only when questions need multiple hops or exact aggregates."

📚 5 Core Types of RAG Architecture (Naive, Advanced, Graph, Agentic, Modular)

Primary Interview Framework

Retrieval-Augmented Generation (RAG) enhances LLMs (Large Language Models) by dynamically retrieving relevant facts from external knowledge repositories before generating responses. The five foundational architectures represent an evolution from naive vector lookups to autonomous multi-agent knowledge synthesis:

Advanced RAG
Production Standard

Optimized retrieval pipeline adding pre-retrieval query rewriting (e.g. HyDE — Hypothetical Document Embeddings, query decomposition), hybrid search (dense vectors + sparse BM25 — Best Matching 25), semantic chunking, and post-retrieval cross-encoder reranking and context compression. Still deterministic in execution order, but delivers dramatically higher precision and lower hallucination than Naive RAG.

Best For: Enterprise policy search, compliance document review, customer support documentation.
Core Strength: Hybrid BM25 + vector search, cross-encoder reranking, HyDE query expansion, metadata filtering.
Agentic RAG
Autonomous Planning

The LLM (Large Language Model) acts as an autonomous agent orchestrating multi-step retrieval. Using tools and MCP (Model Context Protocol) servers, the agent evaluates incoming queries, formulates a multi-step search plan, queries heterogeneous data stores (vector DBs, SQL — Structured Query Language, APIs, live web), reflects on returned evidence, and iteratively loops until sufficient context is gathered.

Best For: Complex security incident triage, deep competitive intelligence, cross-system financial investigations.
Core Strength: Multi-step reasoning, dynamic tool selection, iterative self-correction, heterogeneous source synthesis.
Graph RAG
Relational & Multi-Hop

Combines Knowledge Graphs (KGs with entities, relationships, and property attributes) with vector search. Instead of treating text as isolated chunks, Graph RAG extracts structured entity-relationship triples (e.g., Service-A → depends_on → Database-B) and executes multi-hop graph traversals (via Neo4j, Amazon Neptune) to answer relational and topology questions that flat vector search misses.

Best For: Identity and Access Management (IAM) privilege path analysis, cloud attack path mapping, pharmaceutical drug interaction.
Core Strength: Multi-hop relationship traversal, topological reasoning, global corpus summarization, zero chunk-boundary fragmentation.
Modular RAG
Composable Pipeline

A composable, service-oriented architecture where routing, retrieval, memory, fusion, and verification are decoupled into interchangeable plug-and-play micro-modules. Systems dynamically assemble specialized pipelines based on query intent — routing simple questions to cached vectors and complex regulatory queries through hybrid graph-vector fusion with guardrails.

Best For: Unified enterprise platforms serving disparate business units (legal, engineering, finance, HR).
Core Strength: Maximum architectural flexibility, independent module scaling and caching, tailored per-domain routing.
Naive / Classic RAG
Baseline Architecture

The standard 3-step baseline pipeline: (1) chunk and embed raw documents into vector embeddings during ingestion, (2) retrieve top-k chunks matching the raw user query via cosine similarity, and (3) concatenate retrieved chunks directly into the LLM system prompt. While straightforward and fast to prototype, it suffers from context stuffing, semantic mismatch, and zero self-correction.

Best For: Simple internal FAQ search, personal desktop notes assistants, rapid proof-of-concept prototypes.
Core Strength: Extremely simple to implement, minimal latency overhead, lowest compute and engineering cost.

Side-by-Side Comparison: The 5 RAG Architectural Styles

DimensionNaive / ClassicAdvanced RAGGraph RAGAgentic RAGModular RAG
Retrieval MechanismSingle-pass dense vector similarity (top-k cosine / dot product)Hybrid search (dense vector + sparse BM25) + cross-encoder rerankerGraph traversal (Cypher / SPARQL) over entity-relationship triples + vectorDynamic multi-step tool calls across vector, SQL, APIs, and live webDynamic composable routing across swappable retriever microservices
Query Pre-ProcessingNone (raw user string directly embedded)Query rewriting, HyDE (Hypothetical Document Embeddings), sub-query decompositionNamed Entity Recognition (NER), entity linking, graph schema mappingMulti-turn intent decomposition, tool selection, plan generationConfigurable per-route pre-processors (classifier, router, re-writer)
Self-Correction & Reflection❌ None (single forward pass)⚠️ Basic (confidence threshold filtering & context compression)⚠️ Schema validation & connected path verification✅ Full (evaluates chunk relevance, detects gaps, loops to re-fetch)✅ Configurable verification and guardrail modules
Multi-Hop Reasoning❌ Fails (cannot link disconnected document chunks)⚠️ Limited (relies on sub-query decomposition and reranking)✅ Superior (natively traverses entity relationship edges)✅ Strong (agent chains sequential queries across tools)✅ Supported via plug-in graph or agentic reasoning modules
Typical Latency< 500 ms (single vector lookup + LLM completion)800 ms – 1.5 s (hybrid search + cross-encoder rerank)1.0 s – 2.5 s (entity extraction + graph query + vector)2.5 s – 8.0 s (multiple LLM reasoning steps & tool roundtrips)Variable (500 ms – 4.0 s depending on routed pipeline)
Complexity & Maintenance🟢 Low (minimal infrastructure, 1 vector DB)🟡 Medium (vector DB, BM25 index, reranker model)🟠 High (graph DB maintenance, entity extraction pipelines)🔴 High (orchestrator loops, tool sandboxing, state tracking)🟣 Highest (microservice orchestration, interface versioning)
Primary Security & Threat SurfaceVector data poisoning, direct prompt injectionQuery rewriting manipulation, poisoned chunks passing rerankersGraph knowledge poisoning, malicious entity relation injectionIndirect Prompt Injection (OWASP LLM01), unauthorized tool execution (LLM06)Inherits all threat planes; requires boundary validation at each module
💡 Interview Question

Explain the 5 types of RAG architectures — Naive, Advanced, Graph, Agentic, and Modular — and when would you use each?

Retrieval-Augmented Generation (RAG) grounds LLMs (Large Language Models) in external knowledge.

1NAIVE RAG
  • Embeds documents into vectors, pulls top-k by cosine similarity, and stuffs them into the prompt
  • It is fast to prototype but lacks query optimization, exhibits high irrelevance rates, and cannot handle multi-hop questions
  • Use for simple FAQs
2ADVANCED RAG
  • The production standard
  • Adds pre-retrieval query rewriting (e.g
  • HyDE — Hypothetical Document Embeddings), hybrid search (dense vectors + sparse BM25 — Best Matching 25), and post-retrieval cross-encoder reranking and context compression
  • Use for enterprise policy and knowledge-base search
3GRAPH RAG
  • Extracts entity-relationship triples into Knowledge Graphs (KGs via Neo4j or Amazon Neptune)
  • Enables multi-hop relational reasoning across connected entities that flat vector similarity misses
  • Use for IAM (Identity and Access Management) permission graphs, IT dependencies, and regulatory lineage
4AGENTIC RAG
  • Treats the LLM as an autonomous agent that plans retrieval steps, queries multiple tools (SQL — Structured Query Language, APIs, vector DBs), evaluates retrieved context sufficiency, and loops dynamically
  • Use for multi-system incident triage and deep research
5MODULAR RAG
  • Decouples routing, search, and validation into plug-and-play microservices, routing simple queries to cache and complex queries to hybrid graph-vector fusion
  • In terms of security, Naive RAG is vulnerable to vector data poisoning; Advanced adds query manipulation; Graph adds graph entity poisoning; Agentic introduces severe Indirect Prompt Injection (OWASP LLM01) and Excessive Agency (OWASP LLM06); and Modular inherits all risks across its distributed seams

🔄 LLM vs RAG vs Agentic RAG vs AI Agents vs Multi-Agent AI

Evolutionary Spectrum

As AI systems advance from standalone Large Language Models (LLMs) to multi-agent ecosystems, capability and adaptability increase alongside cost, latency, and attack surface.

Aspect🧠 Base LLM📚 RAG🔗 Agentic RAG🤖 AI Agent🏢 Multi-Agent AI
Information AccessStatic training weights only (frozen at pre-training cutoff date).Dynamic external retrieval from vector DBs and enterprise document repositories.Strategic multi-source retrieval — decides what, when, and how to query.Direct read/write access to external tools, APIs, filesystems, and databases.Collaborative, federated knowledge gathering across specialized agents.
Reasoning CapabilityStatistical token prediction based on pre-trained patterns.Context-augmented generation — grounds reasoning in retrieved chunks.Goal-driven reasoning — plans retrieval steps, validates context sufficiency.Autonomous goal decomposition, error recovery, and iterative execution.Collective distributed reasoning with peer critique and consensus mechanisms.
Adaptability & StateStatic (requires fine-tuning or retraining to learn new facts).Moderately dynamic (updates instantly when new documents are indexed).Highly dynamic (adapts retrieval strategy dynamically on runtime failures).Highly adaptive (maintains short/long-term memory and execution history).Extremely adaptive (dynamic role delegation and distributed state machines).
Problem-Solving PatternSingle-turn prompt-in, completion-out text generation.Retrieve-then-generate contextual synthesis.Looping: Plan → Retrieve → Grade → Refine → Generate.ReAct cycle: Observe → Orient → Decide → Act via external tools.Orchestrated division of labor: Supervisor assigns subtasks to specialists.
External InteractionNone (pure text processing within context window).Read-only queries to document indices and vector stores.Dynamic read queries across vector DBs, SQL, search APIs, and MCP tools.Full read/write execution (API mutations, bash scripts, database transactions).Complex inter-agent messaging protocols and distributed workflow execution.
Cost & Latency$ LOW · Single inference pass token cost only.$$ MEDIUM · Embedding generation + vector DB query + LLM inference.$$$ HIGH · Multiple LLM reasoning turns + multi-source retrieval calls.$$$$ VERY HIGH · Multi-turn tool execution + recursive self-correction loops.$$$$$ HIGHEST · Multiplied token consumption across parallel/sequential agents.
Security Risk ProfileDirect prompt injection (jailbreaks), sensitive data memorization leakage.Corpus data poisoning, contextual leakage, cross-tenant vector contamination.Indirect Prompt Injection (OWASP LLM01), retrieval query tampering.Excessive Agency (OWASP LLM06), Server-Side Request Forgery (SSRF), tool abuse.Cascading delegation hijacks, unlogged autonomous actions, privilege drift.
💡 Interview Question

How do you explain the transition from Traditional RAG to Agentic RAG and Autonomous AI Agents?

Traditional RAG (Retrieval-Augmented Generation) is a deterministic, linear data pipeline: the user submits a prompt, the system executes one vector similarity lookup, concatenates the top-k chunks into the context window, and the LLM (Large Language Model) generates a completion in a single turn. The model has zero control over what was retrieved or whether the data is sufficient. In AGENTIC RAG, the LLM becomes the active orchestrator: it decomposes complex queries into sub-tasks, selects appropriate retrieval tools (vector search, Text-to-SQL, internal APIs), inspects intermediate retrieved chunks for gaps or hallucinations, and autonomously loops to refine queries until confidence is established. When moving further to FULL AI AGENTS and MULTI-AGENT systems, the scope expands beyond read-only information retrieval into write-capable state mutations — executing API calls, writing and running code, interacting with third-party systems via Model Context Protocol (MCP), and coordinating across specialized agent personas. Crucially, each step up this ladder expands the security attack surface: while Traditional RAG faces data poisoning and retrieval evasion, Agentic and Multi-Agent systems face Indirect Prompt Injection (OWASP LLM01), Insecure Tool Execution (OWASP LLM06), Cascading Delegation Failures, and Denial of Wallet (OWASP LLM10) from runaway recursive loops.

🎛️ 7 RAG Build Patterns (Control Plane) × 8 Data Sources (Data Plane)

Production Control × Data Matrix

Production RAG (Retrieval-Augmented Generation) systems decouple control from data. The build pattern is the control plane (how and when retrieval loops trigger). The data source is the data plane (where structured, unstructured, or operational knowledge lives). Every production application joins one control pattern to one or more data sources through an intelligent retrieval orchestrator:

1. Naive RAG
Embed the question, fetch the top-k chunks, put them in the prompt, generate. One fixed pass.
2. Advanced RAG
Adds query rewrite (e.g. HyDE — Hypothetical Document Embeddings), smarter chunking, reranking and context compression.
3. Modular RAG
Router, retrievers, memory and fusion are plug-in modules, so one system can mix every other pattern.
4. Agentic RAG
The LLM (Large Language Model) decides what to fetch, in what order, and when it has enough, using tools or MCP (Model Context Protocol) servers.
5. Self-RAG
The model decides whether to retrieve at all, then grades its own evidence and answer before replying.
6. Corrective RAG
CRAG (Corrective RAG) scores retrieved documents. If they are weak, it falls back to web search or rewrites the query.
7. Adaptive RAG
A classifier picks the path: no retrieval for simple questions, one search for medium ones, multi-step for hard ones.

Connection Matrix: 7 Build Patterns × 8 Data Sources

Rows represent the 7 build patterns; columns represent the 8 enterprise data sources from the LLM Connection Map. Solid circles represent primary architectural fit; ringed circles represent secondary fit. Modular and Agentic RAG span the widest variety of sources because they natively support heterogeneous tool calling.

Pattern ↓ / Source →Vector
Nearest-neighbor embeddings
Hybrid
Keyword + vector
Graph
Knowledge Graph
SQL
Text-to-SQL
Tools / MCP
Function calls
Web
Live search
Multimodal
Images, PDFs
Memory
User history
Naive RAG
Fixed pipeline
Advanced RAG
Pre + post retrieval
Modular RAG
Swappable parts
Agentic RAG
LLM plans retrieval
Self-RAG
Self-critique
Corrective RAG
CRAG
Adaptive RAG
Strategy per query
Primary fit Works well Rare

Runtime Execution Pipeline: How Control Joins Data

1. Framework
LangGraph
CrewAI
LlamaIndex
2. Build Pattern
Agentic / Adaptive
Corrective (CRAG)
Self-RAG
3. Router (Join Key)
Intent classifier
Source registry
ACL (Access Control List) scope
4. Data Sources
Vector / Hybrid
Graph / SQL
Web / Tools / Memory
5. Grounded Answer
RRF (Reciprocal Rank Fusion)
Citations
Output Guardrails
⟲ Continuously evaluate each pattern × source pair with RAGAS (RAG Assessment) metrics: Faithfulness, Answer Relevance, Context Precision, and Context Recall.

Production Worked Recipes (Pattern + Sources)

Policy & Regulatory Runbook Assistant
How: Advanced RAG
Where: Hybrid + Vector
Exact compliance control IDs require BM25 (Best Matching 25) keyword search; paraphrased risk questions require dense vectors. A cross-encoder reranker fixes chunk ordering.
Security Analyst Autonomous Copilot
How: Agentic RAG
Where: SQL + Graph + Tools (MCP)
Vulnerability counts require SQL (Structured Query Language), blast radius requires the KG (Knowledge Graph), and active host triage relies on live MCP (Model Context Protocol) tool calls.
Threat Intelligence Zero-Day Q&A
How: Corrective RAG (CRAG)
Where: Vector + Web
Internal threat intel vector store is checked first. If relevance scoring is below threshold (e.g., brand-new CVE — Common Vulnerabilities and Exposures), CRAG triggers automated web fallback.
💡 Interview Question

How many types of RAG are there, and how do you choose the right one in production?

There is no single fixed number, because production RAG (Retrieval-Augmented Generation) is architecturally decoupled into two axes:

1The Control Plane (how retrieval loops execute): Naive, Advanced, Modular, Agentic, Self-RAG, Corrective RAG (CRAG), and Adaptive RAG.

2The Data Plane (where information lives): Vector embeddings, Hybrid (BM25 — Best Matching 25 + vector), Knowledge Graph (KG), Structured SQL (Structured Query Language), Live Web, MCP (Model Context Protocol) tool execution, Multimodal stores, and Memory buffers. A production system selects one control pattern and joins it to one or more sources via a router. My architectural default is ADVANCED RAG over HYBRID search with cross-encoder reranking. I introduce Graph RAG when relationships and multi-hop paths matter, SQL when exact numerical aggregation is required, and transition to AGENTIC or CORRECTIVE RAG (CRAG) only when offline evaluation using RAGAS (Retrieval-Augmented Generation Assessment) demonstrates that single-pass retrieval fails context precision or recall targets.

⚡ LangGraph vs CrewAI: Orchestration Frameworks for Agentic RAG

Runtime Orchestration

Agent frameworks govern the state machine, control flow loops, and tool execution boundaries of Agentic RAG (Retrieval-Augmented Generation). LangGraph and CrewAI represent the two dominant design paradigms:

LangGraph
Graph & State-Machine Orchestration (LangChain Ecosystem)
  • Nodes represent discrete execution steps (LLM call, tool invocation, custom Python function); edges define conditional branching and cyclic loops.
  • A centralized, strongly typed state schema flows immutably through every node.
  • Native checkpointing enables durable execution state persistence, time-travel debugging, and instant fault resumption.
  • Built-in Human-in-the-Loop (HITL) interrupt hooks for approval gates prior to sensitive tool actions.
  • Best for production systems: deterministic control, complex cyclic loops (Self-RAG, CRAG), and strict enterprise auditing.
CrewAI
Role-Based Autonomous Multi-Agent Teams (Python Native)
  • Agents are defined with explicit human-readable personas: Role, Goal, and Backstory (e.g. Lead Threat Researcher, Compliance Auditor).
  • Tasks are assigned to specific agents and composed into a coordinated Crew.
  • Supports sequential execution workflows or dynamic hierarchical delegation under a manager agent.
  • Flows provide structured, event-driven state control for hybrid deterministic-agentic tasks.
  • Best for rapid multi-agent prototyping, exploratory research, and workflows that decompose cleanly by organizational role.

Side-by-Side Comparison: LangGraph vs CrewAI

DimensionLangGraphCrewAI
Mental ModelFlowchart / cyclical state machineCollaborative team of role-based specialists
Control & PredictabilityFine-grained determinism; every node & edge explicitHigh-level abstraction; autonomous task delegation
Learning CurveSteeper (requires state schema & graph theory)Gentler (intuitive prompt-like agent definitions)
State & Fault ToleranceFirst-class database checkpointing & replayBuilt-in memory buffers; Flows for structured state
Human SupervisionNative HITL interrupt primitives at any nodeSupported via human-input task flags
Primary Enterprise FitHigh-auditability production RAG & banking workflowsRapid multi-agent prototyping & creative exploration
💡 Interview Question

When would you choose LangGraph over CrewAI for an enterprise Agentic RAG deployment?

LangGraph models agent workflows as explicit, cyclical state machines where every node represents a deterministic computational or LLM (Large Language Model) step, edges enforce conditional routing, and a strongly typed state schema is checkpointed to persistent storage after each turn. This architecture provides replayability, deterministic audit logging, and first-class Human-in-the-Loop (HITL) interrupt primitives — essential requirements for high-assurance banking or healthcare systems running Corrective RAG (CRAG) or Self-RAG loops. In contrast, CrewAI abstracts agents around roles, goals, and backstories with autonomous hierarchical delegation, making it exceptionally fast to prototype multi-agent collaboration. In enterprise architecture, I use CrewAI to validate multi-agent role decomposition with product stakeholders, then implement the production pipeline in LangGraph to ensure strict deterministic boundary enforcement, scoped Model Context Protocol (MCP) tool access, and end-to-end cryptographic auditability.

🛡️ RAG Trust Boundaries: Why the LLM Is Never an Enforcement Point

Critical Defense Architecture

In any RAG (Retrieval-Augmented Generation) system, security failures occur when developers treat the LLM as an authorization or sanitization filter. Because LLMs are probabilistic token predictors, they cannot reliably enforce security boundaries. Enforcement must occur deterministically at the architectural boundaries:

TB-3: LLM ➔ Retrieval & Tools Boundary

The model produces text that becomes executable queries or tool calls. Enforce strict JSON-schema parameter validation, apply least-privilege API scopes tied to the authenticated user (never a shared superuser service account), and restrict tools with explicit allowlists.

TB-4: Retrieval Return Path Boundary (CRITICAL)

Retrieved chunks and tool outputs flow directly back into the model context window. This return path is the #1 vector for Indirect Prompt Injection (OWASP LLM01). Enforce XML/delimiter encapsulation, dual-LLM verification, and document-level Access Control List (ACL) pre-filtering.

TB-5: Context ➔ Persistent Memory Boundary

Writing conversation turns or extracted entities into long-term vector stores or session buffers. Enforce strict tenant namespace isolation, sanitize memory writes to prevent persistent memory poisoning, and apply cryptographic tenant tags to every stored vector embedding.

💡 Interview Question

Where do you draw trust boundaries in a retrieval-augmented generation (RAG) agent, and why is the LLM not one of them?

A trust boundary is any seam in the architecture where identity, privilege, data sensitivity, ownership, or tenant contexts change. In a RAG (Retrieval-Augmented Generation) agent, we establish six explicit boundaries: TB-1 at public ingress (WAF — Web Application Firewall, OAuth rate limiting); TB-2 between input and context assembly (PII — Personally Identifiable Information redaction, delimiter tagging); TB-3 between the orchestrator and tool execution (least-privilege scopes, strict JSON schemas); TB-4 on the critical retrieval return path where retrieved documents re-enter the context window (document ACL — Access Control List filtering, dual-LLM indirect injection inspection); TB-5 at persistent memory storage (tenant-isolated namespaces, cryptographic context tagging); and TB-6 at action egress (Human-in-the-Loop approval for financial or data mutations). The LLM itself CANNOT be a trust boundary because it is a probabilistic token predictor, not a deterministic reference monitor. If an attacker injects an instruction into an ingested RAG document, system prompt instructions like 'ignore malicious commands' fail probabilistically. Therefore, all security policy enforcement — authentication, authorization, schema validation, and sanitization — must live in deterministic application code and infrastructure before data enters and after outputs leave the model.

Setting Up Trust Boundaries (TB0 through TB6)

A boundary is any place where the level of trust changes, and each one needs a written enforcement contract

Draw a boundary wherever any of these change between two components:

Identity
Who is acting changes: user → service account, agent → tool
Privilege
The next component can do more: read → write, internal → payment API
Data sensitivity
Public text meets confidential or regulated data
Ownership
Your code hands off to a vendor model, SaaS tool, or third-party MCP server
Execution context
Text becomes action: model output → tool call, code run, or SQL
Tenant
Data from one customer could reach another through shared stores
1
Inventory components and actors
List every user type, service, model, data store, tool, and external system, including build-time inputs like datasets, base models, and plugins.
2
Assign a trust level to each
Untrusted (users, web content, uploaded files), semi-trusted (your app and the LLM), trusted core (data stores, tools with scoped credentials), privileged (control plane, model registry).
3
Group into zones and draw the lines
Components with the same trust level share a zone. Every data flow that crosses a zone edge is a boundary crossing: give it an ID (TB0-TB6).
4
Write the enforcement contract
For each boundary define: what is authenticated, what is validated (schema, size, content), what is authorized, and what is logged. Put the check in code or infrastructure, never in the prompt.
5
Enforce with real controls
Network segmentation and egress allowlists, mutual Transport Layer Security (mTLS) between services, per-user tokens, JSON-schema validation, role- or attribute-based access control (RBAC / ABAC) at the tool layer.
6
Verify and keep current
Red-team each boundary, alert in the SIEM when a check fails, and re-draw boundaries whenever a new tool, data source, or agent is added.
Untrusted
End users / agents
Web pages, emails, uploaded files
Indirect injection source
Application (semi-trusted)
AI gateway + input guardrails
Orchestrator / agent loop
LLM
Not an enforcement point
Data & Tools (trusted core)
Vector DB + memory
Per-tenant
Tool / MCP servers
Scoped credentials
Control plane (privileged)
System prompts, model config
Model registry + AIBOM
Supply chain
End users / agents→AI gateway + input guardrailsTB1: prompt + identity
AI gateway + input guardrails→LLMTB2: assembled context
Orchestrator / agent loop→Tool / MCP serversTB3: validated tool call
Web pages, emails, uploaded files→Orchestrator / agent loopTB3 return path: retrieved content
Orchestrator / agent loop→Vector DB + memoryTB4: tenant-filtered query
Model registry + AIBOM→LLMTB0: signed model load
External entity Process Data store Trust boundaryRed flows cross a trust boundary — threat-model these first
BoundaryCrossingTrust ChangeMust ValidateEnforcement Controls
TB1User → Input LayerInternet / untrusted → authenticated appWho is calling, how much, how bigOAuth / OpenID Connect (OIDC) login at the gateway, Web Application Firewall (WAF), per-user rate limits and token quotas, input length caps
TB2Input Layer → LLMUser data mixes with trusted system instructionsInstructions vs data separationFixed system prompt, delimiting / "spotlighting" of user content, prompt-injection classifier, Personally Identifiable Information (PII) redaction before the model
TB3LLM ↔ RAG & ToolsModel text becomes executable tool calls; retrieved text flows back inIs this call allowed for this user? Is returned content safe to read?Tool allowlist, JSON-schema validation of arguments, authorization with the end user's identity (not a shared service account), treat retrieved docs and tool output as untrusted
TB4Tools → Memory / DataShared stores across users and tenantsTenant isolation and write integrityPer-tenant namespaces in the vector database, document-level access control (ACL) filtering at query time, validation on memory writes to block memory poisoning
TB5Memory → Output LayerInternal data heads back toward a userIs the output safe to show this user?Output Data Loss Prevention (DLP), PII and secret filters, safe rendering (strip markdown image links used for exfiltration), grounding / citation checks
TB6Action Layer → External SystemsAgent acts in the real world with real credentialsDestination, scope, and approvalEgress allowlist, Server-Side Request Forgery (SSRF) protection, short-lived scoped credentials, Human-in-the-Loop (HITL) approval for destructive or financial actions
TB0Supply chain → RuntimeThird-party weights, datasets, and plugins enter productionProvenance and integrityModel scanning, SafeTensors only, Cosign signature check at load, AI Bill of Materials (AIBOM), pinned plugin / MCP server versions

AI Threat Modeling with STRIDE (STRIDE-AI)

Operational threat modeling framework adapted specifically for Generative AI, RAG, and Agentic systems

STRIDE (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege) provides the foundational risk taxonomy for assessing AI applications. By evaluating every system interface against the 6 threat classes, security teams establish verifiable controls across prompt ingestion, tool execution, and vector storage.

Applying STRIDE to AI Components

Each category with the AI-specific version of the threat, the questions to ask, and the control that works

S
Spoofing
An attacker pretends to be someone or something they are not.
What it looks like in AI
  • Prompt claims "I am the admin" and the model believes it
  • Forged agent-to-agent messages or a fake tool / Model Context Protocol (MCP) server
  • Poisoned document impersonating an authoritative source
Ask yourself:
  • Can identity be faked?
  • Can inputs be disguised?
  • Can attackers impersonate users, systems, or data sources?
What works: Identity from the auth token, never from prompt text; mutual Transport Layer Security (mTLS) and signed tool manifests; source provenance on retrieved docs
T
Tampering
An attacker modifies data or inputs to manipulate the system.
What it looks like in AI
  • Direct and indirect prompt injection
  • Training-data or RAG-corpus poisoning
  • Swapped or backdoored model weights
Ask yourself:
  • Can data be changed?
  • Can prompts or instructions be altered?
  • Can the model, tools, or outputs be manipulated?
What works: Instruction / data separation, signed models (SafeTensors + Cosign), hashed and access-controlled corpora, write validation on memory
R
Repudiation
Someone denies an action because there is no reliable trace.
What it looks like in AI
  • Agent takes an action and nobody can prove who asked for it
  • No record of which model version or prompt produced an answer
  • Logs missing tool arguments and retrieved sources
Ask yourself:
  • Are actions logged?
  • Can users deny their requests?
  • Is there enough audit information?
What works: Log user identity, prompt, model version, retrieved doc IDs, tool calls and approvals to the Security Information and Event Management (SIEM) system in tamper-evident storage
I
Information Disclosure
Sensitive information reaches people who should not see it.
What it looks like in AI
  • System prompt extraction
  • Cross-tenant leakage through shared vector stores or memory
  • Training-data memorization and markdown-image exfiltration
Ask yourself:
  • Can confidential data leak?
  • Can prompts, system info, or retrieved data be exposed?
  • Are outputs safe to share?
What works: No secrets in prompts, document-level ACL filtering before retrieval, output DLP, block external image and link rendering
D
Denial of Service
An attacker makes the system unavailable or burns its resources.
What it looks like in AI
  • Huge or recursive prompts that max out context and cost ("denial of wallet")
  • Agent loops calling tools forever
  • Flooding expensive embedding or GPU endpoints
Ask yourself:
  • Can the system be overloaded?
  • Can expensive prompts or loops drain resources?
  • Are rate limits and quotas in place?
What works: Per-user token quotas, max input and output tokens, step and time limits on agent loops, budget alerts
E
Elevation of Privilege
An attacker gains more access than they should have.
What it looks like in AI
  • Injected instructions make the agent call admin tools
  • Tool runs with a broad service account instead of the user's rights
  • Jailbreak bypasses role or policy restrictions
Ask yourself:
  • Can a user access tools or data they should not?
  • Can the model be tricked into privileged actions?
  • Are permissions enforced outside the model?
What works: Enforce authorization in code at the tool layer, least-privilege scoped tokens per user, HITL on destructive actions
What STRIDE misses. Model extraction (stealing a model through its API), training-data poisoning that changes behavior over time, and hallucinated facts are hard to fit into traditional STRIDE categories. Supplement STRIDE with MITRE ATLAS and the OWASP Top 10 for LLM Applications after the STRIDE pass.

STRIDE × Trust Boundary Heat Map

Severity of each STRIDE threat at each boundary: red = high risk, yellow = medium, gray = lower

Trust BoundarySTRIDETop Risk to Address
TB1 User → InputHMMLHLAccount takeover, prompt flooding
TB2 Input → LLMMHLMMMDirect prompt injection
TB3 LLM ↔ ToolsMHHMMHIndirect injection → privileged tool call
TB4 Tools → MemoryLHMHLMCross-tenant leak, memory poisoning
TB5 Memory → OutputLMLHLLPII / secret leakage in responses
TB6 Action → ExternalMMHHMHUnauthorized email, payment, or data export

How to Build an AI Threat Model

A repeatable 5-step method for any AI feature, product, or agent

1Map the System

Draw the data flow diagram (DFD): users, input layer, model, retrieval, tools, memory, outputs, and every external system. Include return paths (retrieved docs and tool results flowing back to the model) and build-time flows (model weights, datasets, plugins).

DFDAsset listReturn paths
2Identify Trust Boundaries

Mark every point where data enters, changes trust level, or leaves the system. Label each boundary (TB0-TB6) and write down what must be checked when data crosses it.

Boundary registerEnforcement contract
3Apply STRIDE

Walk each component and each boundary through all six STRIDE categories using the "ask yourself" questions. Add AI-specific threats from MITRE ATLAS (Adversarial Threat Landscape for AI Systems) and the OWASP Top 10 for Large Language Model (LLM) Applications.

STRIDE per elementATLASOWASP LLM Top 10
4Analyze & Prioritize

Score each threat for impact and likelihood. DREAD (Damage, Reproducibility, Exploitability, Affected users, Discoverability) rates each factor 1-10 and averages them: 8+ is critical, 5-7 high, below 5 medium or low.

DREADRisk ranking
5Mitigate & Monitor

Assign a control and an owner to each high threat, add detections for what you cannot prevent, and re-run the model when you add a tool, data source, or model version.

Control ownerDetectionsRe-review triggers

DREAD for AI (DREAD AI): Quantitative Risk Scoring Framework

AI Risk Quantification

Adapting Damage, Reproducibility, Exploitability, Affected Users, and Discoverability for Non-Deterministic & Autonomous LLM Workloads

Traditional Common Vulnerability Scoring System (CVSS) often struggles with Artificial Intelligence (AI) and Large Language Model (LLM) architectures because attacks rely on semantic manipulation, non-deterministic model states, and tool-use privilege escalation rather than binary memory overflows. DREAD for AI (DREAD AI) scores each threat on a calibrated 1–10 scale across 5 dimensions, providing an empirical average to prioritize remediation backlogs.

🧮
DREAD AI Formula: (D + R + E + A + D) / 5
Averages 5 dimensions (each scored 1 to 10) to produce a normalized 1.0–10.0 risk score
Critical: 8.0–10.0High: 6.5–7.9Medium: 4.5–6.4Low: < 4.5
DDamage Potential
Loss of confidentiality, data integrity, or financial theft via autonomous agent tools. Damage surges when the model possesses Model Context Protocol (MCP) or database write permissions.
Real-world calibration: Score 9–10: Indirect prompt injection coerces an agent into executing an unauthenticated wire transfer or SQL drop table.
RReproducibility
Accounts for model non-determinism. While traditional SQL injection is 100% deterministic, LLM responses fluctuate with temperature, sampling (top-p), and safety alignment filters.
Real-world calibration: Score 8: Prompt injection succeeded 85%+ across multiple test temperatures and prompt variations.
EExploitability
Barrier to entry and compute required. Plain natural-language prompt injection requires zero programming skills, whereas gradient-based adversarial perturbations (PGD/FGSM) require ML expertise.
Real-world calibration: Score 9: Attack requires only plain natural language typed into a web support form.
AAffected Users
Blast radius across the enterprise architecture. Ephemeral chat session attacks affect only 1 user, but vector database poisoning or corrupted foundation model weights compromise all enterprise tenants.
Real-world calibration: Score 8: All enterprise customers querying the poisoned support vector index receive tampered instructions.
DDiscoverability
How easily an attacker uncovers the vulnerability. Standard open-source prompts (LangChain / LlamaIndex defaults), publicly exposed OpenAPI specs, or verbose error banners score highest.
Real-world calibration: Score 8: The chatbot reveals its retrieved document sources and internal tool schemas on simple user inquiry.
Worked DREAD AI Score Calculations for the Threat Register Below
Threat ID & NameD (Damage)R (Reprod.)E (Exploit.)A (Users)D (Discov.)Final DREAD ScoreSeverity & SLA
T-01: Indirect Prompt Injection (Refund Exploit)989888.4Critical (Immediate Gate)
T-02: Cross-Tenant Vector Leakage996888.0Critical (Immediate Gate)
T-04: Memory PII Echo878877.6High (< 30 Days)
T-03: System Prompt Extraction578476.2Medium (< 90 Days)

Worked Example: Threat Register for a RAG Support Agent

What the output of an AI threat modeling session looks like

IDBoundarySTRIDEThreatDREADMitigationOwner
T-01TB3T / EHidden instructions in a retrieved support article tell the agent to issue a refund8.4Retrieved content tagged as data, refund tool requires user-scoped token + HITL above $50ML Platform
T-02TB4ICustomer A sees Customer B's tickets via a shared vector index8.0Per-tenant namespace + ACL filter applied before similarity searchData Eng
T-03TB2IUser extracts the system prompt and internal API names6.2No secrets in prompt, canary token in prompt with SIEM alert on leakAI AppSec
T-04TB5IModel echoes a credit card number from an old ticket7.6PII redaction at ingest + output DLP on responsesData Eng
T-05TB6R / EAgent emails ticket exports to an external address with no audit trail7.8Recipient domain allowlist, signed action log with user ID and prompt hashAI AppSec
T-06TB1DScripted 100k-token prompts run up inference cost6.0Per-user token quota, input cap, budget alert at 80%ML Platform
T-07TB0TFine-tuned model replaced with a backdoored copy in the registry7.0Cosign signature verified at load, admission control blocks unsigned modelsMLOps

Interview Preparation: AI Threat Modeling

Questions on trust boundaries, STRIDE for AI, and prioritization

💡 Interview Question

How do you threat-model an AI system?

I use five steps. First I map the system as a data flow diagram: users, the prompt and input layer, the large language model (LLM), retrieval and tools, memory, the output and action layer, and external systems. I include the return paths, because retrieved documents and tool results flow back into the model. Second I mark trust boundaries wherever identity, privilege, data sensitivity, ownership, execution context, or tenant changes, and give each one an ID. Third I apply STRIDE (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege) to every component and boundary, then add AI-specific threats from MITRE ATLAS (Adversarial Threat Landscape for AI Systems) and the OWASP Top 10 for LLM Applications. Fourth I score threats with DREAD (Damage, Reproducibility, Exploitability, Affected users, Discoverability) and rank them. Fifth I assign a control and an owner to each high threat, add detections, and re-run the model whenever we add a tool, data source, or model version.

💡 Interview Question

Give an example of each STRIDE category in an AI system.

Spoofing: a prompt injection says 'I am the admin' or a fake tool server impersonates an approved Model Context Protocol (MCP) server. Tampering: indirect prompt injection inside a retrieved document alters what the LLM instructs an agent to do. Repudiation: an agent takes an action like issuing a refund or deleting a file, but the logs only record the final HTTP call with no record of which prompt, model version, or user identity triggered it. Information Disclosure: a user extracts the system prompt and internal API keys via prompt injection, or a shared vector index leaks Customer A's data to Customer B. Denial of Service: scripted 100k-token prompts burn inference budget ('denial of wallet'), or an agent loop gets stuck calling tools recursively. Elevation of Privilege: an unprivileged user's prompt tricks the model into calling an admin-only tool like a refund API or database write.

💡 Interview Question

How do you adapt the traditional DREAD methodology specifically to AI systems (DREAD AI)?

Traditional DREAD scores Damage, Reproducibility, Exploitability, Affected users, and Discoverability from 1 to 10. For AI, we calibrate each dimension to handle machine learning realities:

1DAMAGE

We score based on autonomous tool execution (e.g. issuing unauthorized refunds, dropping tables via MCP) and proprietary IP exfiltration.

2REPRODUCIBILITY
  • Because generative models are non-deterministic, we account for stochasticity
  • A prompt jailbreak that requires 20 tries at high temperature scores lower (4-5), whereas a deterministic prefix attack or universal adversarial suffix (Greedy Coordinate Gradient / GCG) that reliably executes across temperatures scores an 8-9
3EXPLOITABILITY

Plain English natural language prompt injection scores high (9-10) because any user can type it without coding skills, while gradient-based evasion (PGD/FGSM) requiring white-box tensor access scores low (2-3).

4AFFECTED USERS

Ephemeral in-session injection scores low (1-2), but poisoning a shared vector database (RAG) or backdooring a base model registry scores an 8-10 because it poisons the experience for all tenants.

5DISCOVERABILITY
  • Default LangChain/LlamaIndex prompt templates or exposed OpenAPI specifications score high (8-9)
  • We average the 5 dimensions; anything scoring 8.0 or above is a critical production blocker