Sub topic 17
Maintenance and upgrades
This chapter assumes you can install and manage the database service with systemd, edit its configuration files, take logical backups, and restore them into a scratch database. It covers routine maintenance and the two kinds of upgrade: minor and major. It does not cover replication setup. Replication appears only where it changes an upgrade plan.
Why maintenance matters
A database server that is installed and left alone slowly degrades. Tables accumulate dead rows, disks fill with logs and old backups, and the software falls behind security fixes. Most of the work here is small and repeatable, so you can schedule it and check the results.
There are three kinds of work:
- Routine maintenance: keeping statistics fresh, reclaiming space, watching disk use and rotating logs.
- Minor upgrades: moving between releases of the same major version, such as PostgreSQL 16.3 to 16.4, or MySQL 8.0.36 to 8.0.37.
- Major upgrades: moving to a new major version, such as PostgreSQL 15 to 16, or MySQL 8.0 to 8.4.
Routine maintenance in PostgreSQL
PostgreSQL uses multiversion concurrency control (MVCC). When a row is updated or deleted, the old version stays on disk until it is no longer visible to any transaction. These leftover versions are called dead tuples. The VACUUM command marks their space as reusable.
The autovacuum daemon runs VACUUM and ANALYZE automatically, and it is on by default. Leave it on. ANALYZE refreshes the table statistics the query planner uses to choose plans. Stale statistics are a common cause of a query that suddenly gets slow.
Check whether autovacuum is keeping up:
SELECT relname,
n_live_tup,
n_dead_tup,
last_autovacuum,
last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;A table with a large n_dead_tup and an old last_autovacuum is a warning sign. Common causes are a long-running transaction that holds back cleanup, or a table that changes so fast that the default thresholds are too lax. You can tune one table without changing the global defaults:
ALTER TABLE events SET (autovacuum_vacuum_scale_factor = 0.02);Plain VACUUM makes space reusable inside the table file but usually does not shrink the file on disk. VACUUM FULL rewrites the table and returns space to the operating system, but it takes an exclusive lock that blocks reads and writes while it runs. Use it only in a maintenance window, and only when a table has grown far beyond its useful size.
Indexes can also bloat. REINDEX rebuilds them. Use REINDEX INDEX CONCURRENTLY index_name; to avoid blocking writes.
Transaction ID wraparound
PostgreSQL numbers transactions with a 32-bit counter. Autovacuum periodically freezes old rows so the counter can be reused safely. If freezing falls too far behind, PostgreSQL protects itself by refusing new writes until a vacuum finishes. Monitor the age of each database:
SELECT datname, age(datfrozenxid) AS xid_age
FROM pg_database
ORDER BY xid_age DESC;The hard limit is about 2 billion. Autovacuum starts aggressive freezing at 200 million by default. If a value climbs well past that, find out why autovacuum is blocked. Typical causes are abandoned prepared transactions, idle-in-transaction sessions, and stale replication slots.
Routine maintenance in MySQL
InnoDB, the default MySQL storage engine, cleans up old row versions itself in a background purge thread, so there is no vacuum command to schedule. The tasks that remain are:
ANALYZE TABLErefreshes index statistics. InnoDB recalculates some statistics automatically, but you can run it after a large data load.OPTIMIZE TABLErebuilds a table and its indexes to reclaim space. For InnoDB it recreates the table, so run it off-peak on large tables and make sure free disk space exceeds the table size.- Binary logs grow until they expire. Set
binlog_expire_logs_seconds(default 30 days) to a value that fits your disk and recovery needs. Never delete binary log files by hand withrm; usePURGE BINARY LOGSinstead, so the index file stays consistent.
ANALYZE TABLE appdb.orders;
SHOW BINARY LOGS;
PURGE BINARY LOGS BEFORE NOW() - INTERVAL 7 DAY;Disk space and log housekeeping
Running out of disk is the most common way a database server fails, and recovery can be messy. Watch these places:
| Item | Where it grows | What to do |
|---|---|---|
| PostgreSQL WAL | `pg_wal` in the data directory | Find the cause of retention: a stale replication slot, failing `archive_command`, or a large `max_wal_size`. |
| MySQL binary logs | The data directory or `log_bin` path | Set `binlog_expire_logs_seconds`. |
| Server logs | `/var/log/postgresql` or `/var/log/mysql` | Rotate with logrotate or journald limits. |
| Backups | Your backup directory | Apply a retention rule and delete dumps that you have already verified and superseded. |
| Temporary files | Sort and join spill files | Raise the memory setting for the workload or fix the query. |
Alert when any data volume passes about 80 percent full. A growing pg_wal directory is a particular warning, because the usual cause is a replication slot that nobody is consuming.
Minor upgrades
A minor upgrade replaces the server binaries and keeps the on-disk format. Minor releases contain bug and security fixes only. Apply them regularly.
With distribution packages, the process is:
- Read the release notes for anything marked as requiring action.
- Take a fresh backup.
- Upgrade the packages.
- Restart the service if the package did not do so, then check the logs.
sudo apt update
apt list --upgradable 2>/dev/null | grep -i -E 'postgresql|mysql'
sudo apt install --only-upgrade postgresql
sudo systemctl status postgresql
sudo journalctl -u postgresql --since '10 minutes ago'A restart closes every client connection. Applications need to reconnect, so plan a brief window, or use replicas and fail over if you need no downtime. Connect afterwards and confirm the running version, because a package upgrade does not take effect until the process restarts:
SELECT version();On Debian and Ubuntu, package scripts may restart the service for you. Check systemctl status to see the start time so you know whether that happened.
Major upgrades
A major upgrade changes the internal storage format, so you cannot just install new binaries over the old data directory. There are three approaches.
| Method | How it works | Downtime | Risk and cost |
|---|---|---|---|
| Dump and restore | Dump from the old version, restore into the new one | Long, grows with data size | Simplest and cleanest. Needs space for the dump and a full reload. |
| In-place upgrade | `pg_upgrade` for PostgreSQL, or starting the new MySQL binaries on the old data directory | Short, especially with `pg_upgrade --link` | Needs a good backup. With `--link`, the old cluster cannot be started again after the new one runs. |
| Logical replication or replica promotion | Build the new version alongside, sync it, switch clients | Seconds to minutes | Most setup effort and the most moving parts. |
PostgreSQL with pg_upgrade
On Debian and Ubuntu, several major versions can be installed side by side, each as its own cluster. The postgresql-common tools manage them:
sudo apt install postgresql-16
pg_lsclusters
sudo pg_upgradecluster 15 main
pg_lsclusterspg_upgradecluster creates a new cluster with the new version, upgrades the data, and leaves the old cluster in place but stopped. After you have tested the application against the new version, drop the old cluster:
sudo pg_dropcluster 15 mainAfter any pg_upgrade, planner statistics are not carried over. Run ANALYZE on every database, for example with vacuumdb --all --analyze-in-stages, or queries will be slow until autovacuum catches up. Also check that extensions are installed for the new version, because each major version needs its own extension packages.
MySQL major upgrades
MySQL supports in-place upgrades between adjacent release series, such as 8.0 to 8.4. Moving across more than one series, or from 5.7, needs stepwise upgrades. Before you start:
- Run the upgrade checker from MySQL Shell:
util.checkForServerUpgrade(). It reports removed features, changed defaults, and invalid data. - Read the release notes for changed default values and removed options. A configuration file that contains a removed option can stop the server from starting.
- Take a backup with
mysqldumpand, if possible, a copy of the stopped data directory.
Recent MySQL versions upgrade the data dictionary and system tables automatically at first start of the new binaries. Watch the error log during that first start.
Rehearse, then run
Never test a major upgrade for the first time on production. Restore your latest backup onto a spare host, run the upgrade there, and time it. This also gives you an honest downtime estimate and tests your restore procedure at the same time. Then run your application's test suite against the upgraded copy.
Rollback planning
Decide before you start how you will go back if the upgrade fails. The options differ by method:
- Dump and restore leaves the old server untouched, so rollback means pointing clients back at it.
- In-place upgrades with copied data keep the old directory, so you can start the old binaries on it.
- In-place upgrades with
pg_upgrade --linkcannot go back once the new cluster has started. Your rollback is the backup, so make sure you have restored it successfully at least once.
Writes made after the cutover exist only in the new version. If you roll back later, you lose them unless you carry them across. That is a reason to make the decision quickly, in the first minutes after the upgrade, while the data is still the same.
Support lifecycle
Each major version has an end-of-life date after which it gets no fixes. PostgreSQL supports each major version for five years. MySQL publishes its own support policy for each release series. Put the end-of-life dates for your versions in a calendar, and plan the next major upgrade a few months before the date, not after it.
Common mistakes
- Turning autovacuum off to save load. Bloat and wraparound risk follow.
- Upgrading packages without restarting, then assuming the new version is running.
- Skipping the backup because the upgrade "only changes binaries".
- Running
pg_upgrade --linkwithout a tested restore. - Forgetting to run
ANALYZEafter a PostgreSQL major upgrade. - Deleting MySQL binary logs with
rm. - Starting a MySQL upgrade with a configuration file that holds options the new version removed.
Exercise
After a package upgrade, apt reports that PostgreSQL 16.4 is installed, but SELECT version(); still shows 16.3. What most likely explains this, and how do you fix it?
Show answer
The package files were replaced, but the running server process was started before the upgrade and still uses the old binaries. Restart the service (sudo systemctl restart postgresql) in a planned window, then run SELECT version(); again to confirm 16.4.
Exercise
A PostgreSQL table has 40 million dead tuples and a last_autovacuum value from three weeks ago. Name two likely causes and one way to investigate.
Show answer
Likely causes include a long-running or idle-in-transaction session that stops vacuum from removing old row versions, and autovacuum settings that are too lax for how fast the table changes. To investigate, query pg_stat_activity for old xact_start values and for sessions in the idle in transaction state.
Exercise
You plan a major PostgreSQL upgrade with pg_upgrade --link. Why is the rehearsal and a tested restore especially important for this method?
Show answer
Hard links share data files between the old and new clusters. Once the new cluster has started, the old cluster cannot be used again, so the backup is your only rollback. A rehearsal on a spare host verifies the procedure, gives a real downtime estimate, and shows that the backup restores correctly.