Sub topic 4
Cloning the primary with pg_basebackup
This chapter assumes you have already prepared the primary. That means wal_level = replica, enough max_wal_senders, a replication line in pg_hba.conf, and a role with the REPLICATION attribute. It also assumes you can start and stop a PostgreSQL server as the postgres OS user and read a shell command with flags.
Why a standby starts from a copy
A standby replays WAL, so it needs a starting point that WAL can be applied to. That starting point is a physical copy of the primary's data directory, called a base backup. The standby then replays every WAL record generated after the backup began and keeps following the primary.
You could copy the files with rsync between pg_backup_start() and pg_backup_stop(). pg_basebackup does this correctly for you over an ordinary replication connection. It needs no shell access to the primary and no file-system snapshot.
What happens during a base backup
The files in a running cluster change while they are being copied, so the copy is internally inconsistent. The WAL generated during the copy fixes this. When the standby replays that WAL, the pages become consistent. That is why the backup must include, or be able to obtain, all WAL from the backup's start to its end.
The steps are:
- The client connects with the replication protocol, using the
replicationpseudo-database entry inpg_hba.conf. - With
-C -S, the primary creates the named slot first. The slot holds WAL from that point on, so none of it can be recycled before the standby needs it. - The primary runs a checkpoint. The default is a spread checkpoint, which can take minutes on a busy server.
-c fastforces an immediate one. - The primary records the starting point in
backup_labeland streams the data directory. - With
-X stream, the client opens a second connection and receives WAL while the files copy. This uses a second walsender. - When the files are done, the primary finishes the backup, and the client receives the remaining WAL.
The command
pg_basebackup -h primary.example.com -U replicator \
-D /var/lib/postgresql/data -X stream -R -C -S standby1 -PRun it on the standby host, as the OS user that will own the standby's server process. If you run it as root, the files will be owned by root and the server will refuse to start.
Prepare the target directory first. It must be empty or not exist yet. It also needs restrictive permissions: 0700, or 0750 if the cluster was initialized with group access.
sudo install -d -o postgres -g postgres -m 0700 /var/lib/postgresql/data
sudo -u postgres pg_basebackup -h primary.example.com -U replicator \
-D /var/lib/postgresql/data -X stream -R -C -S standby1 -PIf the server is Debian's packaged service, stop and empty its default cluster directory before you do this. Never point -D at a directory that holds data you want to keep.
Options in this command
| Option | Meaning |
|---|---|
| `-h`, `-U` | Host and role for the replication connection. The role needs `REPLICATION` and `LOGIN`. |
| `-D` | Target directory. It must be empty. |
| `-X stream` | Stream WAL over a second connection while the backup runs. |
| `-R` | Write `standby.signal` and add connection settings to `postgresql.auto.conf`. |
| `-C -S standby1` | Create the physical slot `standby1` and use it. The command fails if the slot already exists. |
| `-P` | Show progress. |
Other options you will meet in practice:
-c faststarts the backup after an immediate checkpoint instead of waiting for a spread one.-r 50Mlimits transfer rate, which protects the primary's network and disk on a busy system.-T /old/ts=/new/tsremaps a tablespace directory. This matters because a plain-format backup restores tablespaces to their original absolute paths unless you remap them.--waldir=/fast/walplacespg_walon a separate volume on the standby.-F t -zwrites compressed tar files instead of a ready-to-run directory. You then unpack them yourself, so this suits archival backups better than a quick standby build.
WAL methods
The -X option decides how the backup gets its WAL.
| Method | Behavior | Risk |
|---|---|---|
| `stream` | A second connection receives WAL during the backup. | Needs two walsender slots. |
| `fetch` | WAL files are collected after the data files are copied. | Fails if the primary recycles the WAL before the fetch. |
| `none` | No WAL is included. | You must supply the WAL some other way, such as an archive. |
stream is the right default. Without -S, -X stream uses a temporary slot for the length of the backup (PostgreSQL 10 and later), so the primary keeps the WAL the backup needs. --no-slot turns that off.
What -R writes
With -R, pg_basebackup does two things in the target directory:
- It creates an empty
standby.signalfile. At startup, its presence makes the server enter standby mode and recover continuously instead of ending recovery. - It appends
primary_conninfotopostgresql.auto.conf. When you also pass-S, it addsprimary_slot_name.
Inspect the result before starting the server:
ls /var/lib/postgresql/data/standby.signal
cat /var/lib/postgresql/data/postgresql.auto.confThe generated primary_conninfo contains the host, user and port. It also includes the password if you supplied one on the command line or through PGPASSWORD. Use a .pgpass file for the postgres user on the standby instead, and remove the password from the setting. That keeps credentials out of a file that can be read from configuration views.
The next chapter covers the settings you still add yourself, such as hot_standby and application_name.
Files that are and are not copied
pg_basebackup copies the cluster's data directory, including pg_wal contents needed for recovery. It skips temporary files, pg_replslot contents, and postmaster.pid, among others. It does not copy slot state, so the slot you created with -C exists only on the primary.
Configuration files that live inside the data directory, such as postgresql.conf and pg_hba.conf, are copied. That means the standby starts with the primary's settings. If your distribution keeps configuration under /etc/postgresql, those files are not copied and you must provide them on the standby. Check settings that must differ, such as listen_addresses, file paths, and max_connections. For hot standby, max_connections, max_worker_processes, max_wal_senders and max_prepared_transactions must be at least as large on the standby as on the primary, or the standby refuses to start.
Verifying the backup
On PostgreSQL 13 and later, pg_basebackup writes a backup_manifest file with checksums. For a plain-format backup you can check it:
pg_verifybackup /var/lib/postgresql/dataThis confirms that every file is present and unmodified and that the WAL needed to reach consistency exists. Run it before you start the standby, since it reads the directory without starting a server.
Afterwards, check on the primary that the slot exists:
SELECT slot_name, active, restart_lsn
FROM pg_replication_slots
WHERE slot_name = 'standby1';Right after the backup finishes, active is false. The slot retains WAL from restart_lsn onward until the standby connects. If you leave the standby unstarted for days, the primary's pg_wal directory keeps growing. The slots chapter covers this risk in detail.
Common errors
| Message or symptom | Cause and fix |
|---|---|
| `directory "..." exists but is not empty` | Target is not empty. Move or delete the old data, deliberately. |
| `no pg_hba.conf entry for replication connection` | The `replication` line is missing or the address or auth method does not match. Reload after editing. |
| `number of requested standby connections exceeds max_wal_senders` | All walsender slots are used. Remember `-X stream` needs two. |
| `replication slot "standby1" already exists` | `-C` was used on a name that exists. Drop the slot, or omit `-C` and reuse it. |
| `password authentication failed` | Wrong password, or the stored password uses a different encryption than `scram-sha-256`. |
| Server will not start: `data directory has invalid permissions` | Fix with `chmod 700` and make sure `postgres` owns the files. |
| Backup seems stuck at the start | A spread checkpoint is in progress. Wait, or rerun with `-c fast`. |
Failed backups leave partial data in the target directory. pg_basebackup removes it on most errors, but check before retrying.
Exercise
You run pgbasebackup with -X stream -R -C -S standby1, and it fails with "number of requested standby connections exceeds maxwalsenders". Your primary has maxwal_senders = 2, and one existing standby is already connected. Why does it fail, and what do you change?
Show answer
One walsender is used by the existing standby. The backup needs two (one for the data files and one for the streamed WAL), so three are required in total and only one is free. Raise maxwalsenders on the primary to a higher value, such as 10, and restart the primary, since this setting only takes effect at server start. Alternatively, stop the existing standby for the duration of the backup, but raising the limit is the lasting fix.
Exercise
After a successful pgbasebackup, you query pgreplication_slots on the primary and see standby1 with active = false. Is something wrong, and what should you do next?
Show answer
Nothing is wrong. The slot was created by -C and no standby has connected yet, so it is inactive. It already retains WAL from its restartlsn, so start the standby soon, after checking postgresql.auto.conf and any settings that must match the primary. If you decide not to use the standby, drop the slot with pgdropreplicationslot('standby1') so the primary does not accumulate WAL.