Fixing PostgreSQL RLS Latency Spikes in Multi-Tenant SaaS
PostgreSQL RLS latency spikes often come from a policy that re-runs a membership subquery for many rows. Check plans with EXPLAIN ANALYZE as the app role, then use a STABLE claim helper, an equality policy and a tenant-first index.

What an RLS Latency Spike Looks Like
Your multi-tenant SaaS platform experiences a severe latency spike during a high-traffic period, and your database CPU usage maxes out while connection pools saturate. Queries that previously executed in single-digit milliseconds now take hundreds of milliseconds, even with small table sizes. When you pull the active query list, you notice many sequential scans tied directly to tables protected by Row-Level Security (RLS).
The core issue is not a lack of general database compute, but how PostgreSQL evaluates security policies. RLS policy expressions are added to every query on the table, and they are checked for candidate rows unless the planner can turn them into an index condition or a one-time value. If a policy runs a subquery against a lookup table, or calls a function the planner cannot treat as constant for the statement, the check can be repeated for many rows. A cheap index lookup becomes repeated scans, and the cost grows with table size and concurrency.
Diagnosing this requires moving beyond standard application monitoring to inspect exact query plans under simulated multi-tenant security contexts. Before modifying application code, you need to understand how the PostgreSQL query planner interacts with policy expressions and connection poolers like PgBouncer for PostgreSQL, Cloudflare for App Traffic. Pinpointing the exact bottleneck allows you to apply surgical indexing and function optimizations without rewriting your entire data access layer.
Anatomy of an Unoptimized RLS Policy Evaluation

Understanding why RLS scales poorly requires examining how PostgreSQL applies security filters during the rewrite phase of query planning. When a query hits a protected table, the query rewriter injects the USING and WITH CHECK expressions directly into the parse tree as implicit WHERE clauses. If your policy checks tenant ownership by querying a membership mapping table using an unindexed subquery, the planner executes that subquery for every tuple evaluated in the parent relation.
Consider a common multi-tenant SaaS schema where organizations share a single documents table. A poorly constructed policy might look like USING (org_id IN (SELECT org_id FROM user_organizations WHERE user_id = current_setting('request.jwt.claim.sub', true)::uuid)). If user_organizations lacks a composite index on (user_id, org_id), or the planner cannot turn the subquery into a join or a one-time filter, it may re-run that subquery many times in a single query. Wrapping a function call in a scalar subquery, such as (SELECT my_function()), lets the planner evaluate it once per statement as an InitPlan.
Connection poolers add one more trap in transaction mode. Each transaction can run on a different server connection, so a session-level SET can leak to another client, and a value set in an earlier transaction may be missing. Set claims with SET LOCAL or set_config(..., true) inside every transaction so they reset at commit. If a claim is missing, the policy should return no rows rather than fall back to a broad check.
Diagnostic Workflow: Using EXPLAIN ANALYZE With Auth Context

To diagnose RLS performance issues safely without impacting live production traffic, replicate your production auth context in a staging environment. You must test queries while actively simulating the session variables that your application passes to the database. Running a standard EXPLAIN ANALYZE without setting these variables will output misleading execution plans because PostgreSQL will optimize away security checks that evaluate to static boolean values.
Start by setting your session context explicitly in your interactive PostgreSQL client before running your analysis queries. Switch to the same role your application uses: superusers, roles with BYPASSRLS and (by default) the table owner skip RLS, so their plans hide the problem.
-- Step 1: Simulate the application session context in your test session
BEGIN;
SET LOCAL ROLE app_user; -- the role your application connects as
SELECT set_config('request.jwt.claim.sub', 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', true);
SELECT set_config('request.jwt.claim.org_id', 'b1ffcd88-8d1a-4ef8-bb6d-6bb9bd380a22', true);
-- Step 2: Run EXPLAIN ANALYZE with timing and buffers enabled
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT id, title, created_at
FROM documents
WHERE status = 'published'
ORDER BY created_at DESC
LIMIT 20;
ROLLBACK;Examine the resulting query execution plan for sequential scans (Seq Scan) on large tables where an index scan was expected. Look specifically at the node execution counts and shared buffer hits. If you see high Buffers: shared hit=... numbers relative to the rows returned, or a SubPlan on the membership table with a large loops= count, the policy check is being repeated instead of using an index.
High-Performance RLS Implementation and Indexing Playbook
Fixing RLS latency requires three structural changes: wrapping dynamic security claims in STABLE functions, refactoring subqueries into indexed joins or EXISTS clauses, and ensuring foreign keys supporting tenant isolation have explicit covering indexes. First, define a helper function marked as STABLE rather than VOLATILE. STABLE tells the planner the result will not change within one statement, which allows index use; calling it through a scalar subquery in the policy makes PostgreSQL evaluate it once:
-- Create a STABLE helper function to retrieve the current user tenant ID
CREATE OR REPLACE FUNCTION public.get_current_user_org_id()
RETURNS UUID
LANGUAGE sql
STABLE
AS $$
SELECT NULLIF(current_setting('request.jwt.claim.org_id', true), '')::uuid;
$$;Next, drop the naive IN subquery policy and replace it with a clean equality check or an indexed EXISTS clause. Pair this policy with a compound index on the target table that includes the tenant identifier as the leading column, followed by your primary filtering and sorting attributes:
-- Drop the slow policy and create an optimized version
DROP POLICY IF EXISTS tenant_isolation_policy ON documents;
CREATE POLICY tenant_isolation_policy ON documents
FOR ALL
USING (org_id = (SELECT public.get_current_user_org_id()))
WITH CHECK (org_id = (SELECT public.get_current_user_org_id()));
-- Create a compound covering index matching the query workload
CREATE INDEX CONCURRENTLY idx_documents_org_status_created
ON documents (org_id, status, created_at DESC);This policy is permissive (the default). Do not mark it AS RESTRICTIVE on its own: a restrictive policy only narrows access granted by a permissive one, so with no permissive policy every row is hidden. The index lets PostgreSQL jump to one tenant's rows, apply the status filter and read them already sorted by created_at, so a LIMIT 20 query can stop early. It still visits the table for columns that are not in the index. For workflows requiring complex multi-organization access, combine this indexing strategy with proper PgBouncer connection tuning to maintain session state consistency without starving connection pools.
Worked Example: Before and After Optimization

Illustrative Scenario: a multi-tenant document app keeps all tenants in one large documents table. The original policy checks membership with an IN subquery, and no index leads with org_id. The plans below show what to look for; measure timings on your own staging data rather than expecting a set speed-up.
- Before: the list query that fetches 20 sorted documents shows a
Seq Scanondocuments, a filter that contains the policy subquery, and a sort step over every matching row. Under load, these scans keep CPU busy and hold pool connections longer. - After: with the
STABLEhelper called through(SELECT ...), the equality policy and the(org_id, status, created_at DESC)index, the plan should show aLimitover anIndex Scan using idx_documents_org_status_created, no repeated membership subplan, and far fewer buffers read. Record execution time before and after on the same data to measure your own gain.
Rollback, Security Risks, and Verification Checklist
When altering database security policies in production, deploy policy changes inside a transaction block or use migration tooling that supports immediate rollback if query planner regressions occur. Run CREATE INDEX CONCURRENTLY as its own step, because it cannot run inside a transaction block. Test your policies thoroughly against security edge cases, such as unauthenticated requests or expired tokens, to ensure users never cross tenant boundaries.
- Verification Checklist:
- Run
EXPLAIN ANALYZEwith simulated JWT claims and confirm zero unexpected sequential scans. - Verify all tenant ID columns used in RLS policies are the leading columns (
col_1) of their respective indexes. - Ensure helper functions that read session claims are marked
STABLE(notIMMUTABLE, becausecurrent_settingcan change between statements) and are called through(SELECT ...)in the policy. - Confirm every transaction sets its claims with
SET LOCALorset_config(..., true), so pooled connections never carry one user's context into another user's transaction.
Your immediate next action is to open your staging database, run an EXPLAIN ANALYZE on your most frequent multi-tenant list query with an active session variable, and check if your RLS policy is triggering sequential scans.
Related resources
Frequently Asked Questions
Why can PostgreSQL RLS cause latency spikes?
If the planner cannot turn the policy check into an index condition or a one-time value, PostgreSQL can re-run a membership subquery for many candidate rows.
How do you diagnose RLS latency without affecting production traffic?
In staging, switch to the application's role, set the JWT claims with set_config inside a transaction, run EXPLAIN ANALYZE with BUFFERS, and look for unexpected sequential scans, repeated subplans and high buffer counts.
Which compound index matches the published documents query?
Use (org_id, status, created_at DESC) so the index leads with the tenant ID, followed by the filter and sort columns.
How do I know the fix worked?
The plan should show a Limit over an index scan on the tenant-first index with no repeated membership subplan and fewer buffers read. Compare execution time before and after on the same staging data.
Get the Weekly SMB AI & SaaS Brief
Practical software benchmarks, prompt templates, and ROI breakdowns delivered every Tuesday. No fluff, unsubscribe anytime.