Artag.dev
AI Agents & SecurityPublished: 2026-11-12Updated: 2026-11-2112 min read

Secure Multi-Tenant RAG Architecture: Data Isolation in Enterprise AI Agents

How to prevent cross-tenant context leaks in SaaS AI platforms using PostgreSQL Row-Level Security (RLS), hybrid pgvector + lexical retrieval (RRF), and automated isolation tests in CI.

RAGMulti-TenantPostgreSQL RLSpgvectorAI Security
RLS
Engine-enforced isolation
0
Cross-tenant leaks tolerated
Hybrid
Vector + Lexical RRF

The number-one engineering risk in a multi-tenant Retrieval-Augmented Generation (RAG) platform is not robotic phrasing—it is a snippet from Customer A's pricing sheet or internal contract leaking into Customer B's agent response. In prototypes, adding `WHERE tenant_id = $1` to a vector query looks sufficient. In production systems with dozens of endpoints, background workers, and fast iteration cycles, relying solely on application-layer filtering is an incident waiting to happen.

In this note, I lay out the multi-tenant RAG architecture we deploy in production: database-enforced isolation using PostgreSQL Row-Level Security (RLS), hybrid vector plus lexical search via Reciprocal Rank Fusion (RRF), strict separation between authenticated session context and LLM tool arguments, and automated cross-tenant canary tests running on every pull request.

Why application-only tenant filtering fails in multi-tenant AI

Across a real AI backend there are at least four places where tenant boundaries can silently break: a missing `WHERE` clause in a new SQL query, a shared cache key, a misconfigured external vector store namespace, or an indirect prompt-injection payload tricking a tool call into passing another organization's ID.

Defense in depth assumes application code will eventually contain a bug. When we push tenant enforcement down into PostgreSQL Row-Level Security and bind `app.current_tenant_id` strictly from verified server-side session credentials—never from LLM-generated arguments—even an unfiltered `SELECT * FROM rag_chunks` returns exclusively the active tenant's rows.

Enforcing Row-Level Security (RLS) with pgvector in PostgreSQL

Running `pgvector` inside PostgreSQL keeps transactional metadata, access control, and vector embeddings inside a single ACID boundary. You eliminate eventual-consistency lag and permission drift between your primary database and a separate vector SaaS.

Two operational details make RLS bulletproof: enable `FORCE ROW LEVEL SECURITY` while connecting with a non-superuser role that lacks `BYPASSRLS`, and always scope the tenant setting with `set_config(..., true)` (transaction-local) inside an explicit `BEGIN`/`COMMIT` block so pooled connections never leak state to subsequent requests.

migrations/021_rag_rls_isolation.sqlsql
CREATE TABLE rag_chunks (
  id           UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id    UUID NOT NULL,
  document_id  UUID NOT NULL,
  chunk_index  INTEGER NOT NULL,
  content      TEXT NOT NULL,
  tsv          TSVECTOR GENERATED ALWAYS AS (to_tsvector('english', content)) STORED,
  embedding    vector(1536) NOT NULL,
  metadata     JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at   TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_rag_chunks_tenant_hnsw
  ON rag_chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX idx_rag_chunks_tsv ON rag_chunks USING gin (tsv);

-- Enable and force Row-Level Security
ALTER TABLE rag_chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE rag_chunks FORCE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation_policy ON rag_chunks
  USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid)
  WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);

Structure-aware chunking and hybrid retrieval (Vector + Lexical RRF)

Pure dense vector search handles synonyms and natural phrasing well, yet struggles with exact SKU codes, invoice IDs, or niche domain acronyms. PostgreSQL full-text search (`tsvector`) excels at exact identifiers but misses paraphrases. Fusing both ranked lists via Reciprocal Rank Fusion (RRF) inside a single SQL CTE gives reliable recall across both query styles without adding another search cluster.

For ingestion, we avoid blind fixed-character slicing. Documents are split along structural boundaries—Markdown headings, tables, and complete paragraphs—into 350–500 token chunks with 15% overlap, prepending the document title and parent heading to every chunk so each vector carries unambiguous context.

src/ai/rag/tenant-rag.repository.tstypescript
import type { Pool } from "pg";

export interface RetrievedChunk {
  id: string;
  documentId: string;
  content: string;
  rrfScore: number;
}

export async function searchTenantKnowledge(
  pool: Pool,
  tenantId: string,
  queryText: string,
  queryEmbedding: number[],
  limit = 6
): Promise<RetrievedChunk[]> {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    // Transaction-scoped tenant context (safe under connection pooling)
    await client.query("SELECT set_config('app.current_tenant_id', $1, true)", [tenantId]);

    const vectorLiteral = `[${queryEmbedding.join(",")}]`;
    const { rows } = await client.query<RetrievedChunk>(
      `WITH vector_rank AS (
         SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> $1::vector) AS rank
           FROM rag_chunks
          ORDER BY embedding <=> $1::vector
          LIMIT 25
       ),
       lexical_rank AS (
         SELECT id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(tsv, plainto_tsquery('english', $2)) DESC) AS rank
           FROM rag_chunks
          WHERE tsv @@ plainto_tsquery('english', $2)
          LIMIT 25
       )
       SELECT c.id,
              c.document_id AS "documentId",
              c.content,
              COALESCE(1.0 / (60 + v.rank), 0) + COALESCE(1.0 / (60 + l.rank), 0) AS "rrfScore"
         FROM rag_chunks c
         LEFT JOIN vector_rank v ON v.id = c.id
         LEFT JOIN lexical_rank l ON l.id = c.id
        WHERE v.id IS NOT NULL OR l.id IS NOT NULL
        ORDER BY "rrfScore" DESC
        LIMIT $3`,
      [vectorLiteral, queryText, limit]
    );

    await client.query("COMMIT");
    return rows;
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}

Automated cross-tenant isolation and groundedness tests in CI

Multi-tenant security cannot live only in architecture slides—it must be continuously asserted in CI. Our integration suite seeds synthetic canary tokens into Tenant A and executes identical vector and lexical queries under Tenant B's session, plus an unauthenticated query with no `app.current_tenant_id` set to prove fail-closed behavior.

Beyond database-level assertions, we verify connection-pool hygiene under concurrent load. By firing parallel queries for Tenant A and Tenant B across a small `pg.Pool` (size 2) and inspecting every returned chunk's `tenant_id`, we prove that `set_config('app.current_tenant_id', ..., true)` never bleeds across pooled connections even when one transaction rolls back mid-flight.

Alongside isolation tests, we run groundedness evaluations verifying that the agent only cites facts present in retrieved chunks, refuses to extrapolate missing prices or contract terms, and ignores adversarial instructions embedded inside untrusted uploaded documents.

  • Fail-closed assertion: querying `rag_chunks` without `app.current_tenant_id` must always return 0 rows.
  • Cross-tenant canary test: searching Tenant A's exact secret string under Tenant B's session must return 0 matches.
  • Pool concurrency test: alternating Tenant A and Tenant B queries over a constrained pool must produce zero cross-tenant hits.
  • Tool boundary rule: `tenantId` is never exposed in the LLM tool JSON Schema; it is injected exclusively from authenticated server context.

Closing thoughts: structural safety for enterprise AI

Consolidating PostgreSQL, pgvector, and Row-Level Security eliminates an entire class of catastrophic multi-tenant data leaks while keeping your infrastructure footprint small. If you are designing or auditing a production RAG system over sensitive business data, visit our Production AI Engineering, RAG Pipelines & Autonomous Agents page to see how we build these pipelines end to end.

Next architectural step

Production AI Engineering, RAG Pipelines & Autonomous Agents

Want to apply this architecture in your stack? Reach out at info@artagdev.com.co or review the full deliverables of our dedicated service.