Supabase "canceling statement due to statement timeout": why queries die after 3 or 8 seconds
By AI App Medic · Updated · Supabase · Performance · RLS · Database
A list page, a dashboard or a search in your app stops loading, usually once the table has grown past a few hundred thousand rows. The request to /rest/v1/ or /rest/v1/rpc/ fails with HTTP 500 and this body:
{
"code": "57014",
"details": null,
"hint": null,
"message": "canceling statement due to statement timeout"
}
Nothing crashed. Postgres stopped the query because it ran longer than the time limit for the role that sent it. Supabase sets these limits per role:
anon(visitors who are not signed in): 3 secondsauthenticated(signed-in users): 8 secondsservice_role: no limit of its own, so the 8 seconds of theauthenticatorrole apply through the APIpostgres(the SQL editor): capped at 2 minutes
So the same query can work for a logged-in user and fail for a visitor, or work in the SQL editor and fail in the app. If the request fails after almost exactly 3 or 8 seconds, this is your problem. There are two ways out: make the query faster, which is nearly always possible, or give that one query more time.
Step 1: reproduce the query as your app runs it
Running the query in the SQL editor tells you very little, because the editor runs as postgres, which owns the tables and bypasses row level security. Run it as the app's role instead. Take a real user id from Authentication, Users:
begin;
set local role authenticated;
select set_config(
'request.jwt.claims',
'{"sub":"PASTE-USER-ID","role":"authenticated"}',
true
);
explain analyze
select * from public.tasks
where project_id = 'PASTE-PROJECT-ID'
order by created_at desc
limit 50;
rollback;
Write the same filters, order and limit the app sends. You can read them from the failing request URL, for example ?project_id=eq.123&order=created_at.desc&limit=50. Look at the Execution Time at the bottom and for these lines in the plan:
Seq Scan on taskswith a large row count: no usable index. See Step 3.Filter: (user_id = auth.uid())or a call to your own function under the scan: the policy runs a function on every row. See Step 2.SubPlanrepeated for each row, often from a policy that queries another table: see Step 2.
The Query Performance report in the Supabase dashboard lists the slowest queries the API has run, which helps when you do not know which request is the slow one.
Step 2: fix policies that run per row
Row level security adds the policy to every query and checks it on every row Postgres reads. A function call in a policy is often evaluated row by row. On a large table that alone can push a query past 8 seconds.
Wrap auth.uid() and auth.jwt() in a select. Postgres then evaluates it once per query instead of once per row. Supabase recommends this pattern in its RLS performance advice:
drop policy "Users read own tasks" on public.tasks;
create policy "Users read own tasks"
on public.tasks for select to authenticated
using (user_id = (select auth.uid()));
Team and role checks are the bigger cost. A policy like using (private.is_member(team_id)) calls the helper for every row. Change the helper to return the user's team ids once and compare against that list. The helper is security definer, so its own read of team_members is not filtered by RLS again:
create schema if not exists private;
create or replace function private.my_team_ids()
returns setof uuid
language sql
security definer
stable
set search_path = ''
as $$
select team_id from public.team_members
where user_id = (select auth.uid())
$$;
grant usage on schema private to authenticated;
grant execute on function private.my_team_ids() to authenticated;
drop policy "Members read team tasks" on public.tasks;
create policy "Members read team tasks"
on public.tasks for select to authenticated
using (team_id in (select private.my_team_ids()));
Also add to authenticated to every policy that only signed-in users need. Without it the policy is also checked for anon, which wastes time on every visitor request. If a policy on one table queries another table whose policy queries back, you get a different error, covered in infinite recursion detected in policy.
Step 3: add the missing indexes
AI builders create tables with a primary key and nothing else. Every column used in a policy, an eq() filter, a join or an order() needs an index once the table grows:
create index if not exists tasks_user_id_idx on public.tasks (user_id);
create index if not exists tasks_team_id_idx on public.tasks (team_id);
-- filter plus sort used by the list page
create index if not exists tasks_project_created_idx
on public.tasks (project_id, created_at desc);
Foreign key columns are not indexed automatically in Postgres, so check each *_id column. For a table with millions of rows in production, use create index concurrently from a direct connection, so writes are not blocked while the index builds. Run Step 1 again and the Seq Scan should turn into an Index Scan. The Index Advisor and Performance Advisor in the dashboard also suggest indexes for slow queries.
Step 4: stop counting and loading everything
Two patterns in generated code are expensive on large tables:
// counts every row the user can see, checking the policy on each one
const { data, count } = await supabase
.from("tasks")
.select("*", { count: "exact" });
// loads the whole table into the browser
const { data } = await supabase.from("tasks").select("*");
An exact count has to visit every visible row even when the page shows ten. Use an estimate for "about 120,000 results" labels, and always paginate:
const pageSize = 50;
const from = page * pageSize;
const { data, count, error } = await supabase
.from("tasks")
.select("id, title, status, created_at", { count: "estimated" })
.eq("project_id", projectId)
.order("created_at", { ascending: false })
.range(from, from + pageSize - 1);
Select only the columns you show. Large jsonb or text columns and deep embedded relations such as select("*, comments(*, author(*))") make every row heavier. Search with ilike '%term%' on a big table cannot use a normal index either; a pg_trgm index or full text search fixes that.
Step 5: check for locks
The timer also runs while a query waits for a lock. If simple queries suddenly time out together, something else may be holding the table: a migration, a long batch update, or a session left idle in transaction. Look for it:
select pid, state, now() - xact_start as running_for, left(query, 120) as query
from pg_stat_activity
where state <> 'idle'
order by xact_start;
A session that has been running or idle in transaction for minutes is the suspect. Find out what it is before you stop it with select pg_cancel_backend(pid);, and run large migrations outside busy hours.
Step 6: raise the limit only where it is needed
Some work is slow even when written well, such as a monthly report or a bulk recalculation called with rpc(). Give that one function more time instead of changing the limit for every request:
alter function public.monthly_report(uuid)
set statement_timeout = '30s';
Supabase documents that a function level setting applies when the function is called through the client libraries. If signed-in users really need a higher limit across the board, change the role and reload the API config:
alter role authenticated set statement_timeout = '15s';
notify pgrst, 'reload config';
-- check it
select rolname, rolconfig from pg_roles
where rolname in ('anon', 'authenticated', 'authenticator');
API queries are capped at 60 seconds whatever you set. Anything longer belongs in a background job, an Edge Function that processes in batches, or a scheduled task with pg_cron, not in a request a user waits for. Do not raise the anon limit to make a public page work: a slow public query is also an easy way for anyone to load your database.
Prevention
Write every new policy with (select auth.uid()) and a to role, and index the column it uses in the same migration. Paginate every list from the first version. Before launch, load a table with realistic data, for example a few hundred thousand rows from generate_series, and run the main screens as a normal user, because a query that is instant on 50 test rows can take seconds on real data. Check the Query Performance report after each release, and treat any API query above one second as a bug to fix before it reaches the 3 or 8 second limit. If the first page load is slow but queries are not, the cause is in the front end; see Lovable app slow first load.
FAQ
What is the default statement timeout in Supabase?
Supabase documents 3 seconds for the anon role, 8 seconds for the authenticated role, and 8 seconds for service_role through the API, inherited from the authenticator role. The postgres role used by the SQL editor is capped at 2 minutes. API queries can be configured up to 60 seconds.
Why does the query run fine in the SQL editor but time out in my app?
The SQL editor runs as postgres, which bypasses row level security and has a much longer timeout. Your app runs as anon or authenticated, so every policy is checked on every row and the 3 or 8 second limit applies. Test the query as the app's role to see the real cost.
Should I just increase the statement timeout?
Rarely as a first step. A longer limit makes users wait longer for the same slow query and uses more database capacity. Fix the policy, index or count first. If one function really needs more time, raise it on that function only.
How do I raise the timeout for signed-in users?
Run alter role authenticated set statement_timeout = '15s'; and then notify pgrst, 'reload config'; so the API picks up the change. Check it with select rolname, rolconfig from pg_roles where rolname = 'authenticated';
Can a lock cause a statement timeout?
Yes. Time spent waiting for a lock counts toward the limit. A long migration, an open transaction or a heavy update on the same rows can make simple queries time out. Look in pg_stat_activity for long running or idle in transaction sessions.
Does upgrading the compute size fix it?
Sometimes, when the database is short on memory or CPU and every query is slow. When one query does a full table scan or runs a function on every row, a bigger instance only moves the point where it fails. Fix the query first and check the database health charts before paying for more compute.
Related guides
- Lovable + Supabase RLS not working: why your data is empty (and how to fix it)
- Supabase error: infinite recursion detected in policy for relation
- Lovable app slow first load: find the huge bundle and cut it down
- Supabase PGRST116 "JSON object requested, multiple (or no) rows returned": what .single() is telling you
- Fix “new row violates row-level security policy” (Supabase error 42501)