IamBishal

Filter Before You Rank: Multi-Tenant RAG Isolation, Measured

My secure RAG tutorial says to filter inside the retrieval query and back it with row-level security, and demonstrates it on two tiny tenants. So I measured it on thirty.

The secure RAG tutorial's isolation design, on a shared pgvector index of 30 tenants with real embeddings. Post-filtering found 4% of a tenant's answers; iterative scans found 98.5-100%. Each isolation layer caught the other's bugs.

of a tenant's answers found by post-filtering
4%
recall with pgvector's iterative scans
98.5-100%
injected bugs that leaked through both layers
0
unanswerable questions answered anyway
0 / 240
  • Experiment
  • 7 min read
  • AI Security
  • Evals & AgentOps
  • Python
  • PostgreSQL
  • pgvector
  • RAG
Figure 1. Recall by tenant size

Overview

My tutorial "Build a Secure RAG API" makes three claims a multi-tenant RAG API depends on: filter by tenant and role inside the retrieval query, before the top k are chosen, keeping k results with pgvector's iterative scans; back that filter with row-level security, with an app role that doesn't own the tables and a principal that lasts one transaction; and refuse before calling the model when nothing relevant was found. Its companion code demonstrates each on two tenants with a fake embedder.

This experiment measures them where they matter: one pgvector index shared by 30 synthetic tenants, from one holding a third of the index down to tenants under a quarter of a percent, all writing about the same 32 support topics in their own products and numbers. Real Voyage embeddings, real PostgreSQL 18, the tutorial's schema, roles and policies, on a throwaway database the harness creates and drops.

Three studies: where the filter goes (recall against an exact scan, checked with numpy, for 287 questions); which layer catches which bug (the tutorial's cross-tenant probe under six bugs and three defences); and refusals and citations (100 questions answered by Claude with the tutorial's prompt). The first two need no model. About USD 0.50 in all.

The retrieval and isolation claims all held, more sharply than I expected: filtering inside a plain HNSW query was exactly as bad as post-filtering a top-40, and RLS alone was worse than the explicit filter for the largest tenant. The refusal claim had nothing to test: neither model ever answered an unanswerable question, so the threshold could only turn good answers away.

Did it hold up?

Full results

The hypothesis, written down before the first run, and what the results said.

  1. Confirmed

    Post-filtering after a global top-k starves small tenants; oversampling softens it without fixing it.

    4% recall overall, 1.7% for small tenants; oversampling 4x reached 14%.

  2. Confirmed

    Filtering inside the HNSW query without iterative scans under-returns; iterative scans restore k results.

    Without them, exactly as bad as post-filtering a top-40 (14%); with them 98.5-100%.

  3. Confirmed

    RLS alone behaves like a post-filter on an HNSW index: a backstop, not the retrieval filter.

    It matched the in-query filter on HNSW, and did worse for the largest tenant (57% vs 79%).

  4. Confirmed

    Each isolation layer alone misses a bug the other catches.

    The matrix matched the tutorial cell for cell; no injected bug leaked through both layers.

  5. Wrong

    Without a similarity threshold the model sometimes answers what its chunks don't support.

    0 of 240 unanswerable questions were answered; a threshold could only refuse good answers.

  6. Not testable

    The citation check is a floor: some answers cite valid chunks that don't contain the fact.

    No invalid or unsupported citations occurred in 400 answers, so the check had nothing to catch.

What it does

  • One pgvector index shared by 30 tenants, from 32.8% of the index down to 0.23%
  • The tutorial's schema, roles and RLS policies on a throwaway PostgreSQL 18 database
  • Recall@k for post-filtering, in-query filtering, iterative scans and RLS alone
  • An exact scan checked against numpy on every one of 1,148 query runs
  • The cross-tenant probe under six injected bugs and three defences, with controls
  • Refusals and citations graded against facts known by construction
  • An offline threshold sweep from the same model runs
  • Database tests that create and drop everything they touch

How it's built

  1. Inputs

    • 30-tenant corpus10,974 chunks, real embeddings
    • The tutorial's schemaRoles, RLS, NULLIF, FORCE
  2. Three studies

    • Where the filter goes
    • Iterative scans vs not
    • RLS as the only filter
    • Six bugs x three defences
    • Refusals and citations
  3. Outputs

    • Recall by tenant size1,148 runs vs exact
    • Isolation matrixLeaked, blind or safe
    • Refusal sweep400 answers
db.py and study_a.py
-- db.py: the tutorial's row-level security policy. NULLIF turns a cleared setting ('') into NULL:
-- a connection without a principal sees no rows instead of raising an error.
ALTER TABLE chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE chunks FORCE ROW LEVEL SECURITY;          -- the table owner obeys it too
CREATE POLICY tenant_isolation ON chunks FOR SELECT TO fbr_app USING (
  tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid
  AND allowed_roles && string_to_array(NULLIF(current_setting('app.roles', true), ''), ','));

-- study_a.py: filter before you rank. Without iterative scans, HNSW hands back ef_search (40)
-- candidates and the WHERE clause filters only those: post-filtering by another name.
BEGIN;
SET LOCAL hnsw.iterative_scan = relaxed_order;
SELECT id FROM chunks
WHERE tenant_id = $1 AND allowed_roles && ARRAY[$2]::text[]
ORDER BY embedding <=> $3 LIMIT 10;
COMMIT;

Figures

Figure 1. Recall by tenant size1 of 3

What I learned

  • Filter before you rank, and check the plan. A top-10 filtered in the app found 4% of a tenant's answers, under 2% for small tenants.
  • A WHERE clause on a plain HNSW scan is post-filtering in disguise: it filters only the ef_search candidates. Iterative scans fixed it (98.5-100%).
  • The planner rescues small tenants with an ordinary index, but not the biggest one: the largest tenant lost 21% of its results.
  • RLS is a backstop, not a retrieval filter. Alone, it did worse than the explicit WHERE for the largest tenant.
  • Two layers cover each other: no injected bug leaked through both, though a stale session setting left callers blind.
  • A transaction can outlive its request: outside autocommit, my SET LOCAL survived the request it belonged to.
  • A strict refusal rule can cost more than it saves: no model confabulated, but Sonnet refused 12 questions its chunks answered.

Next steps

  • Raise ef_search and compare its recall and latency with iterative scans
  • Near-miss questions, to give the threshold and the citation check something to catch
  • A prompt that allows a general answer when every chunk agrees
  • Larger corpora and real tenant distributions

Run it yourself

Everything on this page comes from code and data in the repository. The dry run is free and needs no API key. A full live rerun costs about USD 0.50.

Terminal
git clone https://github.com/bishal-saha/ai-lab-code.git
cd ai-lab-code/multi-tenant-rag-isolation-benchmark
uv sync
export DATABASE_URL_ADMIN=postgresql://postgres@localhost:5432/postgres
uv run filter-before-rank --dry-run       # fake embedder and model, $0
mv results results-published
cp .env.example .env                      # ANTHROPIC_API_KEY, VOYAGE_API_KEY
uv run --env-file .env filter-before-rank --max-usd 3
uv run python -m fbr.report

Bishal SahaLet's build together

Have a system to design, or an AI feature to get right?

Tell me about the problem. You'll get a clear, honest view of the best way forward.

  • Reply within 24 hoursOn business days, with my honest view and a next step.
  • Accepting select engagementsArchitecture, AI features and full builds.
  • Remote, worldwideWorking with startups, SMEs and enterprises.