Sub topic 14
Limits, eviction, and overhead
This chapter assumes you have enabled pg_stat_statements, can read its core columns, and have ranked queries by total and mean time. It covers three things: what the extension cannot tell you, what happens when its fixed-size table fills up, and what it costs to run. The examples assume PostgreSQL 14 or later, and the notes mark where older versions differ.
What the statistics cannot tell you
pg_stat_statements keeps running totals per entry. Each row is one accumulated summary, not a log of executions. Four consequences follow.
- No per-execution history.
max_exec_timesays the slowest run took 4,200 ms. It does not say when that run happened, which parameters it used, or what else the server was doing at the time. - No time axis. Every counter starts at the last reset, or at the entry's creation. A query with 10 million calls may have been busy last week and idle today, and a single snapshot cannot show that.
- Completed statements only. Statements that fail or are cancelled before finishing are generally not counted. A query that always times out can be missing from your ranking.
- Nested statements are hidden by default. With
pg_stat_statements.track = top, only top-level statements are recorded. SQL run inside a function appears only as the call to that function. Settrack = allto see the inner statements.
For single slow events, use log_min_duration_statement or auto_explain. Use pg_stat_statements to find which query shapes deserve that attention.
Building your own history
You can add the missing time axis by copying the view into a table on a schedule, for example every five minutes from cron or pg_cron. Differences between snapshots then give per-interval numbers.
CREATE TABLE pgss_snapshot AS
SELECT now() AS captured_at, *
FROM pg_stat_statements
WITH NO DATA;
-- run this on a schedule
INSERT INTO pgss_snapshot
SELECT now(), * FROM pg_stat_statements;SELECT captured_at,
queryid,
calls - lag(calls) OVER w AS calls_in_interval,
round((total_exec_time - lag(total_exec_time) OVER w)::numeric, 2) AS ms_in_interval
FROM pgss_snapshot
WINDOW w AS (PARTITION BY userid, dbid, queryid, toplevel ORDER BY captured_at)
ORDER BY captured_at DESC, ms_in_interval DESC NULLS LAST
LIMIT 20;A negative delta means a reset or an eviction happened between the two snapshots. Discard those rows.
Entry limits and eviction
The extension stores entries in shared memory. The number of entries is capped by pg_stat_statements.max, which defaults to 5000 and can only be changed with a server restart. An entry is keyed by user, database, queryid, and, in PostgreSQL 14 and later, whether the statement was top-level. The same SQL text run by three roles therefore uses three entries.
When a new statement arrives and the table is full, the server removes the least-executed entries, about 5% of the table, to make room. This is called deallocation.
Eviction favours frequently run statements, which is usually what you want. The cost is that rarely run but expensive statements, such as a monthly report, are the first to disappear. They also lose their counters when they come back.
Detecting churn
Compare the entry count to the limit, and check how often deallocation has happened.
SELECT (SELECT count(*) FROM pg_stat_statements) AS entries,
current_setting('pg_stat_statements.max') AS max_entries,
i.dealloc,
i.stats_reset
FROM pg_stat_statements_info AS i;If dealloc keeps growing between checks, entries are being discarded and your rankings are incomplete. pg_stat_statements_info exists in PostgreSQL 14 and later. On older versions you can only watch whether the entry count sits at the limit.
Two common reasons for churn:
- The limit is too small for the number of distinct statements, roles, and databases. Raise
maxand restart. - Many near-identical entries. Normalization replaces constants, but statements can still differ in structure. Examples are
INlists with different numbers of items (newer releases collapse some of these), queries with generated table or column names, andSETorSAVEPOINTstatements with literal names whentrack_utilityis on. One application bug can generate thousands of entries and push out the useful ones.
Check for the second cause before raising the limit:
SELECT left(query, 60) AS query_start,
count(*) AS entries,
sum(calls) AS calls
FROM pg_stat_statements
GROUP BY left(query, 60)
HAVING count(*) > 20
ORDER BY entries DESC
LIMIT 10;A prefix with hundreds of entries and few calls each is a sign of a query shape that is not being normalized well.
Query text limits
Display truncation and storage truncation are different things.
- The
left(query, 80)calls in this tutorial shorten the text only in your result set. Entries keep the full text. - Since PostgreSQL 9.4 the extension stores query text in an external file on disk, not in shared memory. The text is not cut at
track_activity_query_size. pg_stat_activityis different. It cuts the current query attrack_activity_query_sizebytes (default 1024) and needs a restart to change. If you copy a long query frompg_stat_activityto match it againstpg_stat_statements, match onqueryidinstead of text.- Each entry keeps the text of the first form it saw, with constants replaced by
$1,$2, and so on. You never see the actual parameter values. Reproduce the problem with realistic values before runningEXPLAIN (ANALYZE, BUFFERS). - Users without permission to see another role's statements get a placeholder instead of the text, as covered in the permissions chapter.
Overhead
For most workloads the overhead is small. The extension runs a few counter updates per statement, and it reads the query text file only when you query the view. Costs show up in particular situations:
| Situation | Effect | What to do |
|---|---|---|
| Thousands of very short queries per second on many cores | Contention on the lock that protects each entry | Measure before and after enabling; keep `track_planning` off |
| `pg_stat_statements.track_planning = on` | Planning time is recorded too, which adds work per statement | Enable only when you need planning time, and test under load |
| Constant eviction | Repeated writes of the query text file and its cleanup | Raise `max` or fix non-normalized queries |
| Very large `max` | More shared memory and a larger view to scan | Size it to your real number of distinct statements |
| Frequent polling of the view | Each read scans every entry and can read the text file | Select `queryid` and numbers only, and fetch the text for the few rows you need |
Also remember the lifetime of the data. With pg_stat_statements.save = on (the default) the statistics survive a clean shutdown. A crash or a restore from a base backup loses them, so a sudden drop in calls may mean a restart and not a change in traffic. A standby keeps its own statistics, separate from the primary's.
Settings to review
# postgresql.conf (restart required for max)
pg_stat_statements.max = 10000
pg_stat_statements.track = top
pg_stat_statements.track_utility = on
pg_stat_statements.track_planning = off
pg_stat_statements.save = onOnly max is about capacity. The others decide what is counted and whether it persists.
Exercise
Your top-10 query by totalexectime shows a monthly report with only 3 calls, but the team says it has run every night for a year. pgstatstatements_info shows dealloc = 412. What is the most likely explanation, and what two steps would you take?
Show answer
The report's entry was evicted many times, because rarely run statements are the first to be removed when the table is full, so its counters restarted at zero each time and now cover only the recent runs. Step one: find out why the table is overflowing. Group entries by query prefix to look for near-duplicate, non-normalized statements. Step two: raise pgstatstatements.max if the distinct statements are legitimate, and restart. Optionally snapshot the view on a schedule so totals survive eviction.
Exercise
Why can pgstatstatements not tell you which parameter value made a query take 4 seconds once, and what would you use instead to capture such a case?
Show answer
It stores only cumulative per-entry counters and the normalized query text with constants replaced by $1, $2, and so on, with no record of individual executions. To capture the slow execution itself, set logmindurationstatement so the statement and its duration are logged, or use autoexplain to log the plan of slow statements.