brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: auto_explain writes the plan of slow PostgreSQL queries to the log

Postgresql
~/tips/tip-postgresql-auto-explain

LOAD 'auto_explain';

A contrib module that logs the execution plan of any statement slower than a limit you set.

A slow query that only shows up in production is annoying, because by the time you run EXPLAIN yourself the problem has moved. auto_explain comes with PostgreSQL and logs the plan at the moment it happens.

LOAD 'auto_explain';
SET auto_explain.log_min_duration = '250ms';
SET auto_explain.log_analyze = true;

That is the session version, and the docs say you must be a superuser to use LOAD. Any statement that runs 250 ms or longer now gets its plan written to the server log. A value of 0 logs every plan and -1, the default, logs nothing.

To have it everywhere, preload it in postgresql.conf:

session_preload_libraries = 'auto_explain'
auto_explain.log_min_duration = '3s'

The caveat is log_analyze. With it on, per-node timing is measured for every statement, not just the slow ones, and the docs warn this can have an extremely negative impact on performance. Setting auto_explain.log_timing to off reduces the cost, at the price of less detail. auto_explain.log_buffers only does something when log_analyze is on, and auto_explain.sample_rate lets you explain only a fraction of statements.

The docs show what the result looks like. With log_min_duration at 0 and log_analyze on, a query against pg_class and pg_index logs a line like LOG: duration: 3.651 ms plan:, followed by the query text and the plan with actual times.

A few more parameters from that page: auto_explain.log_format accepts text, xml, json and yaml, with text as default. auto_explain.log_nested_statements is off by default, so statements inside functions aren’t logged until you turn it on. auto_explain.log_verbose is the same as the VERBOSE option of EXPLAIN. Only superusers can change these settings.

Further reading: auto_explain

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb FROM pg_stat_user_indexes All Postgresql tips (24) All topics

Link