Skip to content

Identify Slow Queries

Rank the statements that cost your Managed PostgreSQL service the most execution time, I/O and temporary files, with the pg_stat_statements extension and the slow-statement log.

Enable pg_stat_statements

pg_stat_statements aggregates statements that differ only by their literal values into one entry: WHERE customer_id = 42 and WHERE customer_id = 7 are counted together as WHERE customer_id = $1. The library is loaded on every service; create the extension to get the view in the database you are connected to:

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

The counters are shared by the whole service, so the view also returns entries of other databases, identified by the dbid column. The queries on this page filter on the current database.

What is tracked is controlled by the service parameter pg_stat_statements.track: top (the default, statements sent by clients), all (also statements run inside functions) or none. avnadmin cannot change it with SET; set it in --pg-settings, see Configure PostgreSQL settings.

Note

avnadmin is a member of pg_read_all_stats, so it sees the text of statements run by every database user. Another user sees <insufficient privilege> for statements that are not its own. Statements run by the platform’s postgres role stay hidden even from avnadmin: they show as <insufficient privilege> with a NULL queryid, and belong to the _aiven database, which the dbid filter below excludes.

Know the Column Names of Your Version

The columns most useful for finding slow statements, as named on PostgreSQL 17 and 18:

ColumnMeaning
callsNumber of executions
total_exec_time, mean_exec_time, min_exec_time, max_exec_time, stddev_exec_timeExecution time in milliseconds
rowsRows returned or affected, all calls together
shared_blks_hit, shared_blks_readBlocks found in the buffer cache, and blocks read from outside it
temp_blks_writtenBlocks written to temporary files by sorts and hashes
shared_blk_read_time, shared_blk_write_timeTime spent on block I/O, only filled when track_io_timing is on
wal_bytesWAL generated
stats_sinceWhen this entry started accumulating

From psql, \d pg_stat_statements lists every column of your server version.

Older snippets often use total_time or mean_time, which were renamed with the _exec_ infix in PostgreSQL 13. On PostgreSQL 15 and 16, the I/O timing columns are called blk_read_time and blk_write_time, and stats_since does not exist: adapt the queries below if your service runs one of those versions (SHOW server_version;).

Rank Statements by Total Time

Start here. The statements that cost the service the most are often cheap statements executed very often:

SELECT round((total_exec_time / 1000)::numeric, 2) AS total_seconds,
       round((100 * total_exec_time
              / NULLIF(SUM(total_exec_time) OVER (), 0))::numeric, 1) AS pct_of_total,
       calls,
       round(mean_exec_time::numeric, 2) AS mean_ms,
       rows,
       query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
ORDER BY total_exec_time DESC
LIMIT 10;

pct_of_total is the share of the execution time recorded for the current database.

Rank Statements by Mean Time

To find individually slow statements, sort by mean time and ignore those executed only a handful of times, such as one-off maintenance commands:

SELECT calls,
       round(mean_exec_time::numeric, 2)           AS mean_ms,
       round(max_exec_time::numeric, 2)            AS max_ms,
       round(stddev_exec_time::numeric, 2)         AS stddev_ms,
       round((total_exec_time / 1000)::numeric, 2) AS total_seconds,
       query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
  AND calls > 100
ORDER BY mean_exec_time DESC
LIMIT 10;

A stddev_ms of the same order as mean_ms means the same statement is sometimes fast and sometimes slow, which points to lock waits or to a plan that suits only some parameter values.

Rank Statements by Blocks Read

SELECT calls,
       shared_blks_read,
       pg_size_pretty(shared_blks_read * current_setting('block_size')::bigint) AS read_outside_cache,
       round(100.0 * shared_blks_hit
             / NULLIF(shared_blks_hit + shared_blks_read, 0), 1)              AS cache_hit_pct,
       round(mean_exec_time::numeric, 2)                                     AS mean_ms,
       query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
ORDER BY shared_blks_read DESC
LIMIT 10;

A frequent statement with a low cache_hit_pct keeps reading pages that are not in shared_buffers, typically through a sequential scan of a large table.

Rank by I/O Time

The shared_blk_read_time and shared_blk_write_time columns stay at zero while track_io_timing is off, which is the default. avnadmin cannot SET it in a session; enable it on the service while you investigate:

exo dbaas update SERVICE_NAME -z ZONE -f --pg-settings '{"track_io_timing":"on"}'

Parameters:

  • SERVICE_NAME: name of the Managed PostgreSQL service, for example my-postgresql.
  • ZONE: zone the service runs in, for example ch-gva-2.
  • track_io_timing: a string, "on" or "off". The change applies without a restart.

Then:

SELECT calls,
       round(((shared_blk_read_time + shared_blk_write_time) / 1000)::numeric, 2) AS io_seconds,
       round((total_exec_time / 1000)::numeric, 2)                                AS total_seconds,
       round((100 * (shared_blk_read_time + shared_blk_write_time)
              / NULLIF(total_exec_time, 0))::numeric, 1)                          AS pct_time_in_io,
       query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
ORDER BY (shared_blk_read_time + shared_blk_write_time) DESC
LIMIT 10;

A high pct_time_in_io means the statement waits on storage. A long statement with a low pct_time_in_io spends its time on CPU: sorting, hashing or filtering rows. With track_io_timing on, EXPLAIN (ANALYZE) also prints I/O Timings per plan node.

PostgreSQL warns that timing every I/O can add overhead on some platforms. Send {"track_io_timing":"off"} when you are done.

Find Statements That Write Temporary Files

A sort or hash that does not fit in work_mem writes temporary files:

SELECT calls,
       temp_blks_written,
       pg_size_pretty(temp_blks_written * current_setting('block_size')::bigint) AS temp_written,
       round(mean_exec_time::numeric, 2)                                         AS mean_ms,
       query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
  AND temp_blks_written > 0
ORDER BY temp_blks_written DESC
LIMIT 10;

See Optimize slow queries to confirm the spill in the plan and size work_mem.

Log Slow Statements

The server log records slow statements and temporary files continuously, with the user, database and client of each one. Two service parameters control it; both have superuser context, so they are set on the service, not with SET:

  • log_min_duration_statement: log every statement that runs longer than this many milliseconds. -1 disables it. A new service logs statements slower than 1000 ms.
  • log_temp_files: log every temporary file larger than this many kilobytes. -1 disables it. A new service logs files above 100 kB.
exo dbaas update SERVICE_NAME -z ZONE -f \
  --pg-settings '{"log_min_duration_statement":500,"log_temp_files":1024}'

Read the log:

exo dbaas logs SERVICE_NAME -z ZONE -l 200 \
  --output-template '{{range $l := .Logs}}{{println $l.Message}}{{end}}' | grep -E 'duration:|temporary file'

Lines look like this:

[20-1] pid=4424,user=avnadmin,db=testdb,app=psql,client=203.0.113.10 LOG:  duration: 4501.745 ms  statement: SELECT count(*) FROM (SELECT * FROM orders ORDER BY created_at) s;
[19-1] pid=4424,user=avnadmin,db=testdb,app=psql,client=203.0.113.10 LOG:  temporary file: path "base/pgsql_tmp/pgsql_tmp4424.0", size 17465344

Log lines can take a few seconds to show up. For longer retention or search, forward the logs, see Monitor your service.

Reset the Statistics

Counters accumulate until they are reset. Reset everything to measure a precise window, such as a load test:

SELECT pg_stat_statements_reset();

Or one statement only:

SELECT pg_stat_statements_reset(0, 0, QUERYID);

Parameters:

  • QUERYID: the queryid value of the statement.

EXECUTE on pg_stat_statements_reset() is granted to avnadmin (through avnadmin_group) and to the owner of the current database. Other users get permission denied for function pg_stat_statements_reset. A reset clears the counters for every database and every user of the service.

Compare Two Snapshots Instead of Resetting

On a shared service, take a baseline and compute the difference:

CREATE TABLE pgss_baseline AS
SELECT now() AS taken_at, userid, dbid, queryid, toplevel,
       calls, total_exec_time
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database());

Run the workload, then:

SELECT s.calls - coalesce(b.calls, 0) AS calls_delta,
       round(((s.total_exec_time - coalesce(b.total_exec_time, 0)) / 1000)::numeric, 3) AS seconds_delta,
       round(((s.total_exec_time - coalesce(b.total_exec_time, 0))
              / NULLIF(s.calls - coalesce(b.calls, 0), 0))::numeric, 2) AS mean_ms_in_window,
       s.query
FROM pg_stat_statements s
LEFT JOIN pgss_baseline b
  ON  b.userid   = s.userid
  AND b.dbid     = s.dbid
  AND b.queryid  = s.queryid
  AND b.toplevel = s.toplevel
WHERE s.dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
  AND s.calls > coalesce(b.calls, 0)
ORDER BY s.total_exec_time - coalesce(b.total_exec_time, 0) DESC
LIMIT 10;

An entry is identified by userid, dbid, queryid and toplevel together: the same statement run by two users gives two entries with the same queryid, so join on all four. The LEFT JOIN keeps statements that first appeared during the window. Drop the baseline afterwards:

DROP TABLE pgss_baseline;

The view keeps at most pg_stat_statements.max entries (5000 on a new service) and evicts the least used ones when full, so a rarely executed statement can disappear between two snapshots.

Related Pages

Last updated on