TL;DR
- Permission-aware RAG applies authorization before chunks enter a reranker, prompt, trace, or cache. Use the caller’s verified identity and tenant scope to constrain both lexical and vector retrieval.
- In PostgreSQL, row-level security can keep both ranking queries inside the authorized set. pgvector indexes can still underfill a query when very few candidates are visible. Compare their recall against an exact eligible-set search.
- Permissions need a freshness contract as much as documents do. Treat connector errors, failed revocation processing, and access-policy changes as explicit states. Test what happens to search results, citations, and stored answers when a user’s access changes.
Where unscoped retrieval breaks enterprise access control
An internal assistant searches product docs, customer files, and team folders. An employee can view both general manuals and the runbooks for their current team. Their search query often resembles language found in private folders they cannot open. A query that retrieves chunks for every team and filters citations before rendering still gives a generator a chance to quote or summarize the private material. A trace, cache, reranker request, or suggestion service can expose the same content even when the answer omits it.
Authorization must apply before content leaves its retrieval boundary. In a hybrid system, that means both lexical and semantic candidates must pass the same decision. A document may be visible at the source because an individual is named in an ACL, belongs to a group, or meets a sharing rule inherited from a folder. Translate those semantics explicitly. Organization membership, document ownership, and document read permission are different relationships.
Search vendors describe permission synchronization as part of connector behavior. Glean’s connector documentation, for example, describes indexing source content and permissions for permission-aware results. Using that principle in a custom system still leaves you to design identity mapping, permission freshness, indexing and cache invalidation. Glean connector architecture overview.
Separate authorization from relevance ranking
Map source readers to stable application principals
Use stable tenant and actor IDs as the input to retrieval. The application determines them after validating the request and its tenant relationship. A project can use a source connector to maintain allowed reader edges for a document. When permissions inherit from folders or groups, the connector must preserve the source semantics and apply revocations. A user’s current email domain or arbitrary request header cannot reliably stand in for the verified access policy.
The small schema below stores resolved positive grants. It works when a connector can maintain effective access edges for a manageable population. Expanding large nested groups into a row for every user and document can become the bottleneck. At scale, model document-to-principal grants and principal membership separately, then benchmark the join and test conflicting grants or explicit denies according to the source policy. Keep ACL revision and freshness status beside the materialized state so a source that has stopped syncing can be handled deliberately.
Choose a freshness boundary for revocation
A replica of permissions reflects an observation from a source system. Define how stale that observation can be for each document class. For tightly restricted content, use a fresh decision from the source or authorization service before passing text to any model. Hide sources whose ACL state is unknown or stale beyond policy. Batch checks if the provider supports them and carry a policy or document version into the decision record. Revocation during an in-flight answer requires a defined boundary, particularly if the answer streams and already emitted tokens cannot be recalled.
Implement ACL-filtered hybrid search in PostgreSQL
Set up the retrieval tables and row policies
This demonstration uses PostgreSQL 17 and pgvector. It assigns read access per document and tenant and applies a row policy to every chunk query. Three-dimensional vectors keep the example small. Use the model’s actual dimension and matching operator class in a real index. Run migrations through a separate owner role and configure the application service with a distinct login that can assume rag_search. Superusers and roles with BYPASSRLS bypass row policies, and table owners typically bypass them unless the policy is forced. PostgreSQL row security policies.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE ROLE rag_search NOLOGIN;
CREATE TABLE rag_document (
tenant_id uuid NOT NULL,
document_id bigint NOT NULL,
PRIMARY KEY (tenant_id, document_id)
);
CREATE TABLE rag_reader (
tenant_id uuid NOT NULL,
document_id bigint NOT NULL,
actor_id uuid NOT NULL,
PRIMARY KEY (tenant_id, document_id, actor_id),
FOREIGN KEY (tenant_id, document_id)
REFERENCES rag_document ON DELETE CASCADE
);
CREATE TABLE rag_chunk (
chunk_id bigint PRIMARY KEY,
tenant_id uuid NOT NULL,
document_id bigint NOT NULL,
body text NOT NULL,
embedding vector(3) NOT NULL,
search_terms tsvector GENERATED ALWAYS AS (
to_tsvector('english'::regconfig, body)
) STORED,
FOREIGN KEY (tenant_id, document_id)
REFERENCES rag_document ON DELETE CASCADE
);
CREATE INDEX rag_chunk_scope ON rag_chunk (tenant_id, document_id);
CREATE INDEX rag_chunk_fts ON rag_chunk USING gin (search_terms);
ALTER TABLE rag_reader ENABLE ROW LEVEL SECURITY;
ALTER TABLE rag_reader FORCE ROW LEVEL SECURITY;
ALTER TABLE rag_chunk ENABLE ROW LEVEL SECURITY;
ALTER TABLE rag_chunk FORCE ROW LEVEL SECURITY;
CREATE POLICY rag_reader_self ON rag_reader FOR SELECT TO rag_search
USING (
tenant_id = nullif(current_setting('rag.tenant_id', true), '')::uuid
AND actor_id = nullif(current_setting('rag.actor_id', true), '')::uuid
);
CREATE POLICY rag_chunk_authorized ON rag_chunk FOR SELECT TO rag_search
USING (
tenant_id = nullif(current_setting('rag.tenant_id', true), '')::uuid
AND EXISTS (
SELECT 1 FROM rag_reader AS reader
WHERE reader.tenant_id = rag_chunk.tenant_id
AND reader.document_id = rag_chunk.document_id
)
);
GRANT SELECT ON rag_reader, rag_chunk TO rag_search;
The inner ACL lookup sees only reader rows permitted by its own policy, hence the actor check applies to both tables. With no context set, the comparisons do not admit any rows. The example defines only retrieval policies. A trusted ingestion role needs explicit write policies and grants through its own credential path before it can populate the protected tables. Decide its exact scope separately from the search role.
Use the application’s verified actor and tenant UUIDs as bound parameters. In a transaction, set both values and execute the retrieval query on the same database connection. set_config with its last argument set to true limits the value to the transaction. This model assumes the caller is a trusted application issuing fixed SQL through bound parameters. If clients can submit arbitrary SQL under the same database role, session settings they can change are not a sufficient identity boundary. PostgreSQL configuration settings functions.
-- Execute these via the service connection in the same transaction.
SET LOCAL ROLE rag_search;
SELECT set_config('rag.tenant_id', $1::uuid::text, true),
set_config('rag.actor_id', $2::uuid::text, true);
Merge vector and lexical results after authorization
The semantic branch uses cosine distance. The lexical branch uses PostgreSQL’s ts_rank_cd cover-density score, which is a different ranking method from BM25. Reciprocal rank fusion combines the rank positions, avoiding direct comparisons between the two score scales. Bind a nonzero query vector of the configured dimension and a bounded text query. The example requests up to 40 candidates from each branch and returns at most 8. Adjust those sample limits after measuring quality on your corpus. PostgreSQL text search ranking · Original reciprocal rank fusion paper.
-- $1 = query embedding, $2 = query text
WITH vector_hits AS MATERIALIZED (
SELECT chunk_id, embedding <=> $1::vector(3) AS distance
FROM rag_chunk
ORDER BY embedding <=> $1::vector(3)
LIMIT 40
), lexical_hits AS MATERIALIZED (
SELECT chunk_id,
ts_rank_cd(search_terms, websearch_to_tsquery('english', $2::text)) AS relevance
FROM rag_chunk
WHERE search_terms @@ websearch_to_tsquery('english', $2::text)
ORDER BY relevance DESC, chunk_id
LIMIT 40
), rankings AS (
SELECT chunk_id, row_number() OVER (ORDER BY distance, chunk_id) AS rank
FROM vector_hits
UNION ALL
SELECT chunk_id, row_number() OVER (ORDER BY relevance DESC, chunk_id)
FROM lexical_hits
), fused AS (
SELECT chunk_id, sum(1.0 / (60 + rank)) AS score
FROM rankings
GROUP BY chunk_id
)
SELECT c.chunk_id, c.document_id, c.body, fused.score
FROM fused
JOIN rag_chunk AS c USING (chunk_id)
ORDER BY fused.score DESC, c.chunk_id
LIMIT 8;
Without an approximate index, the vector branch considers the visible rows using an exact search. pgvector supports HNSW cosine indexing as an optional rollout. With approximate search, pgvector can apply filters after scanning candidates from the index. That can affect the number and quality of returned authorized results. Test whether your plan uses the index under RLS and compare it with exact results. pgvector 0.8.0 introduced iterative scans that can search further within configured limits. pgvector filtering and iterative scans.
-- Run index creation separately, outside a transaction block.
CREATE INDEX CONCURRENTLY rag_chunk_vector
ON rag_chunk USING hnsw (embedding vector_cosine_ops);
-- pgvector 0.8.0+, in the app's search transaction.
SET LOCAL statement_timeout = '300ms';
SET LOCAL hnsw.iterative_scan = 'strict_order';
Validate the security and quality failure modes
A revocation races retrieval or cache reuse
Test removing a direct grant, removing a group member, and moving a document into a restricted folder. Check search results and citations first, then look for stale generated answers or embeddings used indirectly by caches. A tenant-only cache key is rarely sufficient. Use a caller or verified entitlement scope and a policy revision, with invalidation or a bounded freshness policy. Recheck authorization whenever a cached result is expanded with source text. Define behavior for conversation history and exports after a revocation.
Approximate search underfills a narrow ACL slice
Run a test where a user can see 100 chunks in a much larger corpus. If a broad ANN index returns few eligible rows, compare an exact search over those 100 chunks and inspect the plan. A separate index or partition can help when tenant boundaries match most queries. Dynamic per-user permissions usually need a separate recall strategy. If results are too sparse, choose an exact fallback on the same ACL or return a narrower answer with fewer citations. Load test the fallback path so sparse visibility does not produce an unbounded request cost.
The ranker receives data from a broad search mode
An experimental lexical path or internal reranker can accidentally query the table as an owner role. Test the real runtime role and both retrieval branches. Use fixture content with the same terms and close vectors across different tenants and groups. When access is denied, assert that no body or citation reaches the ranker, generator, or trace payload. A successful answer from one authorized actor says little about missing access checks for a second actor.
Compare authorization designs and measure under realistic ACLs
Exact PostgreSQL search is a good baseline for narrow eligible sets or small corpora. It reduces recall surprises and simplifies testing. Partitioned or approximate indexes can be worthwhile when larger tenants need faster retrieval and you can measure underfilled queries for restrictive permissions. Partitioning by tenant helps isolate the candidate pool, but document-level grants still need enforcement within that pool. Live source authorization fits highly sensitive or rapidly changing permissions if its availability and latency meet the request budget. A mirrored ACL plus a final live check can reduce unnecessary source calls when each stage handles only permitted data.
Record p50 and p95 retrieval time by tenant, eligible-set size, candidate count, and cache status. Compare approximate retrieval against exact rankings on the same authorized snapshots. Include ACL churn, no-access users, and sources in an uncertain synchronization state. A deliberate target such as p95 under 50 ms is a budget. Prove it against your corpus, workload, filter selectivity, and concurrent load before promising it. Use the connection pool and reranker timing separately to see which stage actually consumes the budget. Production RAG evaluation and release gates · Index planning for multi-tenant PostgreSQL workloads.
Frequently asked questions
Where should ACLs be checked in a permission-aware RAG pipeline?
Check access before sending candidate content to the reranker, generator, or cache. Apply the same tenant and document policy to lexical and vector retrieval. Recheck where access may have changed, such as when expanding a cached result or opening a citation. Use verified caller identity and deny unknown or stale decisions according to policy.
Can a pgvector index reduce recall when access control filters are selective?
Yes. Approximate search may find a group of nearby candidates and then discard rows that fail authorization, leaving fewer visible results than the requested limit. Measure recall against an exact search using the same permissions. Consider iterative scans, an exact eligible-set fallback, or tenant partitioning depending on cost and workload.
Is PostgreSQL full-text search with ts_rank_cd the same as BM25?
PostgreSQL’s ts_rank_cd uses cover-density ranking, including the proximity of matching terms. BM25 is a separate ranking algorithm. Either can supply the lexical list for a hybrid search if implemented by the chosen engine. Fuse rank positions or calibrate the score scales before combining lexical and vector results.
Review the authorization boundary before shipping
If you are building permission-aware RAG, talk to our engineering team about source ACL modeling, revocation tests, or a hybrid search benchmark that reflects real access patterns.
