Supabase performance · 9 minute read
Supabase RLS is slow? The (select auth.uid()) fix, measured on PostgreSQL 17
A policy that reads the JWT once should not read it 200,000 times. When a bare auth.jwt() call sits inside a USING clause, PostgreSQL 17 re-evaluates the call for every row the scan touches. Wrapping the same call in a scalar subquery moves it into an InitPlanthat runs exactly once. Same rows returned, ~52× faster on the measured workload.
The measured setup
Everything below was measured on a local PostgreSQL 17.12 container (Debian build, no Supabase in the loop), so the plans are the stock planner’s, not hosted behaviour. Two tables, 200,000 rows each:
org_notes(org_id int, body text)— no index onorg_id, so the policy runs as a filter on a sequential scan: the shape where per-row evaluation is visible.notes(tenant_id uuid, body text)— indexed on(tenant_id, created_at desc), for the equality path.
The JWT helpers were typed exactly the way Supabase defines them:
create schema auth;
create function auth.jwt() returns jsonb
language sql stable
as $$ select nullif(current_setting('request.jwt.claims', true), '')::jsonb $$;
create function auth.uid() returns uuid
language sql stable
as $$ select (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')::uuid $$;The app role is appuser, with request.jwt.claims set to a realistic claims blob (sub, role, org_id, a five-element groups array, session id, aal, two nested metadata objects). Queries ran as that role, in a transaction, with the JWT GUC set per statement — never as the table owner (see the trap below).
Bare call: the policy becomes a per-row expression
create policy jwt_bare on public.org_notes
for select to appuser
using (org_id = ((auth.jwt() ->> 'org_id')::int));The plan inlines the whole call into the scan filter:
Aggregate (actual time=756.5..756.5 rows=1)
-> Seq Scan on org_notes (actual time=0.142..756.4 rows=40)
Filter: (org_id = (((NULLIF(current_setting('request.jwt.claims', true), ''))::jsonb ->> 'org_id'))::integer)
Rows Removed by Filter: 199960
Execution Time: 756.6 msThree consecutive runs: 774 ms, 727 ms, 678 ms. Forty rows matched — the same forty the wrapped version returns. The cost is not the filter; it is the chain current_setting → ::jsonb → ->> being rebuilt for each of the 200,000 tuples the scan touches.
Wrapped call: the same policy as an InitPlan
create policy jwt_wrapped on public.org_notes
for select to appuser
using (org_id = ((select auth.jwt() ->> 'org_id')::int));Now the call is hoisted out of the scan:
Aggregate (actual time=13.587..13.589 rows=1)
InitPlan 1
-> Result (actual time=0.025..0.029 rows=1)
-> Seq Scan on org_notes (actual time=0.039..13.579 rows=40)
Filter: (org_id = ((InitPlan 1).col1)::integer)
Rows Removed by Filter: 199960
Execution Time: 13.6 msThree consecutive runs: 13.7 ms, 14.1 ms, 13.8 ms. The median ratio is 727 ms → 13.8 ms, about 52×, and the InitPlan 1 → Result node is the visual fingerprint: when you see it, the call ran once; when you see the call spelled out inside Filter, it is running per row.
Why this is safe, and where it is not
auth.uid() and auth.jwt() are STABLE, not VOLATILE: within one statement the value cannot change, so evaluating once and comparing many times is semantically identical. That is why wrapping is the documented Supabase recommendation and not a semantic shortcut.
The caveat matters for other functions. Wrapping a VOLATILE expression — now(), random(), nextval() — freezes it to one evaluation for the whole statement. A policy column that must re-read the clock per row would be wrong if wrapped. Wrap the claim readers, not the clock.
The index question: RLS cost and index cost are different things
An index does not become useless because a policy exists — the policy predicate is ANDed in after the index step, and the wrapped value shows up directly in the index condition:
-- equality on the indexed tenant_id, wrapped call
Aggregate (actual time=0.075..0.076 rows=1)
InitPlan 1
-> Result (actual time=0.015..0.015 rows=1)
-> Index Only Scan using notes_tenant_created on notes
Index Cond: (tenant_id = (InitPlan 1).col1)
Execution Time: 0.127 msThe same query with the bare call measured 1.58–1.67 ms (the expression re-appeared in both the index condition and the recheck). So on an indexed equality path the wrap is a smaller win — 0.13 ms versus 1.6 ms — but it is still a win, and on unindexed filters it is the difference between 14 ms and 727 ms.
Two practical rules from the same fixture. First, an index on the policy column is still worth having: it turns the filter into an index condition. Second, if the filter column is genuinely unindexed, the per-row expression is the multiplier — fix the shape before adding hardware.
The trap that hides all of this: explaining as the owner
With FORCE ROW LEVEL SECURITY removed, the table owner is exempt from its own policies. The identical EXPLAIN as the owner returns:
Aggregate (actual time=18.341..18.342 rows=1)
-> Seq Scan on org_notes (actual time=0.007..11.051 rows=200000)
Execution Time: 18.4 ms -- 200000 rows, no filter at allNo Filternode, no policy cost, and 5,000× the rows. A slow-endpoint investigation run as the owner will conclude that RLS is free — because it is not being applied. On Supabase, the equivalent mistake is reading the dashboard’s query statistics for a postgresconnection and calling it the app’s latency.
The measurement recipe that avoids it:
begin;
set local role authenticated; -- the role your app really runs as
set local request.jwt.claims = '{"sub":"...","org_id":"42"}';
explain (analyze, buffers, costs off) select count(*) from public.org_notes;
commit;On hosted Supabase the SQL editor runs as postgres, so the set local role inside a transaction is the step that makes the plan real; if the editor refuses the GUC, reproduce in a local PostgreSQL 17 container with the fixture above — the planner is the same code.
What a catalog check can and cannot tell you here
Policy shape is readable without touching a single row: pg_policies.qual shows the expression, and whether it contains a bare auth.jwt()/auth.uid() call or a wrapped one is text you can grep for across every policy at once. That catches the slow shape before you profile a single endpoint.
What no catalog query can tell you is which policy is actually slow — that needs a plan for the real query under the real role, on data sized like production. A nightly drift check can tell you that the expression changed; only EXPLAIN (ANALYZE) as the app role tells you what the change costs.
The free, read-only RLS drift monitor covers the thirteen catalog shapes that turn into incidents (RLS off, USING (true), missing WITH CHECK, definer without search_path, pg_default_acl grants, non-invoker views, PUBLIC-scoped policies) and fails closed when the credential breaks. It reads only catalogs, never application rows, and never runs as service_role. Get the free RLS Drift Monitor (13 checks, n8n + SQL) →
Honest limits
The numbers here come from one local PostgreSQL 17.12 container with synthetic data and a claims blob of realistic size; they are a shape demonstration, not a benchmark of your schema. A 730 ms versus 14 ms gap on a 200,000-row unindexed scan will not reproduce exactly on your tables — the ratio scales with rows touched and with the cost of the expression being re-evaluated, so it shrinks on small results and grows on wide scans. Hosted Supabase revisions, pool mode and planner settings are outside what a public post can verify for your project. Zero findings in a catalog check does not mean safe, and a fast plan does not mean a closed policy set. If you want a person to read both — the shape and the plans — that is a separate fixed-scope review: Supabase RLS Spot Check. Work starts only after payment is secured.
Related: USING vs WITH CHECK, the half of policy review that gets skipped · detect RLS drift with a read-only nightly check · why auth.uid() returns null on the server.