In short
Start from two numbers: the recovery point objective (RPO), how much recent data you can afford to lose, and the recovery time objective (RTO), how long the system can be down. The RPO decides how often you copy data, which for PostgreSQL usually means a base backup plus continuous WAL archiving for point-in-time recovery; the RTO decides how much of the system you keep ready elsewhere. Keep at least one copy offline or immutable, and restore it on a schedule, because a backup you have never restored is not yet proof of anything.
Key points
- RPO is about data you lose; RTO is about time you are down. NIST SP 800-34 defines both, and they push the design in different directions.
- A
pg_dumpis a consistent snapshot of one database at one moment. A base backup plus archived WAL lets you replay to any moment after the backup, which is what point-in-time recovery means. - The 3-2-1 rule, from a 2012 paper produced for US-CERT, is three copies on two kinds of media with one offsite. Against ransomware, CISA adds that backups must be offline or otherwise out of an attacker’s reach.
- Replication is not a backup. A replica copies a mistaken
DELETEor corrupted data as faithfully as good data. - Restore tests are the only proof a backup works: restore into a scratch database, check it, and time it, so you know your real RTO.
- Pick a DR strategy, from backup and restore up to multi-site active-active, by the RTO and RPO each system needs, and drill it with a written runbook.
RPO and RTO: the two numbers that shape the design
NIST Special Publication 800-34 Rev. 1, the US federal contingency planning guide, gives the standard definitions. The recovery time objective (RTO) is the maximum time a system can stay unavailable before the impact on the business becomes unacceptable. The recovery point objective (RPO) is the point in time, before the outage, to which data can be recovered from the most recent backup. Put simply: RTO is how long you are down, RPO is how much recent work you lose.
The guide adds a third number, the maximum tolerable downtime (MTD): the total outage the business owner will accept, all impacts considered. The RTO has to fit inside it, and NIST notes it must normally be shorter, because after the system is back someone still has to re-enter or reprocess the work that was lost. The RPO, by contrast, is not part of the MTD; it measures how much data loss the business process can tolerate.
- The RPO sets how often data leaves the system. A nightly dump means an RPO of up to a day. Continuous WAL archiving brings it down to the last few moments of writes that had not yet been archived.
- The RTO sets how much has to be ready before the disaster. Restoring a large database from object storage, replaying a day of WAL and redeploying the app takes time; a standby that is already running takes much less.
- Both are per system, not per company. The orders database and the analytics warehouse rarely need the same numbers, and paying for the strictest target everywhere is how DR budgets get cut.
Write the numbers down with the owner of each system, then work backward. Every later choice in this post, from backup type to DR strategy, is a way of meeting a stated RPO and RTO.
Backup types: full, incremental, differential, logical and physical
NIST SP 800-34 describes the classic three. A full backup copies everything. An incremental backup copies what changed since the last backup of any kind. A differential backup copies what changed since the last full backup. The trade-off is between how long a backup takes and how many pieces a restore needs.
| Type | What it copies | To restore you need | Trade-off |
|---|---|---|---|
| Full | Everything | That one backup | Simplest restore; the slowest and largest backup |
| Incremental | Changes since the last backup of any type | The last full plus every incremental since, in order | Smallest and fastest backups; the longest restore chain, and one missing link breaks it |
| Differential | Changes since the last full backup | The last full plus the latest differential | Restore needs two pieces; each differential grows until the next full |
Cutting across those is a second choice: logical or physical. A logical backup is a description of the data, such as SQL statements or an archive of rows, produced by asking the database. It is portable across versions and machine architectures, can restore one table, and is slow to load at scale. A physical backup is a copy of the database files themselves. It restores fast and can be combined with the write-ahead log for point-in-time recovery, but it is tied to the server’s major version and covers the whole cluster.
PostgreSQL: pg_dump, base backups and point-in-time recovery
PostgreSQL offers both kinds. pg_dump is the logical one. The docs say its dumps are internally consistent, a snapshot of the database as of the moment it started, and that it does not block other work except operations that need an exclusive lock, such as most forms of ALTER TABLE. It dumps one database and leaves out roles and tablespaces, which are cluster-wide; pg_dumpall --globals-only covers those. The custom and directory formats restore with pg_restore, which can restore in parallel and pick single tables. The limit is the RPO: you can only go back to the moment a dump started.
Point-in-time recovery (PITR) uses the physical route. PostgreSQL writes every change to its write-ahead log (WAL) before it touches the data files. Take a base backup, a file-level copy of the whole cluster made while it runs, and archive every WAL segment written after it. To recover, restore the base backup and replay the archived WAL up to the moment you choose: just before the bad migration, the accidental DELETE or the ransomware. The docs list the requirements: wal_level set to replica or higher, archive_mode on, and an archive_command or archive_library that copies each completed segment somewhere safe.
# postgresql.conf on the primary: archive every completed WAL segment
wal_level = replica # the default; minimal cannot archive
archive_mode = on # changing it needs a restart
archive_command = 'test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f'
archive_timeout = 60 # switch segments at least once a minute
# Base backup with a manifest, then check the files against it
pg_basebackup -D /backups/base -X stream -c fast --manifest-checksums=SHA256
pg_verifybackup /backups/base
# Recovery, on a copy of the base backup: settings, then an empty recovery.signal
restore_command = 'cp /mnt/archive/%f %p'
recovery_target_time = '2026-11-12 09:41:00+00'
recovery_target_action = 'pause' # the default; inspect, then pg_wal_replay_resume()The archive line is the docs’ own example, which they call an example rather than a recommendation. Three rules from the docs matter in any real version. The command must exit with zero only if the file is safely stored, because PostgreSQL then recycles the segment. It should refuse to overwrite an existing archive file with different contents. And segments are archived only when complete, so on a quiet database archive_timeout is what bounds your RPO. Dedicated tools such as pgBackRest, Barman and WAL-G wrap these steps, push to object storage and manage retention.
- Recovery needs an unbroken chain of WAL from the start of a base backup to the target. A gap anywhere means you cannot go past it.
- Recovery restores the whole cluster, never one database. To get back one dropped table, restore the cluster elsewhere and copy the table across.
- Replaying a long stretch of WAL takes time, so the age of the last base backup is part of your RTO. Since PostgreSQL 17,
pg_basebackup --incrementaltakes block-level incremental backups thatpg_combinebackupmerges into a full one, which makes frequent base backups cheaper. - WAL does not contain
postgresql.conf,pg_hba.conforpg_ident.conf. Back them up separately.
PITR is also the safety net for schema changes. Zero-downtime database migrations keep the old schema working while the new one rolls out, and a known recovery target covers the case where a backfill writes the wrong values anyway.
The 3-2-1 rule and copies ransomware cannot reach
The 3-2-1 rule is usually quoted without a source. One primary source is “Data Backup Options”, a 2012 paper by Paul Ruggiero and Matthew A. Heckathorn of Carnegie Mellon University, produced for US-CERT and now hosted by CISA. It states the rule as: keep three copies of any important file, one primary and two backups; keep them on two different media types, to protect against different hazards; and store one copy offsite.
In a cloud setup, “two media types” translates into two independent failure domains: a different service, account or provider, so that one bad credential, one bug or one region outage cannot take out every copy. “Offsite” means a different region at least.
Ransomware changed what “a copy” has to mean. CISA’s #StopRansomware Guide warns that many ransomware variants look for accessible backups and delete or encrypt them, and tells organizations to keep offline, encrypted backups of critical data and to test their availability and integrity in a disaster recovery scenario. A backup that the production servers can delete with their normal credentials is not offline in that sense. Practical ways to get there:
- Write-once storage. Object stores with an object-lock or retention mode refuse deletes and overwrites until a retention date passes. CISA notes some cloud vendors offer immutable storage, and advises using it with care: it may not meet every compliance need, and a misconfigured retention period is hard to undo.
- Separate credentials. The database host can write new backups but cannot delete old ones. Pruning runs from a different account that the application never touches.
- Encryption with keys kept apart from the backups, so a stolen backup is unreadable and a lost key is planned for. Test that the key still decrypts during every restore test.
Replication is not a backup
A streaming replica or a multi-region database copy is excellent for availability: if the primary’s machine dies, a replica can take over in moments. It does nothing for a data disaster. A mistaken DELETE, a bad migration or ransomware that encrypts rows reaches the replica within moments, and now every copy is wrong. The AWS disaster recovery whitepaper makes the same point: continuous replication may not protect against data corruption or malicious deletion as well as point-in-time backups, and even a multi-site active-active setup has a recovery point before the corruption was discovered.
So replication lowers RTO for hardware and region failures, and backups with PITR cover mistakes and attacks. You need both. A delayed replica, which PostgreSQL supports with recovery_min_apply_delay, sits in between: it gives you a window to stop replay before a mistake arrives, but it is still one copy on infrastructure the same people can reach. The same caution applies to change data capture streams: they replay deletes downstream just as faithfully.
Restore tests: the only proof a backup works
A backup job that exits with zero proves that a file was written. It does not prove the file is complete, that it restores with the tools you will have on the bad day, or that it contains every table. Those failures are quiet. A full disk truncates a plain SQL dump at a line boundary. A dump run with the wrong flags leaves out a schema. A custom-format archive is newer than the pg_restore on the recovery machine. Each still looks like a perfectly good file until someone restores it.
A restore test does what recovery would do, on a scratch database, and checks the result. The script below shows the shape with SQLite standing in for the real database, so it runs anywhere: dump the source, restore the dump into a scratch database, and compare row counts table by table.
import sqlite3
def row_counts(db):
names = db.execute("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
return {t: db.execute(f'SELECT count(*) FROM "{t}"').fetchone()[0] for (t,) in names.fetchall()}
def restore_test(source, dump_sql):
scratch = sqlite3.connect(':memory:') # stand-in for a scratch database
try:
scratch.executescript(dump_sql) # the restore itself
except sqlite3.Error as err:
return f'FAILED: restore error: {err}'
want, got = row_counts(source), row_counts(scratch)
bad = {t: (got.get(t, 0), n) for t, n in want.items() if got.get(t) != n}
return f'MISMATCH (restored, source): {bad}' if bad else f'VERIFIED: {got}'
source = sqlite3.connect(':memory:') # the live database
source.executescript('CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);'
'CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER);')
source.executemany('INSERT INTO users (email) VALUES (?)', [(f'u{i}@example.com',) for i in range(100)])
source.executemany('INSERT INTO orders (user_id) VALUES (?)', [(i % 100,) for i in range(250)])
source.commit()
dump = list(source.iterdump()) # a logical dump, one statement per line
print(restore_test(source, '\n'.join(dump)))
print(restore_test(source, '\n'.join(dump[:300]))) # the same dump, cut short by a full diskVERIFIED: {'orders': 250, 'users': 100}
MISMATCH (restored, source): {'users': (47, 100)}That is the real output of the script. The second case is the instructive one: the truncated dump restored without a single error, and only the count comparison noticed that 53 users were missing. For PostgreSQL dumps, pg-backup-verify is an open-source tool that does this for real. It restores a custom, tar, directory or plain SQL dump into a scratch database, created by default on the source’s server, compares exact count(*) row counts for every table, fails on any restore error or warning unless told otherwise, and drops the scratch database afterward, even after an error or an interrupt. Its exit code is 0 for verified, 1 for not verified and 2 when it could not tell, so a scheduled job can alert on it.
Its documentation is clear about the limits, and they apply to any count-based test: it checks counts, not contents, so a dump with the right number of wrong rows passes; and it counts the source as it is now, so a busy database drifts from an older dump, which is what its --tolerance option is for. A fuller restore test adds a few checks:
- Time the restore end to end. That number, plus redeploying the app, is your real RTO, and it grows with the data.
- Run a handful of application queries against the restored copy: the newest order, a known customer, a checksum of a critical table.
- For base backups, do a full PITR to a chosen target on a separate server and check that it reaches that target.
pg_verifybackupchecks the files against the backup’s manifest, which is useful, but only starting the server proves it recovers. - Run it from the backup storage the disaster would leave you, with the credentials the runbook names, not from the primary’s own disk.
Disaster recovery strategies compared
Backups cover the data. Disaster recovery covers the whole system: servers, configuration, secrets, DNS and the people who switch it over. The AWS whitepaper “Disaster Recovery of Workloads on AWS: Recovery in the Cloud” sorts the options into four strategies. The names are vendor-neutral and apply to any cloud or data center.
| Strategy | What runs in the recovery site | Recovery time and point | Relative cost and complexity |
|---|---|---|---|
| Backup and restore | Nothing but stored backups; infrastructure is redeployed from code at failover | The slowest recovery; data back to the last backup or archived WAL | Lowest |
| Pilot light | Data is replicated live; core infrastructure exists, but app servers are switched off | Faster: servers are switched on and scaled up | Low to moderate |
| Warm standby | A scaled-down but fully working copy that can serve traffic at once | Faster again: only scaling up remains | Moderate |
| Multi-site active-active | Full copies in several regions, all serving traffic | Near zero for most failures; data corruption still needs backups | Highest |
Two points from the whitepaper are easy to miss. Backup and restore still needs infrastructure as code, because restoring data onto servers nobody can recreate quickly blows the RTO. And for the strategies with live replication, you must still keep point-in-time backups, because replication carries data disasters along with everything else. The usual answer for a young product is backup and restore with PITR for the database, rehearsed, and a move up the table only for the systems whose RTO demands it.
Retention and deletion
Every backup kept is data kept. A retention policy says how long each kind of backup lives and when it is deleted: for example, frequent recent backups for PITR, a smaller set of older ones for slow-to-discover problems, and nothing beyond what the business and the law call for. The policy also has to match the immutability settings, since a write-once copy cannot be deleted early on request.
Privacy law reaches into backups. When a user deletes their account under the GDPR or a similar law, the live database is the easy part; the same person is still in last month’s backups. A common approach is a documented retention period after which deleted data ages out of every backup, plus a record of deletions that is re-applied whenever a backup is restored, so a recovery does not bring deleted people back. GDPR for apps covers the wider obligations. This is not legal advice: the right retention periods depend on your jurisdictions and contracts.
Runbooks and drills
Recovery happens under stress, often at night, sometimes without the person who set things up. A runbook makes it a procedure instead of an investigation. It should name who can declare a disaster, where the backups and archive live, which credentials and keys open them, the exact commands for restore and PITR, how to pick a recovery target, how traffic moves, and how to check that the recovered system is right before users return.
Then practice. NIST SP 800-34 describes two kinds of exercise. A tabletop exercise is a discussion: a facilitator presents a scenario and the team talks through roles and decisions without touching systems. A functional exercise has people perform their duties in a simulated environment, up to a full-scale test of the whole plan. The guide says testing should include system recovery on an alternate platform from backup media, and that every exercise should end with an after-action report whose lessons go back into the plan.
- Automate a restore test of the latest backup on a schedule, and alert when it fails or does not run.
- Hold a tabletop exercise on a realistic scenario: a dropped table, a lost region, encrypted backups.
- Run a functional drill: recover to a chosen point in time on separate infrastructure, using only the runbook.
- Measure the achieved RPO and RTO against the targets, write the after-action report, and fix the runbook.
BYD Tech builds web apps and the backends behind them: the code lives in the client’s GitHub from day one, the founders are on the calls, and AI-assisted work is reviewed by an engineer.
Sources
Checked when this post was written.
- NIST SP 800-34 Rev. 1: Contingency Planning Guide for Federal Information Systems
- PostgreSQL docs: Continuous archiving and point-in-time recovery (PITR)
- PostgreSQL docs: SQL dump
- PostgreSQL docs: Write ahead log settings (archiving and recovery targets)
- PostgreSQL docs: pg_basebackup
- Ruggiero and Heckathorn: Data Backup Options (produced for US-CERT, 2012)
- CISA: #StopRansomware Guide
- AWS whitepaper: Disaster Recovery of Workloads on AWS, disaster recovery options in the cloud