PostgreSQL Backup and Point-in-Time Recovery: A Production-Ready Guide

A database backup is useful only if it can be restored to a state the business can actually use. A nightly backup may be adequate for a development environment, but it leaves a potentially unacceptable gap for an application that processes orders, payments or other important transactions throughout the day.
PostgreSQL offers a recovery model that combines physical base backups with archived write-ahead logs (WAL). With a complete recovery chain, administrators can restore a database cluster to an earlier point rather than simply reverting to the last scheduled backup.
This guide uses PostgreSQL 18 on Linux as its reference environment. It explains the architecture, demonstrates a controlled recovery exercise and describes the operational controls necessary before adopting the approach in production.
1. Understand the recovery objectives
Before selecting a backup tool, establish two measurable business requirements:
| Objective | Meaning | Illustrative target |
|---|---|---|
| Recovery Point Objective (RPO) | Maximum acceptable data loss, expressed as elapsed time | Five minutes |
| Recovery Time Objective (RTO) | Maximum acceptable service interruption | Sixty minutes |
For example, consider an application that records orders continuously. If an incident occurs at 14:00 and the latest recoverable state is 13:57, the recovery point is three minutes behind the incident. Whether that meets the business requirement depends on the agreed RPO.
The RTO must include more than database startup. Provisioning a recovery host, obtaining credentials, downloading backups, replaying logs, reconciling transactions and routing application traffic all consume time. Measure the complete process during exercises rather than estimating it from backup duration.
2. How PostgreSQL recovery works
PostgreSQL records database changes in WAL as part of its durability architecture. Following a crash or during archive recovery, the engine can use these records to reconstruct database state. A physical backup supplies the starting files, while subsequent WAL supplies the changes needed to reach a later consistent state.
Think of a base backup as the starting point of a recovery chain:
Base backup --> WAL segment A --> WAL segment B --> WAL segment C | Recovery target
Missing a required segment can make the intended recovery target unreachable. Keeping the newest backup without ensuring the availability of its corresponding WAL is therefore insufficient.
For the detailed recovery model, see the official continuous archiving documentation.
Logical backups versus physical backups
| Method | Typical use | Main trade-off |
|---|---|---|
| Logical dump using pg_dump | Selective restoration, migration or exporting application data | Import time and object dependencies may be significant |
| Physical base backup | Whole-cluster recovery or standby initialization | Requires compatible PostgreSQL binaries and storage layout |
| Physical backup with WAL archiving | Recovery to a specific point in time | Requires continuous management of the complete recovery chain |
A logical dump is valuable alongside physical backups, particularly when an individual table needs recovery. It is not a substitute for a continuous physical recovery chain. Likewise, a replica is useful for availability but can replay an unwanted deletion just as readily as a legitimate transaction.
3. Build a controlled backup environment
The examples below assume a disposable PostgreSQL 18 lab cluster without additional tablespaces, running on Linux. Adapt service management, paths, authentication and operating system permissions to your deployment. Never run the recovery exercise against the live production data directory.
Create a dedicated backup identity with replication privileges and configure restrictive authentication rules. Use TLS where the backup crosses a network, and store passwords in a protected credential mechanism rather than command history.
For the lab only, prepare a separate archive directory that the PostgreSQL operating system account can write to. In production, move archived objects to independently protected storage; another directory on the same disk is not a sufficient disaster recovery design.
Example PostgreSQL settings:
wal_level = replica archive_mode = on archive_command = 'test ! -f /srv/pg-lab-archive/%f && cp %p /srv/pg-lab-archive/%f' archive_timeout = 60s
This simple archive command illustrates the mechanism; it is not a production archival implementation. Its destination must already exist and be secured. It refuses to overwrite an existing file, so an identical file left behind after an interrupted acknowledgement can require investigation. Production archival tooling should safely handle identical retries, verify durable writes and alert on conflicting content.
Changes to startup-only settings such as archive_mode require a planned restart. Confirm that archiving is working before relying on it. The archive timeout encourages segment switching during low activity, but does not guarantee that a remote archive receives every transaction within sixty seconds.
Refer to the WAL configuration reference for the supported settings and their behavior.
4. Take and verify a physical base backup
Use a backup host with PostgreSQL 18 client utilities installed. The example host name is a placeholder; replace it with your authorized lab database endpoint. Ensure that the replication identity is permitted by pg_hba.conf and that sufficient WAL sender capacity exists.
pg_basebackup \ -h db.example.invalid \ -U backup_user \ -D /srv/backup/lab-base-001 \ -Fp -Xs -P
The target directory must be empty or absent. The options select a plain-format backup, stream WAL during the backup and show progress. Additional tablespaces need explicit planning and, where appropriate, directory mappings. See the pg_basebackup reference before extending this example.
After the command completes, verify the backup:
pg_verifybackup /srv/backup/lab-base-001
The verifier uses the backup manifest to check the backup against expected file information and checksums, with WAL checks subject to the supported backup format. A successful result increases confidence in backup integrity but does not prove that the application will function following recovery.
Record the backup identifier, start and end times, PostgreSQL version, source system identifier, storage location, verification result and the retention policy governing the associated WAL.
5. Practice point-in-time recovery
A recovery exercise should reproduce a realistic operational failure without exposing real customer information.
Step 1: Establish a known restore point
After the base backup has completed, create representative test records in a disposable database. Commit them before creating a named restore point. Using an appropriately authorized administrative connection, execute:
SELECT pg_create_restore_point('before_lab_change');
SELECT pg_switch_wal();
Use a distinct restore-point name for each exercise. Record the time and returned WAL location in your exercise log. Make another controlled change to the synthetic data, commit it and switch WAL again. Confirm that the necessary segments reached the archive before starting the recovery exercise.
Step 2: Prepare an isolated recovery host
Copy the verified backup into a new recovery directory owned by the PostgreSQL operating system account. Do not modify the original backup. Use compatible PostgreSQL 18 binaries and ensure that the restored configuration cannot connect to production replication peers, schedulers, payment services or external application integrations.
For this example, the recovery host has read access to the copied WAL archive at /srv/pg-lab-archive. Keep the recovery environment network-isolated and use a separate local socket directory and port. Inspect both postgresql.conf and postgresql.auto.conf, since the latter can override earlier settings.
Step 3: Configure archive recovery
On the isolated copy, configure the following recovery parameters in postgresql.conf, ensuring no conflicting values override them:
restore_command = 'cp /srv/pg-lab-archive/%f %p' recovery_target_name = 'before_lab_change' recovery_target_action = 'pause' archive_mode = off hot_standby = on listen_addresses = '' port = 55432 unix_socket_directories = '/srv/pg-lab-socket'
Create the socket directory with suitable ownership and permissions, then create the recovery signal file inside the recovered cluster directory and start the isolated server as the PostgreSQL operating system user:
touch /srv/restore/lab-cluster/recovery.signal
pg_ctl -D /srv/restore/lab-cluster \
-l /srv/restore/lab-recovery.log start
The example assumes configuration files are available in the restored directory and that no standby.signal file or unintended recovery settings are present. PostgreSQL 12 and later use signal files and normal configuration parameters rather than the older recovery.conf mechanism.
Step 4: Verify the recovered data
Connect through the isolated socket and check the recovery state:
SELECT pg_is_in_recovery();
SELECT pg_get_wal_replay_pause_state();
SELECT pg_last_wal_replay_lsn();
Inspect the server log to confirm that the intended target was reached. Check that the known test records exist and that the later change is absent. Validate the relevant application invariants, including row counts, relationships and representative business queries.
Do not assume that a running database has reached the requested recovery point. If WAL is missing or the target is not found, investigate the recovery logs and the archive chain before proceeding.
After validation, an authorized recovery lead can decide whether to finish recovery and make the isolated cluster writable. Keep the exercise separate from any production cutover.
6. Monitor the backup and WAL pipeline
A successful backup job is just one of several signals. Monitor archiving independently:
SELECT archived_count,
failed_count,
last_archived_wal,
last_archived_time,
last_failed_wal,
last_failed_time
FROM pg_stat_archiver;
Watch for increases in failed_count, sustained archive delays and unexpected growth of the WAL directory. Interpret the counters in context: an idle database might not generate new archive activity, and counters can reset. Complement database metrics with repository-side checks that independently confirm durable object arrival.
A practical dashboard should answer these questions:
- When was the most recent successful full backup?
- How old is the latest verified recovery point?
- Is the archive accumulating a backlog?
- Is the repository running out of storage?
- When did the last full restore exercise succeed?
- Did the exercise meet the agreed RPO and RTO?
Use the PostgreSQL statistics reference to understand the monitoring fields.
7. Protect recovery data from operational and security failures
Backups deserve at least the same protection as the databases from which they originate. Physical backups and archived logs can contain sensitive records and historical changes.
Separate backup storage credentials from routine database administration credentials. Encrypt backup transfers and stored objects, restrict restore access and maintain a protected copy in a separate failure domain. Where appropriate, enforce immutable retention so a compromised application account cannot erase every recovery copy.
Avoid deleting WAL using a simple age-based script without consulting backup dependencies. A retained base backup is not useful for the promised recovery window if the required logs have already expired. Maintain a recovery catalog and use backup-aware retention tooling.
For larger installations, evaluate tools such as pgBackRest or Barman to manage backup scheduling, archive repositories and retention. Validate compatibility and features against the specific versions you deploy.
8. Treat recovery as a business process
Imagine a financial application that must recover to a point immediately before an erroneous batch job. Restoring the database alone does not establish whether external payment instructions were already accepted or whether another system retained a later state.
Keep the recovered environment isolated while reconciling database transactions with external records. Identify potentially missing or duplicated operations and obtain appropriate authorization before initiating any corrective transaction. Do not automatically replay financial messages merely because the local database was restored.
Maintain a written recovery runbook with responsible owners, communication channels, approved recovery targets, dependency checks and evidence requirements. Exercise it regularly using non-production data and record actual elapsed time for each recovery stage.
Conclusion
PostgreSQL point-in-time recovery is a powerful capability, but its reliability depends on an intact backup chain, trustworthy storage and a tested restoration process. Define recovery objectives first, establish continuous archival monitoring, verify base backups and exercise recovery in isolation.
The most meaningful backup metric is not how many successful jobs appear on a dashboard. It is how confidently the organization can recover the right data within the agreed business recovery window.


