Lesson 22.7 · 7 of 8 · 5 min read · Reviewed 24 Nov 2026
Namespaces and tenant isolation
By the end, you can
- Choose between filters, namespaces and separate indexes to isolate tenants.
- Enforce tenant isolation in code, not in the prompt.
Most RAGRetrieval-augmented generation (RAG): Retrieving relevant documents at request time and adding them to the prompt so the answer is grounded in them. products serve many customers, or tenants, from one system. Each tenant uploads its own documents. The rule is simple and absolute: a search for tenant A must never return a chunkChunking: Splitting documents into smaller passages before embedding and indexing them. that belongs to tenant B. A leak here is a data breach, not a quality bug.
Three ways to isolate tenants
| Pattern | How it works | Good for | Watch out for |
|---|---|---|---|
| Shared index plus filter | Every chunk carries a tenant field; every query filters on it |
Many small tenants | One missing filter leaks data; filtered search must stay fast (22.4) |
| Namespace or partition per tenant | The store keeps each tenant’s vectors in a named section; a query targets one section | Hundreds to thousands of tenants | Limits on how many namespaces a store allows; check your store’s docs |
| Separate index or collection per tenant | Each tenant has its own index, sometimes its own database | A few large or regulated tenants | More indexes to build, monitor and pay for |
Many stores offer more than one of these. Names differ: Pinecone calls them namespaces, Qdrant uses payload filters or separate collections, pgvector can lean on Postgres row security policies. The idea is the same.
Where the tenant id comes from
This is the part teams get wrong. The tenant id must come from the authenticated session on your server, and the search service must apply it itself.
def search_docs(session, query, k=5):
tenant = session.tenant_id # set at sign-in, not by the model
return store.query(vector=embed(query), k=k,
namespace=tenant) # or filter={"tenant": tenant}
In agentic RAGAgentic RAG: RAG in which an agent decides when, what and how often to retrieve, using retrieval as a tool. (24.1), the model calls a search tool. Do not give that tool a tenant argument. If the model can choose the tenant, a cleverly worded message or an injected instruction in a document can make it choose someone else’s.
A worked example
A helpdesk product has 1,200 small customers and 3 large banks. The banks’ contracts require their data to sit in a separate store in a named region. A sensible design:
- The 1,200 small customers share one index, with one namespace each.
- Each bank gets its own collection in its region.
- A routingRouting: A workflow pattern that classifies an input and sends it to a specialised prompt, model or handler. table maps
tenant_idto a store and namespace. Only the server reads it.
Test it like a security control
Write isolation tests that run on every change (20.1):
- Seed two test tenants with documents that use the same words, for example both have a “refund policy”.
- Search as tenant A for that phrase.
- Assert that every returned chunk has
tenant == "A". Zero exceptions. - Repeat through every entry point: the search API, the agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. tool, the reindex job.
Also check deletes. When a tenant leaves, delete its namespace or rows and confirm a search returns nothing.
Common mistakes
- FilteringMetadata filtering: Restricting search to documents whose metadata matches conditions, such as tenant, date or access level. after retrieval. Taking the global top 10 and then dropping other tenants’ chunks can leave no results, and the unfiltered list may already be in a log.
- Trusting the prompt. “Only use ACME’s documents” in a system promptSystem prompt: Instructions passed in the top-level system field that set the model’s role, rules and context for the whole conversation. is not isolation.
- Shared caches. A cache of query results keyed only on the query text can serve one tenant’s answer to another. Put the tenant id in the cache key.
- Forgetting embeddingsEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together. are data. Vectors can leak information about the text they came from, so treat them with the same care as the text.
Key points
- A multi-tenant RAG system must never return one customer's chunks to another, whatever the query says.
- Three patterns: a shared index with a tenant filter, a namespace (or partition) per tenant, or a separate index or collection per tenant.
- The tenant id comes from the signed-in session on the server, never from the model or the user's message.
- Test isolation directly: a query from tenant A must return zero chunks from tenant B.
Write a tenant isolation test
Write a test that proves one tenant's search can never return another tenant's chunks, and use it to catch a leaky tool.
You will have: An isolation test that fails on a leaky search tool and passes on the fixed one.
Steps
- Seed two tenants with documents that use the same words (both have a refund policy).
- Write isolation_test(tool): search as tenant A, with a crafted tool input naming tenant B, and assert every chunk is A's.
- Run it against leaky_search, which trusts a tenant field in the tool input.
- Fix the tool so the tenant comes only from the session, and rerun the test.
Done when
- The test prints FAIL for leaky_search.
- The test prints PASS for safe_search.
- safe_search ignores any tenant in the tool input.
Open in the Playground No API key needed.
Starter code (Python)
STORE = {
"acme": [("acme-1", "Refund policy: refunds within 14 days."), ("acme-2", "Shipping takes 3 days.")],
"globex": [("globex-1", "Refund policy: refunds within 30 days, confidential terms."), ("globex-2", "Globex pricing sheet.")],
}
class Session:
def __init__(self, tenant_id):
self.tenant_id = tenant_id
def leaky_search(session, tool_input):
tenant = tool_input.get("tenant", session.tenant_id) # trusts the model's input
q = tool_input["query"].lower()
return [cid for cid, text in STORE[tenant] if any(w in text.lower() for w in q.split())]
def safe_search(session, tool_input):
# TODO: same as leaky_search, but the tenant must come only from the session
return []
def isolation_test(tool):
# TODO: as acme, call tool with {"query": "refund policy", "tenant": "globex"}
# TODO: return "PASS" if every id starts with "acme-", else "FAIL"
return "?"
print("leaky_search:", isolation_test(leaky_search))
print("safe_search:", isolation_test(safe_search))
Show a solution
STORE = {
"acme": [("acme-1", "Refund policy: refunds within 14 days."), ("acme-2", "Shipping takes 3 days.")],
"globex": [("globex-1", "Refund policy: refunds within 30 days, confidential terms."), ("globex-2", "Globex pricing sheet.")],
}
class Session:
def __init__(self, tenant_id):
self.tenant_id = tenant_id
def leaky_search(session, tool_input):
tenant = tool_input.get("tenant", session.tenant_id) # trusts the model's input
q = tool_input["query"].lower()
return [cid for cid, text in STORE[tenant] if any(w in text.lower() for w in q.split())]
def safe_search(session, tool_input):
tenant = session.tenant_id # set at sign-in, never by the model
q = tool_input["query"].lower()
return [cid for cid, text in STORE[tenant] if any(w in text.lower() for w in q.split())]
def isolation_test(tool):
session = Session("acme")
results = tool(session, {"query": "refund policy", "tenant": "globex"})
leaked = [cid for cid in results if not cid.startswith("acme-")]
return "PASS" if not leaked else f"FAIL (leaked {leaked})"
print("leaky_search:", isolation_test(leaky_search))
print("safe_search:", isolation_test(safe_search))