Sub topic 9
Taking a physical base backup
A physical base backup copies the files of the whole PostgreSQL cluster, not the rows of one database. This chapter shows how to take one with pg_basebackup, what the options mean, and which mistakes make a backup unusable. It assumes you know what a data directory is, can use roles and psql, and have read the earlier chapters on logical versus physical backups and on pg_dump.
What a base backup is
A base backup is a copy of the cluster's data directory taken while the server keeps running. The server is writing to those files as you copy them, so the copy is inconsistent on its own. Some pages are old, some are new, and a table file can be copied at a different moment than its index.
PostgreSQL makes the copy usable with write-ahead log (WAL). WAL is the sequential record of every change. During a base backup the server forces a checkpoint, records where WAL replay must start, and keeps all WAL generated during the copy. On restore, PostgreSQL replays that WAL, which repairs the inconsistent pages. A base backup is therefore only valid together with the WAL written between its start and its end.
pg_basebackup handles this for you. It connects over the replication protocol, copies the files, and can fetch the required WAL in the same step.
Prerequisites on the server
Three things must be in place before the command works.
- A role with the REPLICATION attribute. The role must be allowed to start a replication connection.
- A
pg_hba.confentry for replication. The special database namereplicationinpg_hba.confmatches replication connections. A rule foralldoes not match it. - Enough WAL senders.
max_wal_sendersmust be at least 2 if you stream WAL with-Xs, because the file copy and the WAL stream each use a connection. The default is 10 in current releases, so this is usually already satisfied.
wal_level must be replica or higher. This is the default in current releases.
Create the role and the access rule:
CREATE ROLE replicator WITH LOGIN REPLICATION PASSWORD 'change-me';# pg_hba.conf
# TYPE DATABASE USER ADDRESS METHOD
host replication replicator 127.0.0.1/32 scram-sha-256Reload the configuration after editing pg_hba.conf:
SELECT pg_reload_conf();A role with only REPLICATION can read every file in the cluster through the replication protocol. Treat its password like a superuser password. Use a ~/.pgpass file or the PGPASSWORD environment variable for unattended runs, never a password on the command line.
Running pg_basebackup
This is the command from the plan, as one complete example:
pg_basebackup -h localhost -U replicator -D /backups/base -Ft -z -Xs -PEach option does one job.
| Option | Meaning |
|---|---|
| `-h localhost -U replicator` | Server host and the replication role. |
| `-D /backups/base` | Target directory. It must be empty or not exist yet. |
| `-Ft` | Tar format. Writes `base.tar` and `pg_wal.tar` instead of a copy of the directory tree. |
| `-z` | Compress the tar files with gzip. |
| `-Xs` | Include WAL by streaming it over a second connection while the copy runs. |
| `-P` | Show progress. |
The result in /backups/base is base.tar.gz, pg_wal.tar.gz, and one tar file for each extra tablespace. The tablespace files are named by OID, for example 16401.tar.gz.
Choosing the WAL method
The -X option controls how the WAL needed for consistency gets into the backup.
| Value | Behavior | Risk |
|---|---|---|
| `-Xs` (`stream`) | Streams WAL over a second connection during the copy. | Needs one more WAL sender. Safe default. |
| `-Xf` (`fetch`) | Collects WAL at the end of the backup. | Fails if the server recycles needed WAL segments during a long backup. |
| `-Xn` (`none`) | Includes no WAL. | The backup is only usable if you have a WAL archive that covers the backup period. |
Use -Xs unless you have a reason not to. With -Xn, the backup depends entirely on the WAL archive, which is covered in the next chapter.
Plain format versus tar format
-Fp (the default) writes an exact copy of the directory tree. You can start a server directly from it. It is convenient for building a standby or doing a quick restore, but it is larger because it cannot be compressed by pg_basebackup itself, and tablespaces are copied to their original paths unless you remap them with --tablespace-mapping.
-Ft produces tar files. They are easier to move, compress, and store, and tablespaces do not collide with paths on the machine where you store the backup. You unpack them before use.
Verifying and the backup manifest
Since PostgreSQL 13, pg_basebackup writes a backup_manifest file. It lists every file with its size and checksum. The pg_verifybackup tool uses it to check that nothing is missing or altered.
pg_verifybackup works on plain-format backups, and from PostgreSQL 18 on tar-format backups too. For tar backups on older versions, unpack first:
mkdir -p /tmp/verify
tar -xzf /backups/base/base.tar.gz -C /tmp/verify
tar -xzf /backups/base/pg_wal.tar.gz -C /tmp/verify/pg_wal
cp /backups/base/backup_manifest /tmp/verify/
pg_verifybackup /tmp/verifyVerification confirms the files match what was copied. It does not prove the database starts. Only a test restore proves that, which a later chapter covers.
If the data directory has data checksums enabled (initdb --data-checksums), pg_basebackup also checks page checksums while copying and reports errors. Use --no-verify-checksums only if you deliberately want to skip that.
Restoring a base backup
Restoring a tar backup into a new data directory looks like this:
mkdir -p /var/lib/postgresql/restore
chmod 700 /var/lib/postgresql/restore
tar -xzf /backups/base/base.tar.gz -C /var/lib/postgresql/restore
mkdir -p /var/lib/postgresql/restore/pg_wal
tar -xzf /backups/base/pg_wal.tar.gz -C /var/lib/postgresql/restore/pg_wal
pg_ctl -D /var/lib/postgresql/restore startThe data directory must be owned by the user that runs PostgreSQL, and its mode must be 0700 or 0750. PostgreSQL refuses to start otherwise. On start, the server finds backup_label, replays the WAL included in the backup, and opens for writes once it reaches a consistent state. The restored cluster is a copy as of the end of the backup. To go to a later moment, or a specific one, you need archived WAL, which later chapters in this tutorial cover.
Two things are easy to miss:
- Restore as the same major version. A physical backup cannot be loaded into a different major version, and it needs a compatible CPU architecture and operating system family.
- The restore includes everything: all databases, roles, and configuration files that live inside the data directory. If your
postgresql.conforpg_hba.conflives elsewhere (common on Debian and Ubuntu under/etc/postgresql), the base backup does not contain them. Back those up separately.
Gotchas and failure modes
- Target directory not empty.
pg_basebackuprefuses to write into a non-empty directory. This protects you from overwriting a backup. Use a dated directory name for each run. - Replication connection rejected. The error
no pg_hba.conf entry for replication connectionmeans thereplicationkeyword rule is missing, or the reload was not done. - Interrupted backup. A failed run leaves a partial directory. Delete it and start over. A partial backup is never usable.
- Backup too slow or too heavy. The copy reads the whole cluster and competes with normal traffic for disk and network.
--max-rate=50Mlimits the transfer speed. By defaultpg_basebackupasks for a fast checkpoint only if you pass--checkpoint=fast. The default spreads the checkpoint over time, so the start of a backup can wait for minutes on a quiet, large-checkpoint_timeoutserver. Use--checkpoint=fastfor interactive runs. - Unlogged tables. Their contents are not restored. They are reset to empty on recovery, same as after a crash.
- Size grows with the cluster. A base backup copies everything, including bloat in tables and indexes. It is not smaller than the data directory, apart from compression.
- No partial restore. You cannot restore a single table or database from a base backup into a running cluster. For that, use a logical dump, or restore the whole backup elsewhere and extract the data.
Where base backups fit
A base backup alone gives you a recovery point equal to the end of the backup. If you take one nightly, you can lose up to a day of changes. Its real value is as the starting point for point-in-time recovery: restore the base backup, then replay archived WAL up to the moment you want. The next chapter sets up that archive.
For a first working routine, take a base backup with -Ft -z -Xs, run pg_verifybackup or a test restore on it, and store it on a different machine from the database.
Exercise
You run pg_basebackup -D /backups/base -Ft -Xn on a server with no WAL archiving. Why is the resulting backup likely unusable, and which option would fix it with the least change?
Show answer
-Xn leaves WAL out of the backup, and no archive supplies it, so PostgreSQL cannot replay the changes made during the copy and cannot reach a consistent state. Changing -Xn to -Xs streams the needed WAL into the backup, which makes it self-contained.
Exercise
pg_basebackup fails with "no pg_hba.conf entry for replication connection from host 127.0.0.1, user replicator". The file already has host all replicator 127.0.0.1/32 scram-sha-256. What is wrong, and what do you do after fixing it?
Show answer
The database column all does not match replication connections. Add a line with the database name replication, for example host replication replicator 127.0.0.1/32 scram-sha-256. Then reload the configuration with SELECT pg_reload_conf(); and run the backup again.