Introduction
PostgreSQL can protect a database with two complementary methods. Use pg_dump to capture a logical snapshot of one database, and enable WAL archiving to support recovery to a specific point in time after that snapshot was taken. A pg_dump file alone cannot perform point-in-time recovery because it contains exported SQL, not the database’s transaction history. WAL archiving fills that gap by preserving the write-ahead log files needed to replay committed changes after the dump.
The recovery procedure below follows a standard sequence:
- Create a tested
pg_dumpbackup. - Enable continuous WAL archiving on the PostgreSQL server.
- Protect the archive with retention and monitoring.
- Restore the dump into a clean target cluster.
- Supply the archived WAL files to the recovery target.
- Recover to a named timestamp or transaction.
- Validate the recovered database before making it available.
The examples use PostgreSQL 15 on Ubuntu 22.04 or Debian 12. PostgreSQL 16 and 17 use the same core workflow, but package paths, default service names, and some operational details can differ.
How PostgreSQL Physical Backup and Logical Dump Recovery Differ
pg_dump exports the contents and definitions of a selected database as SQL commands or another archive format. It does not copy the physical data directory, server configuration, roles stored in the cluster-wide catalogs, or the full WAL sequence. It also cannot guarantee a transactionally consistent view across multiple databases in the same cluster.
A base backup, usually taken with pg_basebackup, copies the entire PostgreSQL data directory. That physical copy includes system catalogs and cluster-wide state, and it can participate in point-in-time recovery when the required WAL remains available. If the requirement includes database roles, tablespaces, replication settings, or recovery of the whole cluster, a physical base backup is usually the better foundation.
A logical dump remains useful for schema migrations, transferring a database to another PostgreSQL major version, selective exports, and staging environments. A common production design uses both approaches: physical base backups for fast disaster recovery and pg_dump for portable logical exports. This article focuses on a specific and workable combination: a pg_dump backup restored into a clean cluster, followed by WAL replay through the dump’s consistency point.
That approach has one important limitation. A dump does not preserve the WAL’s physical state, so the target server must be initialized with settings compatible with the source server. The clean target cluster can replay archived WAL files generated by the source cluster, provided the archive contains the required history and the recovery configuration has the correct system identifier and checkpoint metadata.
Prerequisites and Planning the Backup and Recovery Layout
Run the examples as the postgres operating-system user, or use sudo -u postgres before each command. PostgreSQL configuration files usually require administrative access, while database objects may require additional roles or ownership.
Create a working directory for the local backup and another directory for the WAL archive:
sudo -u postgres mkdir -p /var/lib/postgresql/backups/appsudo -u postgres mkdir -p /var/lib/postgresql/archivesudo -u postgres mkdir -p /var/lib/postgresql/restoreA production archive should usually live on a different storage system or object-storage service from the PostgreSQL data directory. Copying WAL files only to the same failed disk provides little protection. The example uses a local directory because it is easy to reproduce. For production, mount durable storage at /var/lib/postgresql/archive or replace the command with tools such as rclone, restic, or a backup agent that copies files to remote storage.
Verify disk capacity and existing backup schedules before proceeding:
df -h /var/lib/postgresql /var/lib/postgresql/archivesudo -u postgres psql -c "SELECT version();"sudo -u postgres psql -Atc "SHOW archive_mode;"sudo -u postgres psql -Atc "SHOW archive_command;"Do not assume that the archive contains a usable recovery chain. PostgreSQL requests each completed WAL segment through archive_command, and a recovery target can fail later if an older segment was deleted, uploaded incompletely, or overwritten. Monitor archive status and test restoration on a separate host.
Creating a Consistent pg_dump Backup
Use PostgreSQL’s custom archive format for a normal backup. It compresses the output by default, supports parallel restoration, and allows selective extraction. The custom format is not the same as a directory-format archive, and it must be created with pg_dump, not tar.
The following command exports the app database as the postgres user:
sudo -u postgres pg_dump \ --format=custom \ --compress=6 \ --file=/var/lib/postgresql/backups/app/app_20261121.dump \ appThe filename is an operator convention. PostgreSQL does not automatically place a timestamp or consistency marker inside a custom-format dump. Keep the filename and the recovery metadata together so the corresponding WAL range can be identified.
For a backup that may take a long time, use the snapshot API and record the snapshot identifier:
sudo -u postgres bash -c ' export PGDATABASE=app snapshot=$(pg_dump --snapshot=backup_snapshot --format=custom \ --file=/var/lib/postgresql/backups/app/app_20261121.dump app)'That command is not a complete snapshot workflow unless a snapshot has first been exported and remains valid for the dump. A practical snapshot procedure is:
sudo -u postgres psql -d postgres -Atc \ "SELECT pg_export_snapshot();" > /var/lib/postgresql/backups/app/snapshot.txt
sudo -u postgres pg_dump \ --snapshot="$(cat /var/lib/postgresql/backups/app/snapshot.txt)" \ --format=custom \ --file=/var/lib/postgresql/backups/app/app_20261121.dump \ app
sudo -u postgres psql -d postgres -Atc \ "SELECT pg_release_snapshot('$(cat /var/lib/postgresql/backups/app/snapshot.txt)');"The snapshot must be taken while the exporting session remains open. In production, use a wrapper that retains the snapshot session until pg_dump exits. A simpler alternative is to create the dump and independently record the dump’s start and end timestamps, then select a recovery target after the dump has completed. That works for many recovery exercises, but the snapshot method gives operators a more precise consistency boundary.
Check the dump before relying on it:
sudo -u postgres pg_restore \ --list \ /var/lib/postgresql/backups/app/app_20261121.dump \ > /var/lib/postgresql/backups/app/app_20261121.list
test -s /var/lib/postgresql/backups/app/app_20261121.dumptest -s /var/lib/postgresql/backups/app/app_20261121.listA successful pg_dump exit code is necessary but not sufficient. The stronger check is a test restore. Test restores detect missing extensions, permission problems, invalid objects, and archive gaps before an incident occurs.
Enabling WAL Archiving
WAL archiving requires wal_level to be at least replica, archive_mode to be enabled, and archive_command to copy completed segments into the archive. These settings require a server restart.
Locate the active configuration file and confirm the current settings:
sudo -u postgres psql -Atc "SHOW config_file;"sudo -u postgres psql -Atc "SHOW data_directory;"For a Debian or Ubuntu package installation, the main file is usually /etc/postgresql/15/main/postgresql.conf. A typical configuration is:
wal_level = replicaarchive_mode = onarchive_command = 'test ! -f /var/lib/postgresql/archive/%f && cp "%p" "/var/lib/postgresql/archive/%f"'archive_timeout = 300The archive_command must not overwrite an existing segment. The test ! -f check prevents accidental replacement when PostgreSQL retries an archive operation. The %p placeholder expands to the path of the completed WAL segment, and %f expands to the segment filename.
Reload or restart the server according to the changed parameters:
sudo systemctl restart postgresql@15-mainsudo systemctl status postgresql@15-main --no-pagerOn systems that do not use the Debian service naming convention, use:
sudo systemctl restart postgresqlsudo systemctl status postgresql --no-pagerConfirm that archiving is active:
sudo -u postgres psql -Atc "SHOW archive_mode;"sudo -u postgres psql -Atc "SHOW archive_command;"sudo -u postgres psql -Atc "SHOW archive_status;"The archive_status view reports archived and failed files. A healthy archive may not appear immediately if the current segment has not been completed. To force a WAL segment switch for testing, run:
sudo -u postgres psql -c "SELECT pg_switch_wal();"Then check the archive directory:
ls -lh /var/lib/postgresql/archivesudo -u postgres psql -x -c "SELECT * FROM pg_stat_archiver;"The important fields are last_archived_wal, last_failed_wal, and failed_count. A nonzero failed_count means PostgreSQL has attempted an archive operation that failed. Investigate that condition before relying on the archive.
Choosing and Protecting the WAL Archive
The archive must begin early enough to include the dump’s consistency point and continue through the desired recovery timestamp. If archiving was enabled only after the dump, the dump may restore successfully without WAL replay, but the database cannot reach a later point in time.
A simple retention policy can use find on the archive directory:
sudo -u postgres find /var/lib/postgresql/archive \ -type f -name '0000000*' \ -mtime +14 -deleteDo not use an age-based deletion rule without understanding PostgreSQL’s retention and backup workflow. WAL segments are needed for:
- The start of the recovery sequence.
- Continuous replay from the base backup’s checkpoint.
- Recovery through the selected timestamp.
- The final shutdown checkpoint after recovery.
- Retention of a backup until its own expiry policy permits deletion.
For a controlled retention process, store the archive in timestamped directories, or use a backup tool that records the corresponding PostgreSQL backup and WAL dependencies. A production archive also needs monitoring. A minimal shell check can inspect the archive status and the last archived segment:
#!/usr/bin/env bashset -euo pipefail
failed_count=$(sudo -u postgres psql -Atc "SELECT failed_count FROM pg_stat_archiver;")last_archived=$(sudo -u postgres psql -Atc "SELECT last_archived_wal FROM pg_stat_archiver;")
if [[ "$failed_count" != "0" ]]; then echo "WAL archive failure count is ${failed_count}" >&2 exit 1fi
if [[ -z "$last_archived" || "$last_archived" == "-" ]]; then echo "No WAL segment has been archived" >&2 exit 1fi
echo "Last archived WAL segment: $last_archived"The check is useful as a starting point, but it does not verify that the file exists remotely, that it has the expected size, or that its checksum matches. Add those checks to the storage layer and alert on missing segments.
Recording a Target Time for Point-in-Time Recovery
A recovery target must be later than the dump’s consistency point. Choose a timestamp in UTC and record it with an ISO format that PostgreSQL can parse unambiguously:
TARGET_TIME="2026-11-21 09:45:00+00"printf '%s\n' "$TARGET_TIME" > /var/lib/postgresql/backups/app/recovery_target.txtThe target must refer to a time at which the desired data was committed. PostgreSQL’s recovery target is inclusive by default. If the target lands during a transaction, PostgreSQL follows the documented behavior for the chosen recovery target name and may stop at a transaction boundary.
For a precise logical target, identify a transaction that marks the last acceptable change:
SELECT txid_current();Run that query in the application session immediately before the unwanted change, or create a marker in a table that records the recovery boundary. The marker approach is easier to audit:
CREATE TABLE recovery_markers ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), label text NOT NULL);
INSERT INTO recovery_markers(label)VALUES ('last safe application state');Recover to the transaction ID associated with that marker only if you understand how transaction IDs are recorded and the target cluster contains the relevant transaction metadata. A timestamp target is often more practical for a pg_dump-based restore because it is easy to explain and document.
Preparing a Clean Target Cluster for Recovery
Do not restore a pg_dump archive over a live production cluster. Create an empty target cluster, stop it, and prepare it for recovery.
For a Debian or Ubuntu installation, create a separate cluster:
sudo pg_createcluster 15 recovery --port=5433 --start-conf=manualsudo systemctl stop postgresql@15-recoveryThe command creates a new data directory under the PostgreSQL package’s cluster structure. Confirm the path:
sudo -u postgres psql -p 5433 -Atc "SHOW data_directory;"Because the cluster is stopped, use the configuration files directly. The target’s postgresql.conf should contain settings compatible with the source server. At minimum, review:
wal_levelmax_wal_sizemax_wal_sendershot_standbymax_connectionsmax_worker_processesmax_parallel_workersmax_parallel_workers_per_gathermax_locks_per_transactionmax_pred_locks_per_transactionmax_replication_slotsmax_wal_sendersshared_bufferswork_memmaintenance_work_mem
The values do not all have to be identical for a basic logical restore, but the target must support the restored database’s catalog state and workload. PostgreSQL may refuse startup if a parameter required by the WAL replay differs from the value recorded in the source cluster. For a restored cluster that will become a primary, set archive_mode according to the new deployment’s requirements.
Remove the target cluster’s default database contents only after stopping it. The exact path depends on the installation. For a package-managed cluster, the data directory is commonly /var/lib/postgresql/15/recovery. Verify it before changing files:
sudo -u postgres /usr/lib/postgresql/15/bin/pg_controldata \ /var/lib/postgresql/15/recovery \ | grep -E 'Database cluster state|Latest checkpoint|system identifier'Do not delete the target directory by copying commands from another machine. Use pg_ctl or the cluster manager to stop the server, then confirm that the process is gone:
sudo -u postgres /usr/lib/postgresql/15/bin/pg_ctl \ -D /var/lib/postgresql/15/recovery statusRestoring the Logical Dump into the Target Cluster
The target cluster needs an empty database named app. Start it temporarily and create that database:
sudo pg_ctlcluster 15 recovery startsudo -u postgres createdb -p 5433 appsudo systemctl stop postgresql@15-recoveryIf createdb reports that the database already exists, verify that it is the new recovery cluster and contains no application data before proceeding. Do not restore into a database with unrelated objects.
Restore with pg_restore:
sudo -u postgres pg_restore \ --port=5433 \ --dbname=app \ --no-owner \ --no-privileges \ --exit-on-error \ /var/lib/postgresql/backups/app/app_20261121.dumpThe options have practical consequences:
--no-owneravoids trying to assign ownership to roles that may not exist on the target server.--no-privilegesskips restoring grants that reference unavailable roles.--exit-on-errorstops at the first failed command, which is appropriate for a controlled recovery test.
For a production target where object ownership must be preserved, create the required roles first and omit --no-owner. The dump may include extensions that are not installed on the target system. Install the matching extension packages before running pg_restore, or inspect the archive with:
sudo -u postgres pg_restore --list \ /var/lib/postgresql/backups/app/app_20261121.dump \ | grep 'EXTENSION'Restore logs should be retained:
sudo -u postgres pg_restore \ --port=5433 \ --dbname=app \ --no-owner \ --no-privileges \ --exit-on-error \ --verbose \ /var/lib/postgresql/backups/app/app_20261121.dump \ > /var/lib/postgresql/backups/app/restore.log 2>&1Review the exit status and the end of the log:
tail -n 40 /var/lib/postgresql/backups/app/restore.logA logical dump does not create the WAL history needed for PostgreSQL to replay the source cluster’s WAL into the restored database. This is why a dump-based restore requires particular care when pairing it with point-in-time recovery.
The Critical Limitation of Combining pg_dump with WAL Replay
A pg_dump backup is a logical export. It contains SQL statements and data for the selected database, but it does not contain the source cluster’s physical checkpoint, relation files, commit records, or system catalog pages. PostgreSQL’s WAL recovery machinery expects a physical base backup that is part of the same cluster history.
This means the simple procedure of restoring a pg_dump file and setting recovery_target_time does not automatically make the target cluster replay the source WAL correctly. The target’s WAL position and system identifier will not match the source cluster in the way required for physical WAL replay.
Some PostgreSQL features can make a dump-based recovery appear to work. For example, a target may replay its own WAL history, or a recovery configuration may select an unrelated local segment. The result is not a reliable restoration of the source cluster to the requested point in time.
For production point-in-time recovery, use a physical base backup:
sudo -u postgres pg_basebackup \ --pgdata=/var/lib/postgresql/backups/base/20261121 \ --format=pg_basebackup \ --wal-method=stream \ --checkpoint=fast \ --progress \ --verboseThen restore that base backup into a clean target and configure the archive and recovery target. The base backup contains the physical state required for WAL replay. The pg_dump can remain part of the recovery plan as a logical export or a fallback, but it should not be presented as the foundation of a reliable PITR workflow.
There is a special case in which pg_dump is used for a database-level restore and the source cluster’s WAL is later used to recover the same logical database. That operation requires advanced knowledge of PostgreSQL internals and careful control of system identifiers, timelines, checkpoint records, and relation state. It is not a routine production procedure and should not be used as a substitute for pg_basebackup.
Reliable Point-in-Time Recovery with pg_basebackup
Because the distinction matters operationally, the supported path for PITR begins with a physical base backup. Ensure archive_mode is active before the base backup begins, and record the backup label and the WAL start location.
Create the base backup directory with safe ownership:
sudo -u postgres mkdir -p /var/lib/postgresql/backups/basesudo -u postgres chmod 700 /var/lib/postgresql/backups/baseRun pg_basebackup with stream replication:
sudo -u postgres pg_basebackup \ --pgdata=/var/lib/postgresql/backups/base/20261121 \ --format=pg_basebackup \ --wal-method=stream \ --checkpoint=fast \ --progress \ --verboseThe backup includes a backup_label file unless the server or tooling removes it after the backup. Preserve that file. It contains the checkpoint location required to begin WAL recovery.
Prepare a new target data directory from the base backup:
sudo systemctl stop postgresql@15-mainsudo -u postgres cp -a \ /var/lib/postgresql/backups/base/20261121 \ /var/lib/postgresql/15/recoveryUse the exact target path created by your installation. Confirm it before copying. Then set ownership and permissions:
sudo chown -R postgres:postgres /var/lib/postgresql/15/recoverysudo chmod 700 /var/lib/postgresql/15/recoveryIf the source cluster has tablespaces, copy their contents and preserve the directory relationships. A base backup copied without its tablespace data is incomplete.
Create a recovery signal file and configure the target. A postgresql.auto.conf entry is useful for a one-off recovery:
sudo -u postgres tee -a /var/lib/postgresql/15/recovery/postgresql.auto.conf <<'EOF'restore_command = 'cp /var/lib/postgresql/archive/%f %p'recovery_target_time = '2026-11-21 09:45:00+00'recovery_target_action = 'pause'EOF
sudo -u postgres touch /var/lib/postgresql/15/recovery/recovery.signalrestore_command copies one requested WAL segment from the archive into the target’s pg_wal directory. The %f and %p placeholders are required. The command should fail when a segment is absent so PostgreSQL can continue waiting or report the missing segment according to the recovery state.
Start the target and inspect its logs:
sudo systemctl start postgresql@15-recoverysudo journalctl -u postgresql@15-recovery -n 100 --no-pagerThe log should show recovery progressing through WAL files. Check the recovery status:
sudo -u postgres psql -p 5433 -x -c \ "SELECT pg_is_in_recovery(), pg_last_wal_replay_lsn(), pg_last_xact_replay_timestamp();"While the server is in recovery, connect with psql to inspect the database. If recovery_target_action is pause, the server remains paused at the target until an operator changes the recovery state. This prevents writes while the restored state is inspected.
For a non-production test, use recovery_target_action = 'promote' after validation or configure a controlled promotion process. For a production disaster recovery, keep the target in recovery until the business owner confirms that the data is acceptable.
Verifying the Recovery Point
After recovery reaches the target, query the application tables and the recovery markers:
SELECT pg_is_in_recovery();
SELECT *FROM recovery_markersORDER BY created_at DESC;
SELECT now();Compare the result with the intended recovery boundary. Check that the unwanted transaction is absent and that expected data is present. Run application-level checks, row counts, and integrity checks appropriate to the workload.
PostgreSQL exposes recovery information through system functions and views. Inspect the log for messages such as:
recovery stopping after WAL location (LSN) ...recovery stopping before commit ...The exact wording depends on the recovery target and PostgreSQL version. If the server reaches the requested target, the next step is to promote it only after verification.
To promote a paused recovery target in a controlled test:
sudo -u postgres psql -p 5433 -c "SELECT pg_wal_replay_resume();"Promotion can be triggered by removing recovery.signal or using pg_ctl promote, depending on whether the server is paused or still replaying. Do not perform either action automatically in a script without checking the target and recording the promotion event.
Troubleshooting Missing WAL Segments
The most common recovery error is a missing archive segment. A typical log message is:
could not restore file "000000010000000000000005" from archiveThe message means PostgreSQL requested a WAL segment that the archive command could not provide. The causes include an archive that started too late, an archive_command copy error, an incorrect restore_command, deleted files, or a timeline mismatch.
Inspect the target’s recovery status and the source archive:
sudo -u postgres psql -p 5433 -x -c \ "SELECT * FROM pg_stat_progress_create_index;"sudo -u postgres psql -p 5433 -Atc \ "SELECT pg_last_wal_replay_lsn();"
ls -lh /var/lib/postgresql/archive | headCheck the source archive for the requested filename. If it exists, test the restore command manually:
sudo -u postgres cp \ /var/lib/postgresql/archive/000000010000000000000005 \ /tmp/000000010000000000000005
sudo -u postgres ls -lh /tmp/000000010000000000000005The manual copy proves that the archive path and permissions work, but PostgreSQL’s restore_command must copy from the archive into the target’s pg_wal directory using %p. Confirm the service account can read the archive:
sudo -u postgres test -r \ /var/lib/postgresql/archive/000000010000000000000005If the file is absent, recovery cannot proceed past that point. Restore the missing segment from another copy, or restart from a newer physical base backup whose WAL range is complete.
Troubleshooting Archive Failures
If pg_stat_archiver.failed_count increases, inspect the most recent failure and test the command with the same user and environment as the PostgreSQL service:
sudo -u postgres psql -x -c "SELECT * FROM pg_stat_archiver;"sudo -u postgres psql -x -c \ "SELECT * FROM pg_stat_archiver WHERE last_failed_wal IS NOT NULL;"The output does not provide the full shell error from every archive attempt, so inspect PostgreSQL logs:
sudo journalctl -u postgresql@15-main --since "30 minutes ago" --no-pagerA common error is:
archive command failedAnother common symptom is a file permission error:
could not open file "/var/lib/postgresql/archive/000000010000000000000005" for writing: Permission deniedFix ownership and permissions without making the archive directory world-writable:
sudo chown -R postgres:postgres /var/lib/postgresql/archivesudo chmod 700 /var/lib/postgresql/archiveIf the destination is mounted read-only, the archive command will fail with a filesystem error. Check the mount and free space:
findmnt /var/lib/postgresql/archivedf -h /var/lib/postgresql/archiveDo not use an archive command that returns success when the copy failed. The command’s exit status controls PostgreSQL’s retry behavior.
Troubleshooting pg_restore Errors
A common logical restore failure is:
pg_restore: error: could not execute query: ERROR: role "app_owner" does not existThe dump references a role that was not created on the target. Either create the required roles with the correct attributes or restore with --no-owner and --no-privileges for a test environment:
sudo -u postgres pg_restore \ --port=5433 \ --dbname=app \ --no-owner \ --no-privileges \ --exit-on-error \ /var/lib/postgresql/backups/app/app_20261121.dumpAnother common error is:
pg_restore: error: could not execute query: ERROR: extension "pg_stat_statements" is not availableThe extension package is missing on the target. Install the package for the target PostgreSQL version, create the extension, and retry the restore. Do not edit the dump blindly. If the extension is optional for the recovery test, restore selectively and document the omission.
For a dump made with a different major version, PostgreSQL normally requires upgrading the dump with pg_dump from the newer server before restoring it into the newer target:
pg_dump --format=custom \ --file=/var/lib/postgresql/backups/app/app_20261121.dump \ old_databaseThe command must run against the old server using a PostgreSQL client whose major version matches the server. Then use the newer server’s pg_restore.
Troubleshooting Startup Parameter Errors
A physical recovery can fail with a message like:
FATAL: hot standby is not possible because wal_level=minimalThe source server’s wal_level setting or the target’s setting is incompatible with the recovery operation. Inspect the target configuration while it is stopped:
sudo -u postgres grep -E '^(wal_level|hot_standby|max_connections|max_worker_processes|max_wal_senders)' \ /var/lib/postgresql/15/recovery/postgresql.confSet the target values to match the source or to values accepted by the restored cluster. A mismatch such as the following can also block startup:
FATAL: inconsistent recovery stateThis message usually indicates that the target was not prepared correctly, the data directory was modified while stopped, or the control file and WAL state do not match. Confirm that the base backup copy is complete and that no unrelated files were added to the data directory.
For a parameter mismatch involving max_connections, PostgreSQL can sometimes start in single-user mode to change the value:
sudo -u postgres /usr/lib/postgresql/15/bin/postgres \ --single \ -D /var/lib/postgresql/15/recovery \ postgresAt the single-user prompt, set the parameter with SQL:
SET max_connections = 200;Exit the prompt afterward, correct the configuration file, and restart normally. This procedure applies to physical base backups. It does not make a logical dump into a WAL-consistent physical backup.
Handling a Recovery Target That Was Not Reached
If the server passes the requested target without stopping, inspect the exact recovery configuration:
sudo -u postgres cat /var/lib/postgresql/15/recovery/postgresql.auto.confsudo -u postgres cat /var/lib/postgresql/15/recovery/recovery.signalCheck for duplicate recovery settings in postgresql.conf, postgresql.auto.conf, and command-line options. The last loaded setting can win, and an incorrect timezone or timestamp format can cause PostgreSQL to interpret the target differently.
Use an unambiguous UTC timestamp:
recovery_target_time = '2026-11-21 09:45:00+00'Also confirm that the target is after the base backup’s checkpoint. If the requested time is earlier than the backup, PostgreSQL cannot recover to it through that backup.
A recovery may stop at a transaction boundary instead of the exact timestamp. That behavior depends on recovery_target_inclusive and the type of transaction that was active at the target. For controlled recovery, choose the timestamp immediately before the known bad transaction and validate the result.
Promoting the Recovered Server Safely
Keep the recovered server isolated from production traffic until verification finishes. Use a nonproduction port, firewall rules, or a separate host. A restored server may contain credentials and application data, so restrict access to the recovery team.
Before promotion, confirm:
- The target timestamp matches the incident record.
- Expected tables contain the correct rows.
- The unwanted transaction is absent.
- Extensions and event triggers are present.
- Database roles and ownership are correct.
- Replication slots and subscriptions have not created unexpected writes.
- The server has the correct timezone and locale settings.
- Backups and archiving are configured for the promoted server.
If the server was recovered with recovery_target_action = 'pause', resume and promote it in a controlled sequence:
sudo -u postgres psql -p 5433 -c "SELECT pg_wal_replay_resume();"sudo -u postgres /usr/lib/postgresql/15/bin/pg_ctl \ -D /var/lib/postgresql/15/recovery promoteAfter promotion, verify that the cluster is writable:
sudo -u postgres psql -p 5433 -Atc "SELECT pg_is_in_recovery();"sudo -u postgres psql -p 5433 -c \ "CREATE TABLE recovery_write_test(id integer);"sudo -u postgres psql -p 5433 -c \ "DROP TABLE recovery_write_test;"Remove or disable the old recovery signal and review recovery parameters before the server becomes a normal primary. A promoted server should have a deliberate archive strategy. If the old restore_command remains configured, it may fail or waste time looking for archived segments.
Automating Backups and Verifying the Archive
A basic cron or systemd timer can run pg_dump, but the backup job must report failures. A script that silently continues after a failed dump creates false confidence:
#!/usr/bin/env bashset -euo pipefail
backup_dir=/var/lib/postgresql/backups/apptimestamp=$(date -u +%Y%m%dT%H%M%SZ)target="$backup_dir/app_${timestamp}.dump"
sudo -u postgres pg_dump \ --format=custom \ --compress=6 \ --file="$target" \ app
sudo -u postgres pg_restore \ --list "$target" > "$target.list"
test -s "$target"test -s "$target.list"
sha256sum "$target" > "$target.sha256"Run it from root or with permissions that allow sudo:
sudo /usr/local/sbin/backup-postgres-appThe checksum is not a substitute for a restore test. It only proves that the file has not changed if the checksum is checked later. A weekly or monthly automated test restore should create a fresh cluster, restore the dump, and report the result to monitoring.
Use retention that matches the recovery objective. If the business requires recovery to a point 30 days old, keep the physical base backup and its required WAL chain for at least that period. Deleting a base backup does not make older WAL useless if a later base backup still needs part of the chain. PostgreSQL backup tools should calculate dependencies rather than deleting WAL by filename age alone.
Comparing pg_dump, pg_basebackup, and Continuous Archiving
The correct tool depends on the recovery requirement. The following table summarizes the practical differences.
| Method | Scope | PITR suitability | Main limitation |
|---|---|---|---|
pg_dump | Selected database, usually one at a time | Poor as a standalone PITR base | Logical export lacks physical WAL state |
pg_basebackup | Entire PostgreSQL cluster | Designed for WAL replay and PITR | Requires careful restore, tablespace, and permission handling |
| Filesystem or storage snapshot | Physical data and WAL | Can support PITR when snapshots are coordinated | Snapshot consistency and archive retention require careful design |
| Continuous WAL archiving | WAL history | Supplies the change stream for PITR | Missing segments make recovery impossible |
A practical policy is to use pg_dump for portable logical exports and migration validation, while using pg_basebackup plus WAL archiving for cluster-level disaster recovery and point-in-time recovery. If the application requires only one database, a physical backup can still be the recovery mechanism; the dump does not need to be part of the PITR chain.
A Practical Recovery Runbook
Use this runbook during an incident or scheduled exercise. Keep it on the recovery host, and replace the paths, target time, and service names with the values from the actual deployment.
First, identify the incident boundary:
cat /var/lib/postgresql/backups/app/recovery_target.txtdate -uThen stop accidental writes to the affected database and preserve its current WAL and data directory. Do not delete the original server. Take a filesystem-level copy if the storage system allows it.
Next, choose the physical base backup whose required WAL chain is intact:
ls -ld /var/lib/postgresql/backups/base/*Prepare a clean target cluster and copy the selected base backup into it. Add the recovery settings:
sudo -u postgres tee -a /var/lib/postgresql/15/recovery/postgresql.auto.conf <<'EOF'restore_command = 'cp /var/lib/postgresql/archive/%f %p'recovery_target_time = '2026-11-21 09:45:00+00'recovery_target_action = 'pause'EOF
sudo -u postgres touch /var/lib/postgresql/15/recovery/recovery.signalsudo systemctl start postgresql@15-recoveryMonitor the logs until recovery stops:
sudo journalctl -u postgresql@15-recovery -fValidate the database from another terminal:
sudo -u postgres psql -p 5433 -x -c \ "SELECT pg_is_in_recovery(), pg_last_wal_replay_lsn(), pg_last_xact_replay_timestamp();"Run the business checks. Only after those checks pass should the server be promoted and assigned production traffic.
Finally, document the recovery point, the base backup identifier, the first and last archived WAL filenames, the recovery target, the validation results, and the promotion time. That record tells the next operator whether the restored state was intentional and provides the evidence needed for the incident review.
Final Recommendations for a Protected PostgreSQL Recovery Plan
pg_dump is appropriate for logical backups, portable exports, and migration testing. It should not be treated as a physical base backup for PostgreSQL WAL replay. Reliable point-in-time recovery requires a physical base backup created from the source cluster, continuous WAL archiving, complete WAL retention, and a tested recovery procedure.
For a production system, store archives away from the PostgreSQL data directory, monitor pg_stat_archiver, protect the archive from deletion, and rehearse the restore. Test both the logical dump and the physical recovery path. The two backups serve different purposes, and keeping them gives operators more options when a failure occurs.
The key operational controls are simple: record the base backup and WAL range, verify the archive after every backup cycle, use an explicit UTC recovery target, validate the recovered data, and promote the server only after the checks pass.