Skip to main content
← PROBLEMS / AI-SYSTEMS
An end-to-end domain learning journey

Design an Enterprise RAG System at
Scale (10M+ Documents with ACLs).

Ingest documents via incremental CDC connectors into sharded Qdrant/Milvus + Elasticsearch BM25 with synced Roaring Bitmap ACLs, fuse via RRF, rerank Top-50 -> Top-5, and verify LLM citations.
Start the journey7 stages· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep the architecture evolvable without sacrificing reliability, sync document ACL changes independently from re-embedding chunks so permission revocations take effect in seconds without recomputing 150M vectors.

TL;DR30-second simplified summary
▾

At 10M documents (~150M 512-token chunks), re-embedding an entire folder just because one user lost Google Drive access would crush GPU pipelines. Decouple Chunk Vector Storage from ACL Metadata (storing allowed_principals in a fast-update payload/bitmap index synced via CDC webhooks).

On query, the gateway resolves the user's transitive Okta/AD group memberships (cached 60s), executes ACL-prefiltered HNSW + BM25 search across sharded Qdrant/Elasticsearch nodes, merges Top-50 via RRF, and reranks to Top-5 with a GPU Cross-Encoder.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Hybrid RAG: RRF Reranking & Document-Level ACL Filtering
Hybrid RAG combines dense HNSW vector search with sparse BM25 lexical search via Reciprocal Rank Fusion (RRF), enforces document-level ACLs via pre-filtered Roaring Bitmaps, and reranks Top-50 -> Top-5 with a Cross-Encoder.
RAG Retrieval Pipelines
Production RAG retrieval combines semantic chunking, hybrid dense (HNSW) + sparse (BM25/SPLADE) search, Reciprocal Rank Fusion (RRF), metadata pre-filtering, and cross-encoder reranking to deliver high-precision context to LLMs.
Vector Databases & RAG
Retrieval-Augmented Generation (RAG) grounds LLM outputs by indexing domain documents as dense/sparse vectors and retrieving top-k relevant chunks at query time via approximate nearest neighbor (ANN) indexes like HNSW.
Full walkthrough · 7 stages
01
STAGE 01 · CORE INTUITIONfoundation

Scale Envelope & Latency Budget.

Why this matters: Size a 10M-doc (150M-chunk) enterprise RAG system with incremental ACL sync, <500 ms latency, and zero cross-tenant leaks.

Think of Scale Envelope & Latency Budget as the intuition layer for Design an Enterprise RAG System at Scale (10M+ Documents with ACLs): Size a 10M-doc (150M-chunk) enterprise RAG system with incremental ACL sync, <500 ms latency, and zero cross-tenant leaks.

Design an enterprise RAG platform indexing 10M+ multi-format documents (~150M chunks) from Drive, Confluence, and Git with incremental CDC permission sync, < 500 ms retrieval + rerank latency, zero cross-tenant/ACL leaks, and inline citation verification.

STAGE 01 · CORE INTUITION

Scale Envelope & Latency Budget

10M Docs / 150MChunksCorpus ScaleIncremental CDC ACLsAuth StateACL-Masked HybridRetrieval Core<500 ms p95End-to-EndLatency SLAfilters

1.Corpus Sizing: 150M 768d PQ8 vectors (~115 GB RAM) + BM25 inverted index across 8 sharded retrieval nodes.

2.Security Invariant: Never leak a single snippet from a restricted document—even under partial CDC lag.

3.Latency Budget: 15 ms auth + 60 ms hybrid shard search + 110 ms Cross-Encoder rerank = ~185 ms retrieval p95.

Pre-filtered Roaring Bitmap ACLs over sharded HNSW + BM25 + Cross-Encoder meet <500 ms on 150M chunks with zero leaks.

02
STAGE 02 · CORE MECHANICSfoundation

Core Architecture & Data Flow.

Why this matters: Resolve transitive Okta/AD groups, run pre-filtered HNSW + BM25 across shards, merge via RRF, and rerank Top-5.

Think of Core Architecture & Data Flow as the intuition layer for Design an Enterprise RAG System at Scale (10M+ Documents with ACLs): Resolve transitive Okta/AD groups, run pre-filtered HNSW + BM25 across shards, merge via RRF, and rerank Top-5.

On query, the gateway resolves the user's transitive Okta/AD group memberships (cached 60s), executes ACL-prefiltered HNSW + BM25 search across sharded Qdrant/Elasticsearch nodes, merges Top-50 via RRF, and reranks to Top-5 with a GPU Cross-Encoder.

STAGE 02 · CORE MECHANICS

Core Architecture & Data Flow

Group Cache (60s)Principal Set8x Qdrant + ESShardsParallel SearchRRF Merger (k=60)Top-50 PoolCross-EncoderRerankGrounded Chunksgathers

1.Transitive Group Expansion: Resolve nested AD/Okta groups at the gateway and cache for 60s (invalidated on webhook).

2.Pre-Filtered Traversal: HNSW skips unauthorized graph edges during search rather than filtering after Top-K.

3.Snippet Grounding: Return chunk IDs, doc URLs, and ACL epoch with every citation.

Gateway group expansion, bitmap-masked HNSW/BM25 shards, RRF fusion, and Cross-Encoder reranking form the query path.

Engineering Decision Framework
Problem
How to implement Design an Enterprise RAG System at Scale (10M+ Documents with ACLs) without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To keep the architecture evolvable without sacrificing reliability, sync document ACL changes independently from re-embedding chunks so permission revocations take effect in seconds without recomputing 150M vectors.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design an Enterprise RAG System at Scale (10M+ Documents with ACLs) experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · SAFE IMPLEMENTATIONintermediate

ACL-Scoped Hybrid Retrieval Guard.

Why this matters: Implement search_enterprise_rag to fail closed on empty user_principals before querying dense or sparse indexes.

Think of ACL-Scoped Hybrid Retrieval Guard as the intuition layer for Design an Enterprise RAG System at Scale (10M+ Documents with ACLs): Implement search_enterprise_rag to fail closed on empty user_principals before querying dense or sparse indexes.

def search_enterprise_rag(user_principals: set[str], query: str, dense_idx, bm25_idx, reranker) -> list[dict]:
    if not user_principals:
        raise PermissionError('Fail closed: user_principals cannot be empty')
    dense_hits = dense_idx.search_prefiltered(query, principals=user_principals, limit=50)
    sparse_hits = bm25_idx.search_prefiltered(query, principals=user_principals, limit=50)
    fused = reciprocal_rank_fusion(dense_hits, sparse_hits, top_n=50)
    return reranker.rerank(query, [doc_id for doc_id, _ in fused], top_k=5)
STAGE 03 · SAFE IMPLEMENTATION

ACL-Scoped Hybrid Retrieval Guard

if notuser_principalsFail-Closed Gatedense_idx.searchVector Recallbm25_idx.searchLexical RecallRRF + reranker.rankFinal Contextif authorized

1.Fail-Closed First: An empty principal set never falls back to 'public'—it raises PermissionError immediately.

2.Defense in Depth: Re-verify document ACLs on the final Top-5 chunk metadata fetch before returning to the LLM.

3.Deterministic RRF: Combine dense and sparse ranks deterministically before GPU reranking.

Failing closed on empty principals and double-checking Top-5 ACLs enforces zero unauthorized leakage.

04
STAGE 04 · SCALING & TRADE-OFFSintermediate

Sharding & Hot-Spot Mitigation.

Why this matters: Shard 150M chunks by tenant/doc_id with PQ8 quantization and adaptive efSearch for narrow ACL scopes.

Think of Sharding & Hot-Spot Mitigation as the intuition layer for Design an Enterprise RAG System at Scale (10M+ Documents with ACLs): Shard 150M chunks by tenant/doc_id with PQ8 quantization and adaptive efSearch for narrow ACL scopes.

Partition state deterministically and apply bounded-load or sub-bucket sharding for hot keys.

STAGE 04 · SCALING & TRADE-OFFS

Sharding & Hot-Spot Mitigation

8 Retrieval ShardsEven PartitionPQ8 Vector CompressMemory ScaleAdaptive efSearchRecall GuardBatch-50 RerankPoolThroughput Scaletunes

1.Why PQ8 + Rerank Works: Cross-Encoder reranking on Top-50 recovers the ~1% precision lost from PQ8 vector compression.

2.Narrow-ACL Recall Fix: When a user can access <1% of docs, raising efSearch prevents HNSW from stalling in restricted regions.

3.Document-Hash Sharding: Sharding by doc_id keeps all chunks of a single document local and spreads large folders evenly.

PQ8 HNSW compression, doc_id sharding, and adaptive efSearch sustain high recall across narrow enterprise ACLs.

05
STAGE 05 · FAULT ISOLATIONadvanced

Failure Modes & Graceful Degradation.

Why this matters: Degrade gracefully on Cross-Encoder GPU overload and prioritize ACL revocations ahead of document grants.

Think of Failure Modes & Graceful Degradation as the intuition layer for Design an Enterprise RAG System at Scale (10M+ Documents with ACLs): Degrade gracefully on Cross-Encoder GPU overload and prioritize ACL revocations ahead of document grants.

Apply circuit breakers, fallback caches, and dead-letter quarantine queues.

STAGE 05 · FAULT ISOLATION

Failure Modes & Graceful Degradation

GPU Rerank BreakerLatency GuardACL-Safe RRF Top-5Degraded ModePriority RevokeQueueSecurity SLAParser Poison DLQIngest Shieldisolates ingest

1.Safe Degradation: Circuit-breaking the Cross-Encoder still returns ACL-verified RRF Top-5 results in <90 ms.

2.Revoke Priority: Dedicated high-priority Kafka topic for permission revocations ensures <5s revoke propagation.

3.Ingest Isolation: Malformed PDFs/ZIPs go to a parser DLQ without blocking Drive/Git CDC progress.

GPU circuit breakers, priority revocation queues, and parser DLQs isolate failures without weakening ACLs.

06
STAGE 06 · RECOVERY & CONSISTENCYadvanced

Consistency, Idempotency & Recovery.

Why this matters: Sync Drive, Confluence, and Git changes idempotently using content hashes, CDC watermarks, and atomic alias swaps.

Think of Consistency, Idempotency & Recovery as the intuition layer for Design an Enterprise RAG System at Scale (10M+ Documents with ACLs): Sync Drive, Confluence, and Git changes idempotently using content hashes, CDC watermarks, and atomic alias swaps.

Enforce atomic state transitions, fencing/idempotency keys, and fast snapshot recovery.

STAGE 06 · RECOVERY & CONSISTENCY

Consistency, Idempotency & Recovery

Connector CDCStreamChange FeedChunk SHA-256 DedupEmbed SavingsMonotonic ACL EpochConsistent AuthSnapshot + KafkaSeekCrash Safecommits

1.Incremental Re-Embedding: Editing 1 paragraph in a 50-page doc re-embeds only the changed chunk via SHA-256 diffing.

2.Tombstone Deletes: Mark deleted docs in the ACL/tombstone bitmap immediately before background HNSW compaction.

3.Idempotent Upserts: Keying chunks by (doc_id, chunk_idx, content_hash) makes CDC replays completely safe.

Chunk SHA-256 diffing, immediate tombstone bitmaps, and Kafka checkpoints keep 10M docs fresh and crash-safe.

07
STAGE 07 · OBSERVABILITY & GUARDRAILSadvanced

Telemetry, Circuit Breakers & Failure Modes.

Why this matters: Monitor CDC permission lag, ACL-filter selectivity, zero-result queries, and synthetic cross-tenant canary probes.

Think of Telemetry, Circuit Breakers & Failure Modes as the intuition layer for Design an Enterprise RAG System at Scale (10M+ Documents with ACLs): Monitor CDC permission lag, ACL-filter selectivity, zero-result queries, and synthetic cross-tenant canary probes.

Track p99 latency, retry/conflict ratios, and saturation metrics; fail fast with bounded retries and circuit breakers whenever invariants degrade.

STAGE 07 · OBSERVABILITY & GUARDRAILS

Telemetry, Circuit Breakers & Failure Modes

ACL CDC Lag < 5sSecurity MetricACL Selectivity %Recall MetricZero-Result RateQuality MetricCross-TenantCanariesContinuous Auditdiagnoses

1.Canary Probes: Synthetic queries run every minute attempting to fetch restricted canary docs—any hit pages Sev-1.

2.CDC Lag Alert: Alert if permission-revocation Kafka lag exceeds 5 seconds.

3.Reranker Queue Alert: Scale GPU rerank pods before batch wait p95 crosses 50 ms.

Continuous cross-tenant canary probes, <5s ACL lag alerts, and zero-result tracking guard security and recall.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why decouple ACL metadata updates from chunk vector re-embedding?

Recommended Learning Flow