Sub topic 13
Performance: policy predicates, indexes, and EXPLAIN
This chapter assumes you can read a basic EXPLAIN plan, have created B-tree indexes, and know the earlier chapters' material on USING, permissive and restrictive policies, and set_config. It covers what RLS costs, how to see that cost, and how to reduce it.
What a policy does to a query
PostgreSQL adds each applicable policy's USING expression to every query on the table as an extra WHERE condition. Permissive policies are combined with OR, restrictive ones with AND, and the two groups are joined with AND. The planner treats the result like any other filter. A policy costs what the same condition would cost if you wrote it by hand in every query.
Three things follow from this:
- A policy that compares an indexed column to a cheap value is nearly free when the index exists.
- A policy that calls a slow function, or runs a subquery per row, slows every query on the table.
- The planner must keep the policy condition ahead of any user-supplied condition that could leak data, which limits some optimizations.
Set up a table you can measure
The following script builds a table with 100 tenants and 200,000 rows. It is self-contained, so you can run it as shown.
CREATE TABLE ledger (
id bigserial PRIMARY KEY,
tenant_id uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
amount_cents bigint NOT NULL
);
INSERT INTO ledger (tenant_id, amount_cents)
SELECT ('00000000-0000-0000-0000-' || lpad((1 + g % 100)::text, 12, '0'))::uuid,
g % 5000
FROM generate_series(1, 200000) AS g;
CREATE INDEX ledger_tenant_created_idx ON ledger (tenant_id, created_at);
ALTER TABLE ledger ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON ledger
USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);
CREATE ROLE app_user;
GRANT SELECT ON ledger TO app_user;
ANALYZE ledger;Run ANALYZE after bulk loads. Without fresh statistics the planner may pick a sequential scan even with a good index.
Read the plan as the restricted role
A superuser or a table owner without FORCE ROW LEVEL SECURITY bypasses RLS, so EXPLAIN run as that role shows no policy at all. Always switch to the role your application uses before you measure.
BEGIN;
SET LOCAL ROLE app_user;
SELECT set_config('app.tenant_id', '00000000-0000-0000-0000-000000000007', true);
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*) FROM ledger WHERE amount_cents > 1000;
ROLLBACK;The plan has roughly this shape. Exact numbers and node names differ on your machine.
Aggregate
-> Bitmap Heap Scan on ledger
Recheck Cond: (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::uuid)
Filter: (amount_cents > 1000)
-> Bitmap Index Scan on ledger_tenant_created_idx
Index Cond: (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::uuid)The policy expression appears as an Index Cond. That is the result you want. current_setting is a STABLE function, so PostgreSQL evaluates it once when the scan starts and uses the result as an index lookup key. If you see the same expression under Filter: on a Seq Scan, the policy is being tested row by row. Check whether the index exists, whether statistics are current, and whether the column types match.
To measure the overhead, compare against a role that bypasses RLS. Run the same query with and without the policy, and compare Execution Time and Buffers. A well-indexed tenant policy should add very little.
Index for the policy first
The policy predicate is in every query, so the index should start with the policy column.
- A single-column index on
tenant_idcovers the policy alone. - A composite index such as
(tenant_id, created_at)serves the policy and a typicalORDER BY created_ator date-range filter in one scan. - Put
tenant_idfirst. An index on(created_at, tenant_id)cannot narrow to one tenant without scanning a date range. - Unique constraints and foreign keys can include
tenant_idtoo, which keeps index scans tenant-local.
Each extra index costs write time and disk space, so add them for the queries you actually run.
Keep the predicate cheap and stable
How the predicate is written matters as much as the index.
Mark helper functions correctly
If a policy calls your own function, declare its volatility honestly. A function declared VOLATILE (the default) is called for every row and cannot be used as an index lookup key. If it only reads settings or tables and returns the same answer within a statement, declare it STABLE.
CREATE FUNCTION current_tenant() RETURNS uuid
LANGUAGE sql STABLE
AS $$ SELECT NULLIF(current_setting('app.tenant_id', true), '')::uuid $$;Never mark a function IMMUTABLE just to make the planner faster. An IMMUTABLE function that reads a setting can be cached or folded to a constant in places such as prepared plans, and then it returns another session's tenant.
Evaluate once with a scalar subquery
Wrapping an expression in (SELECT ...) makes the planner treat it as an initplan, which runs once per query and is reused. This helps when the function is expensive or cannot be declared STABLE.
ALTER POLICY tenant_isolation ON ledger
USING (tenant_id = (SELECT current_tenant()));For a plain current_setting call the gain is small because it is already cheap and stable. The trick pays off for functions that do lookups, such as checking a membership table.
Beware of OR across policies
Several permissive policies combine with OR. A policy such as tenant_id = current_tenant() OR is_public forces the planner to find rows by either condition. It may need a BitmapOr over two indexes, or it may fall back to a sequential scan. Every permissive policy you add widens the OR. Prefer fewer, simpler policies, and index each column that appears in an OR branch.
Leakproof functions and why your filter may not use an index
Row-level security must not let a user's condition reveal rows that the policy hides. If a user writes WHERE some_function(col) ... and the function raises an error for certain values, the error message could expose a hidden row. To prevent this, the planner evaluates the policy predicate before any user condition that is not marked leakproof.
A function or operator is leakproof if it reveals nothing about its arguments, even through errors. Only superusers can mark functions leakproof. Typical equality and comparison operators on integers and text are leakproof. Many pattern operators, casts, and user functions are not.
You can check:
SELECT proname, proleakproof
FROM pg_proc
WHERE proname IN ('int8eq', 'texteq', 'textlike');Expect textlike (the operator behind LIKE) to be false. A user query like WHERE note LIKE 'abc%' on an RLS table is then applied after the policy filter, and the planner usually cannot use an index on note for it. The same query without RLS may use that index. When a filter that should be fast is slow only for restricted roles, check leakproofness first.
Common symptoms and fixes
| Symptom in the plan | Likely cause | Fix |
|---|---|---|
| `Seq Scan` with the policy expression under `Filter` | No index on the policy column, or stale statistics | Create the index, then run `ANALYZE` |
| Policy function appears in `Filter` and runs per row | Function is `VOLATILE` | Declare it `STABLE`, or wrap it in `(SELECT ...)` |
| `BitmapOr` or sequential scan on a multi-policy table | Several permissive policies joined by `OR` | Merge policies, index each branch |
| User filter not used as an index condition | Operator is not leakproof | Rewrite with a leakproof operator, or accept the filter |
| Fast as superuser, slow as the app role | You measured with RLS bypassed | Re-run `EXPLAIN` after `SET ROLE` |
| One tenant is much slower than the rest | Skewed data and a plan reused from another tenant's statistics | Check row counts per tenant, and consider an index that includes the filter columns |
A short checklist
- Run
EXPLAIN (ANALYZE, BUFFERS)as the real application role, with the tenant setting applied. - Confirm the policy expression appears as an
Index Cond, not only as aFilter. - Index the policy column first in composite indexes.
- Declare helper functions
STABLE, and use(SELECT ...)for anything non-trivial. - Keep the number of permissive policies small.
- Re-check plans after you add user-facing filters that use pattern matching or custom functions.
Exercise
A query on an RLS-protected table runs in 3 ms when you run it as the table owner in psql, but takes 900 ms when the application runs it. The policy is USING (tenant_id = current_tenant()), where current_tenant() is declared VOLATILE, and tenant_id has an index. Give two reasons the difference is expected and two changes that would improve the application's plan.
Show answer
The owner bypasses RLS (no FORCE ROW LEVEL SECURITY), so the 3 ms plan has no policy predicate. The application role also pays for evaluating the policy, and because the function is VOLATILE it is called for every row and cannot serve as an index lookup key, so the planner likely scans the table and filters. Two fixes: declare current_tenant() as STABLE (it only reads a setting), and wrap the call as (SELECT current_tenant()) so it is evaluated once as an initplan. Then re-run EXPLAIN (ANALYZE, BUFFERS) after SET ROLE and confirm the expression is an Index Cond.
Exercise
You add the user filter WHERE title LIKE 'inv%' to a query on an RLS table, and an index on title that worked before is no longer used for restricted roles. Why, and how can you check your explanation?
Show answer
The LIKE operator's function is not leakproof, so the planner must apply the policy predicate before it and generally cannot use the condition as an index condition. You can check by querying proleakproof for textlike in pg_proc, which should be false, and by comparing EXPLAIN output run as the table owner (RLS bypassed) with the output run after SET ROLE to the application role.