Backup & restore: pg_dump, PITR
Take logical backups, restore them, and explain point-in-time recovery.
By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.
In short
pg_dump makes a logical backup of one database as SQL or an archive you restore with pg_restore. Point-in-time recovery combines a physical base backup with archived WAL so you can restore to any moment, such as just before a bad delete.
Explained simply
A backup is a copy of your data that you can bring back after something goes wrong: a dead disk, a bug that deletes rows, a command run on the wrong server, or ransomware. Backups are the one thing in operations you cannot add after the disaster.
Postgres has two kinds. A logical backup, made with pg_dump, saves the data as SQL commands or as an archive of table contents. A physical backup copies the actual data files of the whole server, together with the WAL, the log of every change.
Point-in-time recovery (PITR) combines a physical backup with a continuous archive of WAL files. You restore the backup and then replay the changes up to any moment you choose, such as one minute before someone ran DELETE without a WHERE.
A backup only counts if you have restored it. Test restores regularly, keep copies on a different machine and ideally in a different region, and write down how long a restore takes.
Press Play on a diagram to walk through it one step at a time.
- Client to Postgres: INSERT ...; COMMIT1INSERT ...; COMMIT
- Postgres to WAL: append change record2append change record
- WAL to Postgres: flushed to disk3flushed to disk
- Postgres to Client: COMMIT ok4COMMIT ok
- WAL to WAL archive: archive_command copies segment5archive_command copies segment
- WAL archive to Postgres: restore: replay WAL to target time6restore: replay WAL to target time
- One database at a time
- Portable across versions
- Restores to the dump moment
- Slow for very large data
- Whole server, file level
- Same major version only
- Restore to any moment
- Needs continuous WAL archiving
- Readable SQL script
- Restore with psql
- No selective or parallel restore
- Good for small dumps and diffs
- Compressed single file
- Restore with pg_restore
- Pick tables, parallel restore
- Best default for one database
- One file per table
- Parallel dump with -j
- Parallel restore too
- Best for big databases
In depth
pg_dump formats and what they include
pg_dump reads one database inside a single consistent snapshot, so the dump reflects one moment even while the app keeps writing. It does not block normal reads or writes, but it does block DDL such as ALTER TABLE on the tables it is reading.
Formats: plain (-Fp, the default) writes a SQL script you restore with psql. Custom (-Fc) is a compressed archive for pg_restore and lets you restore single tables. Directory (-Fd) writes one file per table and supports parallel dumping with -j. Tar (-Ft) also exists but is rarely used.
What a dump does not contain: roles and tablespaces, which belong to the whole server. Save them with pg_dumpall --globals-only. Also note that pg_dump of a huge database can take hours, and the restore longer, because indexes must be rebuilt. For tens of gigabytes and more, physical backups restore much faster.
- -Fc: compressed, selective restore with pg_restore
- -Fd -j 4: parallel dump into a directory
- pg_dumpall --globals-only for roles
- Use the newer pg_dump version when moving to a newer server
Restoring with pg_restore
pg_restore reads custom, directory and tar archives. Restore into an empty database: createdb shop_new, then pg_restore -d shop_new file.dump. Add -j 4 to run four jobs in parallel; the data loads and index builds then overlap and finish much sooner.
Useful options: --no-owner skips ownership commands, handy when restoring as a different user; --clean --if-exists drops objects before recreating them; -t orders restores one table; -l lists the archive's contents into a file, which you can edit and pass back with -L to restore only the items you keep.
Two habits save pain. Add --exit-on-error (or -e), because by default pg_restore keeps going after errors and you might miss them. And run ANALYZE after a restore, because the restored tables have no planner statistics yet and the first queries may choose bad plans.
- 1Create empty database
createdb shop_restore_test
- 2Restore globals if needed
psql -f globals.sql (roles)
- 3pg_restore -j 4 -e
Parallel, stop on the first error
- 4ANALYZE
Rebuild planner statistics
- 5Check the data
Row counts and a few known records
- 6Record the time
That is your real recovery time
Physical backups, WAL archiving and PITR
pg_basebackup copies the entire data directory of a running server: pg_basebackup -D /backups/base -Ft -z -X stream -P. With -X stream it also includes the WAL needed to make the copy consistent. PostgreSQL 17 added incremental base backups, combined later with pg_combinebackup.
For PITR you also archive every finished WAL segment (16 MB files by default). Set archive_mode = on and an archive_command, for example 'test ! -f /mnt/wal/%f && cp %p /mnt/wal/%f'. The command must return success only when the file is safely stored, or Postgres keeps retrying and holds the WAL.
To recover: restore the base backup into an empty data directory, set restore_command = 'cp /mnt/wal/%f %p' and recovery_target_time = '2026-03-01 14:29:00+00' in postgresql.conf, create an empty file named recovery.signal, and start the server. It replays WAL up to that moment. In practice most teams use pgBackRest, Barman or WAL-G, which handle base backups, archiving to S3, retention and verification.
- DBA to Backup store: Fetch last night's base backup1Fetch last night's base backup
- DBA to New server: Restore files, set recovery_target_time2Restore files, set recovery_target_time
- DBA to New server: touch recovery.signal; start3touch recovery.signal; start
- New server to Backup store: restore_command: fetch WAL segments4restore_command: fetch WAL segments
- New server to DBA: Log: recovery stopping before 14:295Log: recovery stopping before 14:29
- New server to DBA: Paused at target: check, then promote6Paused at target: check, then promote
RPO, RTO and a backup policy that works
Two numbers drive every backup decision. RPO (recovery point objective) is how much data you can afford to lose: a nightly pg_dump means up to 24 hours; continuous WAL archiving means seconds to minutes. RTO (recovery time objective) is how long you can be down: restoring a 500 GB logical dump can take many hours; a physical restore plus WAL replay is usually much faster.
A replica is not a backup. If someone drops a table, the replica drops it a second later. Keep replicas for availability and backups for history.
A solid policy: automated backups on a schedule, copies in another location (the 3-2-1 rule: three copies, two kinds of storage, one off site), encryption, retention that matches your needs (for example 14 daily and 12 monthly), monitoring that alerts when a backup fails or is missing, and a restore test at least monthly. Managed services such as Amazon RDS or Cloud SQL do PITR for you, but you should still practise a restore.
- RPO = how much data may be lost
- RTO = how long the restore may take
- Replicas copy mistakes instantly
- Alert on failed or missing backups
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Back up with pg_dump~45m
- 2Restore with pg_restore~45m
- 3Explain WAL archiving and PITR~45m
- 4Script a scheduled backup~45m
Key points
- pg_dump -Fc creates a compressed custom-format archive for pg_restore.
- pg_dumpall --globals-only saves roles, which pg_dump does not include.
- A backup you have never restored is not proven to work.
- Store backups off the database server and schedule them automatically.
Key terms
Tap a card to flip it. 0/5 known
Examples
#!/usr/bin/env bash
set -euo pipefail
stamp=$(date +%F_%H%M)
pg_dump -h localhost -U postgres -Fc -d shop -f "/backups/shop_$stamp.dump"
# restore into a fresh database to verify
createdb -U postgres shop_restore_test
pg_restore -U postgres -d shop_restore_test "/backups/shop_$stamp.dump"
# keep 14 days
find /backups -name 'shop_*.dump' -mtime +14 -deleteA nightly backup script with cron
Step 1: store the password in ~/.pgpass (mode 600) so the script never contains it. Step 2: dump globals and the database in custom format, with a timestamp in the name. Step 3: copy the files off the server. Step 4: delete local copies older than 14 days. Step 5: schedule it with cron at 02:30 and send output to a log you monitor.
#!/usr/bin/env bash
# /usr/local/bin/pg-backup.sh (~/.pgpass: localhost:5432:*:backup:secret)
set -euo pipefail
stamp=$(date +%F_%H%M)
dir=/var/backups/pg
mkdir -p "$dir"
pg_dumpall -h localhost -U backup --globals-only > "$dir/globals_$stamp.sql"
pg_dump -h localhost -U backup -Fc -d shop -f "$dir/shop_$stamp.dump"
aws s3 cp "$dir/shop_$stamp.dump" s3://acme-db-backups/shop/
aws s3 cp "$dir/globals_$stamp.sql" s3://acme-db-backups/shop/
find "$dir" -type f -mtime +14 -delete
# crontab -e:
# 30 2 * * * /usr/local/bin/pg-backup.sh >> /var/log/pg-backup.log 2>&1Restoring one table that was wiped
Someone ran DELETE FROM coupons on production, and last night's dump is fine for that table. Step 1: list the archive to confirm the table is in it. Step 2: restore only that table into a scratch database, so production is not touched. Step 3: copy the rows back into production with a query you check first. Note: rows changed since the dump are not in it; for those you would need PITR.
pg_restore -l shop_2026-03-01_0230.dump | grep coupons
createdb scratch
pg_restore -d scratch -t coupons --no-owner -e shop_2026-03-01_0230.dump
psql -d scratch -c "SELECT count(*) FROM coupons"
psql -d scratch -c "\copy coupons TO '/tmp/coupons.csv' CSV"
psql -d shop -c "\copy coupons FROM '/tmp/coupons.csv' CSV"Quick reference
- pg_dump -Fc -d shop -f shop.dump compressed archive of one database
- pg_dump -Fd -j 4 -d shop -f shop_dir parallel dump to a directory
- pg_restore -d target -j 4 --no-owner -e shop.dump parallel restore, stop on error
- pg_dumpall --globals-only > globals.sql roles and tablespaces
- pg_basebackup -D /backups/base -Ft -z -X stream -P physical backup
- PITR: restore base, restore_command, recovery_target_time, touch recovery.signal
- ~/.pgpass format host:port:db:user:password, mode 600
- A replica is not a backup: mistakes replicate instantly
Common mistakes
- Never testing a restore until the day you need it.
- Keeping backups on the same disk as the database.
- Forgetting roles and other global objects that pg_dump skips.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Dump database shop in custom format, then restore it into a new database called shop_copy and count the orders in both.
- Exercise 2medium
Dump a large database in parallel with 4 jobs and restore it with 4 jobs into a fresh database, then refresh statistics.
- Exercise 3hard
Configure WAL archiving to /mnt/wal and write the recovery settings to restore a base backup to 2026-03-01 14:29 UTC.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does pg_dump lock the database?
- It takes light locks that let normal reads and writes continue, and it works from one consistent snapshot. It does block schema changes like ALTER TABLE or DROP on the tables it is dumping until it finishes.
- Can I restore a dump into a newer PostgreSQL version?
- Yes. Logical dumps are portable across major versions; use the newer version's pg_dump and pg_restore. Physical backups only restore on the same major version.
- Which backup tool should I use in production?
- For self-managed servers, pgBackRest, Barman and WAL-G are widely used for physical backups with PITR. pg_dump is still useful for single databases, migrations and extra safety copies.
- How often should I test restores?
- Regularly and automatically if you can, for example a weekly job that restores the latest backup into a scratch server and runs a few checks. At minimum, before you rely on a new backup setup.