mirror of
https://github.com/supabase/supabase.git
synced 2026-12-05 07:59:03 +00:00
Closes DOCS-1496 ## Problem The Debugging performance issues page is moved to the Data API as a part of the Information Architecture plan laid out in Option 1 of the [Docs navigation architecture proposal](https://app.notion.com/p/supabase/Q4-2027-Proposal-Docs-navigation-architecture-3f25004b775f81f49dbad710a732ef61). The [docs tree tests](https://github.com/supabase/evals/tree/docs/ia-tree-tests/evals/docs-tree-tests) in supabase/evals drove the rename. Each test gives an agent a developer goal and only the navigation labels, with no page content and no search. - **The task:** [one test](https://github.com/supabase/evals/tree/docs/ia-tree-tests/evals/docs-tree-tests/investigate-tree-036-client-call-execution-plan) asks how to see the plan Postgres uses for a slow supabase-js `.from('orders').select()` call. Its answer is this page. - **Today's label:** the page sits under Database as "Debugging performance issues". That label names a symptom many pages share, not the tool the page teaches. - **The change:** round 4 of the tests split the `explain()` content into its own topic, labeled "Query plans with explain()" and placed in Data API, Tools, next to the other client tools. Option 1 fixed every task its new topics targeted. - **Why the whole page moves:** `explain()` is the only thing the page covers, so a split would leave an empty source. The page takes the topic's label as its title. ## Solution - **Move, not split:** the whole page covers `explain()`, so a split would leave an empty source. The page moves to `guides/api/query-plans`, and the old URL redirects there. The existing `api/rest/debugging-performance` redirect now points straight to the new URL, so there's no chain. - **Anchors:** the four H2s keep their anchors, so the client reference link to `#enabling-explain` resolves through the redirect. The two H3s, Example data and Expected response, are gone. Nothing links to them. - **Navigation:** both entries in today's navigation point to the new URL, with the label "Query plans with explain()". In Option 1, the Data API, Tools entry points to the new page, and the Database entry is gone, since it would list the page twice. This was the last Option 1 topic that linked to a section of its source page, so the test that tracked those topics is removed. - **Inbound link:** Realtime reports links to the new URL. - **Cross-links:** the page links Query Performance for finding slow queries, Query optimization for plans of SQL you run yourself, Row Level Security performance for slow policies, and the `explain()` client reference. Query optimization and Row Level Security performance link back to it. - **Guide shape:** a value-statement opener with the reason `explain()` is off by default, and the sample table before the query that reads it. The SQL samples have no comments, and the `format` option has an example. Production readers are told to set up the filter before enabling, and the options paragraph warns that `analyze` on a write changes data. - **Row Level Security performance:** the caution about restricting plans now sits above the step that enables them. - **Sample fix:** `pgrst.db_pre_request` holds one function, so the production step now checks for an existing one and says to call the filter from it. The disable step clears the pre-request setting only for readers who set the filter directly. The filter function sets `search_path`, so the Security Advisor doesn't flag it. It matches the `Accept` header case-insensitively anywhere in the list, because PostgREST accepts `Application/vnd.pgrst.plan+text` and the old prefix check let it through. The check for an existing pre-request function reads `pg_db_role_setting`, which also shows per-database settings that `pg_roles.rolconfig` leaves out. When both a global and a per-database setting exist, the page says PostgREST uses the per-database one. The function is created and set as `public.filter_plan_requests`, because PostgREST resolves an unqualified name against the requested schema first. After the filter, the page says the Supabase Platform sets `cf-connecting-ip`, and that a self-hosted project needs a header its proxy overwrites. ### Verification `test-the-docs`, local stack, Supabase CLI v2.39.2. Each SQL fence ran in document order. The `supabase-js` calls were checked through the HTTP request they send, with `Accept: application/vnd.pgrst.plan`. | Step | Result | | --- | --- | | Plan request before enabling | 406, as expected | | Enable, then request a plan | 200, text plan, and JSON with `+json` | | Sample table, no extra grant | readable by `anon` | | Pre-request filter with `set search_path = ''`, non-matching IP | 401 `Not allowed to use application/vnd.pgrst.plan`, normal requests 200 | | Filter, mixed-case `Application/vnd.pgrst.plan+text` | old filter 200 with a plan, new filter 401; matching IP 200 | | Insert plan with `options=analyze` | row persists after the request; without `analyze`, no row | | Existing-function check with an `in database` setting | `pg_db_role_setting` shows it, `rolconfig` doesn't | | Disable | plan requests 406, normal requests 200 | | `cf-connecting-ip` on a hosted project | checked in review on a test project: Cloudflare sets it, and a request that sends its own value is rejected at the edge with `error code: 1000` | ### Not verified - **Deferred:** the TypeScript fences, because the sandbox runs Node only for example apps. The plan values in the example response come from the old page and differ slightly from a local run. - **Old links left on the redirect:** the client reference specs (`supabase_{dart,py,kt,swift}`), the supabase-js doc comment, and one `www` blog post still link to the old URL. ## Manual testing 1. Open [Query plans with explain()](https://docs-git-docs-query-plans-supabase.vercel.app/docs/guides/api/query-plans). See the enable, use, production, and disable sections. 2. Open [the old URL](https://docs-git-docs-query-plans-supabase.vercel.app/docs/guides/database/debugging-performance#enabling-explain). See it redirect to the new page at Enabling `explain()`. 3. In the Database sidebar under Debugging, click **Query plans with explain()**. See the new page open.
157 lines
5.4 KiB
Plaintext
157 lines
5.4 KiB
Plaintext
---
|
|
id: 'row-level-security-performance'
|
|
title: 'Row Level Security performance'
|
|
description: 'Measure and tune Postgres Row Level Security policies.'
|
|
---
|
|
|
|
Measure the cost of Row Level Security (RLS) and tune policies that are already correct. To learn how to write correct policies, see [Row Level Security](/docs/guides/database/postgres/row-level-security).
|
|
|
|
Postgres evaluates a policy expression against each candidate row, so the cost scales with the rows a query scans. This matters most for queries that scan every row in a table, like many `select` operations, including those using limit, offset, and ordering.
|
|
|
|
Three policy rules affect performance enough that they belong with the policy itself rather than here. Apply them first:
|
|
|
|
- [Index the columns your policies filter on](/docs/guides/database/postgres/row-level-security#add-indexes)
|
|
- [Call functions with `select`](/docs/guides/database/postgres/row-level-security#call-functions-with-select)
|
|
- [Specify roles in your policies](/docs/guides/database/postgres/row-level-security#specify-roles-in-your-policies)
|
|
|
|
## Diagnose whether RLS is the bottleneck
|
|
|
|
Confirm that policies are the cost before you rewrite one. Run the query with RLS enabled, then again with it disabled, and compare. If the times are similar, the query itself is the problem.
|
|
|
|
<Admonition type="caution">
|
|
|
|
Disabling RLS exposes every row in the table to any role with a matching grant. Only do this in a non-production environment.
|
|
|
|
</Admonition>
|
|
|
|
To reproduce an API request, set the JWT claims and switch to the role the request runs as:
|
|
|
|
```sql
|
|
set session role authenticated;
|
|
set request.jwt.claims to '{"role":"authenticated", "sub":"5950b438-b07c-4012-8190-6ce79e4bd8e5"}';
|
|
|
|
explain analyze select count(*) from rlstest;
|
|
|
|
set session role postgres;
|
|
```
|
|
|
|
The output shows the policy expression as a filter, and the execution time is the number to compare:
|
|
|
|
```
|
|
Seq Scan on rlstest (cost=0.00..4334.00 rows=1 width=35) (actual time=170.999..170.999 rows=0 loops=1)
|
|
Filter: ((COALESCE(NULLIF(current_setting('request.jwt.claim.sub'::text, true), ''::text), ((NULLIF(current_setting('request.jwt.claims'::text, true), ''::text))::jsonb ->> 'sub'::text)))::uuid = user_id)
|
|
Rows Removed by Filter: 100000
|
|
Planning Time: 0.216 ms
|
|
Execution Time: 171.033 ms
|
|
```
|
|
|
|
`Rows Removed by Filter` is the signal to watch. A policy that removes most of the table on every read is a policy whose filter column needs an index.
|
|
|
|
### Measure through the Data API
|
|
|
|
PostgREST can return the query plan to a Supabase client.
|
|
|
|
<Admonition type="caution">
|
|
|
|
`pgrst.db_plan_enabled` exposes query plans over your Data API. In production, restrict it to your own IP address before you enable it, as described in [Query plans with explain()](/docs/guides/api/query-plans#production-use-with-pre-request-protection).
|
|
|
|
</Admonition>
|
|
|
|
Enable it first:
|
|
|
|
```sql
|
|
alter role authenticator set pgrst.db_plan_enabled to true;
|
|
notify pgrst, 'reload config';
|
|
```
|
|
|
|
Then add the `.explain()` modifier to a query:
|
|
|
|
```js
|
|
const { data, error } = await supabase
|
|
.from('projects')
|
|
.select('*')
|
|
.eq('id', 1)
|
|
.explain({ analyze: true })
|
|
|
|
console.log(data)
|
|
```
|
|
|
|
```
|
|
Aggregate (cost=8.18..8.20 rows=1 width=112) (actual time=0.017..0.018 rows=1 loops=1)
|
|
-> Index Scan using projects_pkey on projects (cost=0.15..8.17 rows=1 width=40) (actual time=0.012..0.012 rows=0 loops=1)
|
|
Index Cond: (id = 1)
|
|
Filter: false
|
|
Rows Removed by Filter: 1
|
|
Planning Time: 0.092 ms
|
|
Execution Time: 0.046 ms
|
|
```
|
|
|
|
## Filter in the client query too
|
|
|
|
Policies are implicit `where` clauses, so it's common to run `select` statements without any filters. That's a bad pattern for performance. Instead of this:
|
|
|
|
{/* prettier-ignore */}
|
|
```js
|
|
const { data } = await supabase
|
|
.from('table')
|
|
.select()
|
|
```
|
|
|
|
Always add a filter:
|
|
|
|
{/* prettier-ignore */}
|
|
```js
|
|
const { data } = await supabase
|
|
.from('table')
|
|
.select()
|
|
.eq('user_id', userId)
|
|
```
|
|
|
|
Even though this duplicates the contents of the policy, Postgres can use the filter to construct a better query plan.
|
|
|
|
## Avoid joins in policy expressions
|
|
|
|
You can often rewrite a policy to avoid a join between the source and the target table. Fetch the relevant data from the target table into an array or set instead, then use an `in` or `any` operation in your filter.
|
|
|
|
This policy joins the source `test_table` to the target `team_user`:
|
|
|
|
```sql
|
|
create policy "rls_test_select" on test_table
|
|
to authenticated
|
|
using (
|
|
(select auth.uid()) in (
|
|
select user_id
|
|
from team_user
|
|
where team_user.team_id = test_table.team_id -- joins to the source table
|
|
)
|
|
);
|
|
```
|
|
|
|
Rewriting it selects the filter criteria into a set instead:
|
|
|
|
```sql
|
|
create policy "rls_test_select" on test_table
|
|
to authenticated
|
|
using (
|
|
team_id in (
|
|
select team_id
|
|
from team_user
|
|
where user_id = (select auth.uid()) -- no join
|
|
)
|
|
);
|
|
```
|
|
|
|
You can also use a [security definer function](/docs/guides/database/postgres/row-level-security#use-security-definer-functions) to bypass RLS on the join table.
|
|
|
|
<Admonition type="note">
|
|
|
|
If the list exceeds 1000 items, a different approach may be needed, or you may need to analyze the approach to ensure that the performance is acceptable.
|
|
|
|
</Admonition>
|
|
|
|
## More resources
|
|
|
|
- [Row Level Security](/docs/guides/database/postgres/row-level-security)
|
|
- [Managing indexes in Postgres](/docs/guides/database/postgres/indexes)
|
|
- [Query optimization](/docs/guides/database/query-optimization)
|