Multi-Tenant RAG Security in 2026: PostgreSQL RLS vs Qdrant vs Weaviate
A RAG system can return a beautifully relevant answer and still be catastrophically wrong if the retrieved document belongs to another customer. In a multi-tenant SaaS product, the security boundary is not the prompt, the embedding model, or the LLM. It is the authorization decision made before private context reaches the model.
This guide shows how to build that boundary deliberately. We compare PostgreSQL Row-Level Security (RLS) with pgvector, Qdrant multitenancy, and Weaviate multi-tenant collections; then build a tenant-aware retrieval path, test it against cross-tenant leakage, and plan for per-document permissions, deletion, and operational failures.
Last reviewed: November 27, 2026. The implementation patterns below are based on the official documentation linked throughout. They are reference designs, not a claim that a live production deployment was tested.
Who this guide is for
- Backend engineers building a multi-tenant knowledge assistant or document-search SaaS.
- AI engineers responsible for RAG retrieval, vector stores, and prompt assembly.
- Platform and security teams reviewing tenant boundaries, document ACLs, and deletion workflows.
Prerequisites
- Working knowledge of Python, SQL, HTTP APIs, and authentication tokens.
- A server-side identity layer that verifies users and resolves their organization membership.
- One retrieval backend: PostgreSQL with pgvector, Qdrant, or Weaviate.
- A small test corpus containing at least two tenants and documents with different visibility rules.
The rule that prevents the most dangerous mistake
Never trust a tenant ID supplied by the browser, chat message, model, or tool call. Verify the user's credential, resolve the tenant and user identity on the server, and derive every retrieval filter from that verified principal.
Imagine a customer asks, “What is the renewal date in our contract?” The vector search should not first search the entire corpus and ask the LLM to ignore other customers' contracts. It must search only the documents that this authenticated user is allowed to read. Unauthorized chunks must never enter the candidate context, reranker, model prompt, citation builder, or application response.
Quick decision: which backend should you choose?
| Approach | Best fit | Isolation mechanism | Main trade-off |
|---|---|---|---|
| PostgreSQL + pgvector + RLS | Your application already uses Postgres and needs relational permissions, joins, and transactions | Database policies restrict rows independently of the similarity query | RLS role design and filtered approximate-search behavior need careful testing |
| Qdrant | Vector-first workloads with many small tenants and a path to dedicated shards for large tenants | Tenant payload filters, tenant indexes, custom shards, or tiered multitenancy | A payload filter is not authentication; the application must enforce it on every operation |
| Weaviate | Teams that want explicit tenant-aware collections and a dedicated shard per tenant | Multi-tenant collection configuration and tenant-scoped client handles/queries | Tenant lifecycle, shard count, and resource overhead become operational concerns |
There is no universal winner. If the permission source of truth is already in Postgres, RLS is often the simplest place to enforce access. If vector search is the main data plane, Qdrant offers flexible shared-to-dedicated tenant layouts. If explicit per-tenant shard isolation is a strong fit, evaluate Weaviate's multi-tenancy model. In every case, application authentication and authorization remain mandatory.
Understand the security boundary before choosing a vector database
A production RAG request usually crosses several boundaries:
- Authentication: verify the token signature, issuer, audience, expiry, and required claims.
- Membership: confirm that the user still belongs to the requested organization and that the membership is active.
- Authorization: determine which documents, folders, groups, and classifications the user can read.
- Retrieval: apply those permissions inside the database query or vector-store filter.
- Context assembly: pass only authorized chunks to rerankers and models.
- Response: return citations and metadata only for authorized source records.
The tenant boundary and the document ACL boundary are related but different. A tenant filter prevents Customer A from retrieving Customer B's records. It does not automatically prevent one employee from reading another employee's private HR document inside the same tenant. For that, you need document-level permissions as well.
OWASP's LLM08:2025 Vector and Embedding Weaknesses identifies unauthorized access, cross-context leaks, embedding inversion, and data poisoning as risks in RAG systems. Treat embeddings, payloads, chunk text, metadata, and backups as sensitive data—not as harmless numeric artifacts.
1. Define a trusted principal and a permission model
After authentication, create a server-side principal. The tenant ID must come from a verified membership lookup, not directly from a request parameter.
from dataclasses import dataclass
from uuid import UUID
@dataclass(frozen=True)
class Principal:
user_id: UUID
tenant_id: UUID
role: str
group_ids: tuple[UUID, ...]
Your authentication dependency should verify the token and then load the active membership. A simplified flow looks like this:
async def get_principal(token: str) -> Principal:
claims = verify_jwt(
token,
expected_issuer=ISSUER,
expected_audience=API_AUDIENCE,
)
user_id = UUID(claims["sub"])
membership = await membership_repo.get_active_membership(
user_id=user_id,
membership_id=claims["membership_id"],
)
if membership is None:
raise Unauthorized()
return Principal(
user_id=user_id,
tenant_id=membership.tenant_id,
role=membership.role,
group_ids=tuple(membership.group_ids),
)
This is illustrative application code: implement JWT verification with a maintained library and your identity provider's key-rotation and revocation rules. Do not treat an unsigned decoded token as proof of identity. If users can belong to multiple organizations, resolve the selected membership against the authenticated user on every request.
2. Model documents and chunks with explicit ownership
Every chunk needs a stable link to its source document. Store tenant identity and permission metadata in a form that can be enforced during retrieval. A minimal relational model might look like this:
CREATE TABLE documents (
id uuid PRIMARY KEY,
tenant_id uuid NOT NULL,
owner_id uuid NOT NULL,
visibility text NOT NULL
CHECK (visibility IN ('private', 'tenant')),
title text NOT NULL,
source_uri text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE document_sections (
id uuid PRIMARY KEY,
tenant_id uuid NOT NULL,
document_id uuid NOT NULL REFERENCES documents(id)
ON DELETE CASCADE,
owner_id uuid NOT NULL,
visibility text NOT NULL
CHECK (visibility IN ('private', 'tenant')),
content text NOT NULL,
embedding vector(384) NOT NULL
);
CREATE INDEX document_sections_tenant_idx
ON document_sections (tenant_id);
CREATE INDEX document_sections_document_idx
ON document_sections (document_id);
The 384-dimensional vector is only an example. Set the dimension to match the embedding model you actually deploy. Never mix vectors from incompatible embedding spaces in one index and assume that similarity scores remain meaningful.
For group-based access, add a canonical ACL table such as document_acl(document_id, principal_id, permission) and make the policy check that table. Keep the ACL source of truth in one place. If you denormalize ACL labels into vector payloads for speed, update them atomically or through a reliable outbox/reconciliation process when permissions change.
3. Option A — enforce permissions with PostgreSQL RLS and pgvector
PostgreSQL RLS makes authorization part of normal table access. When RLS is enabled, a query must satisfy a policy to see or modify a row. If no policy allows access, the default is deny. PostgreSQL also documents important exceptions: superusers and roles with BYPASSRLS bypass policies, and table owners normally bypass them unless row security is forced.
Enable RLS on the chunk table and create a read policy for private-owner and tenant-visible documents:
ALTER TABLE document_sections ENABLE ROW LEVEL SECURITY;
ALTER TABLE document_sections FORCE ROW LEVEL SECURITY;
CREATE POLICY section_read_policy
ON document_sections
FOR SELECT
TO rag_app
USING (
tenant_id =
NULLIF(current_setting('app.tenant_id', true), '')::uuid
AND (
visibility = 'tenant'
OR owner_id =
NULLIF(current_setting('app.user_id', true), '')::uuid
)
);
This policy is a deliberately small example. It supports private owner-only chunks and tenant-visible chunks. Add separate INSERT, UPDATE, and DELETE policies for ingestion and lifecycle jobs; do not assume a SELECT policy also authorizes writes. If you use group ACLs, extend the policy with a carefully reviewed membership check. Test policy combinations because PostgreSQL's default permissive policies combine with OR, while restrictive policies combine with AND.
Use a dedicated application role such as rag_app. It should not own the table, be a superuser, or have BYPASSRLS. Keep migrations and administrative jobs on separate credentials. FORCE ROW LEVEL SECURITY makes the table owner subject to policies, but it does not constrain a superuser or a role with BYPASSRLS.
Set identity context inside a transaction
With connection pooling, never leave a tenant setting attached to a reusable database session. Set it transaction-locally, run the retrieval query in the same transaction, and let the setting reset automatically when the transaction ends.
async with pool.acquire() as conn:
async with conn.transaction():
await conn.execute(
"SELECT set_config('app.tenant_id', $1, true)",
str(principal.tenant_id),
)
await conn.execute(
"SELECT set_config('app.user_id', $1, true)",
str(principal.user_id),
)
rows = await conn.fetch(
"""
SELECT id, document_id, content,
embedding <=> $1::vector AS distance
FROM document_sections
WHERE tenant_id = $2
ORDER BY embedding <=> $1::vector
LIMIT $3
""",
query_vector,
str(principal.tenant_id),
min(requested_limit, 20),
)
The explicit tenant predicate is useful for query planning and makes intent visible. RLS is the independent database guardrail: if a developer forgets that predicate in a later query, the policy should still prevent unauthorized rows from being returned. Adapt vector parameter encoding to the PostgreSQL driver and pgvector adapter you use. Identity-context caveat: custom settings such as app.tenant_id are trusted only because this example assumes a private application database role and trusted middleware. They are not cryptographically protected identity claims: anyone who can execute arbitrary SQL as that role may be able to set them. Never expose the database credential to end users, prevent SQL injection, and consider a stronger per-user database identity or signed-claim validation design when your threat model includes untrusted SQL execution.
Understand pgvector filtering and recall
pgvector's documentation explains that with approximate indexes such as HNSW, filtering is applied after the index scan. A selective tenant or ACL filter can therefore leave fewer matching rows than the requested top-k. Iterative index scans can scan more candidates, and list partitioning or separate tables can provide stronger tenant separation. The right choice depends on tenant count, data skew, query selectivity, and measured recall.
-- Example HNSW index
CREATE INDEX document_sections_embedding_hnsw
ON document_sections
USING hnsw (embedding vector_cosine_ops);
-- Example for a filtered workload
SET hnsw.iterative_scan = strict_order;
Do not copy these settings blindly. Benchmark exact search and approximate search on a representative corpus, with the same tenant filters and ACL distribution used in production. A global ANN graph can create recall and latency interference between tenants even when RLS still enforces row visibility.
4. Option B — use Qdrant payload tenancy or dedicated shards
Qdrant supports several layouts: payload-based partitioning for many small tenants, user-defined shards for a smaller number of large tenants, and tiered multitenancy for a mix of small and large customers. Its tenant index can optimize tenant-oriented storage and search.
Create a keyword payload index for the tenant field:
from qdrant_client import models
client.create_payload_index(
collection_name="knowledge",
field_name="tenant_id",
field_schema=models.KeywordIndexParams(
type=models.KeywordIndexType.KEYWORD,
is_tenant=True,
),
)
Write each point with the tenant ID in its payload. At query time, build the filter from the trusted principal:
from qdrant_client import models
tenant_filter = models.Filter(
must=[
models.FieldCondition(
key="tenant_id",
match=models.MatchValue(
value=str(principal.tenant_id)
),
)
]
)
result = client.query_points(
collection_name="knowledge",
query=query_embedding,
query_filter=tenant_filter,
limit=8,
with_payload=True,
).points
Important: the tenant index is an optimization, not an authorization system. Qdrant explicitly instructs applications to include the tenant filter in every query, update, and delete operation and derive the tenant from the authenticated user. A client with unrestricted database credentials can omit the filter. Keep Qdrant behind an authenticated application service, restrict API keys, and never ship an administrative key to a browser or mobile app.
When to move a tenant to a dedicated shard
- Use payload partitioning when many tenants share the same collection configuration and have modest, similar workloads.
- Use a dedicated shard when a small number of large tenants need more isolated capacity or placement.
- Use tiered multitenancy when most tenants are small but a few may grow and deserve promotion.
- Use separate collections when tenants require different vector schemas, collection settings, or collection-level permissions.
Dedicated shards consume storage and index resources. A shard key chooses where an operation runs; a payload filter chooses which points match within the shard. For a shared fallback shard, keep the tenant filter even when shard routing is configured. Plan the migration path before creating a collection because the sharding method is not an in-place toggle.
5. Option C — use Weaviate multi-tenant collections
Weaviate stores each tenant on a separate shard in a multi-tenant collection. Multi-tenancy is disabled by default, so enable it when creating the collection. Queries against a multi-tenant collection must specify the tenant.
from weaviate.classes.config import Configure
from weaviate.classes.tenants import Tenant
collection = client.collections.create(
name="Knowledge",
multi_tenancy_config=Configure.multi_tenancy(
enabled=True
),
)
# Provision tenant names from your trusted tenant registry.
collection.tenants.create(
tenants=[
Tenant(name="tenant_7f3a"),
Tenant(name="tenant_91bd"),
]
)
For each request, bind the authenticated tenant to the collection handle before searching:
tenant_collection = (
client.collections
.use("Knowledge")
.with_tenant(weaviate_tenant_name)
)
response = tenant_collection.query.near_vector(
near_vector=query_embedding,
limit=8,
)
authorized_hits = response.objects
Use a stable, validated tenant identifier from your membership registry. Do not auto-create a tenant merely because an untrusted request contains a new tenant string. Weaviate's documentation warns that small spelling differences can create separate tenants when automatic tenant creation is enabled. Tenant creation, activation, offloading, deletion, and backup behavior belong in your tenant lifecycle service.
6. Add document-level ACLs without trusting the model
Tenant isolation is not enough for shared organizations. Consider a company with HR, Finance, Legal, and Engineering spaces. All employees may share the same tenant ID, but they should not share every document.
Use a canonical permission service or relational ACL table to decide which groups the user can access. Then enforce that decision in the retrieval backend:
- Postgres: include the ACL check in RLS, or join against a permission relation in a carefully designed policy.
- Qdrant: store indexed access labels in payload and combine a mandatory tenant filter with server-generated ACL conditions. Keep the payload synchronized with the permission source of truth.
- Weaviate: use the tenant boundary plus filters for document-level properties, with the filter assembled by trusted server code.
For highly sensitive documents, consider a separate collection or database boundary rather than a complicated shared filter. A document permission change must affect retrieval immediately or within a clearly defined, short revocation window. Do not rely on the LLM to decide whether a retrieved chunk is allowed.
7. Make ingestion, revocation, and deletion permission-aware
Authorization can fail even when query-time filters are correct. A document can be moved to another tenant, a user can lose group membership, or a source file can be deleted while stale chunks remain in the index.
- Authenticate every ingestion source and record source ID, tenant ID, document ID, classification, and provenance.
- Validate tenant ownership before splitting or embedding a document.
- Write document metadata and chunk records with a stable ingestion job ID.
- Apply tenant and ACL metadata to every chunk before it becomes searchable.
- When permissions change, update the canonical ACL first and propagate the change to denormalized vector payloads.
- When a document is deleted, remove its chunks, vectors, cached answers, and derived artifacts; record a tombstone until reconciliation confirms deletion.
- Run periodic reconciliation between the source-of-truth document table and the vector store.
For large asynchronous pipelines, make ingestion and deletion idempotent. A retry should not create duplicate chunks or resurrect a deleted document. Keep a version number or source checksum so an older job cannot overwrite a newer permission state.
8. Test the isolation boundary before shipping
Create two tenants with deliberately similar documents. Semantic similarity should not matter: the authorization layer must prevent cross-tenant results even when the foreign document is a perfect vector match.
| Test | Expected result |
|---|---|
| Tenant A searches for its own document | Only authorized Tenant A chunks appear |
| Tenant A asks about Tenant B's secret phrase | No Tenant B chunk reaches the reranker or model |
| Client sends Tenant B's ID in the request body | Server ignores it or rejects the mismatch; principal remains Tenant A |
| Tenant filter is omitted in a Qdrant request | Application wrapper rejects the operation; unrestricted database access is not exposed |
| User loses a group permission | Subsequent retrieval no longer returns that group's documents |
| Database connection is reused after Tenant A | Tenant B request receives only Tenant B context; no session setting leaks |
| Document is deleted | Source and vector records are removed or blocked by a tombstone until cleanup completes |
| Tenant has fewer than top-k eligible chunks | Return fewer authorized results; never fill the gap with another tenant's data |
Automate these as integration tests. Add a canary document per tenant with a unique phrase, then assert that no other tenant's retrieval response, citation list, trace, or model context contains it. Test the raw vector-store API from a restricted application credential as well as the public application endpoint.
9. Observe security without logging everyone’s documents
Record the authenticated tenant ID, user ID or pseudonymous principal ID, policy version, collection, result count, returned document IDs, and authorization outcome. Avoid logging raw document text, full prompts, API keys, or sensitive embedding payloads by default. Alert on missing tenant context, unexpected collection names, denied cross-tenant attempts, and sudden changes in result distributions.
Measure retrieval quality separately from authorization. Track recall@k and answer quality only over the documents the principal is allowed to see. A retrieval system that returns fewer results after a permission change may be behaving correctly. Do not “fix” that by widening the filter.
Trade-offs and limitations
- RLS is not magic: privileged roles can bypass it, and policy logic can become hard to reason about. Separate migration and application credentials, test every policy, and review grants.
- Qdrant payload filters are application-enforced: they are powerful, but a missing filter or over-privileged API key can expose the shared collection.
- Dedicated shards cost more: stronger placement and isolation require additional resources and capacity planning.
- Weaviate tenant shards have lifecycle implications: provisioning, activation, offloading, deletion, and backups need explicit operational handling.
- ANN filtering affects recall: filtered approximate search can return fewer results than expected. Tune and measure with real ACL distributions.
- Embedding privacy is not guaranteed: vectors may reveal information about source content. Protect them like the source documents.
- Prompt injection remains possible: authorized content can still contain malicious instructions. Authorization and prompt-injection defenses solve different problems.
Troubleshooting common failures
RLS returns zero rows for every user
Check that the application sets the tenant and user context inside the same transaction as the SELECT. Confirm the request uses the intended database role and that the policy's UUID types match the session values. Missing settings should fail closed, not fall back to a global tenant.
RLS works locally but leaks in production
Inspect the actual production role. Table owners, superusers, and roles with BYPASSRLS can bypass row security. Review connection-pool behavior, SECURITY DEFINER functions, grants, and any direct database path used by background workers.
Qdrant returns no points
Inspect payload values and types. A UUID string and a different normalized tenant string will not match. Confirm that the payload index exists, the filter field is populated on every point, and the query is using the expected collection. Test the filter with a known point before changing vector parameters.
Qdrant returns too few results
First verify the tenant and ACL filters are correct. Then inspect tenant size, payload indexing, ANN settings, and candidate depth. Do not remove the tenant filter to improve recall. Increase search effort or redesign the tenant index/shard layout only after measuring.
Weaviate reports a missing tenant
Confirm that multi-tenancy was enabled when the collection was created and that the tenant was provisioned. Use the tenant-scoped collection handle for every query. Avoid silently creating tenants from arbitrary client strings.
Revoked users still see old answers
Inspect semantic caches, conversation memory, generated summaries, and stored citations—not just the vector database. Cache keys must include tenant and permission context, or be invalidated when ACL versions change. Reauthorize source IDs before returning cached content.
Security and privacy checklist
- Verify JWT signature, issuer, audience, expiry, and active membership on the server.
- Derive tenant identity from the authenticated principal; never trust the model or client.
- Enforce document ACLs before context assembly, not after generation.
- Use least-privilege database and vector-store credentials; keep administrative keys off clients.
- Use RLS with non-bypass application roles, or mandatory server-generated vector filters.
- Scope caches, traces, citations, exports, and background jobs by tenant and permission version.
- Encrypt data in transit and at rest; restrict backups and operational access.
- Track ingestion provenance and verify deletion across source files, chunks, vectors, caches, and backups.
- Test missing, malformed, stale, and attacker-controlled tenant identifiers.
- Treat retrieved text as untrusted input even after it passes authorization.
Frequently asked questions
Is a tenant_id metadata filter enough to secure RAG?
No. A filter is only effective if trusted server code always applies it and clients cannot query the vector database with unrestricted credentials. Use database-enforced RLS where available, or keep the vector store behind an authenticated service that constructs mandatory filters.
Should every customer get a separate vector collection?
Not automatically. Separate collections can simplify isolation and allow different schemas or settings, but they increase resource and operational overhead. Shared collections with carefully enforced tenant filters can suit many small tenants. Large or regulated tenants may justify dedicated shards, collections, or databases.
Does PostgreSQL RLS automatically secure pgvector similarity search?
RLS applies to rows read by the SQL query, including rows considered by a pgvector similarity query. However, the role must not bypass RLS, the policy must correctly represent the permissions, and approximate-index filtering can affect recall and latency.
Is Qdrant's is_tenant index an access-control feature?
No. It informs Qdrant about tenant-oriented data layout and search optimization. The application still has to authenticate users and apply tenant filters to every relevant operation. Qdrant's own multitenancy guide makes this distinction explicit.
Does Weaviate's separate tenant shard remove the need for application authentication?
No. It provides database-level data separation for tenant-scoped operations, but your application must still verify that the caller is entitled to use the requested tenant. Do not let a client choose an arbitrary tenant name.
Can embeddings be considered anonymous because they are numeric?
No. Embeddings can expose information about source content and should receive the same sensitivity classification and access controls as the documents from which they were generated.
What happens when a user belongs to several tenants?
Resolve the active membership server-side for each request. Use that membership's tenant ID and permission set to construct the retrieval context. Do not let the user switch tenants merely by editing a request parameter.
Conclusion
Secure multi-tenant RAG is an authorization architecture with a vector-search component—not a prompt-engineering trick. PostgreSQL RLS is attractive when relational permissions are the source of truth. Qdrant offers flexible payload, shard, and tiered layouts, provided your service always enforces filters. Weaviate gives explicit tenant-scoped collection operations and per-tenant shards, with lifecycle and resource trade-offs.
Start with a trusted principal, make the permission source of truth explicit, enforce access inside retrieval, and prove the boundary with cross-tenant tests. Only then should you optimize embeddings, reranking, and answer quality.
Further reading on GyanAangan
- RAG Evaluation Deep Dive: Ragas vs DeepEval vs Phoenix with Local Ollama Judges — evaluate retrieval and generation after the authorization boundary is correct.
- Docling vs Marker vs Unstructured: Build a Reliable PDF-to-RAG Ingestion Pipeline — ingest and preserve document structure and provenance.
- Incremental Local RAG with Ollama and SQLite — handle document updates without re-embedding everything.
- Secure Multi-Tenant MCP Servers with Python SDK 2.3.0 — apply tenant isolation and scopes to tool servers that access business data.
- Production RAG Engineering in 2026 — connect retrieval quality, reranking, grounded answers, and observability.
Primary documentation and references
- PostgreSQL 19 documentation: Row Security Policies — policy evaluation, default-deny behavior, role exceptions, and policy composition. PostgreSQL 19 was released on November 19, 2026.
- pgvector official repository — filtering, HNSW/IVFFlat, iterative index scans, and multitenancy guidance.
- Supabase: RAG with Permissions — practical RLS policies applied to document chunks and similarity queries; documentation updated November 18, 2026.
- Qdrant: Multitenancy — payload indexes, tenant filters, and user-defined sharding.
- Qdrant: Choose a Multitenancy Design — shared collections, dedicated shards, tiered multitenancy, and application-enforced access.
- Weaviate: Multi-tenancy operations — tenant shards, collection configuration, tenant lifecycle, and tenant-scoped queries.
- Weaviate: Vector similarity search — near-vector query API.
- OWASP LLM08:2025 Vector and Embedding Weaknesses — risks and mitigations for RAG retrieval and embedding systems.
Implementation caveats
The SQL policy is a minimal owner/private and tenant-visible example, not a complete enterprise ACL engine. Group membership, legal holds, document classification, retention, and delegated access need explicit policies. The Qdrant and Weaviate snippets follow the linked Python client documentation, but exact package versions and deployment settings should be pinned and verified in your environment. No latency, recall, or security certification claims are made. Run the integration tests against your own identity provider, database roles, connection pool, vector-store credentials, and backup/restore process before handling customer data.
