Skip to content

Enterprise RAG System Design

Design production-grade knowledge base systems with document processing, access control, and scale


Learning Objectives

By the end of this module, you will be able to:

  • Architect enterprise RAG systems with multi-tenant support and access control
  • Design document processing pipelines for diverse document types and formats
  • Implement hybrid search strategies combining vector, keyword, and structured search
  • Build scalable retrieval systems handling millions of documents
  • Address enterprise concerns including security, compliance, and auditability

Enterprise RAG Architecture

High-Level System Architecture

Core Components

ComponentPurposeEnterprise Considerations
Source ConnectorsIngest from various systemsSharePoint, Confluence, S3, databases
Document ProcessingExtract and structure contentOCR, table extraction, metadata
Chunking ServiceSplit documents optimallySemantic boundaries, overlap
Embedding ServiceGenerate vector representationsBatch processing, model versioning
Hybrid RetrieverMulti-strategy searchVector + keyword + structured
ACL EngineAccess control enforcementReal-time permission checking
Citation GeneratorSource attributionCompliance, trustworthiness

Document Processing Pipeline

Processing Architecture

Document Type Handling

Document TypeExtraction MethodChunking StrategyConsiderations
PDFPyMuPDF, pdfplumberPage-aware, heading-basedTables, images, OCR fallback
Word/DOCXpython-docxSection/heading-basedStyles, tables, embedded objects
HTMLBeautifulSoupDOM-aware, semantic tagsNavigation removal, content extraction
MarkdownUnified parserHeader-based hierarchyCode blocks, links
PowerPointpython-pptxSlide-basedSpeaker notes, visual context
Excelopenpyxl, pandasSheet/table-basedFormula context, named ranges
Emailemail parserThread-awareAttachments, conversation threading

Chunking Strategies

Chunking Best Practices

  • Chunk size: 256-512 tokens for precise retrieval, 512-1024 for context-rich
  • Overlap: 10-20% overlap to maintain context continuity
  • Semantic boundaries: Prefer splitting at natural breaks (paragraphs, sections)
  • Metadata preservation: Attach source, page, section info to each chunk

Chunking Parameters Comparison

StrategyChunk SizeOverlapUse CaseTrade-offs
Small chunks256 tokens50 tokensPrecise Q&AMay miss context
Medium chunks512 tokens100 tokensGeneral RAGBalanced
Large chunks1024 tokens200 tokensSummarizationLower precision
SemanticVariableNaturalTechnical docsComplex implementation

Hybrid Search Architecture

Multi-Strategy Retrieval

Fusion Strategies

StrategyDescriptionProsCons
Reciprocal Rank Fusion (RRF)Combine by reciprocal ranksSimple, effectiveIgnores score magnitude
Weighted AverageWeight scores by sourceTunableRequires score normalization
Learn-to-RankML model for fusionOptimalTraining data needed
CascadeSequential filteringEfficientMay miss good results

RRF Implementation

python
def reciprocal_rank_fusion(result_lists, k=60):
    """
    Combine multiple ranked lists using RRF.
    k: smoothing constant (typically 60)
    """
    fused_scores = {}

    for result_list in result_lists:
        for rank, doc_id in enumerate(result_list):
            if doc_id not in fused_scores:
                fused_scores[doc_id] = 0
            fused_scores[doc_id] += 1 / (k + rank + 1)

    # Sort by fused score
    return sorted(fused_scores.items(),
                  key=lambda x: x[1],
                  reverse=True)

Access Control System

Multi-Tenant Architecture

Permission Models

ModelDescriptionUse CaseComplexity
RBACRole-based accessSimple org structuresLow
ABACAttribute-basedComplex policiesMedium
ACLPer-document permissionsFine-grained controlHigh
HierarchicalFolder inheritanceFile systemsMedium
HybridCombinationEnterpriseHigh

Query-Time Access Control

Performance Consideration

Access control filtering at query time can significantly impact latency. Pre-compute permission sets where possible, and use efficient filtering strategies.

ACL Implementation Approaches

ApproachDescriptionProsCons
Pre-filterFilter before searchFast queriesIndex per permission set
Post-filterFilter after searchSimple indexOver-fetch needed
HybridCoarse pre + fine postBalancedImplementation complexity
Materialized viewsPre-computed per user/groupFastest queriesStorage cost, staleness

Scaling Strategies

Horizontal Scaling Architecture

Scaling Dimensions

DimensionStrategyImplementation
DocumentsHorizontal shardingShard by tenant, date, or hash
QueriesRead replicasMultiple query nodes per shard
EmbeddingsBatch processingAsync ingestion queue
LLM CallsRate limiting + cachingSemantic cache, request coalescing
TenantsIsolationDedicated shards or namespaces

Caching Strategy

Cache LevelHit RateLatency SavingsFreshness
Query (exact)10-20%95%Immediate
Semantic30-50%90%Configurable
Embedding80%+50msStable
LLM Response20-40%80%Configurable

Enterprise Considerations

Compliance and Audit

Enterprise Features Checklist

FeatureDescriptionImplementation
SSO IntegrationEnterprise identitySAML, OIDC
Audit LoggingQuery and access logsStructured logging, retention
Data ClassificationSensitivity levelsMetadata tagging
Retention PoliciesAutomatic deletionTTL, archival
EncryptionAt rest and in transitTLS, AES-256
Backup/RecoveryDisaster recoveryRegular snapshots
SLA MonitoringUptime and performancePrometheus, alerts

Interview Q&A

Q1: How do you handle documents with different access levels in RAG?

Answer: "I implement a multi-layer access control strategy:

  1. Index-time tagging: Each document chunk gets ACL metadata (permitted users, groups, roles)

  2. Query-time filtering: Two approaches:

    • Pre-filter: Include ACL predicates in vector search (e.g., permitted_groups IN user.groups)
    • Post-filter: Over-fetch results, then filter by permissions
  3. Hybrid approach for scale:

    • Coarse pre-filtering by department/tenant (reduces search space)
    • Fine post-filtering for specific document permissions
  4. Caching: Cache permission sets per user with short TTL to handle permission changes

  5. Audit: Log all queries with user context for compliance

For very sensitive environments, I'd consider separate indexes per permission level to ensure complete isolation."

Q2: How do you optimize retrieval quality in enterprise RAG?

Answer: "I use a multi-stage retrieval pipeline:

Stage 1: Query Enhancement

  • Query expansion using synonyms and related terms
  • Query decomposition for complex questions
  • Intent classification to route to appropriate sources

Stage 2: Hybrid Retrieval

  • Vector search for semantic similarity
  • BM25 for keyword matching
  • Metadata filters for structured constraints
  • Fusion using Reciprocal Rank Fusion

Stage 3: Reranking

  • Cross-encoder reranking (e.g., Cohere, BGE)
  • Diversity injection to avoid redundant results
  • Recency weighting for time-sensitive queries

Stage 4: Context Optimization

  • Parent-child retrieval: retrieve chunks, expand to parent context
  • Lost-in-the-middle mitigation: order by relevance, not position
  • Compression: summarize verbose contexts

I measure quality using retrieval metrics (MRR, NDCG) and end-to-end evaluation with LLM-as-judge."

Q3: How would you scale a RAG system to handle millions of documents?

Answer: "I design for horizontal scalability at each layer:

Ingestion:

  • Async processing via message queue (Kafka)
  • Parallel workers for embedding generation
  • Batch embedding (reduce API calls)
  • Incremental indexing (update only changed documents)

Storage:

  • Sharded vector database (by tenant or document hash)
  • Index partitioning for large collections
  • Tiered storage (hot/warm/cold) based on access patterns

Query:

  • Query routing to relevant shards
  • Caching at multiple levels (query, embedding, LLM)
  • Read replicas for high-traffic tenants
  • Rate limiting per tenant

Specific numbers:

  • 1M documents: Single node Qdrant/Pinecone
  • 10M documents: Sharded deployment, 3-5 shards
  • 100M+ documents: Distributed cluster, tenant isolation

Key optimizations:

  • Quantization (reduce vector size by 4x)
  • HNSW parameter tuning (ef_construction, M)
  • Product quantization for memory efficiency"

Q4: How do you ensure answer quality and prevent hallucinations?

Answer: "I implement multiple layers of quality assurance:

Retrieval Quality:

  • Relevance thresholds (reject low-scoring retrievals)
  • Source diversity requirements
  • Citation extraction and verification

Generation Quality:

  • Grounded generation prompts ('only answer based on provided context')
  • Temperature 0 for factual responses
  • Structured output formats where possible

Post-Generation Checks:

  • Citation verification (does the answer match sources?)
  • Consistency checking (multiple generations agree?)
  • Fact-checking against structured data

Confidence Signaling:

  • 'I don't have information about X'
  • 'Based on available documents...'
  • Confidence scores exposed to users

Continuous Improvement:

  • User feedback collection
  • Regular human evaluation sampling
  • Automated regression testing on known Q&A pairs

For high-stakes domains (legal, medical), I add human-in-the-loop review for uncertain responses."


Trade-off Analysis

DecisionOption AOption BRecommendation
Chunking SizeSmall (precise)Large (contextual)Medium with overlap
Search StrategyVector only (semantic)Hybrid (comprehensive)Hybrid for enterprise
Access ControlPre-filter (fast)Post-filter (flexible)Hybrid approach
Embedding ModelSmall (fast)Large (accurate)Large for quality-critical
CachingAggressive (fast)Conservative (fresh)Semantic cache with TTL
RerankingSkip (fast)Cross-encoder (accurate)Always for enterprise

PreviousNext
Chatbot DesignCode Assistant

Sources