PostgreSQL backups with PITR: back to any minute

This guide sets up a PITR backup for PostgreSQL step by step. A nightly backup with pg_dump is fine, but if someone drops a table by mistake at 6 pm, a whole day's work is gone. With PITR (Point-In-Time Recovery) you can bring the database back to exactly 5:59.
How PITR works
PostgreSQL writes every change to the WAL first. If you have a base backup and keep every WAL file after it, you can replay the changes up to any moment you want.
1. Turn on WAL archiving
# postgresql.conf
wal_level = replica
archive_mode = on
archive_command = 'test ! -f /backup/wal/%f && cp %p /backup/wal/%f'
archive_timeout = 60
Changing archive_mode needs a service restart. With archive_timeout = 60, at least one WAL file is archived every minute, so at most a minute of data is lost.
2. The base backup
pg_basebackup -D /backup/base/$(date +%F) -Ft -z -X stream -P
Run it once a day from cron. Delete WAL files older than the oldest base backup you keep.
3. Send the backup somewhere else
A backup left on the same server isn't a backup. Send the /backup folder to outside storage with rclone or restic: S3, a Storage Box or another server.
4. Recovering to a point in time
- Stop the service and move the current data folder aside. Don't delete it.
- Unpack the last base backup taken before that time into the data folder.
- Add the recovery settings:
# postgresql.conf restore_command = 'cp /backup/wal/%f %p' recovery_target_time = '2026-11-20 17:59:00+03:30' recovery_target_action = 'promote' - Create an empty
recovery.signalfile in the data folder and start the service.
PostgreSQL replays the WAL up to that moment and then becomes ready.
An untested PITR backup isn't a backup
Practise a recovery on a separate server once a month and note how long it takes. Add an alert for when the last archived WAL file is more than ten minutes old. Tools like pgBackRest and WAL-G automate all of this, and we recommend them for production.
This PITR backup runs on the same three-node Docker Swarm. If you are moving from Laravel to Go, see moving without a migration too. Full details are in the PostgreSQL documentation.
Comments
Sign in to leave a comment.
Sign inLoading…



