Two customers upload similar contracts. When one customer asks about renewal terms, which clauses is the search system allowed to pass to the model? Multi-tenant RAG data isolation in web apps starts with that question, before ranking passages or drafting an answer.

Treat permission and relevance as separate decisions. The authenticated request establishes which documents the user may read. Vector search ranks passages within that boundary. A restrictive search can return too few relevant passages, but low recall is not evidence of unauthorized access. Conversely, a fluent answer with a correct citation is a failed result if the cited contract belongs to another customer.

A stencil exposes one passage from a stack of document cards, illustrating permission filtering before retrieval.

To build secure retrieval foundations, examine our technical breakdown of RAG access control and preventing permission leaks, inspect implementation patterns in PostgreSQL pgvector hybrid search, check caching tenant boundaries in semantic caching with Redis, and review tool isolation in MCP server security hardening.

How Do You Prevent Cross-Tenant Data Leaks in Multi-Tenant RAG?

Treat unauthorized disclosure as an incident. Preserve the evidence and involve your privacy and legal leads. Notice obligations depend on the data, jurisdiction, contracts and facts; a SOC 2 report is not a blanket notification rule.

Preventing cross-tenant leakage requires moving beyond naive application-layer filtering to structural database guarantees:

  1. Defense-in-Depth Query Enforcement: Never rely solely on application developers remembering to append .filter({ tenant_id: user.tenantId }) in backend controllers. Without another enforcement layer, an omitted filter can expose documents from another account.
  2. Database-Native Row-Level Security (RLS): Enforce tenant isolation at the database level using PostgreSQL Row-Level Security paired with FORCE ROW LEVEL SECURITY and a non-superuser application role. Use a non-owner role without BYPASSRLS or policy-management privileges. The policy must compare rows to a trustworthy tenant identity.
  3. Tenant-Prefixed Cache and Embedding Keys: Separate caches and lookup keys by authenticated tenant. Within one tenant, share cached answers only among users with equivalent access, or reauthorize every source document on each hit. Invalidate entries when access changes.

A cached answer sits inside a notched sleeve beside two key tabs representing tenant identity and document permissions.

Should You Use Metadata Filtering or Isolated Vector Collections per Tenant?

When choosing an architectural pattern for multi-tenant vector storage, engineering teams evaluate three structural models:

1. Isolated Vector Indexes per Tenant (Silo Model)

In this model, each tenant receives a physically separate vector table, schema, or dedicated collection index.

  • Pros: Separate storage can simplify tenant-specific access grants and offboarding. It is a permission boundary only if the credentials used for one tenant cannot read another tenant’s data. Backups and caches still need a retention plan.
  • Cons: Severe resource fragmentation. Maintaining thousands of separate HNSW graphs multiplies memory overhead, file descriptors, and connection-pool pressure.
  • Verdict: Best for regulated enterprise tiers (healthcare, finance, legal) that contractually require dedicated storage isolation.

2. Shared Table with Database-Enforced Filtering

All document chunks reside in a shared table (or declarative PostgreSQL partitions) keyed by tenant_id.

  • Pros: High memory efficiency, simpler schema migrations, and predictable scaling across thousands of mid-market tenants.
  • Cons: Requires careful query planning and pgvector index tuning so restrictive tenant filters do not starve LIMIT k recall.
  • Verdict: Recommended for standard multi-tenant B2B SaaS applications when enforced with PostgreSQL Row-Level Security.

3. Application-Layer Post-Filtering (Anti-Pattern)

The vector engine executes an unconstrained similarity search across all documents, and application code filters out unauthorized chunks after retrieval.

  • Fatal Flaw: Never use post-filtering. If the top 20 nearest neighbors belong to another tenant, post-filtering discards all 20 hits, returning zero context to the active user while wasting recall budget and leaking cross-tenant latency differences.

PostgreSQL Row-Level Security (RLS) attaches access predicates directly to a table so every SELECT, INSERT, UPDATE, and DELETE automatically enforces tenant ownership.

In multi-tenant RAG systems, the application sets a transaction-scoped configuration parameter immediately after acquiring a connection: SET LOCAL app.current_tenant_id = 'tenant_corp_8841';

The database policy uses NULLIF so an unset or empty session variable evaluates to NULL and matches zero rows: CREATE POLICY tenant_isolation_policy ON document_embeddings USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), ''));

One critical operational rule: by default in PostgreSQL, table owners bypass RLS unless ALTER TABLE ... FORCE ROW LEVEL SECURITY; is set, and roles with SUPERUSER or BYPASSRLS always bypass it. Always run application traffic under a dedicated non-superuser role with NOBYPASSRLS and enable FORCE ROW LEVEL SECURITY on every vector table.

With RLS active, even if an application query omits WHERE tenant_id = ..., PostgreSQL injects the tenant predicate automatically. Note what happens inside the index: a standard HNSW index built on (embedding) does not contain tenant_id inside the graph itself. With an approximate pgvector index, filters can discard candidates after the index scan. The planner can also choose another path, such as a tenant index followed by a distance sort. Check the actual plan rather than assuming tenant checks happen inside the HNSW graph.

{
  "illustrative_rls_query_trace": {
    "authenticated_tenant": "tenant_enterprise_7719",
    "query_embedding_model": "text-embedding-3-small",
    "rls_policy_enforced": "tenant_isolation_policy",
    "hnsw_iterative_scan": "relaxed_order",
    "chunks_returned": 5,
    "security_violation_count": 0
  }
}

Index Partitioning Strategies and Query Execution Plans

When querying multi-tenant vector tables, choosing the right index strategy is necessary for both recall and latency. The HNSW search candidate list is sized by hnsw.ef_search. Filtering can leave fewer than LIMIT k eligible rows even when the tenant has enough matching documents.

To solve this, use iterative scanning or partitioning:

  1. Iterative Index Scans in pgvector 0.8.0+: Starting in pgvector 0.8.0, setting SET LOCAL hnsw.iterative_scan = 'relaxed_order'; (or 'strict_order') instructs the HNSW index to continue traversing the graph until LIMIT k rows satisfy the WHERE / RLS predicate, or the scan reaches a work or memory limit. The default 20,000-tuple limit is approximate and excludes the initial scan. Relaxed ordering allows small departures from distance order.
  2. Partition by List or Hash: A list partition can dedicate an index to one large tenant. A hash partition typically holds several tenants. Neither scheme replaces permissions.

A search circle captures two of six stars among many dots, illustrating how a search can miss a small tenant’s relevant passages.

PostgreSQL RLS Schema and Query Pattern

This example assumes a trusted backend derives the tenant from authenticated membership and binds the query vector as a 1,536-dimensional parameter. The application role must not accept arbitrary SQL from clients. A transaction setting carries an identity decision; it does not authenticate anyone. The policy below separates tenants, not users within a tenant. Apply document permissions before returning passages to users who have different access within the same account.

-- 1. Enable pgvector and create the multi-tenant embeddings table
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE tenant_document_chunks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(64) NOT NULL,
    document_id UUID NOT NULL,
    chunk_index INTEGER NOT NULL,
    content TEXT NOT NULL,
    metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
    embedding vector(1536) NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- 2. Build tenant B-tree and vector HNSW indexes
CREATE INDEX idx_chunks_tenant ON tenant_document_chunks(tenant_id);
CREATE INDEX idx_chunks_vector ON tenant_document_chunks
    USING hnsw (embedding vector_cosine_ops)
    WITH (m = 16, ef_construction = 64);

-- 3. Enable AND force Row-Level Security (blocks table-owner bypass)
ALTER TABLE tenant_document_chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE tenant_document_chunks FORCE ROW LEVEL SECURITY;

-- 4. Create the tenant isolation policy (empty/unset setting fails closed)
CREATE POLICY tenant_isolation_policy ON tenant_document_chunks
    FOR ALL
    USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), ''))
    WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), ''));

-- 5. Safe query execution inside a transaction as a non-superuser app role
BEGIN;
  SET LOCAL app.current_tenant_id = 'tenant_corp_8841';
  SET LOCAL hnsw.iterative_scan = 'relaxed_order';

  SELECT id, document_id, content,
         (embedding <=> $1::vector) AS distance
  FROM tenant_document_chunks
  ORDER BY embedding <=> $1::vector
  LIMIT 5;
COMMIT;

Four-Stage Multi-Tenant AI Isolation SOP

Engineering teams deploying multi-tenant generative software should structure security governance across four phases:

Phase 1: Security Model Definition and Tenant Tiering

  • Classify customer data tiers: shared multi-tenant with forced RLS, partitioned tenant groups, and dedicated single-tenant schemas or databases.
  • Ban application-only post-filtering and require non-superuser application roles (NOBYPASSRLS).
  • Review contractual data residency and deletion SLAs across client jurisdictions.

Phase 2: RLS Implementation and Connection Pool Hardening

  • Enable and force PostgreSQL Row-Level Security across all tables storing chunks, embeddings, metadata, and chat transcripts.
  • Always wrap SET LOCAL app.current_tenant_id inside an explicit transaction block when running behind transaction-mode connection poolers such as PgBouncer so session variables never bleed to the next tenant’s pooled query.
  • Never set tenant identity at session scope: after the transaction ends, the previous setting is restored. Verify that missing context returns no rows and that an unauthorized tenant request is rejected before the backend assigns any context.

Phase 3: Index Calibration and Performance Profiling

  • Measure latency and inspect query plans on skewed tenant sizes, such as 50 chunks versus 500,000. For recall, compare returned IDs with the exact nearest eligible passages under identical permissions. A fast plan is not a relevance score.
  • Tune hnsw.max_scan_tuples and hnsw.scan_mem_multiplier (or partition large tenants) when small tenants fail to fill LIMIT k.
  • Alert on unexpected sequential scans or dropped recall in production logs.

Phase 4: Continuous Audit Logging and Offboarding Verification

  • Log every vector retrieval event with authenticated tenant ID, user ID, document ACL filter, and row count returned.
  • Run adversarial prompt-injection and tool-call boundary tests to ensure prompts cannot override session tenant context.
  • Automate full tenant deletion across Postgres tables, Redis semantic caches, and object storage on offboarding.

One tenant’s record card is removed from its slot while three neighboring cards remain in their sleeves.

Conclusion

Multi-tenant data isolation is a baseline requirement before any B2B RAG system touches customer documents. Application-layer .filter() clauses fail the first time an engineer writes a raw query or refactors an endpoint. Enforcing FORCE ROW LEVEL SECURITY under a NOBYPASSRLS database role, scoping SET LOCAL per transaction for pooled connections, and pairing HNSW indexes with pgvector 0.8.0+ iterative scans or partitioning gives teams verifiable tenant boundaries at scale.

Planning a customer-facing search rollout? Discuss your architecture with Veduis using a data-flow diagram and one access rule you need to demonstrate. Do not send customer documents.