skip to content

On a PostgreSQL server, why is calling pg_stat_reset() before a load test risky, and how should you measure cumulative-statistics changes over a time window instead?

level: seniorimportance: should knowfreq 30%

answer

  1. someone else reads these counters
  2. autovacuum counts dead rows here
  3. snapshot, wait, subtract
  4. stats_reset marks the window start

basics

~20 s

pg_stat_reset() zeroes every counter of the current database, including the dead-tuple and modification counts autovacuum uses to decide when to vacuum and analyze, so needed maintenance can be skipped. Snapshot the views with now(), run the test, and subtract instead.

solid answer

~40 s

`pg_stat_reset()` zeroes all cumulative counters for the current database: scan and tuple counts and also `n_dead_tup`, `n_mod_since_analyze` and `n_ins_since_vacuum`, which autovacuum reads to decide when to work. The manual warns this can stop autovacuum doing necessary work, causing bloat or stale planner statistics, and recommends a database-wide `ANALYZE` afterwards. It also erases history other monitoring depends on. The safe way is to copy the views with `now()` into a table, run the test, and subtract. Shared views have their own resets, such as `pg_stat_reset_shared('io')`, and `stats_reset` columns show when each window began. Counters are also reset by a crash, immediate shutdown, base-backup start or PITR, and `pg_upgrade` does not carry them, even in 18, where it keeps optimizer statistics.

code

sql · 8 lines
sql
SELECT datname, stats_reset, now() - stats_reset AS window_length
FROM pg_stat_database
WHERE datname = current_database();

SELECT 'pg_stat_io' AS stats_view, max(stats_reset) AS stats_reset FROM pg_stat_io;

-- if a reset really was run, refresh what autovacuum and the planner need
ANALYZE;

go deeper

for a junior

Recall that the statistics views are counters since a reset, and that pg_stat_reset() zeroes the current database's counters.

for a middle

Explain the reset scopes, database, single table, shared view and backend, and why snapshot-and-subtract gives a clean window.

for a senior

Show why a reset can starve autovacuum, which events reset counters silently, and how stats_reset, flush lag and stats_fetch_consistency affect a measurement.

for a principal

Set the team rule: counters are shared infrastructure, nobody resets them casually, and metrics pipelines store snapshots so any window can be computed later.

## What the reset functions zero PostgreSQL's cumulative statistics live in shared memory, are written to the `pg_stat` directory on a clean shutdown, and survive a restart. There is one reset function per scope: | Function | Scope | |---|---| | `pg_stat_reset()` | every counter of the current database: tables, indexes, functions and its `pg_stat_database` row | | `pg_stat_reset_single_table_counters(oid)` | one table or index; it also moves the database's `stats_reset` timestamp | | `pg_stat_reset_shared(target)` | one cluster-wide view: `'archiver'`, `'bgwriter'`, `'checkpointer'`, `'io'`, `'recovery_prefetch'`, `'slru'` or `'wal'` | | `pg_stat_reset_shared()` | all of the shared views above, with no argument or NULL (since 17) | | `pg_stat_reset_backend_stats(pid)` | one backend's I/O and WAL figures (new in 18) | | `pg_stat_reset_replication_slot`, `pg_stat_reset_subscription_stats`, `pg_stat_reset_slru` | their own views | All are restricted to superusers by default, and `EXECUTE` can be granted to others. Per-query statistics have their own `pg_stat_statements_reset()`, which the query-stats sibling covers. ## Why resetting is risky - **Autovacuum reads these counters.** `n_dead_tup`, `n_mod_since_analyze` and `n_ins_since_vacuum` in `pg_stat_user_tables` feed the decision to vacuum or analyze a table. The manual warns that `pg_stat_reset()` resets them too, which can make autovacuum skip necessary work and cause table bloat or out-of-date planner statistics, and recommends a database-wide `ANALYZE` after a reset. `pg_stat_reset_single_table_counters` zeroes that table's entry, so the same reasoning applies to it. How the thresholds work belongs to the autovacuum leaf. - **Shared history disappears.** Dashboards, capacity reports and colleagues' investigations compute rates from the same counters. A reset leaves them with a gap and a sudden drop. - **It does not isolate the test.** Other sessions keep running during the test, so a reset window still mixes their traffic with yours. ## Measure a window instead The cumulative design is meant for differencing: 1. Copy the views you need, `pg_stat_user_tables`, `pg_stat_database` or `pg_stat_io`, into a table with `now()`. 2. Run the load test. 3. Select the same views again, join on `relid`, `datid` or the key columns, and subtract. 4. Divide by the elapsed time for rates. Two details make the numbers trustworthy: - **Flush lag.** Each backend sends its counts to shared memory before going idle, at most about once a second, so wait a moment after the test finishes before the second snapshot. - **Transaction caching.** With the default `stats_fetch_consistency = cache`, values read inside one transaction stay fixed until it ends. Take each snapshot in its own transaction, or call `pg_stat_clear_snapshot()`. ## When counters reset without anyone asking Check `stats_reset` in `pg_stat_database` and in each shared view before trusting lifetime totals. Counters start from zero after: - a crash or an **immediate** shutdown, which restarts through crash recovery; - starting a server from a **base backup**, including a new standby; - **point-in-time recovery**; - a major upgrade with `pg_upgrade`. In PostgreSQL 18 it transfers most optimizer statistics, but not extended statistics and not the cumulative statistics, so the post-upgrade steps include `vacuumdb --all --analyze-only` to rebuild the counters that trigger vacuum and analyze. A **fast** or **smart** `pg_ctl stop` is a clean shutdown and keeps the counters. ## Making windows routine Once snapshot-and-subtract is the habit, nobody needs a reset: - **Keep a history table** of periodic snapshots of the views you care about, each row stamped with `now()`. Any window, last hour or last month, is then a subtraction between two rows. - **Handle discontinuities.** When a counter goes down between two snapshots, a reset or an unclean start happened in between. Detect it by a smaller value or a newer `stats_reset`, and start a new series instead of computing a negative rate. - **Keep the reset rights narrow.** The reset functions are superuser-only by default. Grant `EXECUTE` on them only to the role that genuinely owns statistics, never to an application role. - **Write down every deliberate reset** with its time and reason, so the next person reading `stats_reset` knows the window was cut on purpose. If a reset was run anyway, the repair is a database-wide `ANALYZE`, which refreshes planner statistics and lets autovacuum's counters rebuild from fresh activity.

  • Does pg_stat_reset() clear the planner statistics in pg_statistic?
    No. Planner statistics are column histograms and most-common values gathered by `ANALYZE` and kept in the `pg_statistic` catalog; the reset functions touch only cumulative activity counters. The risk is indirect: autovacuum's modification counters are zeroed, so the next auto-analyze can come late and planner statistics go stale.
  • Why might two queries of pg_stat_user_tables in one transaction return identical numbers while the workload runs?
    With the default `stats_fetch_consistency = cache`, values a session reads are cached until its transaction ends, so you can correlate several queries without the numbers moving underneath. Set it to `snapshot` for a consistent view of everything, `none` for fresh reads, or call `pg_stat_clear_snapshot()`.

Calling pg_stat_reset() is like zeroing a shared car's odometer to time one trip: you get your trip number, but the service schedule that reads the same odometer now thinks the oil was just changed. Use the trip meter instead: note the reading, drive, and subtract.

  • pg_stat_reset() only affects monitoring dashboards and has no effect on maintenance.
  • pg_stat_reset() resets pg_stat_io and pg_stat_checkpointer for the whole cluster.
  • Cumulative statistics are lost on every restart, even a clean fast shutdown.
  • In PostgreSQL 18, pg_upgrade carries the cumulative statistics over to the new cluster.
  • Resetting the counters before a test isolates the test from other sessions' traffic.

Assumes PostgreSQL 18: pg_upgrade now transfers optimizer statistics but still not cumulative statistics, pg_stat_reset_backend_stats() is new in 18, and since 17 pg_stat_reset_shared() with no argument resets every shared view.