FullStack AI Hub
Studio
Reference architecture

Multi-Tenant AI Data Isolation

End-to-end SaaS AI isolation spanning server-derived identity, PostgreSQL RLS, pre-filtered HNSW indexes, tenant-salted caches, traces, and GDPR deletions.

18 minVerified 2026-11-254 primary sources
Multi-Tenant AI Data Isolation
On This Page

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.

Intent and policy
Validated request
Controlled execution
Independent verification
Telemetry and response
Conceptual teaching model synthesized from:Zero Trust ArchitectureNIST Privacy FrameworkData Controls in the OpenAI PlatformPROV Overview

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

  1. 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 accept tenant_id inside tool arguments generated by the LLM.
  2. Pre-Filtered vs Partitioned Vector Search: Naive HNSW post-filtering retrieves global top-KK vectors first and drops forbidden tenants afterward—returning 0 results 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 (pgvector partitioned tables by tenant_id), or physical collection isolation.
  3. 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.
  4. Tool Execution & Brokered Secrets: Agent runtimes fetch short-lived scoped tokens (5m TTL) per tool call via a broker gateway; prompts and sandboxes never hold raw static DB/S3 credentials.
  5. 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.
  6. Cascade Deletion & Cryptographic Erasure (GDPR Art. 17): Source deletes propagate cleanly via W3C PROV lineage DAGs into SQL chunks, vector nodes, BM25 docs, and cache epoch invalidations; per-tenant DEKs inside S3 backups guarantee cryptographic erasure upon key destruction.
Architecture claim
Representative test
Production signal
Decision gate
Review or rollback
Conceptual teaching model synthesized from:Zero Trust ArchitectureNIST Privacy FrameworkData Controls in the OpenAI PlatformPROV Overview

2. Tenancy Topology Trade-Off Matrix

Tenancy ModelIsolation StrengthHNSW RAM & Cache EfficiencyGDPR Deletion ComplexityBest Workload Fit
Shared Table + Server RLS FiltersLogical DB/query gate (risk if bypassed)Highest density (1 index, high locality)Tombstone delete + async cache epoch bump10,000+ SMB SaaS workspaces with strict query gates
PostgreSQL List/Hash Partitions + Per-Tenant HNSWPhysical segment isolation per shardMedium (1 HNSW graph per shard)DROP PARTITION instant cleanup (O(1))Mid-market enterprise tiers (100–5,000 orgs)
Dedicated Schema / VPC / Customer KMS DEKCryptographic & physical blast isolationLow (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 settings
ALTER TABLE knowledge_chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE knowledge_chunks FORCE ROW LEVEL SECURITY;
​
CREATE POLICY tenant_acl_isolation ON knowledge_chunks
USING (
tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid
AND 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 starvation
BEGIN;
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_sim
FROM knowledge_chunks
ORDER BY embedding <=> $1::vector
LIMIT 12;
COMMIT;

Decisions

DecisionRequired evidenceReview 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 testsSchema 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 removalAdding 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_id parameters: Letting JSON tool schemas emit "tenant_id": "acme" invites cross-tenant IDOR immediately upon indirect prompt injection.
  • Global semantic cache collisions: Skipping acl_digest or tenant_id in 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-KK 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 LOCAL transaction variables (PgBouncer transaction-pooling safe) inject tenant context without session state leaks.
  • Per-tenant acl_epoch integers 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

Sources

  • Multi-tenant isolation primary references: nist-zero-trust, nist-privacy-framework, openai-data-controls, w3c-prov-overview
Guided Architecture Track

Follow the prerequisite-safe Production RAG Tour

Connect chunking, hybrid BM25 + dense retrieval, reranking, and evaluation concepts into a verifiable study sequence.

Weekly Engineering Dispatch

Subscribe to Engineering Briefings

Join AI systems engineers receiving architecture teardowns, benchmark notes, and new simulator releases. Unsubscribe anytime.