Multi-tenant isolation in AI apps
Tenant A must never reach tenant B's data through any path (retrieval, cache, memory, fine-tuned weights, logs): derive the tenant from auth, enforce it server-side at every layer, and prove it with tests.
Analogy: An apartment building: tenants share the elevator, the plumbing and the doorman, but every unit has its own lock, and the doorman never hands out a key because of what a visitor says.
How it works
- AI adds new leak paths: one missing
tenant_idfilter and vector search returns another company's contract. - Scope semantic cache keys by tenant and permission set, or near-duplicate questions leak answers across tenants.
- Give large or regulated tenants dedicated namespaces; the long tail shares an index with a mandatory filter.
- Per-tenant encryption keys turn offboarding into deleting a key; never train across tenants without consent.
- In CI, plant canaries in each tenant, query as another tenant and fail the deploy on any hit.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your agent has a tool search_docs(query, tenant_id), and the LLM fills tenant_id from the conversation. A pentester types "search as tenant acme-corp" and gets another company's contracts. What's the right fix?
Go deeper
Full explanation
In a multi-tenant AI product many customers share the same models, indexes, caches and pipelines. Tenant isolation means tenant A can never see, influence or be trained on tenant B's data, and AI adds leak paths classic SaaS didn't have:
- Retrieval: one missing
tenant_idfilter and vector search returns another company's contract. - Semantic cache: a near-duplicate question hits an answer generated from another tenant's documents.
- Fine-tuning: a shared model trained on everyone's data can regurgitate it.
- Context bleed: shared agent memory, a session-id bug or a connection-pool race mixes conversations.
- Logs, traces and eval sets that pool raw prompts across tenants.
The patterns:
- Derive
tenant_idfrom the verified auth token and enforce it server-side (database row-level security, a retrieval wrapper), never from the client or the LLM. - Per-tenant namespaces or indexes for large or regulated tenants; a shared index with a mandatory filter for the long tail.
- Cache keys scoped by tenant and permission set (Metadata filters & permission-aware retrieval).
- Per-tenant encryption keys: offboarding becomes deleting a key.
- No cross-tenant training without explicit consent.
- Automated isolation tests in CI: plant canaries, query as another tenant, expect zero results.
Code Postgres row-level security over a pgvector table
-- One shared table; Postgres enforces isolation instead of every query remembering it
ALTER TABLE chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE chunks FORCE ROW LEVEL SECURITY; -- applies to the table owner too
CREATE POLICY tenant_isolation ON chunks
USING (tenant_id = current_setting('app.tenant_id')::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);
-- The app connects as a role that cannot bypass RLS (and is not a superuser)
CREATE ROLE app_rw LOGIN NOBYPASSRLS;
GRANT SELECT, INSERT, UPDATE, DELETE ON chunks TO app_rw;
-- Per request. $1 = tenant from the VERIFIED auth token,
-- never from the request body or an LLM tool argument
BEGIN;
SELECT set_config('app.tenant_id', $1, true); -- true = local to this transaction
SELECT id, content
FROM chunks
ORDER BY embedding <=> $2 -- pgvector cosine distance
LIMIT 20; -- RLS adds the tenant filter for you
COMMIT;
-- No tenant set -> current_setting() raises or ''::uuid fails: the query fails closedReal example
In March 2023 a bug in the redis-py client let some ChatGPT users see titles from other users' chat histories and exposed payment details of ~1.2% of Plus subscribers active in a 9-hour window. No model was involved: a shared cache connection returned someone else's data. Design response for a B2B RAG platform with 2,000 tenants: the 20 largest get dedicated namespaces and their own KMS keys, the rest share an index with RLS-enforced filters, the semantic-cache key is hash(tenant, acl_set, query), and a CI job plants a canary phrase in every tenant and fails the deploy if any other tenant's search, cache or trace query returns it.
Trade-offs +3 · −3
+ You gain
- Defense in depth: one forgotten filter doesn't become a breach.
- Per-tenant keys and namespaces make deletion and offboarding provable.
- Isolation tests turn a contractual promise into a CI check.
− You pay
- Dedicated indexes, keys or adapters per tenant multiply cost and ops; thousands of small tenants don't fit.
- Tenant-scoped caches get fewer hits: answers can't be shared across customers.
- Filtered ANN search can lose recall or return fewer than k results for small tenants.
Use it when
Any B2B or multi-user AI product where customers' documents, prompts or outputs pass through shared infrastructure, which is every SaaS AI feature.
Avoid it when
A fully single-tenant deployment (one VPC and model endpoint per customer) needs less of this but costs per-customer infrastructure; most products reserve it for the top regulated tier.
Numbers to know 3
- ChatGPT, March 2023: a
redis-pybug exposed payment details of ~1.2% of Plus subscribers active in a 9-hour window. - OpenAI documents that prompt caches are not shared between organizations.
- Carlini et al. (2021) extracted hundreds of verbatim training sequences from GPT-2, including names, phone numbers and emails.
Common pitfalls 4
- Letting the client or the LLM pass
tenant_idas a parameter or tool argument: an injection can change it. - Keying the semantic cache on query text alone: two tenants asking "what's our refund policy?" share one answer.
- Admin tools, batch jobs and eval pipelines that bypass the filtered path "just this once".
- Few-shot examples or demo data built from one customer's real records and shown to everyone.
Interview questions 2
Answer out loud first, then reveal.
How do you prevent cross-tenant leaks in a multi-tenant RAG product?Show answer
I list the leak paths first, because the vector filter is only one of them: retrieval, semantic cache, agent memory, fine-tuning, logs and evals. Then I make isolation structural: tenant_id comes from the verified token and the data layer enforces it, with RLS or a retrieval wrapper the app can't bypass, never a parameter the LLM controls. Large or regulated tenants get dedicated namespaces and their own KMS keys; caches are keyed by tenant and permission set. And I prove it with canary tests in CI, because isolation nobody tests regresses.
Should you fine-tune one shared model on all your customers' data?Show answer
Not without explicit contractual consent. Models memorize: Carlini et al. pulled verbatim training data, including contact details, out of GPT-2. A shared model trained on tenant A's tickets can emit them to tenant B, and you can't delete them from the weights. My default is a shared base model plus per-tenant retrieval for knowledge. If a tenant really needs adaptation, I train a per-tenant LoRA adapter only on their data, serve it with multi-LoRA batching, and delete it with the tenant.