In this article
This is Part 22 of the PostgreSQL DBA series. In Part 21 we set up pgBackRest and ran our first restores with it. In this part you will learn how to verify a PostgreSQL backup properly: not only that the backup job said "completed", but that the backup restores, reaches the point in time you expect, and holds correct, uncorrupted data.
By the end you will be able to run a full restore drill on Ubuntu with PostgreSQL 18: check the backup files with pg_verifybackup, check the WAL chain with pg_waldump, restore into a throwaway cluster, compare the data with a saved reference, scan it for corruption with pg_amcheck and pg_checksums, measure how long it all took, and turn the whole drill into one script you can schedule every month.
What you will learn
- The four levels of backup verification, and why a successful backup job proves very little on its own
- How to check base backup files and the archived WAL chain without restoring anything
- How to restore into a separate drill cluster and prove the data matches a saved reference
- How to find corruption in a restored copy with pg_amcheck and pg_checksums
- How to measure recovery time (RTO) and possible data loss (RPO), and automate the drill
Prerequisites
- Parts 17 to 21 of this series: pg_dump and pg_restore, pg_basebackup, WAL archiving, point-in-time recovery and pgBackRest. This part reuses the same layout: base backups in
/var/lib/postgresql/backupsand archived WAL in/mnt/wal_archive. - One Ubuntu server (db1) with PostgreSQL 18 from the PGDG repository, cluster
18 mainon port 5432, WAL archiving turned on as in Part 19. - Free disk space for one more full copy of the cluster, because the drill restores a complete copy on port 5433.
- A user with sudo. Commands that touch PostgreSQL files run as the
postgresoperating system user.
How it works
A backup is a promise that you can get your data back. A restore drill is how you check the promise before you need it, the same way a fire drill checks that people can actually leave the building. The first real restore should never be the one you do during an outage.
Backups fail quietly. A WAL segment goes missing from the archive, a backup file is cut short when the disk fills, a disk flips a few bits, or a restore step only exists in the head of someone who has left the company. None of these shows up until you try to restore. So a DBA checks backups at four levels, from cheapest to most complete:
| Level | Question it answers | Tools in this part |
|---|---|---|
| 1. Job status | Did the backup and archiving finish without errors? | exit codes, pg_stat_archiver |
| 2. Files | Are all backup files present and unchanged? Is the WAL chain complete? | pg_verifybackup, pg_waldump, pg_restore --list, pgbackrest verify |
| 3. Restore | Does the backup restore and replay WAL up to the target? | a drill cluster on port 5433 |
| 4. Data | Is the restored data correct and free of corruption? | a fingerprint query, pg_amcheck, pg_checksums |
Only levels 3 and 4 really prove the backup. The PostgreSQL documentation says this directly about pg_verifybackup: even if you use it, you should still perform test restores and verify that the resulting databases work as expected and contain the correct data.
Two numbers come out of every drill. RTO (recovery time objective) is how long a restore takes, from the decision to restore until users can work again. RPO (recovery point objective) is how much recent data you could lose, which for WAL archiving is roughly the age of the newest archived WAL segment. A drill measures your real RTO, and the archiver view shows your real RPO.
db1 (10.0.0.11)
cluster "18 main" port 5432 production
| pg_basebackup | archive_command
v v
/var/lib/postgresql/backups/ /mnt/wal_archive/
base_2026_11_20 000000010000000000000003 ...
| |
+--------- restore -----------+ restore_command
v
cluster "18 drill" port 5433 throwaway copy: check, measure, dropPrepare the lab
Step 1: Check archiving and data checksums
On db1, as postgres. A drill is only useful if the basics are on. Check that WAL archiving is working and that the cluster has data checksums. A data checksum is a small number stored in every 8 kB data page; PostgreSQL recalculates it when it reads the page, so a page changed by a faulty disk is detected instead of silently returning wrong data.
sudo -u postgres psql -c "SELECT name, setting FROM pg_settings WHERE name IN ('data_checksums','archive_mode','archive_command','archive_timeout') ORDER BY name;"
sudo -u postgres psql -x -c "SELECT archived_count, last_archived_wal, last_archived_time, failed_count, last_failed_wal FROM pg_stat_archiver;" name | setting
-----------------+------------------------------------------------------------
archive_command | test ! -f /mnt/wal_archive/%f && cp %p /mnt/wal_archive/%f
archive_mode | on
archive_timeout | 60
data_checksums | on
(4 rows)
-[ RECORD 1 ]------+-----------------------------
archived_count | 1
last_archived_wal | 000000010000000000000001
last_archived_time | 2026-11-20 12:48:22.18006+00
failed_count | 0
last_failed_wal |data_checksums is read-only and shows whether the cluster was created with checksums. New in PostgreSQL 18: initdb enables data checksums by default, and Ubuntu's pg_createcluster uses that default, so a fresh 18 cluster shows on. Clusters created on PostgreSQL 17 or earlier without --data-checksums, and clusters upgraded from them, show off; pg_checksums --enable can turn checksums on later, but only while the server is stopped. failed_count must be 0 here. If it grows, fix archiving first (Part 19), because no drill can succeed with a broken archive.
Step 2: Create sample data
On db1, as postgres, in psql. We use a small shop database with two related tables and an index, so that the corruption checks later have tables and indexes to look at.
CREATE DATABASE shop;
\c shop
CREATE TABLE customers (
customer_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
full_name text NOT NULL,
city text NOT NULL
);
CREATE TABLE orders (
order_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers,
amount numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_customer_idx ON orders (customer_id);
INSERT INTO customers (full_name, city)
SELECT 'customer_' || g, (ARRAY['Chennai','Pune','Delhi','Kochi'])[1 + g % 4]
FROM generate_series(1, 2000) AS g;
INSERT INTO orders (customer_id, amount)
SELECT 1 + g % 2000, (g % 500) + 0.99
FROM generate_series(1, 50000) AS g;Verify: SELECT count(*) FROM orders; in the shop database returns 50000.
Step 3: Take a base backup
On db1, as postgres. This is the same command as in Part 18. In real life you test the backups your scheduled job already made; we take one here so the lab is complete.
sudo -u postgres mkdir -p /var/lib/postgresql/backups
sudo -u postgres pg_basebackup -D /var/lib/postgresql/backups/base_2026_11_20 \
--checkpoint=fast --label=base_2026_11_20 --progresswaiting for checkpoint
35483/35483 kB (100%), 0/1 tablespace
35483/35483 kB (100%), 1/1 tablespaceVerify: the backup_label file inside the backup shows the first WAL segment this backup needs. Write it down; you use it in Step 6.
sudo -u postgres head -2 /var/lib/postgresql/backups/base_2026_11_20/backup_labelSTART WAL LOCATION: 0/3000028 (file 000000010000000000000003)
CHECKPOINT LOCATION: 0/3000060Step 4: Save a reference fingerprint and a restore point
On db1, as postgres. To prove that restored data is correct, you need something to compare it with. A fingerprint is a short summary of table contents: the row count and an MD5 hash of all rows in key order. If even one value differs, the hash differs. Save the query in a file so you run exactly the same query on production and on the restored copy.
sudo -u postgres mkdir -p /var/lib/postgresql/drill
sudo -u postgres tee /var/lib/postgresql/drill/fingerprint.sql >/dev/null <<'EOF'
SELECT 'customers' AS table_name, count(*) AS row_count,
md5(string_agg(c::text, ',' ORDER BY customer_id)) AS content_md5
FROM customers AS c
UNION ALL
SELECT 'orders', count(*),
md5(string_agg(o::text, ',' ORDER BY order_id))
FROM orders AS o;
EOFNow add some rows after the backup, so the drill must replay WAL to get them back. Then save the fingerprint and create a named restore point at the same moment. A restore point (Part 20) is a label in the WAL stream; recovery can stop exactly there, which makes the comparison exact.
sudo -u postgres psql -d shop -c "INSERT INTO orders (customer_id, amount) SELECT 1 + g % 2000, 250.00 FROM generate_series(1, 5000) AS g;"
sudo -u postgres psql -d shop -f /var/lib/postgresql/drill/fingerprint.sql -o /var/lib/postgresql/drill/expected.txt
sudo -u postgres psql -Atc "SELECT pg_create_restore_point('drill_2026_11_20');"
sudo -u postgres cat /var/lib/postgresql/drill/expected.txtINSERT 0 5000
0/41BC420
table_name | row_count | content_md5
------------+-----------+----------------------------------
customers | 2000 | 72fc6c26b552b6a5e8ba0f757619d7aa
orders | 55000 | b92a1b43b2d4582aa13294fbd9e3b45a
(2 rows)0/41BC420 is the WAL position of the restore point. Finally, keep working after the restore point and close the current WAL segment, so the archive holds everything:
sudo -u postgres psql -d shop -c "UPDATE orders SET amount = amount * 2 WHERE order_id <= 1000;"
sudo -u postgres psql -Atc "SELECT pg_switch_wal();"UPDATE 1000
0/4221F40Check the backup files before restoring
Step 5: Verify the base backup with pg_verifybackup
On db1, as postgres. You met pg_verifybackup in Part 18. It reads the backup_manifest that the server wrote during the backup, checks that every file is present with the right size, recomputes each file's checksum, and parses the WAL the backup needs. It is in /usr/lib/postgresql/18/bin/, not in your PATH, so give the full path.
sudo -u postgres /usr/lib/postgresql/18/bin/pg_verifybackup /var/lib/postgresql/backups/base_2026_11_20; echo "exit=$?"backup successfully verified
exit=0Exit status 0 means no problems were found. Useful options from the reference page:
| Option | What it does |
|---|---|
| -q, --quiet | Print nothing when a backup is successfully verified (good for scripts) |
| -e, --exit-on-error | Exit as soon as a problem is detected, instead of reporting all problems |
| -n, --no-parse-wal | Do not parse WAL. Needed for tar-format backups |
| -w, --wal-directory=path | Parse WAL from another directory, for example the WAL archive |
The documentation is clear about the limits: pg_verifybackup finds missing files and changed contents, but it cannot run every check the server will run when it actually uses the backup. That is why the restore in Step 7 is still needed.
Step 6: Check that the archived WAL chain has no gaps
On db1, as postgres. A base backup alone only restores to the moment the backup ended. To reach any later point, recovery needs every WAL segment from the backup's start segment onwards, with no gap. pg_waldump (seen in Part 20) can read a range of segments from the archive; with --quiet it prints nothing unless it hits an error, such as a missing file.
sudo -u postgres ls /mnt/wal_archive
sudo -u postgres /usr/lib/postgresql/18/bin/pg_waldump --path=/mnt/wal_archive --quiet \
000000010000000000000003 000000010000000000000004; echo "exit=$?"000000010000000000000001
000000010000000000000002
000000010000000000000003
000000010000000000000003.00000028.backup
000000010000000000000004
exit=0| Option | What it does |
|---|---|
| --path=/mnt/wal_archive | Directory in which to find WAL segment files |
| --quiet | Do not print any output, except for errors |
| first segment | The segment from backup_label (Step 3), where replay starts |
| last segment | The newest archived segment, shown as last_archived_wal in pg_stat_archiver |
The file ending in .backup is the backup history file that PostgreSQL archives when a base backup finishes; it records the backup's start and stop WAL positions. For comparison, this is what a gap looks like. We copied segments 03 and 05 into a test directory but not 04:
pg_waldump: error: could not find file "000000010000000000000004": No such file or directory
exit=1A gap means recovery can never get past that segment. Every point in time after it is lost until you take a new base backup.
Restore into a drill cluster
Step 7: Create an empty drill cluster and restore the backup
On db1, as a user with sudo. The procedure follows the recovery steps from Part 20 and the documentation: empty data directory, copy the base backup, remove old files from pg_wal, set restore_command and the target, create recovery.signal.
date -u '+%F %T'
sudo pg_createcluster 18 drill --port 5433
sudo -u postgres find /var/lib/postgresql/18/drill -mindepth 1 -delete
sudo -u postgres cp -a /var/lib/postgresql/backups/base_2026_11_20/. /var/lib/postgresql/18/drill/
sudo -u postgres find /var/lib/postgresql/18/drill/pg_wal -mindepth 1 -type f -delete
sudo -u postgres tee /etc/postgresql/18/drill/conf.d/drill.conf <<'EOF'
archive_mode = off
restore_command = 'cp /mnt/wal_archive/%f %p'
recovery_target_name = 'drill_2026_11_20'
recovery_target_action = 'promote'
EOF
sudo -u postgres touch /var/lib/postgresql/18/drill/recovery.signal2026-11-20 12:49:08| Setting | Why the drill needs it |
|---|---|
| archive_mode = off | The copy must never write its WAL into the production archive (/mnt/wal_archive). Can only be set at server start |
| restore_command | How the drill fetches archived WAL segments; %f is the file name, %p the destination path |
| recovery_target_name | Stop at the restore point from Step 4. Recovery targets can only be set at server start |
| recovery_target_action = 'promote' | When the target is reached, finish recovery and accept connections. The default is pause |
Verify: pg_lsclusters lists 18 drill 5433 down, and sudo -u postgres ls /var/lib/postgresql/18/drill shows backup_label, backup_manifest and recovery.signal.
Step 8: Start the drill cluster and read the log
On db1, as a user with sudo.
sudo systemctl start postgresql@18-drill
sudo tail -n 25 /var/log/postgresql/postgresql-18-drill.logLOG: database system was interrupted; last known up at 2026-11-20 12:48:36 UTC
cp: cannot stat '/mnt/wal_archive/00000002.history': No such file or directory
LOG: starting point-in-time recovery to "drill_2026_11_20"
LOG: starting backup recovery with redo LSN 0/3000028, checkpoint LSN 0/3000060, on timeline ID 1
LOG: restored log file "000000010000000000000003" from archive
LOG: redo starts at 0/3000028
LOG: restored log file "000000010000000000000004" from archive
LOG: completed backup recovery with redo LSN 0/3000028 and end LSN 0/3000100
LOG: consistent recovery state reached at 0/3000100
LOG: database system is ready to accept read-only connections
LOG: recovery stopping at restore point "drill_2026_11_20", time 2026-11-20 12:48:41.785246+00
LOG: redo done at 0/41BC3B8 system usage: CPU: user: 0.01 s, system: 0.00 s, elapsed: 0.06 s
LOG: last completed transaction was at log time 2026-11-20 12:48:41.664731+00
LOG: selected new timeline ID: 2
LOG: archive recovery complete
LOG: database system is ready to accept connectionsRead it from top to bottom: replay starts at the backup's start segment, the copy becomes consistent (the earliest moment it could be opened), recovery stops at the restore point, a new timeline 2 starts and the server accepts connections. The cp: cannot stat ... .history lines are normal: recovery asks the archive whether newer timelines exist, and none do.
Verify: the server must be out of recovery.
sudo -u postgres psql -p 5433 -Atc "SELECT pg_is_in_recovery();"fNote the time now. The difference from the start time in Step 7 is the restore part of your RTO. In this lab it was a few seconds; with hundreds of gigabytes it is mostly copy time plus WAL replay, and only a drill tells you the real number.
Prove the data is correct
Step 9: Compare the restored data with the reference
On db1, as postgres. Run the same fingerprint file on the drill cluster and compare it with the file saved in Step 4. diff prints nothing and returns 0 when the files are identical.
sudo -u postgres psql -p 5433 -d shop -f /var/lib/postgresql/drill/fingerprint.sql -o /var/lib/postgresql/drill/actual.txt
sudo -u postgres diff /var/lib/postgresql/drill/expected.txt /var/lib/postgresql/drill/actual.txt && echo "MATCH: restored data equals the reference"MATCH: restored data equals the referenceFor contrast, the same query on production now gives a different hash for orders, because of the UPDATE we ran after the restore point:
sudo -u postgres psql -d shop -f /var/lib/postgresql/drill/fingerprint.sql table_name | row_count | content_md5
------------+-----------+----------------------------------
customers | 2000 | 72fc6c26b552b6a5e8ba0f757619d7aa
orders | 55000 | 91f87a77b00854dee560da0e7f3d2b04
(2 rows)This proves two things at once: the restore brought back all 55,000 orders, and it stopped exactly at the restore point, not before or after.
Step 10: Scan the copy for corruption with pg_amcheck
On db1, as postgres. pg_amcheck runs the checks of the amcheck extension on every table and B-tree index: it reads table pages looking for damaged rows, and walks each index checking that it is internally consistent. Run it on the drill copy, not on production, so the extra reading costs production nothing.
sudo -u postgres /usr/lib/postgresql/18/bin/pg_amcheck -p 5433 --all \
--install-missing --heapallindexed --jobs=2; echo "exit=$?"exit=0| Option | What it does |
|---|---|
| -p 5433 | Connect to the drill cluster |
| --all | Check all databases |
| --install-missing | Install any missing extensions required to check the databases (only amcheck); goes into pg_catalog by default |
| --heapallindexed | Also verify that every table row is present in each index. Takes several times longer |
| --jobs=2 | Use 2 connections to check objects in parallel |
No output and exit status 0 means nothing was found. Two notes from the documentation: amcheck can only prove the presence of corruption, never its absence; and pg_amcheck checks tables, sequences, materialized views and B-tree indexes, silently skipping other index types. If you forget --install-missing, you get:
pg_amcheck: warning: skipping database "postgres": amcheck is not installed
pg_amcheck: warning: skipping database "shop": amcheck is not installed
pg_amcheck: warning: skipping database "template1": amcheck is not installed
pg_amcheck: error: no relations to checkStep 11: Verify every data page checksum with pg_checksums
On db1, as a user with sudo. pg_checksums --check reads every data file and recomputes every page checksum. It is the most complete page-level check, but the documentation requires the server to be shut down cleanly first.
sudo systemctl stop postgresql@18-drill
sudo -u postgres /usr/lib/postgresql/18/bin/pg_checksums --check -D /var/lib/postgresql/18/drill; echo "exit=$?"Checksum operation completed
Files scanned: 1255
Blocks scanned: 4406
Bad checksums: 0
Data checksum version: 1
exit=0To see what a failure looks like, we overwrote 16 bytes in one page of the orders table file in the drill copy only and ran the checks again:
pg_checksums: error: checksum verification failed in file "/var/lib/postgresql/18/drill/base/16384/16394", block 10: calculated checksum 47CF but block contains 4F21
Checksum operation completed
Files scanned: 1255
Blocks scanned: 4406
Bad checksums: 1
Data checksum version: 1
exit=1After starting the drill cluster, SELECT count(*) FROM orders; failed with the same problem, and pg_amcheck -p 5433 -d shop -t orders exited with status 2:
WARNING: page verification failed, calculated checksum 18383 but expected 20257
ERROR: invalid page in block 10 of relation base/16384/16394If a drill finds this, do not delete the backup. Restore the previous backup to see whether the damage is older, run pg_amcheck on production at a quiet time, and check the disks. The checksum_failures column of pg_stat_database (Part 24) counts these errors per database, so monitor it on production too.
Step 12: Test a logical dump the same way
On db1, as postgres. pg_dump backups (Part 17) need their own drill. pg_restore --list only reads the table of contents at the start of the file, so it does not prove the file is complete. Restore it into a scratch database instead.
sudo -u postgres pg_dump -Fc -d shop -f /var/lib/postgresql/backups/shop_2026_11_20.dump
sudo -u postgres createdb shop_drill
sudo -u postgres pg_restore -d shop_drill --exit-on-error /var/lib/postgresql/backups/shop_2026_11_20.dump; echo "exit=$?"
sudo -u postgres psql -d shop -f /var/lib/postgresql/drill/fingerprint.sql -o /tmp/prod.txt
sudo -u postgres psql -d shop_drill -f /var/lib/postgresql/drill/fingerprint.sql -o /tmp/drill.txt
diff /tmp/prod.txt /tmp/drill.txt && echo "MATCH: dump restore equals production"exit=0
MATCH: dump restore equals production--exit-on-error makes pg_restore stop at the first SQL error; without it, errors are reported but the restore carries on, and you can miss them. We also cut a copy of the dump file in half to show why --list is not enough: pg_restore --list still returned 0, but the real restore failed:
pg_restore: error: could not read from input file: end of fileCleanup: sudo -u postgres dropdb shop_drill.
If you use pgBackRest
With pgBackRest from Part 21 the levels are the same, only the commands change. For level 2, the verify command checks that the backups and WAL archive in the repository are valid. By default it reports only errors; --verbose with --output=text also lists what was verified, and --set limits it to one backup set.
sudo -u postgres pgbackrest --stanza=app --output=text --verbose verifyFor level 3, restore into the drill cluster's empty data directory with --type=immediate, which recovers only until the database becomes consistent, or with the default type, which replays to the end of the archive. Levels 3 and 4 then continue with Steps 8 to 11 exactly as above.
sudo -u postgres pgbackrest --stanza=app --pg1-path=/var/lib/postgresql/18/drill \
--type=immediate --target-action=promote --archive-mode=off restoreMake the drill a routine
Step 13: Put the whole drill in one script
On db1, as a user with sudo. A drill that depends on someone remembering twelve steps will stop happening. The script below runs Step 5 and Steps 7 to 11 in order (add the Step 6 pg_waldump check with your own segment range if you like), stops at the first failure (set -euo pipefail), prints timings, and drops the drill cluster at the end. Save it as /usr/local/bin/restore-drill.sh and make it executable with sudo chmod 755 /usr/local/bin/restore-drill.sh.
#!/bin/bash
# restore-drill.sh: restore a base backup into a throwaway
# cluster "18 drill", verify it, report timings, then remove it.
# Run as root: sudo /usr/local/bin/restore-drill.sh <backup_dir> <restore_point>
set -euo pipefail
VER=18
BIN=/usr/lib/postgresql/$VER/bin
BACKUP=$1
TARGET=$2
DRILL=/var/lib/postgresql/$VER/drill
WORK=/var/lib/postgresql/drill
as_pg() { sudo -u postgres "$@"; }
log() { echo "$(date -u '+%F %T') $*"; }
log "drill start: backup=$BACKUP target=$TARGET"
T0=$(date +%s)
log "1/6 verify backup files"
as_pg $BIN/pg_verifybackup -q "$BACKUP"
log "2/6 create empty drill cluster on port 5433"
pg_dropcluster $VER drill --stop 2>/dev/null || true
pg_createcluster $VER drill --port 5433 >/dev/null
as_pg find "$DRILL" -mindepth 1 -delete
log "3/6 copy backup and configure recovery"
as_pg cp -a "$BACKUP/." "$DRILL/"
as_pg find "$DRILL/pg_wal" -mindepth 1 -type f -delete
as_pg tee /etc/postgresql/$VER/drill/conf.d/drill.conf >/dev/null <<CONF
archive_mode = off
restore_command = 'cp /mnt/wal_archive/%f %p'
recovery_target_name = '$TARGET'
recovery_target_action = 'promote'
CONF
as_pg touch "$DRILL/recovery.signal"
log "4/6 start and wait for recovery to finish"
pg_ctlcluster $VER drill start
for i in $(seq 1 600); do
[ "$(as_pg psql -p 5433 -Atc 'SELECT pg_is_in_recovery()' 2>/dev/null)" = "f" ] && break
pg_lsclusters -h $VER drill | grep -q online || break
sleep 1
done
[ "$(as_pg psql -p 5433 -Atc 'SELECT pg_is_in_recovery()')" = "f" ]
T1=$(date +%s)
log "database open for writes after $((T1 - T0)) seconds"
log "5/6 compare data with the reference and run pg_amcheck"
as_pg psql -p 5433 -d shop -f $WORK/fingerprint.sql -o $WORK/actual.txt
as_pg diff $WORK/expected.txt $WORK/actual.txt
as_pg $BIN/pg_amcheck -p 5433 --all --install-missing --heapallindexed --jobs=2
log "6/6 stop and check data checksums"
pg_ctlcluster $VER drill stop
as_pg $BIN/pg_checksums --check -D "$DRILL" | grep 'Bad checksums'
pg_dropcluster $VER drill
log "DRILL PASSED in $(( $(date +%s) - T0 )) seconds"sudo /usr/local/bin/restore-drill.sh /var/lib/postgresql/backups/base_2026_11_20 drill_2026_11_20; echo "exit=$?"2026-11-20 12:50:36 drill start: backup=/var/lib/postgresql/backups/base_2026_11_20 target=drill_2026_11_20
2026-11-20 12:50:36 1/6 verify backup files
2026-11-20 12:50:36 2/6 create empty drill cluster on port 5433
2026-11-20 12:50:37 3/6 copy backup and configure recovery
2026-11-20 12:50:38 4/6 start and wait for recovery to finish
2026-11-20 12:50:40 database open for writes after 4 seconds
2026-11-20 12:50:40 5/6 compare data with the reference and run pg_amcheck
2026-11-20 12:50:40 6/6 stop and check data checksums
Bad checksums: 0
2026-11-20 12:50:41 DRILL PASSED in 5 seconds
exit=0The script uses pg_ctlcluster, which works the same as the systemctl commands in Steps 8 and 11. If the target is wrong or WAL is missing, the server stops during recovery, the wait loop sees the cluster go down, and the script exits with status 1 before printing PASSED. The cluster is left in place so you can read its log.
Step 14: Schedule it and keep a drill record
On db1, as a user with sudo. A monthly drill needs a fresh reference and restore point after the newest base backup. This small script saves both:
#!/bin/bash
# drill-reference.sh: save the reference fingerprint and mark the
# matching point in the WAL stream for the next restore drill.
set -euo pipefail
sudo -u postgres psql -q -d shop -f /var/lib/postgresql/drill/fingerprint.sql \
-o /var/lib/postgresql/drill/expected.txt
sudo -u postgres psql -Atc "SELECT pg_create_restore_point('drill_monthly');"Then add two lines to root's crontab with sudo crontab -e: the reference at 02:00 and the drill at 03:00 on the first day of each month, after your nightly base backup has finished.
#m h dom mon dow command
0 2 1 * * /usr/local/bin/drill-reference.sh
0 3 1 * * /usr/local/bin/restore-drill.sh "$(ls -d /var/lib/postgresql/backups/base_* | tail -1)" drill_monthly >> /var/log/restore-drill.log 2>&1We ran the same pair by hand: drill-reference.sh printed the restore point position 0/80319D8, and the drill against drill_monthly ended with DRILL PASSED. Recovery stops at the first restore point with that name after the backup started, which is why the reference must run after the nightly backup. Verify: sudo crontab -l shows both lines, and on the second of the month tail /var/log/restore-drill.log ends with DRILL PASSED. Hook the log or the exit status into your alerting so a failure reaches a person.
For RPO, check the archiver on production. archive_age is roughly how much work you would lose if the server died now:
sudo -u postgres psql -c "SELECT last_archived_wal, last_archived_time, now() - last_archived_time AS archive_age, failed_count FROM pg_stat_archiver;" last_archived_wal | last_archived_time | archive_age | failed_count
--------------------------+------------------------------+-----------------+--------------
000000010000000000000007 | 2026-11-20 12:50:51.98234+00 | 00:00:01.495604 | 0
(1 row)With archive_timeout = 60 the age stays near or under a minute even when the server is quiet. Keep a short record of every drill: the date, the backup and target tested, the checks that passed, the measured RTO, and any problem found. Auditors ask for it, and the RTO trend tells you when backups are outgrowing your restore window.
Step 15: Clean up
On db1, as a user with sudo. The script already drops its cluster. If you followed Steps 7 to 11 by hand, remove the drill cluster; this deletes its data directory and its configuration in /etc/postgresql/18/drill.
sudo pg_dropcluster 18 drill --stop
pg_lsclustersVer Cluster Port Status Owner Data directory Log file
18 main 5432 online postgres /var/lib/postgresql/18/main /var/log/postgresql/postgresql-18-main.logCommon mistakes and how to fix them
FATAL: recovery ended before configured recovery target was reached
Recovery replayed all the WAL it could find but never met the target. We got this by giving the drill a restore point name that does not exist:
LOG: restored log file "000000010000000000000006" from archive
cp: cannot stat '/mnt/wal_archive/000000010000000000000007': No such file or directory
LOG: redo done at 0/62F4628 system usage: CPU: user: 0.01 s, system: 0.01 s, elapsed: 0.13 s
LOG: last completed transaction was at log time 2026-11-20 12:49:37.287163+00
FATAL: recovery ended before configured recovery target was reachedFix: check the spelling of the restore point, that the target time is after the backup ended, and that the archive holds WAL up to the target (Step 6). If a segment is genuinely missing, the target cannot be reached from this backup; take a new base backup today.
pg_checksums: error: cluster must be shut down
You ran pg_checksums --check while the drill cluster was running. Fix: sudo systemctl stop postgresql@18-drill first. Never run it against a running production data directory.
The drill wrote WAL into the production archive
You left archive_mode on in the drill cluster, so after promotion it archived its own timeline 2 files into /mnt/wal_archive. Fix: always set archive_mode = off in the drill configuration (Step 7, or --archive-mode=off with pgBackRest), and if it already happened, remove only the files the drill created, such as 00000002.history and segments starting with 00000002.
Trusting the backup job's exit code alone
A job can finish with status 0 while archiving has been failing for days, or while a dump was written to a disk that later filled. Fix: alert on pg_stat_archiver.failed_count and archive_age, run pg_verifybackup after every backup, and run the full drill at least monthly and after every change to backup tooling, storage or PostgreSQL version.
Practice exercise
- Copy your WAL archive into a test directory, delete one segment from the middle of the copy, and run the Step 6 pg_waldump command against the copy. Which message do you get, and what is the newest point you could still recover to?
- Change the drill to use recovery_target = 'immediate' instead of the restore point. Does the fingerprint still match the one from Step 4? Why or why not?
Quick reference
# Level 1: archiving healthy, checksums on (production)
sudo -u postgres psql -c "SHOW data_checksums;"
sudo -u postgres psql -c "SELECT last_archived_wal, now() - last_archived_time AS archive_age, failed_count FROM pg_stat_archiver;"
# Reference fingerprint and restore point (production)
sudo -u postgres psql -d shop -f /var/lib/postgresql/drill/fingerprint.sql -o /var/lib/postgresql/drill/expected.txt
sudo -u postgres psql -Atc "SELECT pg_create_restore_point('drill_2026_11_20');"
# Level 2: backup files and WAL chain
sudo -u postgres /usr/lib/postgresql/18/bin/pg_verifybackup /var/lib/postgresql/backups/base_2026_11_20
sudo -u postgres /usr/lib/postgresql/18/bin/pg_waldump --path=/mnt/wal_archive --quiet <first_segment> <last_segment>
# Level 3: restore into the drill cluster
sudo pg_createcluster 18 drill --port 5433
sudo -u postgres find /var/lib/postgresql/18/drill -mindepth 1 -delete
sudo -u postgres cp -a /var/lib/postgresql/backups/base_2026_11_20/. /var/lib/postgresql/18/drill/
sudo -u postgres find /var/lib/postgresql/18/drill/pg_wal -mindepth 1 -type f -delete
# write /etc/postgresql/18/drill/conf.d/drill.conf (archive_mode, restore_command, target, action)
sudo -u postgres touch /var/lib/postgresql/18/drill/recovery.signal
sudo systemctl start postgresql@18-drill
sudo -u postgres psql -p 5433 -Atc "SELECT pg_is_in_recovery();"
# Level 4: data correct and uncorrupted
sudo -u postgres psql -p 5433 -d shop -f /var/lib/postgresql/drill/fingerprint.sql -o /var/lib/postgresql/drill/actual.txt
sudo -u postgres diff /var/lib/postgresql/drill/expected.txt /var/lib/postgresql/drill/actual.txt
sudo -u postgres /usr/lib/postgresql/18/bin/pg_amcheck -p 5433 --all --install-missing --heapallindexed --jobs=2
sudo systemctl stop postgresql@18-drill
sudo -u postgres /usr/lib/postgresql/18/bin/pg_checksums --check -D /var/lib/postgresql/18/drill
# Logical dump drill
sudo -u postgres createdb shop_drill
sudo -u postgres pg_restore -d shop_drill --exit-on-error /var/lib/postgresql/backups/shop_2026_11_20.dump
# pgBackRest repository check
sudo -u postgres pgbackrest --stanza=app --output=text --verbose verify
# Whole drill in one go, and cleanup
sudo /usr/local/bin/restore-drill.sh /var/lib/postgresql/backups/base_2026_11_20 drill_2026_11_20
sudo pg_dropcluster 18 drill --stopSummary and what's next
- A backup is only proven when it has been restored and its data checked
- Level 2: pg_verifybackup for base backups, pg_waldump --quiet for the WAL chain, pgbackrest verify for a pgBackRest repository
- Level 3: restore into a separate drill cluster with archive_mode = off and a precise recovery target
- Level 4: compare a saved fingerprint, then run pg_amcheck and pg_checksums on the copy, never load production with them
- Restore pg_dump files into a scratch database with --exit-on-error; pg_restore --list is not a test
- Script the drill, schedule it monthly, alert on failure, and record the measured RTO every time
In Part 23 we move from backups to monitoring and set up logging that helps: log_min_duration_statement, log_line_prefix and auto_explain.