34.3. Maintaining PostgreSQL
Between outages, a database needs attention that has nothing to do with
failure: sessions that block each other, queries that run too long,
the vacuum machinery that reclaims space behind a workload, and
package updates that must not surprise the application. This section
exercises each of those against the live inventory cluster with real
concurrent sessions, because the point of every demonstration is that
it runs on a server that is simultaneously doing work.
34.3.1. Transactions, Locks, Long-Running Queries, and Connection Limits
The lock exercise needs two live sessions, so it uses the window layout an administrator would actually use. Everything happens on db1. In a second window, start a session that takes an exclusive lock on the items table and holds it for thirty seconds:
$ sudo -u postgres psql -d inventory -c "BEGIN; LOCK TABLE app.items IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(30); COMMIT;"
The session produces no output for the full thirty seconds - the
pg_sleep(30) call inside the open transaction is what keeps the
lock held - and then finishes with the empty result of the sleep. In a third
window, start a query that needs the same table:
$ sudo -u postgres psql -d inventory -c "SELECT count(*) FROM app.items;"
This session produces no output and does not return: even a SELECT
must take a short-lived ACCESS SHARE lock on every table it reads,
and ACCESS EXCLUSIVE conflicts with it. Leave both windows as they
are and inspect from the first. Still on db1:
$ sudo -u postgres psql -d inventory -x -c "SELECT pid, state, wait_event_type, wait_event, left(query,45) AS query FROM pg_stat_activity WHERE datname = 'inventory' AND pid <> pg_backend_pid();"
-[ RECORD 1 ]---+----------------------------------------------
pid | 14617
state | active
wait_event_type | Timeout
wait_event | PgSleep
query | BEGIN; LOCK TABLE app.items IN ACCESS EXCLUSI
-[ RECORD 2 ]---+----------------------------------------------
pid | 14637
state | active
wait_event_type | Lock
wait_event | relation
query | SELECT count(*) FROM app.items;
pg_stat_activity shows both sessions, and the columns tell the story
without guessing. Record 1 is the holder: active, but waiting on
Timeout/PgSleep - it is sleeping, not stuck. Record 2 is the waiter:
wait_event_type Lock, wait_event relation - the kernel is not
involved; PostgreSQL's own lock manager has parked it. The truncated
query text (left(query,45)) keeps the report readable. The lock
table makes the conflict explicit:
$ sudo -u postgres psql -d inventory -c "SELECT relation::regclass, mode, granted, pid FROM pg_locks WHERE NOT granted;"
relation | mode | granted | pid
----------+-----------------+---------+-------
app.items | AccessShareLock | f | 14637
(1 row)
pg_locks lists lock requests that have not been granted - exactly
one, the reader's AccessShareLock, waiting (granted f) on the table
displayed by relation::regclass. The holder's granted lock does not
appear because the filter selects the waiting side. One more view names
the blocker directly:
$ sudo -u postgres psql -d inventory -Atc "SELECT pg_blocking_pids(pid) FROM pg_stat_activity WHERE query LIKE 'SELECT count(*) FROM app.items%';"
{14617}
pg_blocking_pids() returns the set of processes blocking a given
session - here the single PID 14617, the sleeping holder. This is the
query to reach for in production: given a stuck session, it walks the
lock graph for you. The response to a blocked session is a decision,
not a reflex: the holder may be a legitimate batch job (wait, or
reschedule the conflicting work), or it may be a forgotten session (end
it). To cancel just the waiting query:
$ sudo -u postgres psql -d inventory -Atc "SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE datname = 'inventory' AND pid <> pg_backend_pid() AND query LIKE 'SELECT count(*) FROM app.items%';"
t
pg_cancel_backend() sends the session a cancellation request; it
returns t when the signal was delivered. The waiting session in the
third window returns immediately with ERROR: canceling statement due
to user request - the same error a client-side Ctrl+C produces, since
that is what Ctrl+C sends. The holder is untouched and finishes on its
own. pg_terminate_backend() is the stronger tool - it kills the
whole connection - and is the right one for sessions stuck in idle in
transaction, which do not respond to a query cancel.
Locks scale up to whole-database problems, and so does the diagnosis:
pg_stat_activity plus pg_blocking_pids finds any blocking chain,
and state = 'idle in transaction' rows are usually the root of them.
Before the diagnostics come the limits that keep a runaway application
from consuming every backend. PostgreSQL bounds total connections with
max_connections (default 100, of which 5 are reserved for
superusers), and each role can have its own stricter ceiling:
$ sudo -u postgres psql -d inventory -c "ALTER ROLE app_reader CONNECTION LIMIT 1;"
ALTER ROLE
The role may now hold exactly one connection at a time. Occupy it - in a second window, as the reader:
$ PGPASSWORD=reader-secret psql -h 127.0.0.1 -U app_reader -d inventory -c "SELECT pg_sleep(30);"
No output for thirty seconds; leave it running. Then, back in the
first window, as john:
$ PGPASSWORD=reader-secret psql -h 127.0.0.1 -U app_reader -d inventory -c "SELECT 1;"
psql: error: connection to server at "127.0.0.1", port 5432 failed: FATAL: too many connections for role "app_reader"
The second connection is refused at login with
too many connections for role - the application sees an immediate,
explicit error rather than a mysterious later failure. Lift the limit
once the demonstration is over:
$ sudo -u postgres psql -d inventory -c "ALTER ROLE app_reader CONNECTION LIMIT -1;"
ALTER ROLE
-1 means unlimited, the default. A per-role limit is crude but
effective containment for a misbehaving service, and it composes with
max_connections: the server-level ceiling is the last line of
defense, the role-level one is the policy.
One session from this exercise is still open - the sleeping reader in the second window. End it deliberately before moving on: an open transaction, even one doing nothing but sleeping, sets the cleanup horizon for the whole cluster, and row versions that die after its snapshot cannot be reclaimed anywhere until it ends - the next section's vacuum exercise depends on that horizon being clear. From the first window on db1:
$ sudo -u postgres psql -Atc "SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE datname = 'inventory' AND usename = 'app_reader' AND query LIKE 'SELECT pg_sleep(30)%';"
t
t - the same cancellation request the lock exercise sent, delivered
to the sleeping session; the second window ends with the usual
cancellation error, and pressing Ctrl+C there would have sent the
same request. Letting the thirty seconds run out ends the session
just as cleanly, only later.
34.3.2. Autovacuum, Statistics, Bloat, and Capacity Monitoring
PostgreSQL's storage model never overwrites a row in place. An
UPDATE writes a new version of the row elsewhere and marks the old
version dead; a DELETE marks the row dead. Dead versions must stay
visible to transactions that were running when they died, so removing
them is a separate, deliberate job - vacuum. It matters for two
reasons: dead tuples bloat tables and indexes until queries scan
garbage, and the oldest still-open transaction cannot advance past any
dead tuple that transaction might still need to see. A long-running
idle in transaction session is therefore not just a lock risk - it
pins the entire cleanup horizon.
Watch the whole lifecycle in one pass on db1. The following fills the table with churn, vacuums it, and reports the statistics view:
$ sudo -u postgres psql -d inventory -v ON_ERROR_STOP=1 -c "INSERT INTO app.items (name, quantity) SELECT 'part-' || g, g FROM generate_series(1,5000) g;" -c "UPDATE app.items SET quantity = quantity + 1 WHERE id % 2 = 0;" -c "DELETE FROM app.items WHERE id % 5 = 0;" -c "VACUUM (ANALYZE) app.items;" -c "SELECT relname, n_live_tup, n_dead_tup, last_vacuum IS NOT NULL AS vacuumed, last_analyze IS NOT NULL AS analyzed FROM pg_stat_user_tables WHERE relname = 'items';"
INSERT 0 5000
UPDATE 2501
DELETE 1000
VACUUM
relname | n_live_tup | n_dead_tup | vacuumed | analyzed
---------+------------+------------+----------+----------
items | 4002 | 0 | t | t
(1 row)
Arithmetic first: the table starts with 2 rows, gains 5000, loses 1000
to the DELETE, and keeps 4002. The UPDATE rewrote 2501 rows, so
2501 dead versions existed, plus the 1000 deleted rows - 3501 dead
tuples at the peak. After VACUUM (ANALYZE) the statistics view
reports exactly what should be true: 4002 live, 0 dead, vacuum and
analyze both recorded. The n_live_tup and n_dead_tup figures are
estimates maintained incrementally - accurate enough for monitoring,
not a substitute for counting.
What vacuum actually did to the physical file is visible with the
pgstattuple extension, which walks pages directly. The contrib
extensions ship inside the server package, so enabling it is one
statement:
$ sudo -u postgres psql -d inventory -c "CREATE EXTENSION IF NOT EXISTS pgstattuple;" -c "SELECT pg_size_pretty(pg_total_relation_size('app.items')) AS total_size, pg_size_pretty(pg_database_size('inventory')) AS database_size;" -c "SELECT * FROM pgstattuple('app.items');"
CREATE EXTENSION
total_size | database_size
------------+---------------
656 kB | 8294 kB
(1 row)
table_len | tuple_count | tuple_len | tuple_percent | dead_tuple_count | dead_tuple_len | dead_tuple_percent | free_space | free_percent
-----------+-------------+-----------+---------------+------------------+----------------+--------------------+------------+--------------
393216 | 4002 | 191772 | 48.77 | 0 | 0 | 0 | 169884 | 43.2
(1 row)
Read it against the theory. The table file is 393216 bytes (384 kB)
and still holds 4002 live tuples at 48.77% of the file - but the 3501
dead versions are gone and 169884 bytes (43.2%) of each page are now
free space, ready to be reused by future inserts and updates. Vacuum
reclaims space inside the file; it does not shrink the file, and
that is by design - shrinking means rewriting. A table whose
dead_tuple_percent and free_percent stay high and keeps growing
is bloated, and the remedy is VACUUM FULL (which rewrites the table
and takes an exclusive lock - schedule it) or the online
pg_repack-style tools. A table whose dead tuples refuse to shrink at
all has a pin: check for idle in transaction sessions and old
replication slots before blaming vacuum.
Manual VACUUM is for demonstrations and emergencies; the
autovacuum daemon does the routine work. Its settings, on db1:
$ sudo -u postgres psql -Atc "show autovacuum; show autovacuum_naptime; show autovacuum_max_workers;"
on
1min
3
Autovacuum is on by default and must stay on. Every autovacuum_naptime
(1 minute) it wakes, and for each table compares dead-tuple counts
against the trigger threshold - 50 dead tuples plus 20% of live rows by
default. Three workers run concurrently, so one large table cannot
starve the rest. A high-churn table may need its own settings;
per-table storage parameters (ALTER TABLE ... SET
(autovacuum_vacuum_scale_factor = ...)) override the defaults for
just that table, and monitoring pg_stat_user_tables -
n_dead_tup against n_live_tup, last_autovacuum recency - tells
you when the defaults are losing.
Capacity monitoring closes the loop. The same statistics views give
table and index sizes (pg_total_relation_size, used above), database
size (pg_database_size, 8294 kB here), and the chapter's later
sections add two more: WAL archive growth on the archive disk
(section 34.4.3) and replication lag (34.5.2). The habit worth forming
is to check growth against a baseline rather than absolute size - a
table doubling every week at 10 MB is a bigger problem than a stable
terabyte.
34.3.3. Routine Package Updates and Major-Version Upgrade Choices
Routine updates are the easy case. PostgreSQL security and bug fixes
arrive as point releases within the packaged major version - the
17.12-0+deb13u1 seen in section 34.2.1 becomes 17.12-0+deb13u2 and
so on - and these are designed to be safe: same on-disk format, same
replication protocol, drop-in replacement. Apply them with the normal
Chapter 6 workflow:
$ sudo apt update
The command prints its repository summary and any warnings; it does not upgrade anything by itself. Then review and apply what appeared:
$ sudo apt full-upgrade
Answer the prompts normally and let apt install the packages. When a
new postgresql-17 point release lands, the running server binaries
are updated on disk but the cluster keeps running on the old ones until
restarted - pg_lsclusters keeps showing online. Restart the cluster
in a maintenance window, exactly as section 34.2.3 did:
$ sudo pg_ctlcluster 17 main restart
The command prints nothing on success, and the restart itself takes
seconds - recovery replays only the WAL written since the last
checkpoint. Verify with pg_lsclusters and the application check in
section 34.3.4.
Major versions are a different project, and PostgreSQL makes no pretense otherwise: a major upgrade moves data between two on-disk formats and needs both versions installed at once. Debian supports this cleanly because versions are parallel packages and clusters are parallel directories. The path the packaging intends:
- Install the new major's package (for example
postgresql-18when Debian ships it); it creates its ownmaincluster on a free port, running and empty. - Run
pg_upgradecluster <old-major> <cluster>- with the old cluster running or stopped, it stops it, copies and converts the data with PostgreSQL'spg_upgrademachinery, starts the new cluster on the old cluster's port, and leaves the old data directory untouched on disk. - Validate the application against the new cluster (section 34.3.4),
then remove the old version's cluster with
pg_dropcluster <old-major> <cluster> --stop- only after you are satisfied, because this deletes the old data directory.
The alternatives are the ones you already know from this chapter: a
logical dump and restore (pg_dumpall into the new cluster - slower
but works across any versions and produces a defragmented copy), or a
replication-based switch (logical replication into a new-version
cluster, then fail over applications to it). One constraint binds
whichever you choose: physical streaming replication only works
between servers of the same major version, so a replicated or
Patroni-managed cluster cannot be upgraded one node at a time. The
safe sequence is to build the new-version cluster from a backup or a
logical copy, let applications use it, and only then decommission the
old one.
34.3.4. Validating an Application After Maintenance
Every maintenance action in this chapter ends the same way, and it
should become reflex: connect as the application, exercise a write and
a read, and reconcile what comes back. On db1, as john:
$ PGPASSWORD=owner-secret psql -h 127.0.0.1 -U app_owner -d inventory -c "INSERT INTO app.items (name, quantity) VALUES ('after-maintenance', 3) RETURNING id; SELECT count(*) FROM app.items;"
id
------
5003
(1 row)
INSERT 0 1
count
-------
4003
(1 row)
The write succeeded as the application role, so authentication and
grants survived the restart and the vacuum. The returned id is
5003 - the identity sequence is where the churn of section 34.3.2 left
it, continuing past the 5000 generated rows, so the maintenance did not
reset or duplicate the table's numbering. The count is 4003, which is
4002 rows plus the one just inserted; the read agrees with the write
that preceded it in the same session. Three checks, one command.
The general checklist after any restart, upgrade, restore, or failover is short: the application's least-privileged role can log in (not the superuser - the superuser hides grant breakage); a representative write commits and returns sane generated values; a representative read reflects it immediately; and anything with a sequence, watermark, or last-updated timestamp advanced monotonically. Sections 34.4.5 and 34.7.3 apply the same pattern after restores and failovers, where the stakes are higher and the check is not optional.