A production-ready Retrieval-Augmented Generation (RAG) system connects trusted enterprise documents to an AI model so that it can answer questions using relevant, authorised, and traceable information rather than relying solely on its training data. RAG was introduced as a method that combines a model’s parametric knowledge with a non-parametric retrieval memory, allowing generation to be conditioned on retrieved evidence. arxiv

The architecture must do more than retrieve similar text. It must preserve document structure, enforce access controls, retrieve relevant evidence, generate grounded answers, validate citations, and handle cases where the evidence is insufficient. arxiv

1. End-to-end architecture

A robust RAG system has two distinct paths:

Two-lane RAG architecture showing the offline path from enterprise sources through extraction, chunking, permission metadata, and Azure AI Search indexing, then the online path from an authenticated question through filtered hybrid retrieval, reranking, grounded generation, citation validation, and an answer, with evaluation and audit controls across both paths.
The ingestion path prepares and secures the index before the query path retrieves authorised evidence for a grounded answer.Open full-size imageDownload editable draw.io file
  • Offline ingestion path: Prepares, secures, enriches, and indexes knowledge before users ask questions.
  • Online query path: Authenticates the user, retrieves permitted evidence, generates an answer, validates the response, and records an audit trail.

Separating these paths allows documents to be indexed incrementally without rebuilding the entire system whenever a user asks a question. Microsoft’s RAG guidance similarly separates data preparation, chunking, enrichment, embedding, indexing, and query-time retrieval.

Architecture flow

  1. Document sources: PDFs, Word documents, SharePoint libraries, databases, wikis, and enterprise APIs.
  2. Ingestion and processing: Connectors, parsing or OCR, text extraction, cleaning, document validation, metadata extraction, and versioning.
  3. Chunking and enrichment: Structure-aware chunking, metadata enrichment, embeddings, and indexing.
  4. User question: Authentication, authorisation, query understanding, and optional query rewriting.
  5. Retrieval pipeline: Security filtering, metadata filtering, keyword search, vector search, hybrid fusion, reranking, and context selection.
  6. Grounded generation: User question, authorised evidence, system instructions, and generation constraints.
  7. Validation and response: Evidence checks, citations, refusal or fallback behaviour, logging, and source links.

RAG systems typically follow a retrieve-augment-generate flow: retrieve relevant content, add it to the model context, then generate a response grounded in that context. arxiv, as described in Microsoft Foundry.

2. Offline ingestion path

Document sources

Enterprise knowledge commonly lives in SharePoint, Blob Storage, databases, file shares, wikis, and internal APIs. The ingestion layer should preserve the source system, document identity, revision, permissions, and lifecycle status.

For regulated or operational environments, ingestion should also capture:

  • Document title and unique document ID.
  • Revision or version number.
  • Effective date and expiry date.
  • Approval or publication status.
  • Owning department, site, product, or asset.
  • Source URL and stable deep link.
  • Access-control information.
  • Language and document type.

Parsing, OCR, and validation

Plain-text extraction is insufficient for complex enterprise documents. Tables, diagrams, scanned forms, headers, footnotes, and cross-references can contain information that is lost if documents are treated as unstructured text.

A production pipeline should include:

  • Layout-aware parsing for headings, paragraphs, tables, and lists.
  • OCR for scanned PDFs and image-based documents.
  • Table extraction that preserves rows, columns, and relationships.
  • Validation checks for empty pages, failed extractions, duplicate documents, and missing metadata.
  • A quarantine process for documents that fail validation.
  • Reindexing when a source document is revised or revoked.

Microsoft’s RAG architecture guidance recommends enriching chunks with metadata fields such as title, summary, and keywords, and embedding both the chunk and relevant metadata used for vector search.

3. Chunking and indexing

Chunking divides large documents into smaller passages that can be retrieved independently. Microsoft describes chunking as breaking documents into appropriately sized pieces that each contain semantically relevant content.

Chunking strategies

StrategyHow it worksBest use
Fixed-sizeSplits text after a token or character limitSimple, uniform documents
OverlappingAdjacent chunks share some textPreserving context across boundaries
Structure-awareSplits by headings, paragraphs, sections, or tablesPolicies, manuals, reports, procedures
SemanticSplits where the subject or meaning changesMixed-topic or narrative documents
Parent-childRetrieves small chunks but supplies a larger parent sectionQuestions that require surrounding context

Microsoft’s RAG guidance recommends chunks that contain a single idea or concept, enriched with metadata fields such as title, summary, and keywords. It also recommends considering vector, full-text, hybrid, and manual multiple-search options when designing retrieval.

Practical recommendation

Start with:

  • Structure-aware chunking based on headings and sections.
  • A token limit appropriate to the embedding model and retrieval design.
  • Modest overlap to reduce context loss at boundaries.
  • Parent-child retrieval for complex procedures, policies, and technical manuals.
  • Metadata preserved on every chunk.

For example, a mining safety procedure may contain a heading, hazard description, numbered controls, responsible roles, and an approval date. A naive splitter could separate the hazard from its controls. A structure-aware or parent-child approach should keep related content together.

There is no universally optimal chunk size. Test chunk size, overlap, and retrieval depth against representative questions, including questions that require evidence from multiple sections.

Metadata to preserve

Every chunk should retain:

  • document_id, chunk_id, and parent_section_id
  • Document title and heading path
  • Page number, section number, or slide number
  • Revision, effective date, and approval status
  • Department, site, equipment, product, or document type
  • Source URL and stable citation identifier
  • Access-control information
  • Language and content classification

Tables, diagrams, scanned PDFs, and cross-references require special handling because extracting plain text alone can destroy important meaning.

4. Online query path

Authentication and authorisation

The query path must authenticate the user before retrieval. It should resolve trusted identity and group claims from the organisation’s identity provider, then apply those claims as query-time filters.

Azure AI Search supports document-level access control from ingestion through query execution. The application can pass a user or group identity as a filter string, excluding documents that do not match. With native token-based querying, Azure AI Search can validate a Microsoft Entra token and trim results to documents the user is authorised to access.

Microsoft’s security guidance states that permission metadata should be captured during indexing and enforced at query time, which is essential for RAG applications and enterprise search.

Query understanding

Before retrieval, the application may:

  • Normalise spelling, abbreviations, and terminology.
  • Expand acronyms using a controlled vocabulary.
  • Rewrite a conversational question into a retrieval-friendly query.
  • Split a complex question into subqueries.
  • Apply metadata filters such as department, document type, date, or site.

Microsoft’s RAG guidance highlights query splitting, filtering, and the choice among vector, full-text, hybrid, and manual multiple-search approaches.

5. Retrieval pipeline

Hybrid search

Hybrid search combines keyword retrieval with vector retrieval. Azure AI Search runs hybrid queries in one request, then merges the results using Reciprocal Rank Fusion (RRF).

  • Keyword search (BM25): Finds exact terms, identifiers, equipment codes, error messages, and technical terminology.
  • Vector search: Finds conceptually related passages even when the user’s wording differs from the document.
  • Hybrid fusion: Combines the rankings into one result set.

Azure AI Search uses BM25 for text ranking and vector algorithms such as Hierarchical Navigable Small World (HNSW) or exhaustive K-nearest neighbours (eKNN) for vector ranking. RRF then merges the separate ranked lists into a unified result set.

A simplified RRF formula is:

Here, \(d\) is a candidate document, \(R\) is the set of ranked result lists, and \(k\) is a smoothing constant. RRF combines ranks rather than raw relevance scores, which often have different scales across search methods.

RRF was introduced by Cormack, Clarke, and Büttcher as a simple method for combining rankings from multiple information-retrieval systems. Their SIGIR 2009 study found that RRF consistently outperformed individual ranking systems and the Condorcet Fuse baseline across TREC experiments. dl.acm

Hybrid search does not automatically guarantee better results. Evaluate it against keyword-only and vector-only baselines using real questions and labelled relevant passages.

Reranking

Initial retrieval should prioritise recall: retrieve enough plausible candidates that the correct evidence is not missed. Reranking then improves precision by scoring candidate passages against the full query.

A typical pipeline is:

  1. Retrieve 50-100 candidates using hybrid search.
  2. Fuse keyword and vector rankings using RRF.
  3. Rerank candidates using a semantic ranker or another relevance model.
  4. Select the best 5-10 chunks, subject to token budget, diversity, and source constraints.
  5. Send those chunks to the language model.

These are illustrative starting values, not universal defaults.

In Azure AI Search, semantic ranking occurs after RRF merging and can rerank full-text and hybrid results when the index contains semantically rich text fields.

Reranking matters because a passage can be semantically similar to a question without actually answering it. Measure whether reranking improves retrieval metrics and answer quality enough to justify its latency and cost.

6. Access-control enforcement

Security must be enforced during retrieval, not merely described in the system prompt.

If a user asks about a confidential finance document but lacks permission to read it, its chunks must not enter the model context. A secure flow should:

  1. Authenticate the user through the organisation’s identity provider.
  2. Resolve trusted user and group claims.
  3. Apply document-level permissions and metadata restrictions during the search operation.
  4. Retrieve and rerank only authorised candidates.
  5. Enforce permissions again when opening source documents.
  6. Record access and retrieval events for auditing.

Azure AI Search’s document-level access-control pattern stores user or group identities in an index field, applies a filter at query time, and trims results that do not match the caller’s identity.

Avoid fetching unrestricted results and filtering them only after the LLM has received them. Also consider inherited SharePoint permissions, group membership changes, document revocation, caching, and stale ACL metadata.

Security test: Create two users with different permissions, index a document visible to only one, and verify that the other user cannot retrieve its content, citation, cached answer, or source link.

7. Grounded generation and citations

Citations should point to the actual source passage used to support an answer. Each indexed chunk should retain enough information to identify its source document, page or section, and revision.

Example:

Question: What is the inspection interval for Pump 204?

Answer: The approved maintenance procedure specifies an inspection every 14 days. [Maintenance Procedure, revision 3, page 12]

That answer is valid only if the retrieved evidence actually supports the 14-day interval.

A robust implementation should:

  • Return stable source identifiers and clickable links.
  • Include page numbers, section headings, or document revisions where possible.
  • Verify that cited sources support the associated claims.
  • Avoid fabricating page numbers or document references.
  • Abstain when evidence is missing, conflicting, outdated, or insufficient.

Citations alone do not prove an answer is correct. A model can cite a real document while making a claim that the document does not support. Microsoft’s RAG evaluators include groundedness measures that assess whether a generated response aligns with the provided context without fabricating content.

8. Prompt injection and untrusted content

Retrieved documents are untrusted input. A malicious document, SharePoint page, support ticket, or web page could contain instructions designed to manipulate the model.

Greshake et al. describe this risk as indirect prompt injection: an attacker embeds instructions in content that an LLM-integrated application later retrieves, potentially causing the application to ignore its intended instructions or take unintended actions. arxiv

Mitigations include:

  • Treat retrieved context as untrusted data.
  • Instruct the model not to follow instructions embedded in retrieved content.
  • Sanitise or flag instruction-like content before adding it to the prompt.
  • Screen retrieved chunks with content-safety controls.
  • Restrict tool permissions and require approval for consequential actions.
  • Test adversarial documents and monitor for injection-like patterns.

Microsoft’s RAG prompt-engineering guidance similarly recommends defensive instructions, sanitising retrieved chunks, content-safety screening, and monitoring for injection-like patterns.

9. Failure modes and mitigations

RAG failures are often pipeline failures rather than model failures. Gao et al. categorise RAG challenges across retrieval quality, generation quality, and system-level concerns such as latency, scalability, and security. arxiv

Failure modeWhat goes wrongMitigation
Poor extractionTables, scans, or headings are lostOCR, layout-aware parsing, extraction validation
Bad chunk boundariesRelevant context is split apartStructure-aware or parent-child chunking
Retrieval misses evidenceCorrect passage never reaches the modelHybrid search, query expansion, retrieval evaluation
Irrelevant evidenceRelated passages crowd out the answerReranking, metadata filters, improved chunking
Stale informationOld revisions override approved proceduresVersion tracking, effective-date filters, reindexing
ACL leakageUsers receive unauthorised informationIdentity-based filtering, isolation tests, cache controls
HallucinationModel invents facts not in the evidenceGrounding instructions, claim checks, abstention
Invalid citationsSources exist but do not support the answerCitation-to-claim verification
Conflicting sourcesDocuments provide different instructionsAuthority and revision rules; surface unresolved conflicts
Prompt injectionA document contains malicious instructionsTreat retrieved text as untrusted data; enforce tool permissions; test adversarial content
Latency or cost spikesRetrieval and generation become expensiveMeasure each stage, limit context, cache safely, use appropriate models

10. How to evaluate the architecture

A RAG system should be evaluated at multiple stages rather than judged only by whether its answers look convincing.

Ingestion quality

Measure extraction accuracy, missing pages, metadata completeness, version correctness, indexing failures, and duplicate detection.

Retrieval quality

Measure whether the correct evidence reaches the model. Standard information-retrieval evaluation uses labelled queries and relevance judgements to measure ranking effectiveness. cambridge

Useful metrics include:

  • Recall@K: Whether a relevant passage appears in the top \(K\) results.
  • Precision@K: How many of the top \(K\) results are relevant.
  • MRR: How highly the first relevant result is ranked.
  • nDCG: How well the ranking reflects graded relevance.

Microsoft Foundry provides document-retrieval evaluation for query-specific document relevance when labels or query relevance judgements are available.

Answer quality

Measure:

  • Correctness.
  • Groundedness.
  • Completeness.
  • Relevance.
  • Citation precision.
  • Appropriate abstention.

Microsoft’s RAG evaluators include groundedness, relevance, and response completeness. Groundedness measures whether the response aligns with the provided context without fabrication; relevance measures how accurately and directly the response addresses the query.

Security and operations

Test:

  • Unauthorised retrieval attempts.
  • Prompt-injection attempts.
  • Latency percentiles.
  • Cost per answer.
  • Failure and fallback rates.
  • Traceability from answer to evidence.
  • Cache correctness after permission or document changes.

The NIST AI Risk Management Framework supports this lifecycle view through its Govern, Map, Measure, and Manage functions, helping organisations identify, assess, prioritise, and manage AI risks. nvlpubs.nist

Build a representative test set containing straightforward questions, exact identifiers, multi-document questions, unanswerable questions, conflicting revisions, and permission-restricted content. Compare configurations against the same test set before promoting changes to production.

11. Example Azure implementation

ComponentAzure service or approach
Document sourcesSharePoint, Blob Storage, SQL, enterprise APIs
IngestionAzure Functions, containerised workers, Azure Document Intelligence
Chunking and enrichmentCustom pipeline, Azure Functions, metadata enrichment
Embeddings and generationAzure OpenAI models in Microsoft Foundry
SearchAzure AI Search with vector and keyword search
Hybrid fusionAzure AI Search hybrid queries with RRF
RerankingAzure AI Search semantic ranker or a separately hosted reranker
Metadata and ACLsSearch filters, identity claims, trusted permission synchronisation
API and orchestrationAzure Functions, App Service, or Azure Container Apps
IdentityMicrosoft Entra ID
MonitoringApplication Insights, Azure Monitor, structured traces
EvaluationVersioned question sets, retrieval metrics, groundedness and security evaluations

The exact services depend on the document estate, security model, scale, and latency requirements. For highly sensitive enterprise knowledge, permission filtering and document lifecycle management should be designed before choosing the embedding model.

12. The most important design principle

RAG quality is a pipeline property, not just an LLM property.

A stronger language model cannot reliably answer from evidence that was never retrieved. Better retrieval cannot compensate for broken permissions. Good citations cannot compensate for inaccurate source documents.

Prioritise the system in this order:

  1. Reliable document extraction and metadata.
  2. Secure access control and document versioning.
  3. Measurable chunking and hybrid retrieval.
  4. Reranking and context selection.
  5. Grounded generation, citation validation, and abstention.
  6. Continuous evaluation, monitoring, and improvement.

This creates a defensible architecture for enterprise knowledge assistants, including operational knowledge systems where incorrect answers or unauthorised disclosure can have serious consequences.

References

  1. Lewis, P., Perez, E., Piktus, A., Petroni, F., Karpukhin, V., Goyal, N., Küttler, H., Lewis, M., Yih, W., Rocktäschel, T., Riedel, S., & Kiela, D. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. arXiv:2005.11401. arxiv
  2. Gao, Y., Xiong, Y., Gao, X., Jia, K., Pan, J., Bi, Y., Dai, Y., Sun, J., Wang, M., & Wang, H. (2023). Retrieval-Augmented Generation for Large Language Models: A Survey. arXiv:2312.10997. arxiv
  3. Cormack, G. V., Clarke, C. L. A., & Büttcher, S. (2009). Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods. Proceedings of the 32nd International ACM SIGIR Conference on Research and Development in Information Retrieval, 758-759. DOI: 10.1145/1571941.1572114. dl.acm
  4. Greshake, K., Abdelnabi, S., Mishra, S., Endres, C., Holz, T., & Fritz, M. (2023). Not What You’ve Signed Up For: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection. arXiv:2302.12173. arxiv
  5. Manning, C. D., Raghavan, P., & Schütze, H. (2008). Introduction to Information Retrieval. Cambridge University Press. cambridge
  6. National Institute of Standards and Technology. (2023). Artificial Intelligence Risk Management Framework (AI RMF 1.0), NIST AI 100-1. DOI: 10.6028/NIST.AI.100-1. nvlpubs.nist
  7. Microsoft Learn. (2026). Design and develop a RAG solution.
  8. Microsoft Learn. (2025). Develop a RAG Solution on Azure: Chunking Phase.
  9. Microsoft Learn. (2026). RAG and Generative AI: Azure AI Search.
  10. Microsoft Learn. (2026). Retrieval augmented generation (RAG) and indexes.
  11. Microsoft Learn. (2026). Hybrid Search Overview: Azure AI Search.
  12. Microsoft Learn. (2025). Hybrid query: Azure AI Search.
  13. Microsoft Learn. (2026). Hybrid Search Scoring (RRF): Azure AI Search.
  14. Microsoft Learn. (2026). Document-Level Access Control: Azure AI Search.
  15. Microsoft Learn. (2026). Best Practices for Security: Azure AI Search.
  16. Microsoft Learn. (2026). Develop a RAG Solution on Azure: Prompt Engineering.
  17. Microsoft Learn. (2026). Retrieval-Augmented Generation (RAG) Evaluators for Generative AI.