SaaS

Why your Supabase row-level security is slow, and the policy change that fixed ours

Why your Supabase row-level security is slow, and the policy change that fixed ours

Row-level security is the reason Supabase works for multi-tenant apps: the database itself decides which rows each signed-in user can see. We use it on the client portals we build on Supabase, and we’ve written about the schema and policies for a client portal before. This post is about the other half. Policies can be correct and the app can work, and a list page still takes three seconds once the tables fill up.

So we built that situation on a Supabase project (PostgreSQL 17): 2,000 customer organizations, 25 members each, 100 tickets per organization, 200,000 tickets in total. Our test user belongs to three organizations. We ran the same two queries as that user under five versions of the policy, seven times each, and kept the median. Every number and plan below comes from those runs.

The setup

Three tables: organizations, memberships (which user belongs to which organization) and tickets. Memberships has its own policy, so a user can only see their own rows there. That detail matters later.

sql
create table rls_perf.orgs (id uuid primary key default gen_random_uuid(), name text not null);
create table rls_perf.memberships (
  user_id uuid not null, org_id uuid not null references rls_perf.orgs(id),
  role text not null default 'member', primary key (org_id, user_id)
);
create table rls_perf.tickets (
  id bigint generated always as identity primary key,
  org_id uuid not null references rls_perf.orgs(id),
  title text not null, status text not null, created_at timestamptz not null
);

alter table rls_perf.memberships enable row level security;
alter table rls_perf.tickets enable row level security;
create policy own_memberships on rls_perf.memberships for select to authenticated
  using (user_id = auth.uid());
The demo schema. Seed data is 2,000 orgs × 25 members and 2,000 orgs × 100 tickets.

The two queries are the ones a ticketing screen actually runs: the 50 newest tickets, and a count of open ones. Neither has a where clause for the organization. The policy is the only thing narrowing 200,000 rows down to the user’s 300.

sql
-- list page
select id, title, status, created_at from rls_perf.tickets order by created_at desc limit 50;
-- badge on the sidebar
select count(*) from rls_perf.tickets where status = 'open';
Run inside a transaction with set local role authenticated and the user’s JWT claims, the same way Supabase runs API requests.

Five policies, one result

All five versions return exactly the same rows: 50 tickets for the list and 99 open tickets for the count. Only the time changes.

Table of list query times on a log scale. 1. Helper function per row, is_member(org_id): 2,799.37 ms. 2. Exists joined to the row: 26.52 ms. 3. In my orgs with auth.uid() wrapped: 26.97 ms. 4. Same plus indexes: 25.23 ms. 5. Array of my orgs plus indexes: 0.68 ms. Version 5 without the tickets index: 22.16 ms.
Median of seven runs per version, measured with EXPLAIN ANALYZE as the signed-in user.
Terminal output of node rls-bench.mjs: version 1 list 2799.37 ms and count 934.63 ms; version 2 26.52 and 23.00; version 3 26.97 and 28.67; version 4 25.23 and 26.84; version 5 0.68 and 0.57. Every version returns 50 rows and a count of 99.
The raw run, both queries.

Version 1: a helper function, called 200,000 times

This pattern is common because it reads nicely, and it’s what you write when you want one rule shared by many tables.

sql
create or replace function rls_perf.is_member(p_org uuid) returns boolean
  language sql stable security definer set search_path = '' as
  $$ select exists (select 1 from rls_perf.memberships where org_id = p_org and user_id = auth.uid()) $$;

create policy member_tickets on rls_perf.tickets for select to authenticated using (
  rls_perf.is_member(org_id));
Correct, readable and 2.8 seconds on our data.

The function takes org_id from the row, so PostgreSQL has to call it for every row it looks at. Being security definer also stops the planner from inlining it into the query. The plan is a sequential scan with the function as a filter: 200,000 calls, each running its own membership lookup, to keep 300 rows.

text
Seq Scan on tickets (actual rows=300 loops=1)
  Filter: rls_perf.is_member(org_id)
  Rows Removed by Filter: 199700
Execution Time: 2892.330 ms
From EXPLAIN (ANALYZE) on the list query.

Versions 2 to 4: correct, quicker, and still reading every row

Moving the membership check into the policy itself, as an exists or an in (select …), takes the time from 2.8 seconds to about 26 ms. PostgreSQL now looks up the user’s three organizations once, builds a hash of them, and checks each ticket against it.

sql
create policy member_tickets on rls_perf.tickets for select to authenticated using (
  org_id in (select m.org_id from rls_perf.memberships m where m.user_id = (select auth.uid())));

create index tickets_org_created on rls_perf.tickets (org_id, created_at desc);
create index memberships_user on rls_perf.memberships (user_id);
Version 4: the policy most guides end with, plus indexes on both policy columns.

Here’s what surprised us. Adding indexes in version 4 changed nothing. The plan was still a sequential scan of all 200,000 tickets:

text
Seq Scan on tickets (actual rows=300 loops=1)
  Filter: (ANY (org_id = (hashed SubPlan 2).col1))
  Rows Removed by Filter: 199700
Version 4. The index on org_id exists; the planner doesn’t use it.

The reason is when the list of organizations is known. With in (select …), PostgreSQL plans the query before it knows which organizations the subquery will return, so it can’t plan an index lookup for them. It plans a scan with a filter and works out the list during the scan.

Version 5: hand the planner a list it can use

The fix is to turn the user’s organizations into an array before the scan starts. array(select …) runs once as an InitPlan, and its result becomes a value the planner can use against the index. We also moved the lookup into a small security definer function, so the policy doesn’t pay for the memberships table’s own RLS.

sql
create or replace function rls_perf.my_org_ids() returns setof uuid
  language sql stable security definer set search_path = '' as
  $$ select org_id from rls_perf.memberships where user_id = auth.uid() $$;
revoke execute on function rls_perf.my_org_ids() from public, anon;
grant execute on function rls_perf.my_org_ids() to authenticated;

create policy member_tickets on rls_perf.tickets for select to authenticated using (
  org_id = any (array(select rls_perf.my_org_ids())));
Same rule, written so the list of organizations exists before the scan.
text
Limit (actual rows=50 loops=1)
  InitPlan 1
    ->  ProjectSet (actual rows=3 loops=1)
  ->  Sort (actual rows=50 loops=1)
        ->  Bitmap Heap Scan on tickets (actual rows=300 loops=1)
              Recheck Cond: (org_id = ANY ((InitPlan 1).col1))
Version 5. Three organization ids first, then only those 300 tickets are read.

0.68 ms for the list and 0.57 ms for the count. Unlike version 1, this function takes no input from the row, which is why it runs once instead of 200,000 times.

Then we dropped the tickets index and ran version 5 again: 22.16 ms, back to a full scan. The array gives the planner a list; the index gives it somewhere to look the list up. You need both.

How to find this in your own project

Run EXPLAIN as the user, not as postgres. As the postgres role, RLS is bypassed and every plan looks fast. In the SQL editor or psql, wrap it in a transaction:

sql
begin;
select set_config('request.jwt.claims', '{"sub":"<a real user id>","role":"authenticated"}', true);
set local role authenticated;
explain (analyze, buffers) select … ;   -- the query your screen runs
rollback;
This is how our benchmark script ran each query.
  • Rows Removed by Filter close to the table size means RLS is filtering after reading everything.
  • A function name on the Filter line, with a column from the row as its argument, means it runs once per row.
  • A hashed SubPlan on the Filter line means the list isn’t known at planning time, so indexes on that column are ignored.
  • An InitPlan with Index Cond or Recheck Cond on your tenant column is what you want to see.

Supabase’s own guide adds two habits we follow: add the tenant filter in the client query too (.eq('org_id', …)) so the planner has a value up front, and always write to authenticated on policies so anonymous requests skip them entirely.

When the array gets big

Our test user belongs to three organizations. A support agent or an accountant who works across hundreds of clients is different: the array is longer and each value is another index lookup. Supabase’s guide says lists in the thousands need a closer look. For staff users like that we usually split the rule. Customers get the array policy; staff get a separate policy based on their role, checked once with (select …), and their screens always filter by the client they’ve opened.

We covered that kind of role-based staff access, approval limits included, in role-based access for an internal finance portal.

What shapes the cost

FactorWhy it matters
Number of tables with policiesEach policy needs checking with EXPLAIN as a real user, on realistic data.
Helper functions shared across policiesRewriting them is quick. Finding every policy and view that depends on them takes longer.
Test data at real volumeProblems like version 4 only show up with production-sized tables. We seed data at that size before tuning.
Staff and cross-tenant usersThey usually need their own policies and screens, and that’s design work, not just indexes.

Mistakes we’d avoid

Sources

Spotted something out of date? Tell us

Questions we often hear

Does wrapping auth.uid() in a select always help?

It never hurt in our tests, and Supabase measured large gains when auth.uid() is compared directly with a column. On our membership-based policy it made no measurable difference, because PostgreSQL already ran that lookup once.

Is a security definer function safe in an RLS policy?

Yes, if it takes no input from the caller, sets search_path, and lives in a schema the API doesn’t expose or has execute revoked from anon. Ours only returns the signed-in user’s own organization ids.

Will these numbers match my project?

The exact milliseconds depend on your plan size and data. The ratios and the query plans are what carry over. Run EXPLAIN as a real user on production-sized data to see where you are.

Can you review our Supabase policies?

Yes. On a free 30-minute call an engineer will look at how your tenants are separated and which screens are slow, and tell you what we’d check first.

Is your Supabase app getting slower as customers join?

Tell us which screens are slow and roughly how much data is behind them. On a free 30-minute call an engineer will say where we’d look first.