Enterprise RAG Architecture
Lesson opener
In one line: Enterprise retrieval-augmented generation is a governed data pipeline first and a language-model feature second: the right documents, in the right version, visible to the right person, assembled with citations, and a refusal when the evidence is not there.
Why it matters: Basic RAG works on a tidy folder with one user. A company has duplicate and superseded documents, conflicting procedures, restricted content, scanned PDFs, tables and constant change. Most "the AI got it wrong" incidents trace back to ingestion, metadata, permissions or authority, not to the model.
Before this lesson: Prompt & Configuration Release Management. Basic RAG is assumed from RAG basics and Retrieval-Augmented Generation for agents; this lesson does not repeat them.
Northline Consumer Goods (illustrative) wants one assistant for ERP questions. Its knowledge is spread across three kinds of material: finance and procurement policies (what is allowed), ERP procedures (how to do it in the system) and vendor manuals (what the screens mean). A buyer asks how to release a blocked purchase order above a threshold. The first prototype quoted the manual's screen steps, ignored the policy's approval requirement, and in another test cited a policy version that was superseded last year. A separate test revealed the existence of an executive compensation document to an ordinary user. The team needs an architecture and a source-governance matrix.
What you will be able to do
- Describe the stages of an enterprise RAG pipeline from ingestion to cited answer.
- Choose chunking and metadata that preserve structure, version, ownership and permissions.
- Explain hybrid (keyword plus vector) retrieval, rank fusion and reranking, and when each helps.
- Assemble context within a token budget with labelled sources and required citations.
- Resolve conflicts with an authority and freshness model.
- Enforce access-aware retrieval so restricted content never reaches the prompt.
- Design the "no supported answer" path.
Deliverable: a RAG design (pipeline diagram in text and decisions per stage) plus a source-governance matrix listing every source with owner, authority level, refresh rule, access rule and exclusion criteria.
Prerequisites
| Prerequisite | Why it matters |
|---|---|
| RAG basics | Chunk, embed, retrieve and prompt in a simple setting. |
| Embeddings & Search | What an embedding is and how similarity search works. |
| Retrieval-Augmented Generation (agent course) | RAG as a tool inside an agent. |
| From Prototype to Production | Readiness criteria, permissions and stop conditions. |
| ERP concepts | Context for purchase orders, approvals and master data. |
| Security, Guardrails & Governance | Access control and data leakage risks. |
| Copilot Governance & Security | Related permission models in enterprise tools. |
Plain English
An enterprise RAG system has two paths. The offline (ingestion) path prepares knowledge; the online (query) path answers questions.
Ingestion path
- Acquire only from approved sources through connectors with their own read identities. Record owner, version and status.
- Parse each format: text PDFs, scanned PDFs (OCR is error-prone; validate), Word, HTML, spreadsheets and tables. Tables need care: keep header rows with the cells, or the numbers lose meaning.
- Clean repeating headers, footers and navigation text that would pollute retrieval.
- Chunk by structure (headings, numbered clauses, procedure steps) rather than by arbitrary character counts alone. Keep a short prefix on each chunk (document title, section heading) so it stands alone. Overlap adjacent chunks modestly if a rule can span a boundary. Chunk size is a tunable decision that you validate with evaluation (next lesson), not a constant to copy.
- Attach metadata to every chunk:
doc_id, version, status (draft, approved, superseded), document type, authority level, effective and review dates, owner, language, source link, page or section, and the access-control list (groups or roles allowed to read). - Embed chunks with an embedding model. Record the model identifier; query and documents must use the same one, and changing it means re-embedding everything.
- Index the vectors and also a keyword (lexical) index, with metadata fields filterable.
Query path
- Authenticate the user and resolve groups.
- Filter to eligible content: approved status, current effective date, and the user's permissions. This happens before ranking and before anything enters a prompt.
- Retrieve by hybrid search. Keyword search is strong for exact identifiers (transaction codes, part numbers, clause numbers). Vector search is strong for paraphrase ("who must sign off" vs "approval required"). Run both and merge.
- Fuse the ranked lists. Reciprocal rank fusion (RRF) is a simple, widely used method that adds
1 / (k + rank)for each list a chunk appears in, avoiding the need to compare incompatible scores. - Rerank the top candidates with a stronger model (a cross-encoder or a model-based reranker; availability and cost are provider-dependent) so the best few chunks come first.
- Assemble context: remove near-duplicates, respect a token budget, order sensibly, and label each passage with its document id, version and date. Long contexts can reduce attention to material in the middle, so keep the context tight and put the strongest evidence where it will be noticed.
- Generate with instructions to answer only from the labelled passages, cite them, and say when evidence is insufficient.
- Validate: every citation refers to a retrieved passage; quoted figures and dates appear in that passage; no citation to a non-approved document.
- Refuse or route when the evidence is missing, conflicting without a rule, or below a relevance threshold.
Authority and freshness. Sources do not carry equal weight. A simple model: policy outranks procedure, which outranks manual; within a type, the document with the latest effective date that is not superseded wins; a draft never wins. When sources of equal authority still disagree, the system does not pick; it shows both with their references and routes to the owner.
Access-aware retrieval. Permissions are enforced at retrieval, using the same entitlements as the source system. Filtering after generation is too late (the model has already seen the text). Filter before ranking so restricted material cannot influence results, and make sure answers and error messages do not reveal that restricted documents exist. When permissions change in the source system, the index's ACLs must update on a defined schedule, and deletions must propagate.
Teacher walkthrough
Design the ERP assistant step by step.
- Business owner. The Head of Finance Operations owns the assistant's scope. Each source has its own content owner (Procurement for the purchasing policy, ERP Support for procedures, an IT vendor manager for manuals).
- Approved users. Finance, Procurement and Supply Chain staff. Contractors are excluded unless their role grants it. Identity comes from the corporate directory.
- Sources. Approved policies, ERP procedure documents and vendor manuals. Excluded: drafts, personal folders, email attachments, executive and HR restricted content, and anything without an owner.
- Permissions. Each chunk carries an ACL copied from the source system. The query path resolves the user's groups and filters before retrieval. A nightly sync updates ACLs; critical revocations trigger an immediate update.
- Ingestion validation. After each run, check counts per source, parse-failure rates, chunks with empty text, and a sample of tables for header integrity. Fail the run when thresholds are exceeded.
- Retrieval design. Use hybrid retrieval with RRF, then rerank the top 20 to a final 5 (numbers are starting points to tune by evaluation).
- Authority rules. Policy > procedure > manual; superseded and draft documents are excluded at the filter step; ties produce a "conflict" response with both references.
- Human review. Low-relevance answers and conflict cases go to the content owners' queue; owners can mark sources outdated or correct metadata.
- Escalation. Suspected leakage of restricted content is a security incident: disable the index segment and notify the security contact immediately.
- Monitoring. Track retrieval hit rate, refusal rate, citation-validation failures, thumbs-down, stale-source citations, ingestion lag and ACL-sync lag.
- Fallback. If the vector index or reranker is unavailable, fall back to keyword-only search with a notice; if the model is unavailable, show search results with links and no generated summary.
- Stop condition. Any confirmed answer containing content the user was not entitled to read, or a citation to a superseded document that goes uncaught, pauses the affected source or the whole service until fixed.
Worked example
The toy pipeline below applies the query-path ideas on a five-document corpus. It uses a deliberately simple token-based "semantic" stand-in (a synonym map and cosine similarity over word counts) so that it runs with no dependencies; a real system would use an embedding model and a vector index, as covered in the embeddings lesson. It demonstrates access filtering before ranking, status filtering, hybrid fusion, authority ordering, citations and an unsupported answer.
import math
import re
from collections import Counter
from datetime import date
DOCS = [
{"id": "POL-12-v3", "type": "policy", "status": "approved", "authority": 3, "effective": date(2026, 1, 1),
"acl": {"finance", "all_staff"},
"text": "Purchase orders above 10000 EUR require approval by the finance controller before release to the supplier."},
{"id": "POL-12-v2", "type": "policy", "status": "superseded", "authority": 3, "effective": date(2024, 1, 1),
"acl": {"finance", "all_staff"},
"text": "Purchase orders above 5000 EUR require approval by the finance controller before release to the supplier."},
{"id": "SOP-ERP-44", "type": "procedure", "status": "approved", "authority": 2, "effective": date(2025, 6, 1),
"acl": {"finance", "all_staff"},
"text": "To release a blocked purchase order in the ERP open transaction PO-RELEASE and attach the approval reference."},
{"id": "MAN-ERP-7", "type": "manual", "status": "approved", "authority": 1, "effective": date(2023, 3, 1),
"acl": {"all_staff"},
"text": "The PO-RELEASE screen shows the field Approval Reference. Blocked orders show status B."},
{"id": "EXEC-PAY-1", "type": "policy", "status": "approved", "authority": 3, "effective": date(2026, 1, 1),
"acl": {"hr_leadership"},
"text": "Executive bonus bands are reviewed annually by the remuneration committee."},
]
STOP = {"a", "an", "the", "is", "to", "of", "in", "for", "what", "how", "do", "i", "by", "and", "before", "needed"}
SYNONYMS = {"authorisation": "approval", "authorization": "approval", "approve": "approval",
"approved": "approval", "buy": "purchase", "sign": "approval"}
def tokens(text):
out = []
for raw in re.findall(r"[a-z0-9\-]+", text.lower()):
raw = SYNONYMS.get(raw, raw)
if raw in STOP:
continue
out.append(raw[:-1] if raw.endswith("s") and len(raw) > 3 else raw)
return out
def keyword_rank(query, docs):
q = set(tokens(query))
scored = [(len(q & set(tokens(d["text"]))), d["id"]) for d in docs]
return [doc_id for score, doc_id in sorted(scored, reverse=True) if score > 0]
def cosine(a, b):
dot = sum(a[t] * b[t] for t in a)
na = math.sqrt(sum(v * v for v in a.values()))
nb = math.sqrt(sum(v * v for v in b.values()))
return dot / (na * nb) if na and nb else 0.0
def vector_rank(query, docs): # stand-in for embedding similarity
qv = Counter(tokens(query))
scored = [(cosine(qv, Counter(tokens(d["text"]))), d["id"]) for d in docs]
return [doc_id for score, doc_id in sorted(scored, reverse=True) if score > 0]
def rrf(rankings, k=60):
scores = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return scores
def answer(query, user_groups, today, min_overlap=2, top_n=3):
eligible = [d for d in DOCS
if d["status"] == "approved" and d["effective"] <= today and d["acl"] & user_groups]
by_id = {d["id"]: d for d in eligible}
fused = rrf([keyword_rank(query, eligible), vector_rank(query, eligible)])
ranked = sorted(fused, key=lambda i: (fused[i], by_id[i]["authority"]), reverse=True)[:top_n]
if not ranked or len(set(tokens(query)) & set(tokens(by_id[ranked[0]]["text"]))) < min_overlap:
return {"answer": "No approved source found for this question. Routed to the owner queue.", "citations": []}
context = [f"[{i}] ({by_id[i]['type']}, effective {by_id[i]['effective']}) {by_id[i]['text']}" for i in ranked]
return {"answer": "Draft answer must use only these passages.", "citations": ranked, "context": context}
today = date(2026, 10, 1)
for q, groups in [("What approval is needed for purchase orders above 10000?", {"finance"}),
("executive bonus bands", {"all_staff"}),
("forklift battery charging", {"all_staff"})]:
r = answer(q, groups, today)
print(q, "->", r["citations"] or r["answer"])Observe the results. For the finance user the policy POL-12-v3 ranks first and the superseded POL-12-v2 never appears because it is filtered by status. For the all-staff user the executive document is not in the eligible set, so the answer is "no approved source found" without revealing it exists. The forklift question has no supporting evidence and is refused. The model is not even called in the refusal cases.
Source-governance matrix (excerpt)
| Source | Owner | Authority | Refresh rule | Access rule | Exclusion |
|---|---|---|---|---|---|
| Purchasing policy | Procurement Director | 3 (policy) | On approval of a new version; supersede old within one day | Finance, Procurement, Supply Chain | Drafts, superseded versions |
| ERP procedures | ERP Support Lead | 2 (procedure) | Monthly review; re-ingest on change | All ERP users | Unreviewed wiki pages |
| Vendor manuals | IT Vendor Manager | 1 (manual) | On vendor release, after owner check | All staff | Manuals for retired ERP versions |
| Executive compensation | HR Leadership | 3 (policy) | Annual | HR leadership only | Never indexed for general assistant |
A second workplace case
Northline's Quality team wants an assistant over supplier audit reports, which are scanned PDFs with tables of non-conformances. The ingestion team finds that OCR merged table columns, so "Severity: Major" attached to the wrong supplier. They add a parse-validation step: sample 30 tables per run against the source, store the table header row with every row-chunk, and exclude files whose parse check fails until a person fixes them. The retrieval design is the same as before; the ingestion governance is what changed. Because audit reports are confidential per supplier category, the ACLs are applied by quality-engineer group.
Failure example
Symptom: A buyer asks about approval for a high-value order. The assistant explains the screen steps from the manual and omits the finance controller's approval. A second answer quotes the old 5000 EUR threshold.
Diagnosis: All documents were chunked and embedded without metadata. The manual's chunk was the most similar to the question wording; the policy chunk ranked lower; the superseded policy was still in the index and ranked equally with the current one. No authority or status rule existed.
Correction: Add status, authority and effective-date metadata; exclude superseded and draft documents at the filter step; fuse keyword and vector results; rerank with authority as a tie-break; require a citation to a policy chunk for any answer about approvals; route to the owner on conflicts.
Validation: Run a test set of 25 approval questions. Each must cite the current policy; none may cite a superseded version; the 10 conflict-trap questions must yield a "conflict" response or the policy answer, never the manual-only answer.
Prevention: Make status filtering and authority ordering part of the retrieval contract, test them on every re-index, and require the source owner to mark supersession when a new version is published.
Guided practice
Scenario: Northline adds HR documents (leave policy, parental-leave procedures, manager guidance slides) and also a folder of unapproved draft policies. A line manager and a regular employee both use the assistant. Design the access-aware parts.
Hints:
- Which documents are visible to everyone and which only to managers?
- At which point in the pipeline must the filter run?
- How do you stop drafts being cited?
- What does the assistant say when a staff member asks about a manager-only document?
- How do ACL changes propagate?
Complete solution:
- Metadata: each chunk has
status,audience(all_staff or managers), owner and effective date. - Filter: at query time resolve the user's groups from the directory. Filter to
status=approved, effective date not in the future, andaudiencein the user's groups, before keyword and vector search and before any prompt is built. - Drafts: the draft folder is not an approved source and is excluded at connector level; a status check at query time is a second layer.
- Manager-only questions from employees: the system answers "No approved source found for this question," identical to a truly unknown topic, so the existence of manager guidance is not revealed. The question is logged for review.
- Citations: each cited chunk must be in the retrieved eligible set; the validator rejects any other citation.
- ACL propagation: nightly sync from the HR system, immediate invalidation when a user's group membership is removed, and deletion propagation within a defined limit (for example 24 hours).
- Monitoring and stop condition: log filter decisions (not the restricted text); a confirmed exposure of manager-only content pauses that source.
Independent practice
Design a RAG architecture and a source-governance matrix for an assistant over three source types in a domain you know (for example warehouse procedures, safety policies and equipment manuals).
Acceptance criteria
- Lists ingestion stages with the validation check for each.
- Specifies chunking approach and the metadata fields, including access-control information.
- Describes hybrid retrieval, fusion, reranking and context assembly with a token budget.
- Defines authority and freshness rules, including how superseded or conflicting documents are treated.
- Shows that access filtering happens before ranking and that restricted existence is not revealed.
- Defines the unsupported-answer path and the owner queue.
- Includes a matrix with owner, authority, refresh rule, access rule and exclusion for every source.
- Includes monitoring signals, a fallback behaviour and a stop condition.
- Marks reranker and vector-store features as provider-dependent.
Common mistakes
- Chunking by fixed character count with no regard to headings, clauses or table headers.
- Embedding everything with no metadata, then trying to fix relevance with a bigger model.
- Filtering by permission after generation instead of before retrieval.
- Leaving superseded or draft documents in the index.
- Using vector search only, so exact codes such as transaction names and part numbers are missed.
- Using keyword search only, so paraphrased questions fail.
- Changing the embedding model for new documents but not re-embedding old ones.
- Treating all sources as equally authoritative, so a vendor manual overrides a policy.
- Forcing an answer when evidence is thin instead of refusing and routing.
- Revealing that a restricted document exists in an error or refusal message.
- Forgetting that ACL and deletion changes in the source system must reach the index.
Quick check
- Why must access filtering happen before ranking and prompt assembly?
- When does keyword search beat vector search, and when does the reverse apply?
- What does reciprocal rank fusion do and why is it useful?
- How should the system treat two approved sources that disagree with the same authority and date?
- What should the assistant say when a user asks about content they are not entitled to read?
Answers:
- Once restricted text enters a prompt the model may reveal or be influenced by it; filtering first guarantees it never reaches the model or the ranking.
- Keyword search is better for exact identifiers like transaction codes and clause numbers; vector search is better for paraphrases and conceptual matches. Hybrid combines both.
- It merges ranked lists by summing
1 / (k + rank)for each list a document appears in, so lists with incompatible scores can be combined without calibration. - It should not choose silently; it shows both with references and routes to the content owner.
- The same neutral message used for unknown topics ("No approved source found"), so it does not reveal that restricted content exists.
Quiz alignment
The quiz (QUIZ_LLMOPS4) covers the ingestion and query pipelines, chunking and metadata, hybrid retrieval and fusion, reranking, context assembly, citation validation, authority and freshness, access-aware retrieval, handling conflicts and unsupported answers, and the ERP policy/procedure/manual scenario.
Lesson summary
Enterprise RAG succeeds or fails on governance: approved sources with owners, structure-aware chunking, rich metadata including ACLs, hybrid retrieval with fusion and reranking, tight labelled context, validated citations, explicit authority and freshness rules, filtering before retrieval, and a graceful refusal path. Record all of this in a source-governance matrix and test it on every re-index.
Bridge to the next lesson
Design is a hypothesis until measured. The next lesson shows how to evaluate a RAG system at scale: retrieval quality, groundedness, citation correctness, completeness, handling unanswerable and conflicting questions, datasets, a failure taxonomy and controlled experiments.
Sources
- Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020): https://arxiv.org/abs/2005.11401
- Liu et al., Lost in the Middle: How Language Models Use Long Contexts (2023): https://arxiv.org/abs/2307.03172
- Cormack, Clarke and Büttcher, Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods (SIGIR 2009; see the ACM Digital Library).
- Microsoft Learn, Hybrid search overview (Azure AI Search; one provider's description, provider-dependent): https://learn.microsoft.com/azure/search/hybrid-search-overview
- Microsoft Learn, Security filters for trimming results in Azure AI Search (one provider's access-trimming pattern; provider-dependent): https://learn.microsoft.com/azure/search/search-security-trimming-for-azure-search
- OWASP, Top 10 for Large Language Model Applications (sensitive information disclosure; vector and embedding weaknesses): https://owasp.org/www-project-top-10-for-large-language-model-applications/
- Python 3 standard library
re,math,collections,datetime: https://docs.python.org/3/library/ (example tested with Python 3.11+, standard library only)
Northline Consumer Goods, document identifiers, thresholds and roles are illustrative. The retrieval code is a teaching stand-in, not a production search engine.