Library

Volume 2 · RAG Architecture

Notebook
Sign in

Section 23

Production RAG (Scalability, Security, Cost, Multi-Tenancy)

934 words · about 4 min

23.1 Security Architecture

┌─────────────────────────────────────────────┐
│              RAG Security Layers             │
│                                               │
│  1. Authentication (OAuth 2.0 / OIDC)        │
│  2. Authorization (RBAC → document ACLs)     │
│  3. PII Masking (before embedding)           │
│  4. Retrieval Filtering (ACL-based)          │
│  5. Output Filtering (PII detection)         │
│  6. Audit Logging (every query + response)   │
│  7. Data Encryption (at rest + in transit)   │
└─────────────────────────────────────────────┘

Document-Level Access Control:

# Store ACL with each chunk
chunk_metadata = {
    "text": "...",
    "access_groups": ["legal_team", "executives"],
    "classification": "confidential",
    "owner": "legal_dept"
}

# At query time, filter by user's groups — PRE-filter, never rely on post-filtering alone
def retrieve_with_acl(query, user):
    user_groups = get_user_groups(user)
    results = vector_db.search(
        query=query,
        filter={"access_groups": {"$in": user_groups}}
    )
    return results

23.2 Multi-Tenancy Patterns

Pattern Isolation Cost Complexity When to Use
Shared index + metadata filter Low Low Low Same org, department-level separation
Separate collections Medium Medium Medium Different clients, similar schemas
Separate instances High High High Regulated industries, strict isolation

23.3 Scalability Design

  • Embedding service: Deploy behind a load-balanced, auto-scaling API with GPU inference
  • Vector DB scaling: Shard indices by collection/tenant, use read replicas for query throughput
  • LLM service: Managed API with provisioned throughput for predictable capacity, or self-hosted with auto-scaling
  • Ingestion: Queue-based async pipeline so document spikes don’t drop or block requests
  • Caching: Cache embeddings for frequent queries; cache LLM responses for identical retrievals (see Section 23.5)

23.4 Stale Data Management

Challenge: Source documents change but embeddings remain outdated, serving stale answers. Solution: Incremental indexing pipeline with change detection (file-hash comparison or event-driven triggers). On document update: version the document, re-chunk and re-embed the new version, atomically swap old chunks for new (keyed by document_id + version), invalidate any cache entries tied to that document, and re-run the evaluation suite against queries known to touch that document. Critical for domains like payer rules or compliance policies where serving an outdated rule has real business/legal consequences — implement effective-date filtering so queries always resolve to the currently valid version.

23.5 Semantic Caching for Cost Reduction

User Query → Embed Query → Search Cache (similarity > 0.95?)
                                │
                          ┌─────┴─────┐
                          Yes         No
                          │           │
                   Return cached   Full RAG pipeline
                   response        │
                                   ▼
                              Cache response
                              (query embedding → response)
class SemanticCache:
    def __init__(self, similarity_threshold=0.95, ttl_hours=24):
        self.vector_db = QdrantClient()
        self.threshold = similarity_threshold
        self.ttl = ttl_hours

    def get(self, query_embedding):
        results = self.vector_db.search(
            collection="cache", query_vector=query_embedding,
            limit=1, score_threshold=self.threshold
        )
        if results and not self._is_expired(results[0]):
            return results[0].payload["response"]
        return None

    def set(self, query_embedding, query_text, response):
        self.vector_db.upsert(collection="cache", points=[{
            "vector": query_embedding,
            "payload": {"query": query_text, "response": response,
                        "created_at": datetime.utcnow().isoformat()}
        }])

Expected impact: 30-40% cache hit rate for enterprise Q&A, 30-40% LLM cost reduction, sub-100ms response for cache hits vs. 2-3s for full pipeline. Invalidate cache entries when source documents update.

23.6 Handling Multi-Turn Conversations

Problem: Follow-up questions lack context (“How many days for senior employees?” is ambiguous without knowing it follows a vacation-policy question).

Solution — Conversation-Aware Query Reformulation:

def reformulate_query(current_query, conversation_history):
    """Use LLM to create a standalone query from conversation context."""
    prompt = f"""Given the following conversation, rewrite the latest
    question to be a standalone question that includes all necessary context.

    Conversation: {conversation_history}
    Latest question: {current_query}
    Standalone question:"""
    return llm.generate(prompt)

Section 23 — Interview Q&A

Q: Design a RAG system for a large enterprise with 10 million documents across multiple formats, including security and multi-tenancy requirements. A: Ingestion uses a workflow orchestrator with format-specific parsers (Unstructured for PDF/DOCX, Trafilatura for HTML) plus OCR/layout analysis for scanned documents, with quality gates flagging documents needing manual review. Chunking is adaptive — structure-aware for technical docs, semantic for unstructured content. Embedding uses a high-quality managed model behind an API-managed endpoint, batched at ~1000 documents per call. Vector storage is sharded by document collection/department for both performance and ACL enforcement, using HNSW for quality, with document-level ACL metadata pre-filtering every query (never relying on post-filtering alone, since that risks retrieving content a user shouldn’t see even briefly). Retrieval is hybrid (dense+BM25) with a multi-stage funnel: top-100 candidates → cross-encoder re-rank → top-10 to the LLM. Generation uses tiered model routing (cheap model for simple factual queries, capable model for complex reasoning), mandatory citations, and streaming for UX. Multi-tenancy uses separate collections per client/department with metadata-filtered shared infrastructure for cost efficiency, escalating to fully separate instances only where regulatory isolation demands it. Monitoring tracks retrieval quality (hit rate, MRR, NDCG), hallucination rate, and per-query-type cost.

Q: What are the key challenges in building a production RAG system and how do you address each? A: (1) Hallucination — mitigate with faithfulness scoring, citation verification, and prompts that constrain generation to “based on the provided context only.” (2) Stale data — incremental indexing with change detection and atomic version swaps (Section 23.4). (3) Access control — pre-filter retrieval by user ACLs stored as chunk metadata; never rely on post-filtering alone. (4) Scale/latency — async retrieval, caching, pre-computed embeddings, HNSW indices to keep retrieval overhead to 200-500ms. (5) Multi-turn conversations — conversation-aware query reformulation so follow-ups resolve to standalone queries. (6) Evaluation at scale — LLM-as-judge pipelines plus automated regression testing against golden Q&A datasets, since manual evaluation doesn’t scale. (7) Cost control — semantic caching, tiered model routing, and distillation for high-volume simple query types.