Architecture
Multi-tenant AI isolation ensures cryptographic customer identity propagates unbroken across SQL tables, dense vector indexes, exact and semantic caches, MCP tools, observability traces, evaluation datasets, and deletion pipelines—preventing derived retrieval shortcuts, prompt injections, or warm caches from ever crossing organizational tenant boundaries.
Relational Row-Level Security (RLS) solves persistence boundaries for CRUD rows, yet modern AI SaaS platforms duplicate sensitive corporate knowledge into half a dozen secondary derived stores (pgvector / HNSW graphs, BM25 inverted indexes, Redis semantic caches, LLM prefix KV caches, LangSmith/OTel span logs, and offline eval suites). If any single secondary projection omits authoritative (tenant_id, acl_group_ids, policy_epoch) scoping, indirect prompt injection or approximate neighbor recall silently surfaces confidential records across customer boundaries even while the primary Postgres table remains completely locked.
1. Seven Security Boundaries Across the Data & Inference Path
- Identity Injection at API Edge Only: Bind
tenant_id,user_id, and resolved RBAC/ABAC document ACLs strictly from signed OAuth/OIDC server tokens (session.tenantId). Never accepttenant_idinside tool arguments generated by the LLM. - Pre-Filtered vs Partitioned Vector Search: Naive HNSW post-filtering retrieves global top- vectors first and drops forbidden tenants afterward—returning
0results when another tenant owns high-scoring clusters, AND risking side-channel leakage via aggregate timing or result counts. Enforce HNSW iterative pre-filtering, composite tenant-keyed partitions (pgvectorpartitioned tables bytenant_id), or physical collection isolation. - ACL-Salted Exact & Semantic Caches: Prefix prompt caches (
Anthropic/vLLM APC) and Redis semantic caches must embed(tenant_id, acl_digest, corpus_epoch)into cache keys AND hash verification—blocking a cached executive compensation summary answered for an Admin from ever hitting for an intern or external tenant. - Tool Execution & Brokered Secrets: Agent runtimes fetch short-lived scoped tokens (
5mTTL) per tool call via a broker gateway; prompts and sandboxes never hold raw static DB/S3 credentials. - PII-Redacted Telemetry & Eval Hygiene: Redact emails, API keys, SSNs, and raw prompt text at OTel ingress before traces hit shared observability lakes, and obtain explicit opt-in with anonymized surrogates before copying logs into shared regression datasets.
- Cascade Deletion & Cryptographic Erasure (
GDPR Art. 17): Source deletes propagate cleanly viaW3C PROVlineage DAGs into SQL chunks, vector nodes, BM25 docs, and cache epoch invalidations; per-tenant DEKs inside S3 backups guarantee cryptographic erasure upon key destruction.
2. Tenancy Topology Trade-Off Matrix
| Tenancy Model | Isolation Strength | HNSW RAM & Cache Efficiency | GDPR Deletion Complexity | Best Workload Fit |
|---|---|---|---|---|
Shared Table + Server RLS Filters | Logical DB/query gate (risk if bypassed) | Highest density (1 index, high locality) | Tombstone delete + async cache epoch bump | 10,000+ SMB SaaS workspaces with strict query gates |
| PostgreSQL List/Hash Partitions + Per-Tenant HNSW | Physical segment isolation per shard | Medium (1 HNSW graph per shard) | DROP PARTITION instant cleanup (O(1)) | Mid-market enterprise tiers (100–5,000 orgs) |
| Dedicated Schema / VPC / Customer KMS DEK | Cryptographic & physical blast isolation | Low (cold-start RAM duplication per tenant) | Destroy tenant KMS key (crypto-shred) | Regulated Healthcare (HIPAA), Finance, Defense |
Worked Selectivity Failure Example (Post-Filter Collapse)
Suppose a pooled HNSW index holds 10,000,000 vectors evenly across 1,000 tenants (10,000 chunks per tenant = 0.1% selectivity). Running un-partitioned ANN search with topK = 20 fetches 20 nearest global matches—statistically capturing 20 x 0.001 = 0.02 matching chunks for the requesting tenant (> 98% zero-result empty retrievals!) unless switched to iterative HNSW filtering (pgvector 0.8+ hnsw.iterative_scan) or per-tenant HNSW partitions.
3. PostgreSQL RLS, Partitioning & Pre-Filtered Semantic Query Implementation
sql-- 1. Enforce strict fail-closed Row-Level Security bound cleanly to transaction session settingsALTER TABLE knowledge_chunks ENABLE ROW LEVEL SECURITY;ALTER TABLE knowledge_chunks FORCE ROW LEVEL SECURITY;CREATE POLICY tenant_acl_isolation ON knowledge_chunksUSING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuidAND acl_groups && string_to_array(coalesce(current_setting('app.acl_groups', true), ''), ',')::text[]);-- 2. Transaction-scoped execution with pgvector >= 0.8 iterative HNSW scan preventing empty post-filter starvationBEGIN;SET LOCAL app.current_tenant_id = '9c4e2a10-4b7d-4e92-88a1-3f2b10c9d400';SET LOCAL app.acl_groups = 'eng-platform,sec-review';SET LOCAL hnsw.iterative_scan = 'strict_order';SELECT chunk_id, doc_id, 1 - (embedding <=> $1::vector) AS cosine_simFROM knowledge_chunksORDER BY embedding <=> $1::vectorLIMIT 12;COMMIT;
Decisions
| Decision | Required evidence | Review trigger |
|---|---|---|
Derive tenant_id & acl_groups strictly from verified gateway session tokens + SET LOCAL PostgreSQL RLS. | Zero cross-tenant leakage in automated IDOR + vector regression tests | Schema changes, pooler config edits, or new auth scopes |
Key every semantic/KV prefix cache explicitly by (tenant_id, acl_epoch, prompt_hash). | ACL revocation test verifying immediate cache miss upon group removal | Adding shared Redis/Memcached cache clusters |
Alternatives and trade-offs
- Per-Tenant Dedicated Physical Indexes vs. Pooled RLS / Pre-Filtered Partial Indexes: Physical isolation simplifies compliance audit and hard per-tenant deletion at higher idle RAM/metadata overhead, while pooled RLS with iterative HNSW pre-filtering maximizes hardware density across thousands of SMB tenants.
Failure modes
- Client-supplied or LLM-chosen
tenant_idparameters: Letting JSON tool schemas emit"tenant_id": "acme"invites cross-tenant IDOR immediately upon indirect prompt injection. - Global semantic cache collisions: Skipping
acl_digestortenant_idin Redis vector cache keys leaks confidential HR/finance answers on semantically similar questions ("What was Q3 operating cash burn?"). - Naive post-filtering HNSW starvation: Filtering ACLs after top- ANN search drops legitimate tenant hits whenever sibling customers own denser corpus clusters.
- Unscrubbed OTel traces mixing customers: Exporting raw debug prompts into pooled telemetry exposes PII across support engineers lacking tenant authorization.
Operational checklist
- Negative cross-tenant isolation tests assert zero leaks across SQL, HNSW, BM25, Redis cache, and traces on every PR.
-
SET LOCALtransaction variables (PgBouncertransaction-pooling safe) inject tenant context without session state leaks. - Per-tenant
acl_epochintegers invalidate semantic caches immediately on permission revocations. - Customer exports and LLM eval replay fixtures apply identical RBAC & PII minimization gates.
- Deletion workflows purge derived vectors/caches synchronously and emit cryptographically hashed purge receipts.
Connected Practice
- Labs: /labs/rag-pipeline-visualizer, /labs/prompt-injection-threat-model
- Projects: /projects/production-rag-blueprint, /projects/governed-agent-reliability
Sources
- Multi-tenant isolation primary references:
nist-zero-trust,nist-privacy-framework,openai-data-controls,w3c-prov-overview
Follow the prerequisite-safe Production RAG Tour
Connect chunking, hybrid BM25 + dense retrieval, reranking, and evaluation concepts into a verifiable study sequence.
Subscribe to Engineering Briefings
Join AI systems engineers receiving architecture teardowns, benchmark notes, and new simulator releases. Unsubscribe anytime.
