Q: Why is PostgreSQL CPU pegging at 100% on Supabase with Row Level Security enabled, and how do you fix it?
Supabase interview questions on RLS performance: wrap auth.uid() in a select, index policy columns, use to authenticated, and read EXPLAIN ANALYZE output.
Want to master this scenario in a live sandbox? KodeKloud's PostgreSQL Database Administration & High Availability Course covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Direct Answer: This is one of the more practical supabase interview questions because the symptom looks like a capacity problem and the cause is usually a policy. Row Level Security adds the policy expression to every query on the table. If that expression calls auth.uid() directly, PostgreSQL may evaluate the function for each row it examines instead of once per query. On a table with a few hundred thousand rows, that turns a cheap lookup into a CPU-bound scan. Here is the order I work in: find the expensive statements, read the plan, rewrite the policy, then index the columns it touches.
Find the Statements Burning CPU with pg_stat_statements
I start with data from the database, not guesses. pg_stat_statements is available on Supabase and ranks queries by cumulative execution time. I look for statements against tables that have RLS enabled, with a high total_exec_time and a high mean_exec_time. The statement text will not show the policy, so the next step is to reproduce it under the same role.
SELECT left(query, 80) AS query,
calls,
round(total_exec_time::numeric, 0) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 5;
-- query | calls | total_ms | mean_ms
-- select * from todos where done = false | 48210 | 913400 | 18.95
Reproduce as the Authenticated Role and Read the Plan
Running EXPLAIN as the postgres role bypasses RLS and tells you nothing. I switch to the authenticated role inside a transaction and set the JWT claims that auth.uid() reads, then run EXPLAIN (ANALYZE, BUFFERS). Watch for a sequential scan on the table, a Filter line that contains auth.uid() and a very high Buffers count. Those three together point at per-row evaluation and a missing index.
BEGIN;
SET LOCAL ROLE authenticated;
SELECT set_config('request.jwt.claims',
'{"sub":"8f6a1c52-0000-4000-8000-000000000001","role":"authenticated"}', true);
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM todos WHERE done = false;
-- Seq Scan on todos (actual time=0.03..412.5 rows=120 loops=1)
-- Filter: ((auth.uid() = user_id) AND (NOT done))
-- Rows Removed by Filter: 410000
-- Buffers: shared hit=5210
ROLLBACK;
Rewrite the Policy: select-wrap auth.uid() and Scope with to authenticated
Wrapping the call as (select auth.uid()) lets the planner treat it as an InitPlan that runs once and caches the result for the statement. This works because the value does not depend on the row. I also add the to authenticated clause so the policy is skipped entirely for the anon role instead of being evaluated and failing. The same wrapping applies to auth.jwt() and to any stable function that does not reference the row.
DROP POLICY IF EXISTS "own todos" ON public.todos;
CREATE POLICY "own todos" ON public.todos
FOR SELECT
TO authenticated
USING ( (select auth.uid()) = user_id );
-- Re-run EXPLAIN: expect an InitPlan line and an index condition
-- InitPlan 1
-- -> Result
-- -> Index Scan using todos_user_id_idx on todos
-- Index Cond: (user_id = (InitPlan 1).col1)
Index the Columns Your Policies Filter On
A cached auth.uid() still needs something to compare against. Any column that appears in a policy, such as user_id or tenant_id, should have a b-tree index, since policy predicates are appended to every query as ordinary filters. For multi-tenant tables I usually add a composite index that matches both the policy column and the most common query filter.
CREATE INDEX CONCURRENTLY todos_user_id_idx ON public.todos (user_id);
-- Composite when most queries also filter on a status flag
CREATE INDEX CONCURRENTLY todos_user_done_idx ON public.todos (user_id, done);
ANALYZE public.todos;
Use security definer Helpers Carefully for Membership Checks
Policies that join to a membership table can be slow and can recurse into that table's own policies. A security definer function runs with its owner's rights and avoids that, but it also bypasses RLS on whatever it reads, so I treat it like a privileged API. I keep it in a schema that is not exposed through the API, set an empty search_path, return only a boolean, and call it through a select wrapper so it is evaluated once per statement.
CREATE SCHEMA IF NOT EXISTS private;
CREATE OR REPLACE FUNCTION private.is_team_member(_team uuid)
RETURNS boolean
LANGUAGE sql STABLE SECURITY DEFINER
SET search_path = ''
AS $$
SELECT EXISTS (
SELECT 1 FROM public.team_members tm
WHERE tm.team_id = _team AND tm.user_id = (select auth.uid())
);
$$;
CREATE POLICY "team read" ON public.projects
FOR SELECT TO authenticated
USING ( (select private.is_team_member(team_id)) );
- I find the hot statements in pg_stat_statements, then reproduce them as the authenticated role so RLS is actually applied.
- I read EXPLAIN (ANALYZE, BUFFERS) for a sequential scan and a Filter that calls auth.uid() per row.
- I rewrite policies with (select auth.uid()) and to authenticated, and index the columns each policy compares.
- For membership checks I use a narrow security definer function with an empty search_path, called inside a select.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- Running EXPLAIN as the postgres role That role bypasses RLS, so the plan shows none of the policy cost you are trying to fix.
- Calling auth.uid() bare in a policy The planner can evaluate it per row, which multiplies CPU cost on large tables.
- Leaving policy columns unindexed Every query becomes a sequential scan with the policy filter applied row by row.
- Creating security definer functions in the public schema without a fixed search_path They can be called through the API and are exposed to search_path hijacking while bypassing RLS.