34.4. PostgreSQL Backup and Point-in-Time Recovery

Backups come in two families with different recovery semantics: logical dumps capture content and port easily, while a physical base backup plus an archived write-ahead log reconstruct the server's exact state at any moment between the backup and the last archived segment. This section builds both on db1, using the disposable pgarchive disk as the archive destination, and then proves the combination by destroying the live data directory and recovering to a timestamp chosen in advance - the operation that separates a real recovery plan from a pile of dumps.

34.4.1. Logical Dumps, Global Objects, and Restoring into an Empty Database

A logical dump exports the content of a database - schema, data, grants - as SQL or a custom archive, with no knowledge of physical layout. It is the right tool for small databases, for migrating between servers or versions, and for grabbing one database out of a busy server; it is the wrong tool for continuous protection of a large server, which is what section 34.4.2 addresses. The chapter's workspace holds the artifacts, and the dump runs as postgres while its output lands in john's directory - the redirection happens in john's shell, so the file is owned by john while the database read happens with the server's own account:

$ cd ~/debian-handbook/databases && sudo -u postgres pg_dump -Fc inventory > inventory.dump

The redirection writes the archive; pg_dump itself is silent on success. Confirm the artifact exists and is nontrivial:

$ ls -lh inventory.dump
-rw-rw-r-- 1 john john 31K Nov 26 12:46 inventory.dump

-Fc selects the custom compressed format - not plain SQL but a pg_restore-able archive that can be restored selectively (single tables, single schemas) and in parallel. Plain SQL (the default) is better when the dump must be read by humans or non-PostgreSQL tools.

Option Description
-Fc Custom compressed archive, restored with pg_restore; enables selective and parallel restore
-f <file> Write to the named file instead of standard output
-s Schema only, no data
--no-owner Emit no ownership commands, so a restore into another role does not require the original owner

Dumps are per database, and one class of object deliberately lives outside them: cluster-level globals - roles and their passwords, tablespaces, database-level grants. pg_dumpall covers them:

$ cd ~/debian-handbook/databases && sudo -u postgres pg_dumpall --globals-only > globals.sql

The redirection writes the file; pg_dumpall is silent. The file is plain SQL, so its contents can be checked directly:

$ grep -E "CREATE ROLE (app_owner|app_reader|rewind_user)" globals.sql
CREATE ROLE app_owner;
CREATE ROLE app_reader;

Both application roles are there. A globals dump belongs in every backup rotation - without it, restoring a database dump onto a rebuilt cluster produces tables whose owners do not exist.

Restoring is the proof of any backup, and it always goes into an empty database, never onto the live one. Create the target, load the archive, and check the result - on db1:

$ sudo -u postgres dropdb --if-exists inventory_restore
NOTICE:  database "inventory_restore" does not exist, skipping

dropdb --if-exists makes the step idempotent: the target does not exist yet, so the command prints a NOTICE and succeeds without doing anything. Then create it and load:

$ sudo -u postgres createdb inventory_restore

The command prints nothing on success. The restore itself:

$ sudo -u postgres pg_restore -d inventory_restore < inventory.dump

Also silent on success - pg_restore prints only errors and progress messages when asked. Verify with a count, as the application role would see it:

$ sudo -u postgres psql -d inventory_restore -c "SELECT count(*) FROM app.items;"
 count
-------
  4003
(1 row)

4003 rows - the exact count section 34.3.4 ended with, including after-maintenance. The restored copy is a second, independent instance of the data; when the restore checks pass, remove it with dropdb inventory_restore so it cannot be mistaken for production later.

34.4.2. Physical Base Backups and Write-Ahead Log Archiving

Logical dumps copy content at a moment; continuous protection copies history. PostgreSQL writes every change to the write-ahead log (WAL) before it touches data pages, and WAL is designed to be kept: replay it forward from any consistent starting point and you reconstruct every transaction in order. The two pieces are a base backup - a physical copy of the data directory - and an archive of every WAL segment after it. With both, any point in time between the base backup and the newest archived segment can be reconstructed; the technique is called point-in-time recovery (PITR).

Continuous archiving model

Figure 34.2. One base backup plus an unbroken WAL archive reaches any moment. The archive command copies each completed 16 MB segment to a separate disk as the server finishes it; a restore copies the base back, then replays archived segments up to the chosen target time. The recorded exercise commits one row before the target and one after - only the first survives the replay.

The archive needs its own failure domain, so the lab puts it on db1's second disk. The next command destroys whatever is on /dev/vdb - in the practice guest that is exactly its purpose, but the command pattern must never be run against a disk that holds anything:

$ sudo mkfs.ext4 -q -L pgarchive /dev/vdb

With -q the tool prints only errors, so success is silence and the disk now holds one empty filesystem. Mount it persistently by label:

$ sudo mkdir -p /srv/pgarchive && echo "LABEL=pgarchive /srv/pgarchive ext4 defaults,nofail 0 2" | sudo tee -a /etc/fstab
LABEL=pgarchive /srv/pgarchive ext4 defaults,nofail 0 2

tee -a appends the fstab line and echoes it back - that is the output shown. nofail keeps the host bootable if the archive disk is absent, which is the correct policy for a backup destination (the database must come up even when the archive does not). Then mount and prepare the directories:

$ sudo mount /srv/pgarchive

The mount is silent on success. Then the archive directories, owned by postgres:

$ sudo install -d -o postgres -g postgres /srv/pgarchive/wal /srv/pgarchive/base

Also silent. Check the capacity now dedicated to WAL:

$ df -h /srv/pgarchive
Filesystem      Size  Used Avail Use% Mounted on
/dev/vdb        2.0G   47M  1.8G   3% /srv/pgarchive

2 GB total, 1.8 GB available - small, as lab disks are, but a real number to monitor. Enable archiving on the server, on db1:

$ sudo -u postgres psql -v ON_ERROR_STOP=1 -c "ALTER SYSTEM SET archive_mode = 'on';" -c "ALTER SYSTEM SET archive_command = 'test ! -f /srv/pgarchive/wal/%f && cp %p /srv/pgarchive/wal/%f';" -c "ALTER SYSTEM SET archive_timeout = '60s';"
ALTER SYSTEM
ALTER SYSTEM
ALTER SYSTEM

Three settings, three confirmations. archive_mode = on turns the server into an archiver of its own WAL - it requires a restart, which comes in a moment. archive_command is the server's contract with your storage: it is executed once per completed WAL segment, must exit 0 only on success, and the placeholders %p (source path) and %f (segment name) are filled in by the server. The command shown is the classic guard - refuse to overwrite a segment that is already archived, copy otherwise - and it is only fit for a single-server archive; real deployments ship WAL off-host with rsync or object storage, but the exit-code contract is identical. archive_timeout forces a segment switch every 60 seconds so a quiet server still archives its recent work - without it, the last partial segment (up to 16 MB of committed transactions) might sit unarchived indefinitely.

Restart to activate archive_mode, then force one segment through the pipeline and check the archiver's own scoreboard:

$ sudo pg_ctlcluster 17 main restart

The restart is silent. Then switch WAL deliberately:

$ sudo -u postgres psql -Atc "select pg_switch_wal();"
0/1FC2440

pg_switch_wal() closes the current segment and starts a new one; the return value is the log sequence number (LSN) at the switch boundary. The closed segment now belongs to the archive command. Give it a moment, then read the archiver statistics:

$ sudo -u postgres psql -x -c "SELECT archived_count, failed_count, last_archived_wal FROM pg_stat_archiver;"
-[ RECORD 1 ]-----+-------------------------
archived_count    | 1
failed_count      | 0
last_archived_wal | 000000010000000000000001

One segment archived, none failed, and the segment name decodes as timeline 1 (00000001), log file 0000000000000000, segment 01. Confirm the file itself landed where the contract says:

$ sudo ls -l /srv/pgarchive/wal
total 16384
-rw------- 1 postgres postgres 16777216 Nov 26 12:46 000000010000000000000001

Exactly 16777216 bytes - the WAL segment size - owned by postgres, named as the archiver reported. Archive and statistics agree.

The base backup comes from pg_basebackup, which streams a physical copy of the data directory over a replication connection:

$ sudo -u postgres pg_basebackup -D /srv/pgarchive/base/base1 -Fp -Xs -P -c fast 2>&1 | tail -4
waiting for checkpoint
39811/39811 kB (100%), 0/1 tablespace
39811/39811 kB (100%), 1/1 tablespace

The progress lines are the output; tail -4 keeps the report to its conclusion.

Option Description
-D <dir> Destination directory; must be empty or nonexistent
-Fp Plain format - files as they are on the server, restorable by copying
-Xs Stream WAL needed for consistency during the backup (stream), rather than relying on the archive
-P Print progress
-c fast Force a checkpoint immediately instead of spreading one out

The result is /srv/pgarchive/base/base1 - a data directory frozen at one moment, 39 MB in this lab, consistent to a specific LSN, sitting on the archive disk next to the WAL that continues from it. In a real deployment the base backup goes to another machine; keeping it on the same disk as the archive is a lab convenience and is still a different device from the live data directory.

34.4.3. Retention, Archive Monitoring, and Preventing WAL Exhaustion

An archive with no retention policy eventually fills its disk, and a full archive is not a passive failure: PostgreSQL will not recycle a WAL segment until the archive command has succeeded for it, so a broken archive backs WAL up inside the data directory until the filesystem holding pg_wal fills and the server stops accepting writes. Watch both sides of that mechanism.

Deliberately break the archive to see the failure mode, on db1:

$ sudo -u postgres psql -c "ALTER SYSTEM SET archive_command = 'false';"
ALTER SYSTEM

archive_command = 'false' is the standard "always fail" command - it exits nonzero for every segment. It takes effect for new segments; a reload suffices because the server re-reads the setting between segment attempts:

$ sudo -u postgres psql -Atc "select pg_reload_conf();"
t

pg_reload_conf() asks the server to re-read configuration that does not need a restart; it returns t when the request was sent. Now push a segment through the broken pipeline:

$ sudo -u postgres psql -Atc "select pg_switch_wal();"
0/302C068

The switch itself succeeds. Give the archiver its retry interval, then look at the scoreboard:

$ sudo -u postgres psql -x -c "SELECT archived_count, failed_count, last_failed_wal FROM pg_stat_archiver;"
-[ RECORD 1 ]---+-------------------------
archived_count  | 1
failed_count    | 3
last_failed_wal | 000000020000000000000003

The counters tell the whole story: failed_count has grown from 0 to 3 - the same segment (note the name: the cluster is now on timeline 2 after the PITR exercise ahead in section 34.4.4, segment 03) attempted three times and failed each time. The server will keep retrying, and until one succeeds it retains that segment - and everything after it - in pg_wal. This is the exact signature of a silently full archive destination: failed_count climbing, last_failed_wal stuck or advancing with the disk, and pg_wal growing. Repair the command:

$ sudo -u postgres psql -c "ALTER SYSTEM SET archive_command = 'test ! -f /srv/pgarchive/wal/%f && cp %p /srv/pgarchive/wal/%f';"
ALTER SYSTEM

Reload again, let the retry succeed, and confirm the archive drains:

$ sudo -u postgres psql -Atc "select pg_reload_conf();"
t

Then check that the pending segment made it through:

$ sudo -u postgres psql -x -c "SELECT archived_count, failed_count, last_archived_wal FROM pg_stat_archiver;"
-[ RECORD 1 ]-----+-------------------------
archived_count    | 2
failed_count      | 3
last_archived_wal | 000000020000000000000003

archived_count advanced from 1 to 2 and the once-failing segment name now appears as successfully archived - the pipeline caught up on its own, exactly as it will in production once the destination is repaired or resized. failed_count stays as history; only monitoring clears it.

Three habits keep this from ever becoming an incident. Monitor the scoreboard - pg_stat_archiver's last_archived_wal, last_archived_time, failed_count, and last_failed_time belong in whatever checks Chapter 28 established; a growing failed_count or a last_archived_time more than a few minutes old (with traffic flowing) is an alert, not a footnote. Monitor the data directory's pg_wal - a few segments of slack is normal; sustained growth means archiving (or a replication slot, which pins WAL the same way) is stuck. Apply retention deliberately - delete archived segments only when they are older than your oldest retained base backup, because WAL before that backup's start point is unrestorable; a find /srv/pgarchive/wal -name '0000000*' -mtime +7 -delete-style rule driven from the timestamps of base backups is the usual shape, and the rule must be tested alongside the backups it serves.

34.4.4. Restoring to a Chosen Time or Recovery Point

The exercise that names the technique: commit one row, note a target timestamp, commit another row, then rebuild the cluster to the instant between them. First the marker rows. On db1:

$ sudo -u postgres psql -d inventory -v ON_ERROR_STOP=1 -c "CREATE TABLE app.pitr_log (id integer PRIMARY KEY, note text, changed_at timestamptz DEFAULT clock_timestamp());" -c "INSERT INTO app.pitr_log (id, note) VALUES (1, 'committed before recovery target');" -Atc "SELECT clock_timestamp();"
CREATE TABLE
INSERT 0 1
2026-11-26 12:46:48.556863+00

Row 1 is committed, and clock_timestamp() reports the server's real clock - this is the recovery target; record it. Note that it is taken after the insert's commit, so any transaction that finished before this instant belongs in the restored cluster. Then commit the row that must not survive:

Commit the second row, on db1:

$ sudo -u postgres psql -d inventory -c "INSERT INTO app.pitr_log (id, note) VALUES (2, 'committed after recovery target');"
INSERT 0 1

Force both rows into archived segments, on db1:

$ sudo -u postgres psql -Atc "select pg_switch_wal();"
0/302C128

And look at the state that is about to be discarded, on db1:

$ sudo -u postgres psql -d inventory -c "SELECT * FROM app.pitr_log ORDER BY id;"
 id |               note               |          changed_at           
----+----------------------------------+-------------------------------
  1 | committed before recovery target | 2026-11-26 12:46:48.442103+00
  2 | committed after recovery target  | 2026-11-26 12:46:50.85345+00
(1 row)

Both rows are live on the primary, and the switch has moved them into archived segments (row 1's timestamp, 48.44, precedes the target, 48.55; row 2's, 50.85, follows it). The cluster is now destroyable on purpose.

The restore is a root-shell script because it touches the data directory itself. Save it as ~/debian-handbook/databases/pitr-restore.sh with the recorded target substituted for TARGET:

#!/bin/bash
set -e
TARGET='2026-11-26 12:46:48.556863+00'
pg_ctlcluster 17 main stop
rm -rf /var/lib/postgresql/17/main.old
mv /var/lib/postgresql/17/main /var/lib/postgresql/17/main.old
cp -a /srv/pgarchive/base/base1 /var/lib/postgresql/17/main
chown -R postgres:postgres /var/lib/postgresql/17/main
chmod 700 /var/lib/postgresql/17/main
touch /var/lib/postgresql/17/main/recovery.signal
cat >> /var/lib/postgresql/17/main/postgresql.auto.conf <<EOF
restore_command = 'cp /srv/pgarchive/wal/%f %p'
recovery_target_time = '$TARGET'
recovery_target_action = 'promote'
EOF
pg_ctlcluster 17 main start

Read it as four moves. It stops the cluster and moves the current data directory aside rather than deleting it - if anything is wrong with the restore, the pre-restore state still exists at /var/lib/postgresql/17/main.old and can be moved back. It copies the base backup into place and fixes ownership and mode (the data directory must be postgres-owned, mode 700). It then creates recovery.signal, an empty file whose entire meaning is "start in recovery and read the recovery settings" - this is the PostgreSQL 12+ mechanism that replaced recovery.conf. And it appends three recovery settings to postgresql.auto.conf: restore_command is the mirror of archive_command, telling recovery where to fetch archived WAL (%f segment name, %p destination path); recovery_target_time is the instant recorded above; and recovery_target_action = promote says that when the target is reached, the cluster should leave recovery and accept writes - the alternatives are pause (open read-only for inspection) and shutdown (stop at the target), and pause is the safer first choice on a real recovery. Run it from a root shell, entered with sudo -i - root's ~ is not /home/john, so the script is called by its full path:

# bash /home/john/debian-handbook/databases/pitr-restore.sh

The script prints nothing except any errors; it ends by starting the cluster, which replays WAL from the archive as it comes up. Leave the root shell with exit before the verification steps, which are ordinary commands again. Give the replay a moment, then ask the cluster what it is:

$ sudo -u postgres psql -d inventory -c "SELECT pg_is_in_recovery();"
 pg_is_in_recovery 
-------------------
 f
(1 row)

f - the cluster has reached the target, promoted, and is open for writes. The data decides whether the target meant what you intended:

$ sudo -u postgres psql -d inventory -c "SELECT * FROM app.pitr_log ORDER BY id;"
 id |               note               |          changed_at           
----+----------------------------------+-------------------------------
  1 | committed before recovery target | 2026-11-26 12:46:48.442103+00
(1 row)

Row 1 is present with its original timestamp. Row 2 - committed 1.4 seconds after the target - does not exist and never will: it lives on only in the WAL past the target, in the moved-aside old data directory, and in the archives of any later base backup. The cluster you are now running accepted the base backup's state plus exactly the transactions that committed before the target instant. Two housekeeping notes close the exercise: the restored cluster is on a new timeline (the promotion created one - section 34.5.4 explains timelines), so the old base backup is now historical; take a fresh one against the restored cluster before more work lands. And once the application checks in section 34.4.5 pass, delete main.old - it is the pre-restore cluster, and leaving it around invites confusion.

34.4.5. Checking Roles, Application Data, and Consistency After Restore

A restore is not done when the server is up; it is done when the application's account says the data is right. The checks are the section 34.3.4 pattern with higher stakes. Roles first - the restore replaced the entire cluster, so verify the application accounts still resolve, on db1:

$ sudo -u postgres psql -Atc "SELECT rolname FROM pg_roles WHERE rolname IN ('app_owner','app_reader') ORDER BY rolname;"
app_owner
app_reader

Both roles exist. They came from the base backup - roles, like all cluster-level objects, live inside the data directory that was copied, which is why this restore did not need the globals dump from section 34.4.1. That dump is the piece you need when rebuilding a cluster from logical dumps alone, and a rotation that includes both never depends on either path being perfect.

Application access, as the application's own role:

$ PGPASSWORD=owner-secret psql -h 127.0.0.1 -U app_owner -d inventory -c "SELECT count(*) FROM app.pitr_log;"
 count
-------
     1
(1 row)

The application role connects over the loopback listener with its password, sees exactly the one surviving row, and - because the restore copied the whole data directory - the pg_hba.conf and TLS settings of section 34.2.3 are exactly as they were; nothing about the network path needs reconfiguration after a restore.

Consistency means the restored cluster agrees with what the application was told. Here the ledger is small and human-readable: one row committed before the target, acknowledged to the client, present after the restore; one row committed after the target, also acknowledged, and deliberately absent. In production the same reconciliation is done with application-level ledgers - order numbers, watermark tables, last_updated maxima - compared against what clients recorded as committed. The one check not to skip: the archive now contains WAL from two timelines around this restore, and the next base backup (fresh, from the restored cluster) is what makes the old one safe to expire.