
PostgreSQL, Part 5: Monitoring and Maintenance — pg_stat_statements, Locks, Bloat, VACUUM, and postgres_exporter
🌐 Machine-translated from Russian. Show original
In this part:
What to watch first#
| What | Why is it important | Where to watch |
|---|---|---|
| Availability and number of connections | focus on max_connections = application failure | pg_stat_activity |
| Long requests and transactions | keep locks and interfere with VACUUM | pg_stat_activity |
| Locks | "all frozen" — most often, these are | pg_blocking_pids() |
| Tough queries | where time is really spent | pg_stat_statements |
| Replica lag, slots, | data loss during failover, disk filling | pg_stat_replication, pg_replication_slots |
| WAL archive and backups | no archive — no PITR | pg_stat_archiver, pgbackrest info |
| Transaction age (wraparound) | when the base approaches the limit, it will stop recording | age(datfrozenxid) |
| Disk space | WAL and bloat grow imperceptibly | OS, pg_database_size() |
pg_stat_statements — the main instrument#
The extension collects statistics for each type of query: how many times it was executed, how long it took.
sudo tee /etc/postgresql/18/main/conf.d/60-monitoring.conf >/dev/null <<'EOF'
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.track = top
compute_query_id = on
track_io_timing = on
EOF
sudo systemctl restart postgresql@18-main
sudo -u postgres psql -d appdb -c "CREATE EXTENSION IF NOT EXISTS pg_stat_statements;"
⚠️ If something already exists in
shared_preload_libraries(for example, in the 1C build), add the value separated by a comma instead of replacing the line.
Top queries by total time:
SELECT round(total_exec_time::numeric / 1000) AS total_s,
calls,
round(mean_exec_time::numeric, 1) AS mean_ms,
rows,
left(query, 100) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 15;
Optimize at the top of the list: a 5 ms query executed a million times is more important than a rare 30-second report. Parsing a specific query — EXPLAIN (ANALYZE, BUFFERS) .... Reset statistics after changes: SELECT pg_stat_statements_reset();.
What is happening right now#
-- активные запросы дольше 30 секунд
SELECT pid, usename, datname, state, now() - query_start AS duration, left(query, 80) AS query
FROM pg_stat_activity
WHERE state <> 'idle' AND now() - query_start > interval '30 seconds'
ORDER BY duration DESC;
-- кто кого блокирует
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, left(query, 80) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
Cancel request — SELECT pg_cancel_backend(pid);, disconnect — SELECT pg_terminate_backend(pid);.
Protection against "forgotten" transactions and endless requests:
ALTER SYSTEM SET idle_in_transaction_session_timeout = '10min';
ALTER ROLE report SET statement_timeout = '15min';
SELECT pg_reload_conf();
Bloat: swelling of tables and indexes#
The pgstattuple extension (included in the PostgreSQL package) helps to accurately estimate:
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT * FROM pgstattuple_approx('public.orders'); -- быстрая оценка таблицы
SELECT * FROM pgstatindex('public.orders_pkey'); -- индекс: avg_leaf_density
A quick look without extensions — dead lines and the last (auto)vacuum:
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum, last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 15;
VACUUM, ANALYZE, REINDEX#
| Command | What does | Locks the table? |
|---|---|---|
VACUUM (VERBOSE, ANALYZE) orders; | frees up space for reuse, updates statistics, | no |
VACUUM FULL orders; | rewrites the entire table, returns the OS location, | yes, fully — only in the service window |
REINDEX INDEX CONCURRENTLY orders_pkey; | recreates a swollen index | no (longer, but without idleness) |
pg_repack | like VACUUM FULL, but without long lockdowns, | only for a short time at the end of |
pg_repack is set from PGDG: sudo apt install -y postgresql-18-repack, then CREATE EXTENSION pg_repack; in the database, and pg_repack -d appdb -t orders.
💡 If the bloat keeps coming back again and again, the cause is usually not a "bad VACUUM," but long transactions or forgotten replication slots: while they are open, VACUUM cannot delete old versions of strings.
Wraparound: check once a day#
SELECT datname, age(datfrozenxid) AS xid_age,
round(100 * age(datfrozenxid) / 2000000000.0, 1) AS pct_to_limit
FROM pg_database ORDER BY xid_age DESC;
Normal — a few percent, above 50% — a reason to figure out why autovacuum can't keep up.
postgres_exporter for Prometheus#
postgres_exporter provides PostgreSQL metrics in Prometheus format (current version as of November 2026 — 0.20.1).
Role for monitoring with minimal rights:
CREATE ROLE postgres_exporter LOGIN;
\password postgres_exporter
GRANT pg_monitor TO postgres_exporter;
Installation:
V=0.20.1
cd /tmp
wget https://github.com/prometheus-community/postgres_exporter/releases/download/v$V/postgres_exporter-$V.linux-amd64.tar.gz
tar xzf postgres_exporter-$V.linux-amd64.tar.gz
sudo install -m 755 postgres_exporter-$V.linux-amd64/postgres_exporter /usr/local/bin/
sudo useradd --system --no-create-home --shell /usr/sbin/nologin postgres_exporter
Connection string — in a separate file with permissions 600:
sudo tee /etc/default/postgres_exporter >/dev/null <<'EOF'
DATA_SOURCE_NAME=postgresql://postgres_exporter:ПАРОЛЬ@127.0.0.1:5432/postgres?sslmode=disable
EOF
sudo chown postgres_exporter: /etc/default/postgres_exporter && sudo chmod 600 /etc/default/postgres_exporter
sudo tee /etc/systemd/system/postgres_exporter.service >/dev/null <<'EOF'
[Unit]
Description=Prometheus PostgreSQL exporter
After=network-online.target
[Service]
User=postgres_exporter
EnvironmentFile=/etc/default/postgres_exporter
ExecStart=/usr/local/bin/postgres_exporter --collector.stat_statements
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload && sudo systemctl enable --now postgres_exporter
curl -s localhost:9187/metrics | grep pg_up
Open port 9187 only for the Prometheus server. Connecting to Prometheus, ready-made Grafana dashboards, and alerts in Telegram are in the "Monitoring: Zabbix, Prometheus, and Grafana" series. If you have Zabbix, it has a ready-made PostgreSQL template by Zabbix agent 2.
Minimal set of alerts#
- PostgreSQL is unavailable (
pg_up == 0) — immediately; - compounds more than 80% of
max_connections; - request or transaction longer than N minutes;
- a replica lag of more than 1–5 minutes or the replica has disconnected;
pg_stat_archiver.failed_countis rising, the last successful backup is over a day;- transaction age over 50% of the limit;
- free space on a volume with data less than 15%.
Service Regulations#
| How often | What to do |
|---|---|
| Daily alert checks, backup results, | |
| Weekly | top pg_stat_statements, slow magazine queries, database growth, |
| Monthly | recovery test, bloat of large tables and indexes, unused indexes (pg_stat_user_indexes.idx_scan = 0) |
| Quarterly | minor PostgreSQL updates, revision of settings for increased load |
Next is PostgreSQL, part 6: security, minor version updates, and upgrading to a new version via pg_upgrade.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.