← All articles
RAG
Security
Multi-tenancy

Tenant isolation in RAG: enforce it at the retrieval layer

· 7 minute read · Pivot-al

A multi-tenant product adds an assistant. Documents from every customer are chunked, embedded and written to one vector index. The system prompt says: "Only use information belonging to the current customer." It works in a demo. Then in testing someone asks a broad question, and the answer includes a detail from another customer's contract.

This is a common and serious defect in multi-tenant RAG systems, and it has one root cause: isolation was expressed as an instruction to the model instead of a constraint on the data the model can see.

Why the prompt does not isolate anything

Similarity search has no concept of ownership: it returns the nearest vectors to the query. If two customers have similar documents, and customers of the same product usually do, the nearest chunks to a question will often belong to someone else.

Consider what the model is working with once a foreign chunk is in the context window:

  • The model has no reliable way to know which tenant a chunk belongs to unless it is labeled, and a label is only more text.
  • An instruction to ignore some of the context is a request the model usually honors, with no guarantee that it will. Paraphrase, summarization and "what else do you know about X" all weaken it.
  • Any prompt injection in a retrieved document or user message can ask the model to disregard the instruction.

A system prompt shapes behavior, but it is not an access control. If the wrong data reached the context, the isolation failure has already occurred, whatever the model then says.

In a representative, anonymized teardown we ran of a Series B B2B SaaS company, the internal assistant retrieved across customer tenants in testing. It takes no unusual mistake to get there. A shared index and a retrieval call without an enforced tenant constraint are enough.

Enforce the filter in retrieval

There are three places to enforce isolation. They are not alternatives; stronger systems use more than one.

Metadata filters

Every chunk carries a tenant_id written at ingestion. Every query applies a filter on it. This is the cheapest option and works on a shared index.

Two details decide whether it holds:

The filter must be applied inside the search, not after it. If the store returns the global top k and the application then discards other tenants' chunks, a tenant with few documents can get zero results because the top k were all someone else's. Worse, the filtering now lives in application code, where the next developer can forget it. Use a store that applies the filter as part of the query.

The filter must not be optional. Do not expose a search function that takes an optional filter argument. Wrap the store in a client that cannot be constructed without a tenant:

class TenantRetriever:
    def __init__(self, store, tenant_id: str):
        if not tenant_id:
            raise ValueError("tenant_id is required")
        self._store = store
        self._tenant_id = tenant_id

    def search(self, query_vector, k: int = 8, extra_filter: dict | None = None):
        # Caller-supplied filters are merged first; the tenant constraint
        # is applied last and cannot be overridden.
        flt = {**(extra_filter or {}), "tenant_id": self._tenant_id}
        return self._store.search(query_vector, k=k, filter=flt)

Then make this the only path to the store. A lint rule or an import restriction that forbids using the raw store client outside this module is worth the hour it takes.

Per-tenant indexes or namespaces

A stronger boundary is physical or logical partitioning: one index, collection or namespace per tenant. A query is addressed to a namespace, so a missing filter produces an error or an empty result instead of a leak.

The trade-offs are operational. Many small indexes cost more to manage, and questions that legitimately span tenants, such as internal analytics, need a separate, explicitly privileged path. For most B2B products with strict customer boundaries, that cost is acceptable. Larger or regulated customers sometimes require it contractually.

Row-level security at the source

If chunks live in a relational database with a vector extension, or if retrieval joins back to source records, the database can enforce isolation itself. In PostgreSQL:

ALTER TABLE chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE chunks FORCE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON chunks
  USING (tenant_id = current_setting('app.tenant_id')::uuid);

The application sets the tenant for each transaction:

BEGIN;
SELECT set_config('app.tenant_id', $1, true);  -- true = transaction-local
SELECT id, content FROM chunks ORDER BY embedding <=> $2 LIMIT 8;
COMMIT;

Things to get right:

  • Without FORCE, the table owner bypasses the policy. Superusers and roles with BYPASSRLS always bypass it. The application should connect as a role with neither.
  • Use the transaction-local setting. With a connection pool, a session-level setting can outlive the request and be inherited by the next one.
  • If the setting is missing, the query raises an error, and it should stay that way: a request with no tenant should fail instead of seeing everything.

Row-level security has one more advantage: it covers code paths you forgot. A new retrieval feature, a debugging endpoint or a reranking query written next quarter inherits the policy without anyone remembering to add a filter.

Propagate the caller's identity, not the service's

A common architecture has the assistant backend call the vector store, the document service and internal APIs with its own service credentials. Those credentials can read everything. Isolation then depends on every line of application code passing the right tenant, every time.

Carry the caller's identity through instead:

  • Resolve tenant and user from the authenticated session on the server. Never accept a tenant id from the request body, and never let the model supply it as a tool argument.
  • Pass that identity to every downstream call: retrieval, tool execution, source-document fetches.
  • Have each downstream system authorize against the caller, not the service.

The last point also covers permissions inside a tenant. Tenant isolation is the outer boundary; document-level access control is the inner one. A user who cannot open a document in the product should not get its contents through the assistant. Store the access attributes on the chunk at ingestion, keep them in sync when permissions change, and filter on them with the same mechanism.

This is how we run our own operations: our internal agent platform authorizes every tool call deny-by-default against the acting user's identity before anything executes. The same principle applies to tools in general, covered in securing agents that call tools.

Caching pitfalls

Caches are where well-built isolation leaks later, because they are added for performance by someone who is not thinking about access control.

  • Response and semantic caches. A cache that returns a stored answer for a similar question must include the tenant in its key or be partitioned per tenant. Two customers asking "what is our renewal date" must never share an entry.
  • Caches keyed by user but not by tenant. This one is easy to miss. If a user can belong to more than one tenant, such as a consultant, a support engineer or an admin of two workspaces, a per-user cache serves tenant A's answer while they are working in tenant B. Key by tenant and user, and name the cache so the convention is visible in code review.
  • Retrieval result caches. Same rule. Also include a version of the user's permissions, or invalidate on permission change, so revoked access does not persist until expiry.
  • Conversation memory. Long-lived memory or summaries are also a cache, so scope them to tenant and user.
  • Embedding caches. A cache from text to its embedding is safe to share, because the vector is a pure function of the text. The retrieved results are not.

A reasonable default: any cached value that depends on what the caller may see has the tenant in its key.

Tests that prove cross-tenant queries come back empty

Isolation that is not tested will regress, and testing it is cheap. The tests target retrieval, not the model, so they are deterministic.

Seed two fixture tenants. Give each a canary document containing a unique string that appears nowhere else. Then query each tenant for the other's canary.

import pytest

CANARY_A = "zx-canary-tenant-a-7f3e"
CANARY_B = "zx-canary-tenant-b-91c2"

def test_cross_tenant_retrieval_is_empty(store, embed):
    retriever_a = TenantRetriever(store, tenant_id=TENANT_A)
    results = retriever_a.search(embed(CANARY_B), k=20)

    assert all(r.metadata["tenant_id"] == TENANT_A for r in results)
    assert not any(CANARY_B in r.text for r in results)

def test_own_canary_is_found(store, embed):
    retriever_a = TenantRetriever(store, tenant_id=TENANT_A)
    results = retriever_a.search(embed(CANARY_A), k=20)

    assert any(CANARY_A in r.text for r in results)

def test_retriever_requires_tenant(store):
    with pytest.raises(ValueError):
        TenantRetriever(store, tenant_id="")

The second test matters as much as the first. Without it, a retriever that returns nothing passes the isolation test.

Extend the same pattern to every path that touches tenant data:

  • Each cache: write as tenant A, read as tenant B, expect a miss.
  • A user with membership in both tenants: results follow the active tenant, not the user.
  • Every retrieval entry point, including hybrid keyword search, rerankers and any "fetch full document by id" tool. Fetch-by-id is a frequent hole: the search is filtered and the follow-up fetch is not.
  • End to end: run a few cross-tenant probes through the full assistant and assert the canary never appears in the output. Put these in the critical tier of your evaluation harness so they block releases.

Run them in CI on every change to ingestion, retrieval or caching.

A short checklist

  • The tenant comes from the server-side session, never from the client or the model.
  • The retrieval client cannot be called without a tenant.
  • Filters are applied inside the search, or the data is partitioned, or the database enforces a policy. Preferably two of the three.
  • Downstream calls carry the caller's identity.
  • Every cache with caller-dependent content has the tenant in its key.
  • Canary tests cover every retrieval path and run in CI.

If you have a RAG system in production and are not certain how it would fare against this list, our Production AI Audit includes a red-team run that tests it directly. For a quicker conversation about your architecture, the teardown clinic is a free 30-minute session with a senior engineer.