All posts
Tutorials

PostgreSQL backups with PITR: back to any minute

18 Nov 20262 min read6 views
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

  1. Stop the service and move the current data folder aside. Don't delete it.
  2. Unpack the last base backup taken before that time into the data folder.
  3. 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'
  4. Create an empty recovery.signal file 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 in

Loading…

Related posts

How to install Claude Code and run your first sessionTutorials

How to install Claude Code and run your first session

Claude Code is a coding agent that runs in your terminal: it reads files, edits them, runs tests and commits. This guide covers installing it on macOS, Linux and Windows, your first session, and a few habits that pay off from day one.

25 Nov 20265 min