The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
migrate(docs): troubleshooting 5 (#30943)
Charisf2c354ef62a4
diff --git a/apps/docs/content/troubleshooting/discovering-and-interpreting-api-errors-in-the-logs-7xREI9.mdx b/apps/docs/content/troubleshooting/discovering-and-interpreting-api-errors-in-the-logs-7xREI9.mdxnew file mode 100644index 00000000000..6acdf33c654--- /dev/null+++ b/apps/docs/content/troubleshooting/discovering-and-interpreting-api-errors-in-the-logs-7xREI9.mdx@@ -0,0 +1,350 @@+---+title = "Discovering and Interpreting API Errors in the Logs"+github_url = "https://github.com/orgs/supabase/discussions/22849"+date_created = "2024-04-18T02:38:44+00:00"+topics = ["database", "platform"]+keywords = ["logs", "api", "errors", "postgrest", "cloudflare"]+---++> A complimentary [guide](https://github.com/orgs/supabase/discussions/26224) was made for the Postgres logs++# Navigating the API logs:++The Database API is powered by a [ PostgREST web-server](https://postgrest.org/en/v12/), recording every request to the API Edge Network logs. To precisely navigate them, use the [Log Explorer](https://supabase.com/dashboard/project/_/logs/explorer). These logs are managed through [Logflare](https://supabase.com/blog/supabase-logs-self-hosted) and can be queried with a subset of BigQuery SQL syntax.++The log table that contains API requests is `edge_logs`.++Notably, it contains:+| field | description |+--------|-------------|+| event_message | the log's message |+| timestamp | time event was recorded |+| request metadata | metadata about the REST request |+| response metadata | metadata about the REST response |++The request and response columns are arrays in the metadata field and must be unnested. This is done with a `cross join`.++**Unnesting example**++```sql+select+ -- the event message does not require unnesting+ event_message,+ -- unnested status_code column from metadata.response field+ status_code+from+ edge_logs+ -- Unpack data stored in the 'metadata' field+ cross join unnest(metadata) as metadata+ -- After unpacking the 'metadata' field, extract the 'response' field from it+ cross join unnest(response) as response;+```++The most useful fields for debugging are:++> NOTE: not every field is included below. For a full list, check the API Edge field reference in the [Log Explorer](https://supabase.com/dashboard/project/_/logs/explorer)++## Request object++### Cloudflare geographic data:++**Suggested use cases:**++- Detecting abuse from a specific region+- Detecting activity spikes from certain regions++| Column | Description | Sample value |+| -------------------- | --------------------- | ----------------------------------------------------- |+| request.cf.city | Requester's city | Munich |+| request.cf.country | Requester's country | [DE](https://www.iso.org/iso-3166-country-codes.html) |+| request.cf.continent | Requester's continent | EU |+| request.cf.region | Requester's region | Bavaria |+| request.cf.latitudex | Requester's latitude | 48.10840 |+| request.cf.longitude | Requester's longitude | 11.61020 |+| request.cf.timezone | Requester's timezone | Europe/Berlin |++**Unnesting example:**++```sql+select+ city+from+ edge_logs+-- Unpack 'metadata' field+cross join unnest(metadata) AS metadata+-- unpack 'request' from 'metadata'+cross join unnest(request) AS request;+-- unpack 'cf' from 'request'+cross join unnest(cf) AS cf;+```++### IP and browser/environment data:++**Suggested use cases:**++- Detecting request behavior from IP+- Detecting abuse by IP+- Detecting errors by user_agent++| Column | Description | Sample value |+| -------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------- |+| request.headers.cf_connecting_ip | Requester's IP | 80.81.18.138 |+| request.headers.user_agent | Requester's browser or app environment | Mozilla/5.0 (Linux; Android 11; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Mobile Safari/537.36 |++**Unnesting example:**++```sql+select+ cf_connecting_ip+from+ edge_logs+-- Unpack 'metadata' field+cross join unnest(metadata) AS metadata+-- unpack 'request' from 'metadata'+cross join unnest(request) AS request;+-- unpack 'headers' from 'request'+cross join unnest(headers) AS headers;+```++### query type and formatting data:++**Suggested use cases:**++- identify problematic queries+- identify unusual behavior by authenticated users++| Column | Description | Sample value |+| --------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |+| request.method | Request Method (PATCH, GET, PUT...) | GET |+| request.url | Request URL, which contains the PostgREST formatted query | https://yuhplfrsdxxxtldakizi.supabase.co/rest/v1/users?select=username&id=eq.63b6190e-214f-4b8a-b72d-3af6e1921411&limit=1 |+| request.sb.auth_users | authenticated user's ID | 63b6190e-214f-4b8a-b72d-3af6e1921411 |++**Unnesting example:**++```sql+select+ method,+ url,+ auth_users+from+ edge_logs+-- Unpack 'metadata' field+cross join unnest(metadata) AS metadata+-- unpack 'request' from 'metadata'+cross join unnest(request) AS request;+-- unpack 'sb' from 'request'+cross join unnest(sb) AS sb;+```++## Response object++### Status code:++**Suggested use cases:**++- detect success/errors++| Column | Description | Sample value |+| -------------------- | --------------------------------------- | ------------ |+| response.status_code | Response status code (200, 404, 500...) | 404 |++**Unnesting example:**++```sql+select+ status_code+from+ edge_logs+ -- Unpack 'metadata' field+ cross join unnest(metadata) as metadata+ -- unpack 'response' from 'metadata'+ cross join unnest(response) as response;+```++# Finding errors++### API Level errors++The `metadata.request.url` contains PostgREST formatted queries.++For example, the following call to the JS client:++```js+let { data: countries, error } = await supabase.from('countries').select('name')+```++translates to calling the following endpoint:++```bash+https://<project ref>.supabase.co/rest/v1/countries?select=name+```++You can use regex ([Advanced Regex Guide](https://github.com/orgs/supabase/discussions/22640)) to find the objects related to your query. Try isolating by:++- function names+- column names+- table names+- query methods (select, insert, ...)++Example:++```sql+select+ cast(timestamp as datetime) as timestamp,+ status_code,+ url,+ event_message+from edge_logs+cross join unnest(metadata) as metadata+cross join unnest(response) AS request;+cross join unnest(response) AS response;+where+ -- find all errors+ status_code >= 400+ and+ -- find queries featuring the a specific <table_name> and <column_name>+ (+ regexp_contains(url, '<table_name>')+ and+ regexp_contains(event_message, '<column_name1>|<column_name2>')+ )+```++PostgREST has an [error reference table](https://postgrest.org/en/v12/references/errors.html) that you can use to interpret status codes.++### Database-level errors++However, some errors that are reported through the Database API occur at the PostgreSQL level. If it is not clear which error occurred you should reference the timestamp of the error and try to see if you can find it in the Postgres logs.++```sql+select+ cast(postgres_logs.timestamp as datetime) as timestamp,+ error_severity,+ user_name,+ query,+ detail,+ sql_state_code,+ event_message+from postgres_logs+ cross join unnest(metadata) as metadata+ cross join unnest(metadata.parsed) as parsed+where+ -- filter only for error events+ regexp_contains(parsed.error_severity, 'ERROR|FATAL|PANIC')+ and+ -- All DB API requests are registered as the authenticator role+ parsed.user_name = 'authenticator'+ and+ -- find failed queries featuring the function <function_name>+ regexp_contains(parsed.query, '<function_name>')+ and+ -- limit the time of the search to be around the time of the failed API request+postgres_logs.timestamp between '2024-04-15 10:50:00' AND '2024-04-15 10:50:27'+order by+ timestamp desc+limit 100;+```++Like PostgREST, PostgreSQL has a [reference table](https://www.postgresql.org/docs/current/errcodes-appendix.html) for interpreting error codes.++## PostgREST server and Cloudflare errors++In some cases, errors may emerge because of Cloudflare or PostgREST server errors. For 500 and above errors, you may want to check your [PostgREST](https://supabase.com/dashboard/project/_/logs/postgrest-logs) logs and the [Cloudflare docs.](https://developers.cloudflare.com/support/troubleshooting/cloudflare-errors/troubleshooting-cloudflare-5xx-errors/#error-502-bad-gateway-or-error-504-gateway-timeout))++# Practical examples:++**Find All Errors:**++```sql+select+ cast(timestamp as datetime) as timestamp,+ status_code,+ event_message,+ path+from+ edge_logs+ cross join unnest(metadata) as metadata+ cross join unnest(response) as response+ cross join unnest(request) as request+where+ -- find all errors+ status_code >= 400+ and regexp_contains(path, '^/rest/v1/');+-- only look at DB API+```++**Group errors by path and code:**++```sql+select+ status_code,+ path,+ count(path) as reoccurrence_per_path+from+ edge_logs+ cross join unnest(metadata) as metadata+ cross join unnest(response) as response+ cross join unnest(request) as request+where+ -- find all errors+ status_code >= 400+ and regexp_contains(path, '^/rest/v1/') -- only look at DB API+group by path, status_code+order by reoccurrence_per_path;+```++**Find requests by region:**++```sql+select+ path,+ region,+ count(region) as region_count+from+ edge_logs+ cross join unnest(metadata) as metadata+ cross join unnest(request) as request+ cross join unnest(cf) as cf+where+ -- only look at DB API+ regexp_contains(path, '^/rest/v1/')+group by region, path+order by requester_region_count;+```++**Find total requests by IP:**++```sql+select+ cf_connecting_ip as ip,+ count(cf_connecting_ip) as ip_count+from+ edge_logs+ cross join unnest(metadata) as metadata+ cross join unnest(request) as request+ cross join unnest(headers) as headers+ cross join unnest(cf) as cf+ cross join unnest(response) as response+where regexp_contains(path, '^/auth/v1/')+group by ip+order by ip_count;+```++**Search frequented query paths by authenticated user:**++```sql+select+ -- only available for front-end clients+ auth_users,+ path,+ count(auth_users) as ip_count+from+ edge_logs+ cross join unnest(metadata) as metadata+ cross join unnest(request) as request+ cross join unnest(sb) as sb+where+ -- only look at DB API+ regexp_contains(path, '^/rest/v1/')+group by auth_users, path;+```diff --git a/apps/docs/content/troubleshooting/fetch-requests-to-api-endpoints-arent-showing-the-session-UbUwRs.mdx b/apps/docs/content/troubleshooting/fetch-requests-to-api-endpoints-arent-showing-the-session-UbUwRs.mdxnew file mode 100644index 00000000000..99faaa1a511--- /dev/null+++ b/apps/docs/content/troubleshooting/fetch-requests-to-api-endpoints-arent-showing-the-session-UbUwRs.mdx@@ -0,0 +1,17 @@+---+title = "Fetch requests to API endpoints aren't showing the session"+github_url = "https://github.com/orgs/supabase/discussions/15859"+date_created = "2023-07-18T12:22:14+00:00"+topics = ["auth"]+keywords = ["session", "cookie"]+---++You must pass along the cookie header with the fetch request in order for your API endpoint to get access to the cookie from this request.++```ts+const res = await fetch('http://localhost:3000/contact', {+ headers: {+ cookie: headers().get('cookie') as string,+ },+})+```diff --git a/apps/docs/content/troubleshooting/how-to-interpret-and-explore-the-postgres-logs-OuCIOj.mdx b/apps/docs/content/troubleshooting/how-to-interpret-and-explore-the-postgres-logs-OuCIOj.mdxnew file mode 100644index 00000000000..87945ac6e6d--- /dev/null+++ b/apps/docs/content/troubleshooting/how-to-interpret-and-explore-the-postgres-logs-OuCIOj.mdx@@ -0,0 +1,401 @@+---+title = "How to Interpret and Explore the Postgres Logs"+github_url = "https://github.com/orgs/supabase/discussions/26224"+date_created = "2024-05-12T21:19:37+00:00"+topics = ["database", "platform"]+---++> A complimentary guide was made for the [API logs](https://github.com/orgs/supabase/discussions/22849)++# Debugging and Monitoring Postgres with Logs++Logs provide insights into Postgres operations. They help meet compliance requirements, detect suspicious activity, and troubleshoot problems.++## Table of Contents++- Querying Logs+ - `postgres_logs` Table Structure+- Filtering Logs+ - Routine Events+ - By Timeframe+ - By Error Severity+ - By Query+ - By APIs/Roles+ - By Supabase Dashboard Queries+ - Full Example For Finding Errors+- Logging for Compliance and Security+- Reviewing Log Settings+- Changing Log Settings+ - Severity levels+ - Configuring queries logged+ - Logging within functions+- Frequently Asked Questions+- Other resources++## Querying Logs++The most practical way to explore and filter logs is through the [Logs Explorer](https://supabase.com/dashboard/project/_/logs/explorer).++It uses a subset of Bigquery SQL syntax and preparses queries for optimization. This imposes three primary limitations:++- No subqueries or `WITH` statements+- No `*` wildcards for column names+- No `ILIKE` statements++Although there are many strategies to filter logs, such as `like` and `in` statements, a helper function called [`regexp_contains`](https://github.com/orgs/supabase/discussions/22640) provides the most flexibility and control.++The `postgres_logs` table contains Postgres events.++### `postgres_logs` Table Structure++The table contains 3 fundamental columns:++| column | description |+| --------------- | ----------------------- |+| event_message | the log's message |+| timestamp | time event was recorded |+| parsed metadata | metadata about event |++The parsed metadata column is an array that contains relevant information about events. To access the information, it must be unnested. This is done with a `cross join`.++**Unnesting example**++```sql+select+ event_message,+ parsed.<column name>+from+ postgres_logs+-- Unpack data stored in the 'metadata' field+cross join unnest(metadata) AS metadata+-- After unpacking the 'metadata' field, extract the 'parsed' field from it+cross join unnest(parsed) AS parsed;+```++### Parsed Metadata Fields++#### Query Information++| Field | Description | Example |+| --------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------- |+| parsed.query | The SQL query executed | `SELECT * FROM table;` |+| parsed.command_tag | Tag identifying the type of command (e.g., SELECT) | `SELECT`, `INSERT`, `UPDATE`... |+| parsed.internal_query | An internal query that is used to facilitate a primary query. Often used by realtime for certain tasks | `select to_jsonb()` |++**Suggested use cases:**++- Identifying slow queries+- Identifying failing queries++#### Error/Warning Information++| Field | Description | Example |+| --------------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------- |+| parsed.error_severity | [event severity](#severity-levels) | `LOG`, `WARNING`, `ERROR`... |+| parsed.detail | Explanation of the event according to Postgres | "Key (fk_table)=(553585367) already exists." |+| parsed.sql_state_code | An error code that maps to Postgres's error table | `42501` |+| parsed.hint | Hint on how to solve the error | "No function matches the given name and argument types. You might need to add explicit type casts." |+| parsed.context | Provides insight into where an error may have occurred | "PL/pgSQL function public.find_text(public.vector,integer) line 3 at IF" |++**Suggested use cases:**++- Filter by error severity or sql code+- Get hints, details, and context about error events++#### Connection/Identification Information++| Field | Description | Example |+| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |+| parsed.session_id | The session ID | 12345 |+| parsed.session_start_time | The start time of the session | 2024-05-08 15:30:00 |+| parsed.connection_from | The connection IP | 192.165.1.100 |+| parsed.user_name | The name of the connecting database user | postgres |+| parsed.application_name | The name of the application | Supavisor, postgREST |+| parsed.database_name | The name of the database | postgres |+| parsed.process_id | The process ID, often used to identify extension workers | 1234 |+| parsed.backend_type | Determine if the event originated internally (e.g., from background workers like pg_net, timescale, or pg_cron) or externally from a client (`client backend`) | `client backend` |++**Suggested use cases:**++- Identify events by server/API+- Filter connections by IP+- Identify connections to specific databases+- Filter connections by sessions for debugging+- identify extension events++## Filtering Logs++### Excluding Routine Events++Most Postgres logs during normal periods are routine events, such as connection authorizations and checkpoints. To see the default types of events that are logged, you can check this [guide](https://gist.github.com/TheOtherBrian1/991d32c2b00dbc75d29b80d4cdf41aa7).++When exploring the logs for atypical behavior, it's often strategic to filter out expected values. This can be done by adding the following filter to your queries:++```sql+...query+where+ -- Excluding routine events related to cron, PgBouncer, checkpoints, and successful connections+ not regexp_contains(event_message, '^cron|PgBouncer|checkpoint|connection received|authenticated|authorized';+```++### By Timeframe++To investigate issues around a specific period:++```sql+-- filtering by time period+...query+where+ timestamp between '2024-05-06 04:44:00' and '2024-05-06 04:45:00'+```++### By Error Severity++This filter finds all errors, fatals, and panics:++| Severity | Usage |+| -------- | ------------------------------------------------------------ |+| ERROR | Reports an error that caused the current command to abort. |+| FATAL | Reports an error that caused the current session to abort. |+| PANIC | Reports an error that caused all database sessions to abort. |++```sql+-- find error events+... query+where+ parsed.error_severity in ('ERROR', 'FATAL', 'PANIC')+```++Failure events include an sql_state_code that can be referenced in the [Postgres Docs](https://www.postgresql.org/docs/current/errcodes-appendix.html)++### By Query++> NOTE: Unless pg_audit is configured, only failed queries are logged++```+-- find queries executed by the Dashboard+...query+where+ regexp_contains(parsed.query, '(?i)select . <some table>')+```++Queries can use complex syntax, so it is often helpful to isolate by referenced database objects, such as `functions`, `tables`, and `columns`. Because query structures can be complex, it is advised to use [regex](https://github.com/orgs/supabase/discussions/22640) to find matches. Some common regex patterns are:++- `(?i)`: ignore case sensitivty+- `.`: wildcard+- `^`: look for values at start of string+- `|`: or operator++## By APIs/roles++All failed queries, including those from PostgREST, Auth, and external libraries (e.g., Prisma) are logged with helpful error messages for debugging.++#### Server/Role Mapping++API servers have assigned database roles for connecting to the database:++| Role | API/Tool |+| -------------------------- | ------------------------------------------------------------------------- |+| supabase_admin | Used by Supabase to configure projects and for monitoring |+| authenticator | PostgREST |+| supabase_auth_admin | Auth |+| supabase_storage_admin | Storage |+| supabase_realtime_admin | Realtime |+| supabase_replication_admin | Synchronizes Read Replicas |+| postgres | Supabase Dashboard and External Tools (e.g., Prisma, SQLAlchemy, PSQL...) |+| Custom roles | External Tools (e.g., Prisma, SQLAlchemy, PSQL...) |++Filter by the `parsed.user_name` role to only retrieve logs made by specific roles:++```sql+-- find events based on role/server+... query+where+ -- find events from the relevant role+ parsed.user_name = '<ROLE>'+...+```++## By Dashboard Queries++Queries from the Supabase Dashboard are executed under the postgres role and include the comment `-- source: dashboard`. To isolate or exclude Dashboard requests during debugging, you can filter by this comment.++```sql+-- find queries executed by the Dashboard+...query+where+ regexp_contains(parsed.query, '-- source: dashboard')+```++## Full Example For Finding Errors++```sql+select+ cast(postgres_logs.timestamp as datetime) as timestamp,+ event_message,+ parsed.error_severity,+ parsed.user_name,+ parsed.query,+ parsed.detail,+ parsed.hint,+ parsed.sql_state_code,+ parsed.backend_type+from+ postgres_logs+ cross join unnest(metadata) as metadata+ cross join unnest(metadata.parsed) as parsed+where+ regexp_contains(parsed.error_severity, 'ERROR|FATAL|PANIC')+ and parsed.user_name = 'postgres'+ and regexp_contains(event_message, 'duration|operator')+ and not regexp_contains(parsed.query, '<key words>')+ and postgres_logs.timestamp between '2024-04-15 10:50:00' and '2024-04-15 10:50:27'+order by timestamp desc+limit 100;+```++# Logging for Compliance and Security++### Customized Object and Role Activity Logging++> ⚠️ NOTE: This is specifically designated for those using the `postgres` role or [custom roles](https://supabase.com/docs/guides/database/postgres/roles) to interact with their database. Those utilizing the Database REST API should reference the [Database API Logging Guide](https://github.com/orgs/supabase/discussions/22849) instead.++When recording what is accessed and by whom, logging based on database roles and objects is the most reliable way to ensure a proper trail of activity.++You can use the [pg_audit](https://supabase.com/docs/guides/database/extensions/pgaudit) extension to selectively log relevant queries (not just errors) by certain roles, against specific database objects.++You should take care when using the extension to not log all database events, but only what is absolutely necessary. Overlogging can strain the database and create log noise that makes it difficult to filter for relevant events.++**Filtering by pg_audit**:++```sql+... query+where+ -- all pg_audit recorded events start with 'AUDIT'+ regexp_contains(event_message, '^AUDIT')+ and+ -- Finding queries executed from the relevant role (e.g., 'API_role')+ parsed.user_name = 'API_role'+```++### Filtering By IP++> If you are connecting from a known, limited range of IP addresses, you should enable [network restrictions](https://supabase.com/docs/guides/platform/network-restrictions).++Monitoring IPs becomes tricky when dealing with dynamic addressing, such as those from serverless or edge environments. This challenge amplifies when relying on certain poolers, such as Prisma Accelerate, Supavisor, or Cloudflare's Hyperdrive, as they record the pooler's IP, not the true origin.++IP tracking is most effective when consistently relying on direct database connections from servers with static IP addresses:++```sql+-- filter by IP+select+ event_message,+ connection_from as ip,+ count(connection_from) as ip_count+from+ postgres_logs+ cross join unnest(metadata) as metadata+ cross join unnest(parsed) as parsed+where+ regexp_contains(user_name, '<ROLE>')+ and regexp_contains(backend_type, 'client backend') -- only search for connections from outside the database (excludes cron jobs)+ and regexp_contains(event_message, '^connection authenticated') -- only view successful authentication events+group by connection_from, event_message+order by ip_count desc+limit 100;+```++# Reviewing Log Settings++The `pg_settings` table describes system and logging configurations.++```sql+-- view system variables+select * from pg_settings;+```++The settings that affect logs are categorized under:+| Category | Description |+|----------|-------------|+| `Reporting and Logging / What to Log` | Specifies system events worth logging.|+| `Reporting and Logging / When to Log` | Specifies certain conditions or rules for logging+| `Customized Options` | Configures extensions and loaded modules, including those enhancing logging like auto_explain and pg_audit. |++To view all log settings for your database, you can execute the following SQL:++```sql+-- view all log related settings+select *+from pg_settings+where+ (+ category like 'Reporting and Logging / What to Log'+ or category like 'Reporting and Logging / When to Log'+ or category = 'Customized Options'+ )+ and name like '%log%';+```++## Changing Log Settings++> WARNING: lenient settings can lead to overlogging, impacting database performance while creating noise in the logs.++#### Severity levels++The `log_min_messages` variable determines what is severe enough to log. Here are the severity thresholds from the [Postgres docs](https://www.postgresql.org/docs/current/runtime-config-logging.html).++| Severity | Usage |+| ---------------- | ---------------------------------------------------------------------------------------------------- |+| DEBUG1 .. DEBUG5 | Provides successively-more-detailed information for use by developers. |+| INFO | Provides information implicitly requested by the user, e.g., output from VACUUM VERBOSE. |+| NOTICE | Provides information that might be helpful to users, e.g., notice of truncation of long identifiers. |+| WARNING | Provides warnings of likely problems, e.g., COMMIT outside a transaction block. |+| ERROR | Reports an error that caused the current command to abort. |+| LOG | Reports information of interest to administrators, e.g., checkpoint activity. |+| FATAL | Reports an error that caused the current session to abort. |+| PANIC | Reports an error that caused all database sessions to abort. |++In most cases, the default is adequate. However, if you must adjust the setting, you can do so with the following query:++```sql+alter role postgres set log_min_messages = '<NEW VALUE>';++-- view new setting+show log_min_messages; -- default WARNING+```++#### Configuring queries logged++By default, only failed queries are logged. The [PGAudit extension](https://supabase.com/docs/guides/database/extensions/pgaudit) extends Postgres's built-in logging abilities. It can be used to selectively track all queries in your database by:++- role+- session+- database object+- entire database++#### Logging within database functions++To track or debug functions, logging can be configured by followin the [function debugging guide](https://supabase.com/docs/guides/database/functions#general-logging)++# Frequently Asked Questions++#### Can I join together different log tables, such as `edge_logs` and `postgres_logs`?++No, log tables are independent from each other and do not share any primary/foreign key relations for joining.++#### Can I download the logs?++At the moment, the way to download logs is through the Log Dashboard as a CSV++#### What is logged?++To see the default types of events that are logged, you can check this [guide](https://gist.github.com/TheOtherBrian1/991d32c2b00dbc75d29b80d4cdf41aa7).++### Other resources:++- [Regex for filtering logs](https://github.com/orgs/supabase/discussions/22640)+- [Debugging with the DB API logs](https://github.com/orgs/supabase/discussions/22849)+- [Debugging Database Functions](https://supabase.com/docs/guides/database/functions#debugging-functions)+- [pg_audit](https://supabase.com/docs/guides/database/extensions/pgaudit)+- [Supabase Logging](https://supabase.com/docs/guides/platform/logs)+- [Self-Hosting Logs](https://supabase.com/docs/reference/self-hosting-analytics/introduction)diff --git a/apps/docs/content/troubleshooting/understanding-postgresql-explain-output-Un9dqX.mdx b/apps/docs/content/troubleshooting/understanding-postgresql-explain-output-Un9dqX.mdxnew file mode 100644index 00000000000..583d1a45373--- /dev/null+++ b/apps/docs/content/troubleshooting/understanding-postgresql-explain-output-Un9dqX.mdx@@ -0,0 +1,209 @@+---+title = "Understanding PostgreSQL EXPLAIN Output"+github_url = "https://github.com/orgs/supabase/discussions/22839"+date_created = "2024-04-17T16:31:47+00:00"+topics = ["database"]+keywords = ["explain", "performance", "query"]++[api]+sdk = ["explain"]+---++### Introduction++This guide is designed to help you understand how to use the PostgreSQL [EXPLAIN and EXPLAIN ANALYZE](https://www.postgresql.org/docs/current/sql-explain.html) commands to optimize and debug SQL queries. Understanding the output of these commands can help you improve the performance of your applications by optimizing database interactions.++### What is EXPLAIN?++The PostgreSQL EXPLAIN command shows the execution plan of a SQL query. This plan describes how the PostgreSQL database will execute the query, including how tables will be scanned—by using sequential scans, index scans, etc.—and how rows will be joined.++### How to Use EXPLAIN in Supabase++**Using EXPLAIN through the SQL Editor**++1. Access your Supabase project+2. Open the SQL editor+3. Execute EXPLAIN with Your Query:+ `EXPLAIN SELECT * FROM users WHERE user_id = 1;`++**Using EXPLAIN with supabase-js Library**++1. Follow the [Performance Debugging Guide](https://supabase.com/docs/guides/database/debugging-performance) to enable the functionality on your project.+2. Once debugging is enabled, you can use the [EXPLAIN](https://supabase.com/docs/reference/javascript/explain?queryGroups=example&example=get-execution-plan-with-analyze-and-verbose) function in your application code. Here's how to use it++```+const { data, error } = await supabase+ .from('countries')+ .select()+ .explain({analyze:true,verbose:true})+```++### Detailed Breakdown of EXPLAIN Output Components++### 1. Plan Type++**- Seq Scan:** A sequential scan that reads all rows from a table. This is often seen in the absence of indexes that can be used for the query.++**- Index Scan:** Uses an index to find rows quickly. This indicates that the query is able to use an index to efficiently locate data.++**- Bitmap Heap Scan:** Uses a bitmap index to find rows quickly and then retrieves the actual rows from the table. This type of scan is efficient when retrieving a moderate number of rows.++### 2. Cost++**cost=0.00..19.00:** This represents the estimated cost of executing the plan. The first number (0.00) is the cost of returning the first row, and the second number (19.00) is the total cost of executing the query and retrieving all rows. These values are arbitrary units determined by the database's cost model, not actual time or resources.++**Start-up Cost:** The cost incurred before returning the first row.+**Total Cost:** The estimated total cost of the operation.++### 3. Rows++**rows=1:** An estimate of the number of rows the query will return. Accurate row estimates depend on updated statistics; if the estimates are off, it might indicate that the database statistics need to be updated.++### 4. Width++**width=240:** The average number of bytes expected for the output rows. This indicates the expected data volume that needs to be processed or transferred, which can impact performance.++### 5. Filters++**Filter: (user_id = 1):** This shows any filters applied post-scan. Filters are conditions that are checked after retrieving the rows. A high number of rows being filtered out could indicate a need for better indexing.++### 6. Execution Time++**Execution Time: 0.069 ms:** measures how long it took to actually execute the query, including retrieving the data, performing any sorts, joins, or other operations defined in the execution plan, and returning the final results. This time is measured in milliseconds.++++### Detailed Components in EXPLAIN ANALYZE++When running EXPLAIN ANALYZE, additional information is provided, including:++- **Actual time:** Shows the time actually spent executing the scan and retrieving rows. This is split into the time to retrieve the first row (first) and the time to retrieve all rows (last).++- **Rows removed by filter:** Indicates how many rows were excluded due to not meeting the filter conditions.++- **Loops:** Shows how many times the node was executed, especially relevant in nested loop joins or subqueries.++Example of Detailed EXPLAIN ANALYZE Output++```+Seq Scan on users (cost=0.00..19.00 rows=1 width=240) (actual time=0.026..0.026 rows=1 loops=1)+ Filter: (user_id = 1)+ Rows Removed by Filter: 999+Planning Time: 0.135 ms+```++- **actual time=0.026..0.026:** The time it took to start returning rows and to finish returning all rows.++- **Rows Removed by Filter:** 999: Indicates that many rows were checked against the filter, but most did not match the criteria.++- **Planning Time: 0.135 ms:** Planning Time refers to the amount of time the PostgreSQL query planner takes to analyze the query and create an execution plan. This time is measured in milliseconds.++### You might be asking yourself now, why there is two different sets of metrics : `(cost=0.42..2.64 rows=1 width=164) (actual time=0.020..0.021 rows=1 loops=1)`?++To answer you, one is for the estimated cost and performance, and another for the actual performance of the query as explained above.++**Planning vs. Execution**: The estimates are based on the query planner's understanding of the data (gathered from statistics about table size, distribution of values, etc.), while the actual metrics tell you what really happened when the query ran. This comparison can highlight inaccuracies in the planner's assumptions.++**Performance Tuning**: By comparing estimated rows and actual rows, or estimated time and actual time, you can identify potential performance issues. For example, if the estimated rows are significantly off from the actual rows, it might suggest that the table statistics are outdated, leading to inefficient query plans.++**Identifying Bottlenecks**: If the actual time is significantly higher than expected, or if loops are more frequent than anticipated, these could be indicators of performance bottlenecks in the query.++### How to read a Complex EXPLAIN Output++First, you have to understand that a PostgreSQL execution plan is a tree structure consisting of several nodes. The top node (the Aggregate above) is at the top, and lower nodes are indented and start with an arrow (->). Nodes with the same indentation are on the same level (for example, the two relations combined with a join).++Here's an example:++```+Aggregate Node (Top Node)+│+└──> Sort Node+ │+ └──> Hash Join Node+ │+ ├──> Seq Scan on users (Filtered)+ │+ └──> Hash+ │+ └──> Seq Scan on activities+```++PostgreSQL executes a plan top down, that is, it starts with producing the first result row for the top node. The executor processes lower nodes “on demand”, that is, it fetches only as many result rows from them as it needs to calculate the next result of the upper node. This influences how you have to read “cost” and “time”: the startup time for the upper node is at least as high as the startup time of the lower nodes, and the same holds for the total time. If you want to find the net time spent in a node, you have to subtract the time spent in the lower nodes. Parallel queries make that even more complicated.++On top of that, you have to multiply the cost and the time with the number of “loops” to get the total time spent in a node.++### Common Nodes in PostgreSQL EXPLAIN Output++| Node Type | Description |+| --------------------- | ---------------------------------------------------------------------------- |+| **Seq Scan** | Scans each row of a table sequentially, often used without suitable indexes. |+| **Index Scan** | Uses an index to quickly find rows, efficient for small fractions of rows. |+| **Index Only Scan** | Retrieves all needed data from the index itself, without visiting the table. |+| **Bitmap Heap Scan** | Uses a bitmap of row locations to efficiently retrieve rows from the table. |+| **Bitmap Index Scan** | Builds a bitmap by scanning the index to efficiently locate rows. |+| **Tid Scan** | Fetches rows directly using tuple identifiers, used in sub-selects. |+| **Nested Loop** | Joins two tables by scanning the first and then the second for each row. |+| **Merge Join** | Joins two pre-sorted tables, efficient for large datasets. |+| **Hash Join** | Uses a hash table to perform joins, often faster for larger datasets. |+| **Aggregate** | Performs aggregation calculations like `SUM`, `COUNT`, etc. |+| **Sort** | Sorts rows based on specified criteria, required for certain operations. |+| **Limit** | Returns a specified number of rows quickly, used with `LIMIT` clause. |+| **CTE Scan** | Scans a Common Table Expression, used for WITH clauses. |+| **Materialize** | Materializes the result of a subquery or node to reuse without re-running. |+| **Subquery Scan** | Executes and provides the results of a subquery to the outer query. |+| **Foreign Scan** | Fetches data from foreign data sources outside the local database. |+| **Function Scan** | Retrieves results from a set-returning function. |++### What to focus on in EXPLAIN ANALYZE output++- Find the nodes where most of the execution time was spent.+ `Hash Join (cost=100.00..200.00 rows=1000 width=50) (actual time=50.012..150.023 rows=1000 loops=1)`+ Explanation:+ The actual time=50.012..150.023 indicates that this join operation took about 100 milliseconds to complete, making it a potential performance bottleneck.+- Find the lowest node where the estimated row count is significantly different from the actual row count.+ `Seq Scan on users (cost=0.00..50.00 rows=100 width=50) (actual time=0.010..25.000 rows=10000 loops=1)`+ Explanation:+ The estimated rows are 100, but the actual rows are 10,000. This discrepancy may lead the query planner to make inefficient choices, such as choosing a sequential scan over an index scan.+- Find long-running sequential scans with a filter condition that removes many rows.++```+Seq Scan on products (cost=0.00..100.00 rows=300 width=50) (actual time=50.000..100.000 rows=3 loops=1)+ Filter: (price > 1000)+ Rows Removed by Filter: 2997+```++Explanation:+This sequential scan took 50 to 100 milliseconds and filtered out 2997 of 3000 rows, indicating that only a few rows met the condition. This scenario is ideal for an index on the price column to optimize the performance by reducing the need for a full table scan.++### Understanding the Significance of Milliseconds in Query Performance++Determining whether 100 milliseconds for e.g is noteworthy in the context of identifying performance bottlenecks depends on various factors:++**Overall Query Execution Time:**++If the total execution time of a query significantly exceeds 100 milliseconds, then this particular step may not represent the main bottleneck. For instance, in queries that take several seconds to execute, a component that consumes just 100 milliseconds may not be the critical target for optimization efforts.++**Complexity and Scale of the Query:**++For complex queries that involve multiple joins, subqueries, or aggregation functions, an operation that takes 100 milliseconds might actually reflect good efficiency. Conversely, for simpler queries or operations expected to be quick (such as fetching a few rows from a well-indexed table), 100 milliseconds could suggest a lack of efficiency.++So, the acceptable performance threshold can vary by application. For real-time systems or high-frequency trading platforms, even a few milliseconds can be critical, whereas for batch processing or data warehousing, longer execution times might be acceptable.++### Tools to interpret EXPLAIN ANALYZE output++Since reading a longer execution plan is quite cumbersome, you can use the website https://explain.depesz.com/ to better visualize the query. If you paste the execution plan in the text area and hit “Submit”, you will get output like this:+++### Tips for Optimizing Queries++- **Add Indexes:** Improve performance by adding indexes on columns that are frequently used in WHERE clauses or JOIN conditions.++- **Avoid Selecting Unused Columns:** Use SELECT to specify only the columns you need.++- **Update Statistics:** Ensure that statistics are up to date to help the optimizer make better choices.++### Conclusion++Understanding EXPLAIN and EXPLAIN ANALYZE output can significantly enhance your ability to write efficient SQL queries. Regularly analyze query performance and make adjustments as your dataset grows and changes.++For more insights, you can also check out: https://aws.amazon.com/blogs/database/how-postgresql-processes-queries-and-how-to-analyze-them/.diff --git a/apps/docs/content/troubleshooting/understanding-postgresql-logging-levels-and-how-they-impact-your-project-KXiJRm.mdx b/apps/docs/content/troubleshooting/understanding-postgresql-logging-levels-and-how-they-impact-your-project-KXiJRm.mdxnew file mode 100644index 00000000000..5e7c957f018--- /dev/null+++ b/apps/docs/content/troubleshooting/understanding-postgresql-logging-levels-and-how-they-impact-your-project-KXiJRm.mdx@@ -0,0 +1,119 @@+---+title = "Understanding PostgreSQL Logging Levels and How They Impact Your Project"+github_url = "https://github.com/orgs/supabase/discussions/29877"+date_created = "2024-10-14T09:17:02+00:00"+topics = ["database"]+keywords = ["logging", "disk", "i/o", "lockups"]+---++Since each Supabase project uses PostgreSQL as its underlying database engine, it’s common to adjust logging settings for various reasons—whether for debugging issues, monitoring database performance, or auditing actions. However, modifying logging levels improperly can lead to an excessive amount of log data being generated, which can quickly fill up your disk space and cause significant performance degradation or even system failure.++### 1. Overview of PostgreSQL Logging Levels++PostgreSQL provides multiple logging levels that allow you to control how much information gets logged. These include:++| Log Level | Description |+| --------- | --------------------------------------------------------------------------------------------------------------------- |+| DEBUG1-5 | Logs very detailed information about the operations of the database, useful only for deep debugging. |+| INFO | Logs information about routine database operations that aren’t necessarily errors but may still be relevant to track. |+| NOTICE | Logs messages that are not errors but may still be noteworthy. |+| WARNING | Logs warnings, which indicate issues that don’t prevent execution but could cause problems later. |+| ERROR | Logs errors that cause statements to fail. |+| LOG | Logs general messages such as startup, shutdown, or checkpoints. |+| FATAL | Logs errors that cause the database session to fail. |+| PANIC | Logs critical issues that force the database to shut down. |++Each of these log levels is useful in specific situations. Here's an example of what messages tagged with each severity level look like:++```+DEBUG: server process (PID 12345) exited with exit code 0+INFO: vacuuming "example_schema.public.example_table"+NOTICE: identifier "very_very_very_long_table_name_exceeding_63_characters" will be truncated to "very_very_very_long_table_name_exceedin"+WARNING: SET LOCAL can only be used in transaction blocks+LOG: statement: UPDATE example_table SET column_name = 'Example Value' WHERE id = 10;+ERROR: relation "exam" does not exist at character 7+FATAL: role "admin" does not exist+PANIC: database system shutdown requested+```++The default log level is set to **WARNING** through the log_min_messages setting, and we recommend keeping it that way.++### 2. How High Log Levels Can Affect Your Database++When users alter a high level of log settings, the database can start generating an overwhelming number of log entries. This can quickly escalate to issues such as:++- Disk Space Exhaustion: Log files can grow exponentially if verbose levels like DEBUG, INFO, or NOTICE are enabled for long periods. And running out of disk space due to log bloat can cause your database to stop accepting writes and slow down query performance.++- I/O Overload: Writing too many logs increases input/output (I/O) operations, which can negatively impact database speed. A database bogged down by heavy logging will take longer to process requests, leading to slower application performance.++- Database Lockups: In extreme cases, if the disk is filled to capacity with logs, your database could lock up, leading to downtime or severe performance degradation.++### 3. Common Scenarios That Cause Log Overload++Here are a few common scenarios where excessive logging can become a problem:++- Extended Use of DEBUG Logging: While useful for troubleshooting, leaving DEBUG logging enabled for a long period can lead to the accumulation of massive amounts of logs.++- Setting INFO for Monitoring: Logging INFO can be helpful for tracking general database activity, but if left on indefinitely, it can still result in a lot of noise and unnecessary log growth.++- Frequent Write Operations: If your database processes a lot of write operations (such as inserts, updates, or deletes), even low-level logs (like NOTICE or INFO) can lead to significant log accumulation.++### 4. How to Manage PostgreSQL Log Levels Effectively++**a. Choose the Right Log Level**+For most users, setting PostgreSQL logs to WARNING or ERROR is sufficient for regular operations. Here’s a general guideline:++- WARNING: Use this level for general logging during normal operations. It captures issues that may not be critical but are worth paying attention to.++- ERROR: This level is ideal for production environments. It logs only failures that prevent queries from being executed, reducing log noise significantly.++- DEBUG, INFO, or NOTICE: Use these levels sparingly and only for short-term debugging or diagnostics. Always remember to revert the setting once you've collected the necessary information.++**b. How to Adjust Log Levels**+You can adjust log levels using SQL commands in the SQL Editor or any connected PostgreSQL client:++- To check the current log level:++```+SHOW log_min_messages;+```++- To set the log level to WARNING (recommended default):++```+ALTER ROLE postgres SET log_min_messages TO 'WARNING';+```++- To set the log level to ERROR:++```+ALTER ROLE postgres SET log_min_messages TO 'ERROR';+```++- To reset to the default level:++```+ALTER ROLE postgres RESET log_min_messages;+```++### 5. Conclusion++PostgreSQL logs provide a powerful way to gain valuable insights into your database activity and performance when properly configured, but the key lies in finding the right balance. When set up properly, they can be incredibly useful.++### 6. Other resources++**a. What Events Are Logged in Postgres**+For a detailed explanation of the types of events logged in your database (such as connection events, checkpoint events, long-running queries, cron jobs, and severity-based logging), you can refer to the official documentation here:++[What Events Are Logged in Supabase](https://gist.github.com/TheOtherBrian1/991d32c2b00dbc75d29b80d4cdf41aa7)++**b. PGAudit: Postgres Auditing for Compliance and Security**++We support PGAudit extension, which extends PostgreSQL’s built-in logging capabilities to track database activities for auditing purposes.++[How to Enable the PGAudit Extension](https://supabase.com/docs/guides/database/extensions/pgaudit?queryGroups=database-method&database-method=dashboard#enable-the-extension)++For detailed configuration instructions and logging options, refer to the complete documentation: [PGAudit Configuration Guide](https://supabase.com/docs/guides/database/extensions/pgaudit?queryGroups=database-method&database-method=dashboard#configure-the-extension)++**c. Debugging Functions**+For more information on how to debug functions in Supabase, refer to the official guide: [Debugging Functions](https://supabase.com/docs/guides/database/functions?queryGroups=language&language=js#debugging-functions).diff --git a/apps/docs/public/img/troubleshooting/10950be3-264b-4a41-bc71-3d431c2756b2.png b/apps/docs/public/img/troubleshooting/10950be3-264b-4a41-bc71-3d431c2756b2.pngnew file mode 100644index 00000000000..6b62f61329fBinary files /dev/null and b/apps/docs/public/img/troubleshooting/10950be3-264b-4a41-bc71-3d431c2756b2.png differdiff --git a/apps/docs/public/img/troubleshooting/830b81aa-ae52-44a4-aa49-32c2a6296af7.png b/apps/docs/public/img/troubleshooting/830b81aa-ae52-44a4-aa49-32c2a6296af7.pngnew file mode 100644index 00000000000..626d84d8fceBinary files /dev/null and b/apps/docs/public/img/troubleshooting/830b81aa-ae52-44a4-aa49-32c2a6296af7.png differ