Skip to content

How to Back Up PostgreSQL with pg_basebackup

Take a physical base backup of a running PostgreSQL cluster with pg_basebackup, stream the WAL so it is restorable, and recover from it — with a note on point-in-time recovery and where pg_dump fits instead.

pg_basebackup takes a physical, block-level copy of a running PostgreSQL cluster — the actual files under the data directory — and, with the right flags, streams the write-ahead log (WAL) generated during the copy so the result is internally consistent and restorable on its own. You restore it by stopping PostgreSQL, replacing the data directory with the extracted copy, and letting the server replay WAL until it reaches a consistent point. This is the fast path for whole-cluster recovery and the foundation for point-in-time recovery (PITR). It is the opposite trade-off from pg_dump, which produces a logical, SQL-level export you can restore one table at a time.

What you’ll accomplish

  • Create a replication-capable role and open the server to a base backup over the network.
  • Produce a compressed, self-contained base backup with pg_basebackup -Ft -z -Xs, including the WAL needed to reach consistency.
  • Verify the backup set on disk before you trust it.
  • Restore the whole cluster onto a clean data directory and confirm the server comes back read-write.
  • Know when to reach for pg_dump, pg_upgrade, or a fleet tool like pgBackRest instead.

Prerequisites

  • PostgreSQL 15 or 16 on both the source and the restore host, at the same major version. Physical backups are byte-format-specific and are not portable across major versions.
  • A role with the REPLICATION attribute. pg_basebackup connects through the replication protocol, not an ordinary SQL session.
  • wal_level set to replica or higher (the default on 15/16 is replica, so usually nothing to change).
  • max_wal_senders greater than 0. The default is 10, which is enough. -Xs uses one sender for the base copy and a second concurrent sender to stream WAL, so budget at least two.
  • A replication entry in pg_hba.conf that matches the backup client’s address and role.
  • Disk space on the backup target of roughly the size of the live data directory. With -z (gzip) expect the compressed set to land somewhere between a quarter and a half of that, depending on how compressible your data is. Leave headroom for the WAL stream.

How it works

A logical backup (pg_dump) reconstructs your data as SQL: CREATE TABLE, COPY, index definitions. It is portable across architectures and major versions, and you can restore a single table — but it re-runs everything on restore, which is slow for large clusters, and it captures a snapshot as of one moment with no way to roll forward.

A physical backup (pg_basebackup) copies the files instead. Restore is just “put the files back and start,” so recovery time tracks how fast you can move bytes, not how fast the server can re-execute SQL. The catch is that a running cluster’s files are a moving target: pages change while you copy them. PostgreSQL solves this with WAL.

When pg_basebackup starts, it asks the server for a checkpoint and records the starting position in a small file called backup_label. It then copies every data file. Any page that changed mid-copy is repaired during restore by replaying the WAL records written between the start checkpoint and the end of the backup. That is why the WAL matters: without it, the file copy is inconsistent and will not start. The -Xs (--wal-method=stream) flag opens a second connection and streams that WAL into the backup as it is produced, so the finished set contains everything needed to reach a consistent state with no dependency on the source server afterward.

Point-in-time recovery builds on the same mechanism. If you also archive WAL continuously (via archive_command), you can restore a base backup and then replay archived WAL forward to any moment — for example, to the instant before a bad DELETE. The base backup is the floor; the WAL archive is how far forward you can climb.

pg_basebackup physical backup and restore with WAL replay

Step-by-step

1. Create a replication role. Connect as a superuser and create a dedicated login with the REPLICATION attribute. Keep it separate from your application roles.

CREATE ROLE repl WITH REPLICATION LOGIN PASSWORD 'change-this-secret';

Expected output:

CREATE ROLE

2. Confirm the WAL settings. These are defaults on 15/16, but confirm rather than assume.

SHOW wal_level;
SHOW max_wal_senders;

Expected output:

 wal_level
-----------
 replica
(1 row)

 max_wal_senders
-----------------
 10
(1 row)

If wal_level is minimal, set wal_level = replica in postgresql.conf and restart. If max_wal_senders is 0, raise it to 10 and restart.

3. Add a replication line to pg_hba.conf. The literal keyword replication in the database column is required — a normal database name will not match a replication connection. Add a line scoped to the backup client’s subnet:

# TYPE  DATABASE        USER   ADDRESS         METHOD
host    replication     repl   10.0.0.0/24     scram-sha-256

Reload so it takes effect without a restart:

SELECT pg_reload_conf();

Expected output:

 pg_reload_conf
----------------
 t
(1 row)

4. Run the base backup. From the backup host, stream a compressed tar-format backup and request a fast checkpoint so the copy starts immediately instead of waiting for the next scheduled checkpoint.

pg_basebackup -h db01.internal -U repl -D /backup/base -Ft -z -Xs -P -c fast

The flags: -Ft writes tar format, -z gzip-compresses it, -Xs streams WAL alongside the copy, -P shows progress, and -c fast forces an immediate checkpoint. Expected output ends with a completed progress line:

Password:
1048576/1048576 kB (100%), 1/1 tablespace

5. Verify the backup contents. A backup you have not inspected is a guess. List the target directory:

ls -lh /backup/base

Expected output — a base tarball, a WAL tarball, and a manifest:

-rw------- 1 postgres postgres  412M base.tar.gz
-rw------- 1 postgres postgres   17M pg_wal.tar.gz
-rw------- 1 postgres postgres  190K backup_manifest

Confirm the backup_label is inside the base tarball — it carries the start checkpoint the restore needs:

tar -tzf /backup/base/base.tar.gz | grep backup_label

Expected output:

backup_label

6. Stop PostgreSQL and set aside the old data directory. On the restore host, stop the server first — never extract over a running cluster.

sudo systemctl stop postgresql
sudo mv /var/lib/postgresql/16/main /var/lib/postgresql/16/main.old
sudo -u postgres mkdir -p /var/lib/postgresql/16/main
sudo chmod 700 /var/lib/postgresql/16/main

These commands print nothing on success; systemctl stop returns to the prompt once the server has fully stopped.

The 0700 permission and postgres ownership matter: PostgreSQL refuses to start on a data directory with looser permissions.

7. Extract the base and WAL. Unpack the base tarball into the empty data directory, then the WAL tarball into pg_wal:

sudo -u postgres tar -xzf /backup/base/base.tar.gz -C /var/lib/postgresql/16/main
sudo -u postgres tar -xzf /backup/base/pg_wal.tar.gz -C /var/lib/postgresql/16/main/pg_wal

Both tar commands print nothing on success. Because -Xs captured the WAL up to the end of the backup, the streamed segments in pg_wal are enough to reach a consistent state on the next start. For point-in-time recovery — replaying beyond the backup to a chosen moment — create a recovery.signal file and point PostgreSQL at your WAL archive in postgresql.auto.conf:

sudo -u postgres touch /var/lib/postgresql/16/main/recovery.signal
# postgresql.auto.conf, only for PITR beyond the base backup
restore_command = 'cp /wal_archive/%f %p'
recovery_target_time = '2026-07-20 14:20:00'
recovery_target_action = 'promote'

8. Start the server and watch recovery. Bring PostgreSQL up and tail the log:

sudo systemctl start postgresql
sudo tail -f /var/log/postgresql/postgresql-16-main.log

Expected output shows WAL replay reaching consistency and the server opening:

LOG:  starting archive recovery
LOG:  redo starts at 0/9000028
LOG:  consistent recovery state reached at 0/9000A18
LOG:  database system is ready to accept connections

Validate it works

First, confirm the server has left recovery and is read-write:

SELECT pg_is_in_recovery();

Expected output after a plain restore (or after a PITR target with recovery_target_action = 'promote'):

 pg_is_in_recovery
-------------------
 f
(1 row)

Then confirm your data is actually there — count rows on a table you know:

SELECT count(*) FROM orders;

Expected output — a non-zero count matching what the source held:

 count
-------
 15432
(1 row)

Finally, check that PostgreSQL finished recovery cleanly. Once recovery completes, it renames backup_label to backup_label.old; the presence of that file and the absence of recovery.signal is your signal the cluster is a normal primary again:

ls /var/lib/postgresql/16/main/backup_label.old

Expected output — the file exists, so ls echoes the path rather than erroring:

/var/lib/postgresql/16/main/backup_label.old

Once you have confirmed the data, remove main.old to reclaim the disk.

Troubleshooting

FATAL: no pg_hba.conf entry for replication connection. The client reached the server, but no pg_hba.conf line matched a replication connection from that address and role. A line with a database name (even one matching your database) does not count — the database column must be the literal keyword replication. Add the line from step 3 and reload.

could not connect to server or password authentication failed. Either the host or port is wrong, or the role lacks the REPLICATION attribute, or the password is wrong. Confirm with ALTER ROLE repl WITH REPLICATION; and re-check the address in your pg_hba.conf line.

FATAL: number of requested standby connections exceeds max_wal_senders. -Xs needs a WAL sender in addition to the one doing the base copy, and other replicas may already be using senders. Raise max_wal_senders in postgresql.conf and restart, then retry.

requested WAL segment ... has already been removed. This happens when you run without -Xs and the server recycles a WAL segment before the backup finishes. The fix is to use -Xs (or -Xf to fetch at the end), which is why the command above includes it. If you must run without it, raise wal_keep_size first.

data directory "..." has invalid permissions or files owned by root. The restored data directory must be mode 0700 and owned by the postgres OS user. Extracting the tarballs as root leaves root-owned files. Extract as postgres (with sudo -u postgres) or chown -R postgres:postgres afterward, and chmod 700 the directory.

Server will not start after restore, complaining about version. A physical backup only restores into the same PostgreSQL major version it came from. A 15 backup cannot start on a 16 server. Match the major version, or move to a logical path — see the next section.

When this is the wrong approach

Physical backups are the right tool for whole-cluster recovery and PITR, but not for everything.

  • You need one table back, not the whole cluster. pg_basebackup restores the entire cluster or nothing. For a single table or schema, a logical dump — pg_dump -t orders — is the surgical option. See our note on what daily backups and WAL archiving actually protect for how these fit together.
  • You are moving across major versions. A physical backup will not start on a newer major version. Use pg_dump/pg_restore or pg_upgrade for that migration.
  • You are on managed Postgres (RDS, Cloud SQL, a PaaS). You usually cannot reach the data directory or run pg_basebackup against it. Use the provider’s snapshot and PITR features, which wrap the same underlying mechanism.
  • You are backing up a fleet, or need retention, incremental backups, and verification. Hand-rolled pg_basebackup gets unwieldy across many servers. pgBackRest or Barman handle scheduling, incrementals, parallelism, and retention on top of the same physical-backup foundation. Keeping the database healthy in the first place — see VACUUM and autovacuum — is a separate but related discipline.

For the exact flag reference, see the official pg_basebackup documentation; for the WAL archiving and PITR mechanics behind the note above, see Continuous Archiving and Point-in-Time Recovery.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.