Est.

Slow Query Diagnostics for Supabase Teams Using Native Postgres Observability

Rank queries, read the plans, and rule out connection limits before upgrading.

· 9 min read
Cover illustration for “Slow Query Diagnostics for Supabase Teams Using Native Postgres Observability”
Supabase Analytics · December 1, 2026 · 9 min read · 2,066 words

Analytics for Supabase teams begins with native Postgres observability when the question is why an application is slow. pg_stat_statements identifies expensive query shapes, EXPLAIN (ANALYZE, BUFFERS) explains their execution, and connection and system views distinguish query problems from resource pressure. The rule is to measure the workload before changing it, then fix the cause that the measurements show will cost the least to fix before buying more compute.

Why slow queries in Supabase are almost always a Postgres problem, not a platform problem

A user reports a slow action, or a dashboard warns that database performance is deteriorating. Neither symptom on its own shows what caused it. Supabase runs PostgreSQL, so the investigation begins with Postgres instrumentation. A slow application is often slow in two or three query shapes. Missing indexes, per-row RLS checks, repeated application queries, excessive direct connections, and undersized compute produce different signals that the native tools can separate.

That distinction keeps diagnosis proportional to the symptom. If logs contain no timeout errors and the slowest endpoint remains comfortably fast, there may be no scaling problem to solve yet. Instrumentation is not an end in itself. The workflow below starts with workload ranking, branches into connection checks when requests cannot begin, and uses cache hit ratio, disk I/O budget, and swap to explain remaining resource pressure.

Starting the triage with pg_stat_statements: ranking the workload before diagnosing any single query

pg_stat_statements is enabled by default on every Supabase project and provides the starting point for workload triage. Supabase’s Query Performance panel also shows which queries run most often and consume the most time. Start there before moving into the SQL editor. Choosing a statement because engineering suspects it is slow can direct attention away from the queries that actually dominate production work.

Two sorting passes answer different questions. For aggregate cost, use SELECT query, calls, total_exec_time, mean_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC;. This ranking is useful when CPU is high because it identifies statements consuming the most execution time across all calls. For per-call latency, use SELECT query, calls, total_exec_time, mean_exec_time FROM pg_stat_statements ORDER BY mean_exec_time DESC;. That ranking is more useful when a particular user-facing action is slow.

A query that runs often and takes a long time on average needs a closer look because a missing index, bad plan, or lock wait can add up across its calls. The result should be a named statement to investigate. It should not be an unranked collection of queries that merely look complicated.

The view has an important limitation, however. It is a running tally, so accumulated results can blur a regression. SELECT pg_stat_statements_reset(); clears the counters, allowing a reset at deployment followed by an hour of production traffic to isolate the new version’s workload. To compare results from before and after the reset, the earlier results must be kept. For queries running right now, use pg_stat_activity instead, because aggregate statistics are not a live activity view.

Reading EXPLAIN (ANALYZE, BUFFERS) output: what the plan tree actually tells you

Once the workload ranking identifies a suspect statement, the next step is to inspect its execution plan. Plain EXPLAIN asks for the plan without executing the query, which is useful for checking index use or inspecting a write that should not run. EXPLAIN ANALYZE executes the statement and adds actual timing and row counts. On Supabase, either can be run through the dashboard’s SQL editor, psql, DBeaver, or pgAdmin, and writes tested with ANALYZE should be wrapped in a transaction and rolled back.

Each plan node compares an expectation with an observation. cost is the planner’s estimate in relative units calibrated to sequential page reads. actual time reports elapsed execution time for the node. Estimated rows and actual rows show whether the planner’s picture of the data matched execution. A large mismatch points to inaccurate statistics that can lead to a poor plan.

The supplied production example makes the contrast concrete. Its Seq Scan on orders takes 450ms, while an Index Scan on users reports an actual time of 0.002..0.003 milliseconds and returns one row. The orders scan is the clear bottleneck.

Adding BUFFERS gives that timing a storage context. Shared hits identify work served from the buffer cache, while shared reads reveal reads that were not served there and help expose disk pressure. High shared reads warrant investigation of storage demand. This prevents a reasonable-looking plan from being mistaken for proof that the system has enough memory and I/O capacity. For programmatic inspection, EXPLAIN (ANALYZE, FORMAT JSON) provides machine-readable output.

The three plan findings that account for most slow queries, and the fix for each

A sequential scan on a growing, heavily used table is the most common finding in this workflow. The relevant signal is a Seq Scan with substantial elapsed time and many rows read before filtering. The targeted fix is an index on the filtered column, using the pattern CREATE INDEX CONCURRENTLY idx_<table>_<column> ON <table>(<column>);. CONCURRENTLY allows the index to be created without blocking writes. Afterward, rerun the same statement with EXPLAIN (ANALYZE, BUFFERS) to check for an Index Scan and lower actual execution time.

A missing join-column index produces a related but distinct problem. In a plan that repeatedly scans the inner table for rows from the driving table, the repeated full reads can dominate execution. Primary keys already have indexes, but custom join columns do not receive them automatically. The fix is to index the inner table’s join column. The before-and-after comparison should establish whether the repeated Seq Scan has been replaced by indexed access and whether the time has fallen.

An N+1 pattern requires returning to workload statistics. A single statement may show an efficient Index Scan taking 1ms while the application is still slow because it runs that statement over and over. The evidence is the call count in pg_stat_statements, especially when many calls accompany one user action. The fix belongs in application code, replacing individual selects in a loop with one JOIN or an .in() filter that batches the work.

Supabase’s RLS policies add another source of per-row work. A query that is fast as the postgres role but slow for a signed-in user calls for a comparison under those two execution contexts. Extra filter cost can reveal policy overhead. The corresponding fixes are to index the column used by the policy and, where appropriate, place user roles or organization IDs in JWT claims using a trigger, allowing the check to read the token and eliminate a disk lookup. Supabase Advisors also flag missing RLS policies and rank findings by how serious they are, though those checks of the configuration are separate from measuring how much work it takes to run a policy.

Connection exhaustion looks like a slow query but is not one

A request waiting for a database connection can time out without executing a slow statement. This is a different diagnostic branch. When serverless functions open separate direct connections, the database can run out of connection slots even though its query plans are reasonable. In that case, pg_stat_statements may show normal call counts and mean execution times because the waiting request has not started executing.

The relevant check is connection usage during the timeout period. pg_stat_activity and the dashboard’s Database Health section reveal whether usage is approaching max_connections. When slots are exhausted, the fix is routing through Supavisor, Supabase’s shared pooler, in transaction mode on port 6543. This changes connection configuration rather than SQL or schema. From the smallest to largest compute sizes, the number of direct connections that can be handled grows roughly 8×, while the number of pooler clients grows roughly 60×, so pooling helps the system scale as well as making connections easier to manage.

Memory pressure can reinforce the diagnosis because every connection consumes memory. A flood of direct connections may therefore appear as elevated swap as well as client timeouts. The timing of those signals is important. A connection spike coinciding with failed requests points toward admission pressure, whereas an expensive executing statement points toward query work.

The system-level signals that contextualize everything above: cache hit ratio, disk I/O budget, and swap

Even with a sound plan, a query can run slowly when resources are under pressure. Cache hit ratio, calculated as blks_hit / (blks_hit + blks_read), indicates how often reads are served from memory. The Supabase CLI exposes it through npx supabase inspect db cache-hit --remote. Hot data should have a high hit ratio. An index can reduce reading, but it cannot make a working set larger than available memory fit into that memory.

Supabase compute sizes up to 2XL can burst above baseline disk performance until their budget is spent, after which performance returns to baseline. Database Health warns when that budget is nearly used up. Low cache hit rates, swapping, long-running queries, and excessive request volume can all contribute. Daily exhaustion after query fixes provides evidence for more compute.

Swap is more informative than RAM usage alone. Supabase runs multiple services with Postgres, so high reported memory use is not automatically a fault. Swap above 70% indicates a strong likelihood that the hardware is unsuitable for the workload. Consequences include degraded performance, processes killed by the operating system, and, rarely, an unresponsive instance. Slow queries, open connections, and extensions that use a lot of memory can all play a part.

With alerts, these checks rely less on someone looking at the system by hand. Alerts are useful when disk space is low, active connections are close to a high share of max_connections, replication lag goes beyond seconds, or transactions are left idle for a long time. The team should set a threshold for the p95 latency of critical queries. The Elastic Supabase Integration provides another view of system pressure by collecting Supabase’s metrics, supplied in a compatible monitoring format, into four dashboards covering node resources and PostgreSQL internals.

The order of fixes: cheapest and safest first, compute upgrade last

Diagram: Fix Sequence: Query First, Compute Last. Visualizes: Show the ordered decision sequence for fixing database performance problems as a stepped flow.

The decision sequence is to fix the query, then the connection pattern, then remaining schema deficiencies, and finally consider more compute. Diagnosis determines which branch applies. Ranking the workload shows the two or three costly query shapes, and execution plans test whether scans, join access, or row-estimate mismatches explain why they take so much work. Repeated fast calls instead direct the investigation toward application batching. Connection exhaustion must be fixed first when requests cannot get a slot at all.

Schema changes should follow demonstrated access problems. A targeted concurrent index removes needless work that keeps recurring without blocking writes, while an instance upgrade leaves that work in place. The financial distinction persists beyond the incident. An upgrade adds recurring cost, while an effective index remains available to subsequent executions. More compute becomes justified when cache, I/O, and swap measurements still show inadequate capacity after the avoidable work has been removed.

Supabase’s resource-exhaustion warning tells teams to check the Query Performance report before an upgrade. That ordering supports the same evidence-first decision. The workflow also becomes a regression check when deployment resets are paired with retained baseline results and a production observation period. Without that comparison, a new inefficiency can disappear into accumulated averages. The objective is not merely to make one request faster, but to identify which change produced the improvement.

What native Postgres tooling cannot do, and when a governed data layer matters

Native tooling is complete for the diagnostic task described here. Third-party monitoring helps teams keep track of the system, as the metrics dashboards above show, but resource charts answer a different question from execution plans. Neither an aggregate snapshot nor a plan checked by hand has stored trends, governed KPI definitions, or a controlled interface through which to use analytical results.

Historical comparison requires stored metrics, while consistent reporting requires one definition of each KPI instead of independent calculations at different moments. Agent access also needs explicit controls. An agent querying production inherits its authenticating role’s privileges, so least-privilege roles and policy enforcement must precede data access. With pre-modeled datasets behind a governed interface, agents can do this work without being given access to query production directly.

Dreambase, an AI-native analytics layer for Supabase, is one option for turning those findings into pre-calculated metrics and live dashboards, with governed datasets available through DuckDB and a single MCP server. It separates agent-facing datasets from production so expensive-query signals can appear with business metrics outside the SQL editor. The native tools retain their diagnostic role.

More in Supabase Analytics