The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
migrate(docs): troubleshooting 14 (#30944)
Charisb90467581e05
diff --git a/apps/docs/content/troubleshooting/deprecated-rls-features-Pm77Zs.mdx b/apps/docs/content/troubleshooting/deprecated-rls-features-Pm77Zs.mdxnew file mode 100644index 00000000000..b27677b816b--- /dev/null+++ b/apps/docs/content/troubleshooting/deprecated-rls-features-Pm77Zs.mdx@@ -0,0 +1,45 @@+---+title = "Deprecated RLS features"+github_url = "https://github.com/orgs/supabase/discussions/16703"+date_created = "2023-08-22T13:17:50+00:00"+topics = ["database"]+keywords = ["rls", "deprecated", "auth", "policy"]+---++## The `auth.role()` function is now deprecated++The `auth.role()` function has been deprecated in favour of using the `TO` field, natively supported within Postgres:++```sql+-- DEPRECATED+create policy "Public profiles are viewable by everyone."+on profiles for select using (+ auth.role() = 'authenticated' or auth.role() = 'anon'+);++-- RECOMMENDED+create policy "Public profiles are viewable by everyone."+on profiles for select+to authenticated, anon+using (+ true+);+```++## The `auth.email()` function is now deprecated++The `auth.email()` function has been deprecated in favour a more generic function to return the full JWT:++```sql+- DEPRECATED+create policy "User can view their profile."+on profiles for select using (+ auth.email() = email+);++-- RECOMMENDED+create policy "User can view their profile."+on profiles for select using (+ (auth.jwt() ->> 'email') = email+);+```diff --git a/apps/docs/content/troubleshooting/do-i-need-to-expose-security-definer-functions-in-row-level-security-policies-iI0uOw.mdx b/apps/docs/content/troubleshooting/do-i-need-to-expose-security-definer-functions-in-row-level-security-policies-iI0uOw.mdxnew file mode 100644index 00000000000..285b7d05e74--- /dev/null+++ b/apps/docs/content/troubleshooting/do-i-need-to-expose-security-definer-functions-in-row-level-security-policies-iI0uOw.mdx@@ -0,0 +1,18 @@+---+title = 'Do I need to expose "security definer" Functions in Row Level Security Policies?'+github_url = "https://github.com/orgs/supabase/discussions/16784"+date_created = "2023-08-24T13:45:01+00:00"+topics = ["database"]+keywords = ["security", "function", "schema", "policy", "definer"]+---++PostgREST supports 2 config parameters:++- Exposed Schemas+- Extra Search Path++++You do not need to add your "security definer" Functions to either of these if you are using them in your Policies.++PostgREST doesn’t need to know about this function on extra search path or exposed schemas, as long as you explicitly use the schema inside RLS (eg: `security.rls_func`).diff --git a/apps/docs/content/troubleshooting/monitor-supavisor-postgres-connections.mdx b/apps/docs/content/troubleshooting/monitor-supavisor-postgres-connections.mdxindex c202f6509bb..787c3331675 100644--- a/apps/docs/content/troubleshooting/monitor-supavisor-postgres-connections.mdx+++ b/apps/docs/content/troubleshooting/monitor-supavisor-postgres-connections.mdx@@ -14,6 +14,7 @@ This guide explains how connections impact your Supabase database's performanceSupabase has an [open-source Grafana Repo](https://github.com/supabase/supabase-grafana) that displays real-time metrics of your database. Although the [Reports Dashboard ](/dashboard/project/_/reports) provides similar metrics, it averages the data by the hour or day. Having visuals of your connection usage can help you better allocate resources._Visual of Grafana Dashboard_+It can be run locally within Docker. Alternatively, you can deploy it to fly.io or Grafana Cloud, which are better for long-term data collection.@@ -23,6 +24,7 @@ Installation instructions can be found in it the [metrics docs ](/docs/guides/pl## Observing connectionsIn Supabase Grafana, the "Client Connections" graph shows connections to both Supavisor and Postgres+- **Yellow**: The yellow line represents the number of actively querying and idle connections to the Supavisor Pooler.@@ -81,6 +83,7 @@ If you believe a connection should be killed, you can do so by running the folloThe Supavisor Pooler is an intermediary between your clients (application servers) and the database. In transaction mode (port 6543), it can enable Postgres to share single connections with many clients, only allowing access when a query is pending. This prevents idle clients from hogging a direct connection and allows for more throughput.In cases where you see significantly more pooler connections than direct connections, if you can, you should consider increasing how many direct connections the pooler is allowed to manage in the [Dashboard's Database Settings](/dashboard/project/_/settings/database):+.The general rule is that if you are using the PostgREST database API, you should avoid raising your pool size past 40%. Otherwise, you can commit 80% to the pool. This leaves adequate room for the Authentication server and other utilities.diff --git a/apps/docs/content/troubleshooting/realtime-concurrent-peak-connections-quota-jdDqcp.mdx b/apps/docs/content/troubleshooting/realtime-concurrent-peak-connections-quota-jdDqcp.mdxnew file mode 100644index 00000000000..be05dc98a95--- /dev/null+++ b/apps/docs/content/troubleshooting/realtime-concurrent-peak-connections-quota-jdDqcp.mdx@@ -0,0 +1,15 @@+---+title = 'Realtime "Concurrent Peak Connections" quota'+github_url = "https://github.com/orgs/supabase/discussions/19391"+date_created = "2023-12-03T17:05:20+00:00"+topics = ["realtime", "self-hosting"]+keywords = ["quota", "connections"]+---++The "Concurrent Peak Connections" quota refers to the maximum number of simultaneous connections to Supabase Realtime.++For example, if you have a chat application that uses Supabase Realtime and you have 100 users who are all connected and subscribed to the chat channel, then you would have 100 concurrent peak connections. Each client can connect to multiple Realtime channels (see: https://supabase.com/docs/guides/realtime/concepts#channels).++This quota applies to all Supabase projects, including self-hosted projects, but you can increase it depending on your use case. For hosted Supabase projects, select the plan that fits your Realtime usage and reach out if you need custom quotas. For those self-hosting Supabase, you can set those limits yourself by setting the `max_concurrent_users` field on the tenant record (see: https://supabase.com/docs/guides/self-hosting/realtime/config).++You can learn more about Realtime quotas here: https://supabase.com/docs/guides/realtime/quotas#quotas-by-plandiff --git a/apps/docs/content/troubleshooting/rls-performance-and-best-practices-Z5Jjwv.mdx b/apps/docs/content/troubleshooting/rls-performance-and-best-practices-Z5Jjwv.mdxnew file mode 100644index 00000000000..8fbca15f020--- /dev/null+++ b/apps/docs/content/troubleshooting/rls-performance-and-best-practices-Z5Jjwv.mdx@@ -0,0 +1,234 @@+---+title = "RLS Performance and Best Practices"+github_url = "https://github.com/orgs/supabase/discussions/14576"+date_created = "2023-05-24T17:46:48+00:00"+topics = ["auth", "database"]+keywords = ["performance", "security", "queries", "indexes", "roles"]+---++## RLS Performance and Best Practices++Although most of the time spent on thinking about RLS is to get it to handle security needs, the impact of it on performance+of your queries can be massive.+This is especially true on queries that look at every row in a table like for many select operations and updates.+Note that queries that use limit and offset will usually have to query all rows to determine order, not just the limit amount so they are impacted too.++Please see the last section for ways to measure the performance of your queries as you test RLS improvements.++### Is RLS causing my performance issue (on a single table query)?++For very slow queries, or if using the tools at end of article, run a query with RLS enabled on the table and then with it disabled (this should only be done in a non production environment). If the results are similar then your query itself is likely the performance issue. Although, remember any join tables in RLS will also need to run their RLS unless a security definer function is used to bypass them. You can also create a service_role client to run the query bypassing RLS if in a secure environment.++### How to improve RLS performance.++The following tips are very broad and each may or may not help the specific case involved. Some changes, like adding indexes, should be backed out if they do not make a difference in RLS performance and you are not using them for filtering performance.++#### (1) The first thing to try is put an index on columns used in the RLS that are not primary keys or unique already.++For RLS like:+`auth.uid() = user_id`+Add an index like:+`create index userid on test_table using btree (user_id) tablespace pg_default;`+Improvement seen over 100x on large tables.++#### (2) Another method to improve performance is to wrap your RLS queries and functions in select statements.++This method works well for jwt functions like auth.uid() and auth.jwt() as well as any other functions including security definer type.+Wrapping the function in some SQL causes an initPlan to be run by the optimizer which allows it to "cache" the results versus calling the function+on each row.+WARNING: You can only do this if the results of the query or function do not change based on the row data.+For RLS like this:+`is_admin() or auth.uid() = user_id`+Use this instead:+`(select is_admin()) OR (select auth.uid()) = user_id`++<details>+ <summary>is_admin() function:</summary>++```sql+CREATE OR REPLACE FUNCTION is_admin()+ RETURNS boolean as+$$+begin+ return exists(select from rlstest_roles where auth.uid() = user_id and role = 'admin');+end;+$$ language plpgsql security definer;+```++</details>++#### (3) Do not rely on RLS for filtering but only for security.++Instead of doing this (JS client example):+`.from('table').select()`+With an RLS policy of:+`auth.uid() = user_id`+Add a filter in addition to the RLS:+`.from('table').select().eq('user_id',userId)`++#### (4) Use security definer functions to do queries on other tables to bypass their RLS when possible.++Instead of having this RLS where the roles_table has an RLS select policy of `auth.uid() = user_id`:+`exists (select 1 from roles_table where auth.uid() = user_id and role = 'good_role')`+Create a security definer function has_role() and do:+`(select has_role())` with code of `exists (select 1 from roles_table where auth.uid() = user_id and role = 'good_role')`+Note that you should wrap your security definer function in select if it is a fixed value per 2.+Remember functions you use in RLS can be called from the API.+Secure your functions in an alternate schema if their results would be a security leak.+Warning: If your security definer function uses row information as an input parameter be sure to test performance as you can't wrap the function as in 2.++<details>+ <summary>has_role() function:</summary>++```sql+CREATE OR REPLACE FUNCTION has_role()+ RETURNS boolean as+$$+begin+ return exists (select 1 from roles_table where auth.uid() = user_id and role = 'good_role')+end;+$$ language plpgsql security definer;+```++</details>++#### (5) Always optimize join queries to compare row columns to fixed join data.++Instead of querying on a row column in a join table WHERE, organize your query to get all+the column values that meet your query into an array or set.+Then use an IN or ANY operation to filter against the row column.+This RLS to allow select only for rows where the team_id is one the user has access to:+`auth.uid() in (select user_id from team_user where team_user.team_id = table.team_id)`+will be much slower than:+`team_id in (select team_id from team_user where user_id = auth.uid())`+Also consider moving the join query to a security definer function to avoid RLS on join table:+`team_id in (select user_teams())`+Note that if the `in` list gets to be over 10K items, then extra analysis is likely needed. See this follow up testing: https://github.com/GaryAustin1/RLS-Performance/tree/main/tests/Supabase-Docs-Test .++#### (6) Use role in TO option or roles dropdown in the dashboard.++Never just use RLS involving auth.uid() or auth.jwt() as your way to rule out 'anon' role.+Always add 'authenticated' to the approved roles instead of nothing or public.+Although this does not improve the query performance for the signed in user it does+eliminate 'anon' users without taxing the database to process the rest of the RLS.++### Sample results++The code used for the below tests can be found here: [LINK](https://github.com/GaryAustin1/RLS-Perfomance):+The tests are doing selects on a 100K row table. Some have an additional join table.++Show RLS and before after for above examples.++| Test | RLS Before | RLS After | SQL | SQL |+| ---- | --------------------------------- | -------------------------------------------------- | ------- | ------ |+| 1 | auth.uid()=user_id | user_id indexed | 171ms | <.1 |+| 2a | auth.uid()=user_id | (select auth.uid()) = user_id | 179 | 9 |+| 2b | is*admin() \_table join* | (select is*admin()) \_table join* | 11,000 | 7 |+| 2c | is_admin() OR auth.uid()=user_id | (select is_admin()) OR (select auth.uid()=user_id) | 11,000 | 10 |+| 2d | has_role()=role | (select has_role())=role | 178,000 | 12 |+| 2e | team_id=any(user_teams()) | team_id=any(array(select user_teams())) | 173000 | 16 |+| 3 | auth.uid()=user_id | add .eq or where on user_id | 171 | 9 |+| 5 | auth.uid() in _table join on col_ | col in _table join on auth.uid()_ | 9,000 | 20 |+| 6 | No TO policy | TO authenticated (anon accessing) | 170 | <.1 |++### Tools to measure performance++Postgres has tools to analyze the peformance of queries. https://www.postgresql.org/docs/current/sql-explain.html+The use of explain in detail for query analysis is beyond the scope of this discussion.+Here we will use it mainly to get a performance metric to compare times.+In order to do RLS testing you need to setup the user jwt claims and change the running user to `anon` or `authenticated`.++```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;+```++This will return results like:++```+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+```++In this case the execution time is the critical number we need to compare.++PostgREST allows use of explain to get performance information on your queries with Supabase clients.++Before using this feature you need to run the following command in the Dashboad SQL editor (should not be used in production):++```sql+alter role authenticator set pgrst.db_plan_enabled to true;+NOTIFY pgrst, 'reload config';+```++Then you can use the .explain() modifier to get performance metrics.++```js+const { data, error } = await supabase+ .from('projects')+ .select('*')+ .eq('id', 1)+ .explain({ analyze: true })++console.log(data)+```++This will return a result like:++```+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+```++\*These two github discussions cover the history that lead to this analysis...++[Stable functions do not seem to be honored in RLS in basic form](https://github.com/orgs/supabase/discussions/9311)+[current_setting can lead to bad performance when used on RLS](https://github.com/PostgREST/postgrest-docs/issues/609#)+Thanks Steve Chavez and Wolfgang Walther in those threads.++### Added example of security definer function having select of a team table, comparing against a column in main table++The example is in the test data as test2f.+In this case we start with a 1M row table with a team_id column.+We have a 1000 row team table that has user_ids and team(s) they belong too.+Basic RLS for a select would be `team_id = ANY(user_teams())`+This case times out with over 3 minutes as 1M rows must be searched and the function is run each time on 1000 rows.+Changing to wrap the function (method 2) `team_id = ANY(ARRAY(select user_teams()))` is a big improvement but can still take seconds.+Adding an index to team_id is the big win, but only with the second case. Without, the index case still times out.++<details>+ <summary>user_teams() function returning an array:</summary>++```sql+CREATE OR REPLACE FUNCTION user_teams()+ RETURNS int[] as+$$+begin+ return array( select team_id from team_user where auth.uid() = user_id);+end;+$$ language plpgsql security definer;+```++</details>++Some results:++| Policy | Index | Main Rs | Team Rs | on 10 teams | 100 | 500 | note |+| -------------------------------- | ----- | ------- | ------- | ----------- | ----- | ----- | ------------------ |+| =ANY(user_teams()) | no | 1M | 1000 | >2Min | >2Min | >2Min | TO or killed |+| =ANY(user_teams()) | yes | 1M | 1000 | >2Min | >2Min | >2Min | TO or killed |+| =ANY(ARRAY(select user_teams())) | no | 1M | 1000 | 170ms | 700 | 3300 | |+| =ANY(ARRAY(select user_teams())) | yes | 1M | 1000 | 2ms | 3 | 3 | |+| in(1,2,3...100) | no | 1M | NA | 130ms | 142 | x | baseline check |+| =ANY(ARRAY(select user_teams())) | yes | 1M | 10K | x | x | x | 24ms (on 1K teams) |diff --git a/apps/docs/content/troubleshooting/rls-simplified-BJTcS8.mdx b/apps/docs/content/troubleshooting/rls-simplified-BJTcS8.mdxnew file mode 100644index 00000000000..3b97b59d072--- /dev/null+++ b/apps/docs/content/troubleshooting/rls-simplified-BJTcS8.mdx@@ -0,0 +1,127 @@+---+title = "RLS Simplified"+github_url = "https://github.com/orgs/supabase/discussions/29114"+date_created = "2024-09-05T15:20:13+00:00"+topics = ["database", "auth"]+keywords = ["rls", "sql", "policy"]+---++### TL;DR Basic Summary:++Row-Level Security (RLS) Policy: A `WHERE` or `CHECK` condition applied automatically to database queries++Key features:++- Applies without being explicitly added to each query, which makes it good for policing row access from unknown entities, such as those leveraging the anon or authenticated roles.+- Can be set for specific actions (e.g., SELECT, INSERT)+- Can target particular database roles (e.g., "anon", "authenticated")++Contrast with regular conditions:++- Regular conditions: Apply to all roles and must be added manually to each query+- RLS policies: Applied automatically to specified actions and roles++## Hands on walk-through for conditions++### USING:++The `USING` keyword inspects the value of row to see if it should be made visible to the query.++When you SELECT, UPDATE, or DELETE, you have to use a WHERE statement to search for specific rows:++```sql+-- select+select *+from some_table+where id = 5;++-- update+update some_table+set id = 6+where id = 5;++-- delete+delete from some_table+where id = 6;+```++Even when you don't use a WHERE statement, there's still an implicit one:++```sql+-- ...your query+WHERE true;+```++The `USING` clause appends more to the WHERE statement:++```sql+-- Your Using condition+USING (+ (select auth.uid()) = user_id+);++-- Your query without RLS:+SELECT * FROM some_table+WHERE id = 5 OR id = 6;++-- Your query after RLS+SELECT * FROM some_table+WHERE+ (id = 5 OR id = 6)+ AND+ (select auth.uid()) = user_id) -- <--- added by the USING clause;+```++### WITH CHECK:++Let's say you have a profile table. Well, you don't want user's to be able to modify their user_id when they make an insert, do you?++The `WITH CHECK` condition inspects values that are being added or modified. For INSERT you'd use it by itself. There's no need for a using clause:++```sql+-- Allow users to add to table, but make sure their user_id matches the one in their JWT:++create policy "Allow user to add posts"+on "public"."posts"+as PERMISSIVE+for INSERT+to authenticated+with check(+ (select auth.uid()) = user_id+);++-- Example: failing insert+INSERT INTO posts+VALUES (<false id>, <comment>);++-- Example: successful insert+INSERT INTO posts+VALUES (<real id>, <comment>);+```++INSERTs do not rely on WHERE clauses, but they can have constraints. In this case, the RLS acts as a CHECK constraint against a column, e.g.:++```sql+ALTER TABLE table_name+ADD CONSTRAINT constraint_name CHECK (condition);+```++What distinguishes it from normal `CHECK` constraints is that it is only activate for certain roles or methods.++### UPDATEs:++UPDATE both filters for rows to change and then adds new values to the table, so it requires both USING and WITH CHECK conditions:++```sql+create policy "Allow user to edit their stuff"+on "public"."<SOME TABLE NAME>"+as RESTRICTIVE+for UPDATE+to authenticated+using (+ (select auth.uid()) = user_id+)+with check(+ (select auth.uid()) = user_id+);+```diff --git a/apps/docs/public/img/troubleshooting/d756aeb0-515f-425d-b737-75a935935b73.png b/apps/docs/public/img/troubleshooting/d756aeb0-515f-425d-b737-75a935935b73.pngnew file mode 100644index 00000000000..10fb585b240Binary files /dev/null and b/apps/docs/public/img/troubleshooting/d756aeb0-515f-425d-b737-75a935935b73.png differ