These five terms describe different layers of the same system, not five separate technologies. A useful mental model: pipeline design is the architecture blueprint, orchestration is the engine that runs each step, RAG is one pattern that engine uses to ground answers in real data, MCP is the standard way that engine connects to outside tools and data sources, and agentic workflows describe what happens when the engine itself starts making decisions instead of following a fixed path.
Concept
What it answers
AI Pipeline Design
What are the stages, data flows, and failure points of the whole system?
LLM Orchestration
How do we sequence/coordinate multiple LLM calls, tools, and steps reliably?
RAG
How do we ground LLM answers in real, current, private data instead of relying on parametric memory?
MCP
How does a model connect to external tools and data sources in a standardized way?
Agentic Workflows
When should the model itself decide what happens next, instead of a fixed sequence?
RAG
grounding pattern, not a framework
MCP
open protocol for tool/data connections
Orchestration
the control layer coordinating steps
Agentic
dynamic, model-driven control flow
Retrieval-Augmented Generation (RAG)
RAG grounds an LLM's response in retrieved external data rather than relying solely on what the model memorized during training. At query time: embed the query, retrieve the most relevant chunks from a vector store (or hybrid search), insert them into the prompt as context, then generate an answer constrained to that context.
User query
→
Embed query
→
Retrieve top-K chunks
→
Build prompt + context
→
LLM generates
→
Answer (+ citations)
What you can actually build
A support assistant that answers from your actual product docs and ticket history instead of generic training knowledge
Compliance-aware Q&A that cites the specific policy section an answer came from
Systems that stay current without retraining the model — update the index, not the weights
Advantages
Reduces hallucination by grounding answers in retrieved evidence
Updates instantly by re-indexing data — no fine-tuning or retraining needed
Supports citation/attribution back to source documents
Keeps proprietary data out of model weights — relevant for HIPAA/PII contexts
Disadvantages
Retrieval quality is a hard ceiling — bad retrieval guarantees a bad answer regardless of model quality
Chunking strategy is non-trivial; poor chunking splits relevant context across boundaries
Adds latency (embedding + search) compared to a direct LLM call
Still doesn't eliminate hallucination entirely — the model can ignore or misread retrieved context
Beyond naive RAG
Hybrid search — combine dense vector search with sparse keyword (BM25) matching for exact-term accuracy (SKUs, codes, names)
Re-ranking — retrieve a larger candidate set, then use a cross-encoder to re-rank for precision before passing to the LLM
Query rewriting / decomposition — break a complex question into sub-queries before retrieving
Self-correcting RAG — grade retrieved docs for relevance and re-retrieve if they fail the check, instead of generating from weak context
Model Context Protocol (MCP)
MCP is an open protocol (introduced by Anthropic) standardizing how LLM applications connect to external tools, data sources, and systems. Instead of every application writing custom, one-off integration code for each tool, MCP defines a common interface: servers expose tools/resources, and any MCP-compatible client (Claude, an IDE, a custom agent) can discover and call them the same way.
What you can actually build
An MCP server that exposes your internal systems (a database, a ticketing system, an EDI processing pipeline) as standardized tools any compatible LLM client can call
A single agent that connects to many MCP servers (Slack, GitHub, a CRM) without bespoke integration code per service
Reusable tool servers shared across multiple applications, instead of re-implementing the same API wrapper repeatedly
// minimal MCP server tool definition (conceptual)
server.tool("lookup_claim_status", {
description: "Look up the status of an insurance claim by ID",
inputSchema: { claimId: "string" },
handler: async ({ claimId }) => {
const result = await db.query(
"SELECT status FROM claims WHERE id = $1", [claimId]
);
return result.rows[0];
}
});
Advantages
Standardizes tool/data integration — write once, usable by any MCP-compatible client
Decouples tool implementation from the orchestration layer calling it
Growing ecosystem means more pre-built connectors instead of custom integration work
Clear separation of concerns: the server owns the business logic, the client owns the reasoning
Disadvantages
Still an emerging standard — tooling, security patterns, and best practices are actively evolving
Adds an architectural layer/process to run and maintain (the MCP server itself)
Security surface: a tool server with broad permissions is a real risk if the model is tricked into misusing it (prompt injection via tool results)
Not every integration needs the overhead of a full protocol — simple one-off API calls may not justify it
MCP is moving quickly; verify current spec details, security guidance, and ecosystem maturity against docs.claude.com before treating specifics as settled.
LLM Orchestration
Orchestration is the control layer that coordinates everything else: sequencing LLM calls, routing between models, managing memory/state across turns, calling tools, handling retries and fallbacks, and deciding what happens next. LangChain/LangGraph from the prior guide are orchestration frameworks; this section is the underlying concept independent of any specific tool.
What you can actually build
Multi-step pipelines: classify intent → route to the right handler → retrieve if needed → generate → validate output
Model routing: cheap/fast model for simple queries, escalate to a stronger model only when needed
Fallback and retry logic when a model call fails, times out, or returns malformed output
Memory management across a multi-turn conversation, deciding what context to keep, summarize, or drop
Common orchestration patterns
Pattern
When to use it
Sequential chain
Fixed, predictable steps with no branching needed
Router
Different query types need different handling (e.g. FAQ vs. complex support case)
Parallel fan-out / fan-in
Multiple independent retrievals or sub-tasks that can run concurrently, then merge
Evaluator-optimizer loop
Generate, grade the output, regenerate if it fails quality checks
Orchestrator-worker
One model plans/delegates, specialized sub-agents execute each piece
Advantages
Makes complex multi-step behavior reliable and observable instead of one giant unmanaged prompt
Enables cost control through model routing (cheap model first, escalate selectively)
Centralizes error handling, retries, and logging in one layer
Disadvantages
Added architectural complexity — more moving parts, more failure points to monitor
Over-orchestrating a simple task adds latency and cost without benefit
State management across steps is genuinely hard to get right and test
Agentic Workflows
An agentic workflow is one where the model itself decides the next action — which tool to call, whether to retrieve more information, when the task is complete — rather than following a developer-defined fixed sequence. This sits at the dynamic end of a spectrum that starts with a single LLM call and ends with a fully autonomous multi-step agent.
Single call
→
Fixed chain
→
Router
→
Tool-using agent
→
Multi-agent system
What you can actually build
A research agent that decides which sources to search, how many times to search, and when it has enough information to answer
A coding agent that writes code, runs tests, reads the failure, and iterates without a human specifying each step
A claims-processing agent that gathers data from multiple systems, checks rules, and only escalates to a human when confidence is low
Advantages
Handles open-ended tasks that can't be fully specified as a fixed sequence in advance
Adapts to unexpected situations mid-task (a failed tool call, an ambiguous result) without a human rewriting the pipeline
Can reduce the number of distinct fixed pipelines you need to maintain for varied task types
Disadvantages
Unpredictable cost and latency — the model may take more steps, more tool calls, than expected
Harder to test exhaustively; agent paths are not enumerable the way a fixed chain's paths are
Higher risk surface — an agent with real tool access can take unintended or harmful actions if it misreads a situation
Requires explicit guardrails: max iteration limits, human-in-the-loop checkpoints for high-stakes actions, scoped tool permissions
Production guardrails for agents
Hard iteration/step limits to prevent runaway loops
Scoped, least-privilege tool permissions — an agent shouldn't have write access it doesn't need
Human-in-the-loop approval gates before irreversible or high-stakes actions
Full logging of every tool call and decision for auditability
AI Pipeline Design
Pipeline design is the architecture-level discipline of deciding how data moves through an AI system end to end: ingestion, processing, storage, retrieval, generation, validation, and monitoring — and where each failure mode is caught. This is the layer where EDI/ETL background transfers most directly.
Model version mismatch between index and query time
Indexing/storage
Store vectors + metadata (pgvector/Pinecone)
Stale index after source data updates
Retrieval
Fetch relevant chunks for a query
Low recall, irrelevant matches, missing filters
Orchestration
Coordinate steps, tools, routing
Unhandled errors, runaway agent loops
Generation
LLM produces the answer
Hallucination, ignoring provided context
Validation
Check output before returning to user
No validation at all — output ships unchecked
Monitoring
Track quality, cost, latency over time
Silent quality drift with no alerting
Why this discipline matters
Most production AI failures are pipeline/data problems, not model problems
Treating each stage as testable and observable (an ETL mindset) catches issues before they reach users
Clear stage boundaries make it possible to swap components (e.g. pgvector → Pinecone) without rebuilding the whole system
Common design mistakes
No evaluation set — shipping changes with no way to measure if quality improved or regressed
Treating the LLM call as the whole system instead of one stage among many
No monitoring for data staleness, embedding drift, or cost spikes
Over-engineering with agents/orchestration where a simple fixed pipeline would do
Chunking Strategies
Chunking is how you split source documents into retrievable units before embedding. It is the single highest-leverage decision in most RAG systems — the right chunk size and strategy can double retrieval quality; the wrong one silently cripples it. Most RAG failures trace back here, not to the model or the prompt.
Chunking strategies compared
Strategy
How it works
Best for
Risk
Fixed-size (characters)
Split every N characters with M overlap
Simple documents, quick prototyping
Cuts mid-sentence, destroys semantic units
Recursive text splitter
Split on paragraph → sentence → word boundaries in order
General prose — the LangChain default
Still ignores document structure
Sentence-window
Index individual sentences; retrieve surrounding window for context
Dense factual documents where precision matters
Window may still miss cross-paragraph context
Semantic chunking
Embed sentences; split when cosine similarity drops below threshold
Documents with clear topic shifts
Slow at ingestion; inconsistent chunk sizes
Document-structure aware
Split on headings, sections, HTML/Markdown elements
Structured docs: policies, manuals, API docs
Requires clean, consistently structured source
Hierarchical / parent-child
Index small child chunks; retrieve parent for LLM context
Best of precision + context — production standard
More complex indexing pipeline
The parent-child (hierarchical) pattern
Index small chunks (128–256 tokens) for high-precision retrieval. When a small chunk matches, return its parent chunk (512–1024 tokens) to the LLM for richer context. This separates the precision of retrieval from the context richness of generation.
from llama_index.core.node_parser import HierarchicalNodeParser
from llama_index.core.retrievers import AutoMergingRetriever
# Build hierarchy: 2048 → 512 → 128 token chunks
parser = HierarchicalNodeParser.from_defaults(
chunk_sizes=[2048, 512, 128]
)
nodes = parser.get_nodes_from_documents(documents)
# Retriever: match on small chunks, return parent for context
base_retriever = index.as_retriever(similarity_top_k=12)
retriever = AutoMergingRetriever(base_retriever, storage_context)
Chunk size guidelines
128–256
tokens — high precision retrieval chunk
512–1024
tokens — context window chunk for LLM
10–20%
overlap recommended between adjacent chunks
~1/4
of context window — max chunk to LLM ratio
What Makes a Good Chunk
Contains one complete semantic unit — a concept, a procedure, a policy rule
Does not cut across a sentence or paragraph boundary
Has enough context that it is interpretable without surrounding chunks
Includes structural metadata: document title, section heading, page number
Chunking Failure Modes
Splitting a table across chunk boundaries — the model gets half a table with no headers
Chunks too small — each chunk lacks enough context to be useful even if retrieved
Chunks too large — retrieval precision drops; relevant sentence buried in noise
No overlap — the answer sits exactly at a chunk boundary and gets split
Multi-Agent Systems
A multi-agent system uses multiple LLM-powered agents working together — one orchestrating, others specialising — to complete tasks too complex or broad for a single agent. Each sub-agent has a focused role, its own tools, and communicates results back to the orchestrator. The architecture trades simplicity for capability.
Core multi-agent patterns
Pattern
Structure
Best for
Orchestrator-Worker
One planning agent delegates tasks to specialised worker agents
Complex workflows with distinct sub-tasks (research, write, review)
Supervisor
A supervisor agent routes each query to the most appropriate sub-agent
Customer support with different agents per topic domain
Sequential Pipeline
Agents pass output to the next agent in a chain
Document processing: extract → analyse → summarise → format
Parallel Fan-out
Multiple agents run simultaneously on sub-tasks; results merged
Research: different agents search different sources concurrently
Debate / Reflection
Multiple agents critique each other's outputs before finalising
High-stakes content requiring self-correction and accuracy
Supervisor agent in LangGraph
from langgraph.graph import StateGraph, END
from typing import Literal
AGENTS = ["claims_agent", "policy_agent", "billing_agent"]
def supervisor(state):
"""Route to the right specialist agent based on query."""
prompt = f"Route this query to one of {AGENTS}: {state['query']}"
route = llm.invoke(prompt).content.strip()
return {"next_agent": route}
def should_continue(state) -> Literal["claims_agent","policy_agent","billing_agent","END"]:
return state.get("next_agent", "END")
graph = StateGraph(dict)
graph.add_node("supervisor", supervisor)
graph.add_node("claims_agent", claims_agent_fn)
graph.add_node("policy_agent", policy_agent_fn)
graph.add_node("billing_agent", billing_agent_fn)
graph.add_conditional_edges("supervisor", should_continue)
[graph.add_edge(a, "supervisor") for a in AGENTS] # loop back
graph.set_entry_point("supervisor")
app = graph.compile()
Communication patterns between agents
Shared state (LangGraph)
All agents read and write to a common typed state object. Simple, consistent, easy to debug — the LangGraph default.
Entire conversation history visible to all agents
State changes are auditable in the graph trace
Risk: large state objects bloat the context window
Message passing
Agents communicate via structured messages. Keeps each agent's context lean — only sees messages relevant to it.
Scales better to many agents
Explicit contracts between agents
Risk: more complex routing and serialisation logic
Production guardrails for multi-agent systems
Hard step limits per agent — each agent should have a max iteration budget; the orchestrator should timeout an agent that exceeds it
Least-privilege tools — the billing agent should not have write access to patient records; scope tools to each agent's role
Human-in-the-loop gates — for irreversible or high-value actions, pause and require human approval before the agent proceeds
Full trace logging — every agent decision, tool call, and message must be logged with agent identity and timestamp for auditability
Failure propagation handling — define what happens when a worker agent fails: retry, fallback, escalate to human, or graceful degradation
AI System Deployment Patterns
Deploying an AI system is not the same as deploying a standard API. The system has non-deterministic outputs, external model dependencies, retrieval pipelines that can go stale, and quality metrics that degrade silently over time. Each of these requires specific production patterns beyond what a standard deployment checklist covers.
Deployment architecture options
Architecture
Description
Best for
Synchronous API
Request → process → respond in one call. Standard REST or gRPC endpoint.
Simple Q&A, classification, extraction with <10s latency budget
Streaming API
Token-by-token streaming response using SSE or WebSocket
Chat interfaces where perceived latency matters more than completion time
Async / Queue-based
Job submitted to queue; result polled or pushed via webhook
Long-running agents, document processing pipelines, batch jobs
Batch processing
Bulk inputs processed off-peak; results stored for retrieval
Nightly document ingestion, re-indexing, bulk embedding jobs
CI/CD for AI systems
# Example GitHub Actions gate for a RAG pipeline change
# Runs on every PR that touches prompts, retrieval, or chain logic
name: RAG Quality Gate
on: [pull_request]
jobs:
eval:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run retrieval eval
run: python eval/run_ragas.py --min-faithfulness 0.80
--min-context-recall 0.75
- name: Run DeepEval suite
run: deepeval test run tests/test_chain.py
- name: Check for prompt regressions
run: promptfoo eval --config promptfoo.yaml --ci
Canary and shadow deployment
Canary rollout
Route a small percentage (5–10%) of production traffic to the new model or prompt version. Compare quality metrics between canary and baseline before full rollout.
Catches regressions on real traffic before full exposure
Requires metric collection and comparison infrastructure
A/B test framework or feature flag system needed
Shadow index for RAG
When upgrading an embedding model or re-chunking, build the new index in parallel. Run evaluation against the shadow index. Swap only after quality is confirmed.
Zero-downtime index upgrades
Evaluation-gated cutover — no guessing
Requires 2x storage during transition window
Production monitoring checklist
What to monitor
Metric
Alert threshold
Answer quality
Sampled faithfulness + relevancy (Ragas)
Drop >5% from baseline
Retrieval quality
Context recall@5 on eval set
Drop below 0.75
Latency p95
End-to-end response time
Exceeds SLA (e.g. >5s)
Token cost
Input + output tokens per request
Spike >20% week-over-week
Error rate
Rate of failed or timed-out requests
>1% of requests
Embedding drift
Query distribution vs index distribution (Evidently AI)
Significant distribution shift detected
The most common production mistake: treating AI system deployment as identical to a standard API deployment. The difference is that quality degrades gradually and silently — you need continuous quality monitoring, not just uptime monitoring.
Production-Level Interview Q&A
Click a question to expand the answer.
How do RAG, MCP, and agentic workflows relate to each other in one system?
RAG is a grounding pattern — it answers 'how does the model get accurate, current data.' MCP is a connection standard — it answers 'how does the model reach that data and other tools in a uniform way.' Agentic workflow is a control-flow style — it answers 'who decides what happens next.' A system can use RAG without being agentic (a fixed retrieve-then-generate chain), and can be agentic without RAG (a pure tool-calling agent with no document retrieval). They're independent dimensions that often combine: an agent that dynamically decides when to retrieve, using MCP-exposed tools to do so.
When would a fixed pipeline be the better choice over an agentic workflow, even though agents are more flexible?
When the task is well-defined, predictable, and doesn't benefit from dynamic decision-making — most production RAG Q&A, classification, and extraction tasks fall here. A fixed pipeline is cheaper, faster, fully testable (every path is enumerable), and has a much smaller risk surface than an agent with tool access. The decision should be driven by whether the task genuinely requires the model to decide its own next steps, not by which approach is more interesting to build.
Walk through how you'd debug a RAG system that's hallucinating despite having relevant documents in the index.
First isolate which stage is at fault: confirm the retrieval step is actually surfacing the relevant chunks for that query (log and inspect retrieved context directly, don't assume). If retrieval is correct but the answer still hallucinates, the issue is in generation — check whether the prompt clearly instructs the model to answer only from provided context, whether the context window is being truncated, or whether the chunk is too fragmented to be useful even though it's topically relevant. This mirrors root-cause isolation in ETL debugging: check each transform stage independently rather than assuming the failure is where the symptom appears.
What guardrails would you put on an agentic workflow before letting it run against production systems?
Hard limits on iteration count to prevent runaway loops, least-privilege scoped tool permissions so the agent can't take actions beyond what the task requires, human-in-the-loop approval gates before irreversible or high-stakes actions (sending external communications, executing financial transactions, modifying records), full audit logging of every tool call and decision, and cost/latency monitoring with alerting since agent runs have unpredictable resource use compared to fixed pipelines.
How does MCP change the integration story compared to writing custom API wrappers for each tool?
Without MCP, each new tool or data source typically means custom integration code specific to that LLM framework and that tool's API. MCP standardizes the interface: a tool exposed once as an MCP server can be used by any MCP-compatible client without rewriting integration logic per consumer. This reduces duplicated integration work across applications, though it does add the overhead of running and securing the MCP server itself, and the ecosystem is still maturing — worth verifying current adoption and tooling against docs.claude.com rather than treating it as fully settled.
How would you design an evaluation strategy for a multi-stage AI pipeline, not just the final output?
Evaluate each stage independently rather than only judging the final answer: retrieval quality via precision@K/recall@K against a labeled set, generation quality via answer relevance and faithfulness to retrieved context (tools like Ragas or DeepEval), and orchestration/agent behavior via scenario tests checking the right path was taken and termination conditions fired correctly. Stage-level evaluation lets you pinpoint exactly where a regression originated instead of only knowing the final output got worse — the same logic as validating each transform in an ETL pipeline rather than only checking the final load.
What's the difference between orchestration and agentic behavior, and why do interviewers conflate them?
Orchestration is the coordination layer itself — it can run a purely fixed sequence with zero dynamic decision-making. Agentic behavior is a property of how that orchestration layer is used — letting the model decide the next step rather than hardcoding it. They get conflated because the same frameworks (LangGraph, for instance) are used for both fixed and agentic flows; the distinguishing factor is whether control-flow decisions are hardcoded by the developer or made dynamically by the model at runtime.
How would you control cost and latency in a system that combines RAG with an agentic loop?
Cap retrieval and tool-call iterations explicitly rather than letting the agent loop indefinitely; use a cheaper/faster model for intermediate reasoning steps and reserve the strongest model for final generation; cache embeddings and frequent queries; and add a router that short-circuits to a fixed, cheap path for simple queries instead of always invoking the full agentic loop. Monitoring actual cost and latency per request in production, not just at design time, is necessary because agent behavior is inherently variable run to run.
From a pipeline-design view, what's the single highest-leverage thing to get right early in a RAG project?
Chunking and data quality at ingestion — far more production RAG failures trace back to bad chunking, stale data, or poor source document structure than to model choice or prompt engineering. Getting the ingestion and chunking strategy right (and building an evaluation set early to measure retrieval quality objectively) pays off more than tuning the generation prompt, which is usually where teams over-invest first.