Sub topic 1
What point-in-time recovery gives you
Prerequisites
This chapter assumes you can start and stop PostgreSQL, edit postgresql.conf, and run commands as the postgres user on Linux. You should also know the basic layout of the data directory.
Point-in-time recovery (PITR) rebuilds a database as it existed at a chosen moment, such as 14:30 yesterday. It needs a base backup, which is a full physical copy of the data directory, plus every archived write-ahead log (WAL) file written after that copy.
How the write-ahead log makes replay possible
PostgreSQL writes each change to the WAL before it changes the data files. The WAL is split into segment files, usually 16 MB each. Because the log records changes in order, replaying it on top of a base backup recreates the database at any point the log covers.
Turning on continuous WAL archiving
Set these parameters in postgresql.conf. Changing archive_mode requires a server restart.
# postgresql.conf
wal_level = replica
archive_mode = on
archive_command = 'test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f'
archive_timeout = 300archive_timeout forces a segment switch at least every 300 seconds, so quiet databases still produce archived WAL.
Making archive_command safe
PostgreSQL decides whether a segment was archived by the command's exit status. A zero exit means success. If the command fails, PostgreSQL keeps the segment in pg_wal and retries. The test ! -f check refuses to overwrite an existing file, which protects the archive from accidental changes.
Taking a base backup with pg_basebackup
pg_basebackup -h localhost -U replicator -D /backups/base/20261127 -Fp -X stream -c fast -P-Fp writes plain files. -X stream copies the WAL generated during the backup, so the copy is consistent. -c fast requests an immediate checkpoint, and -P shows progress. The replicator role needs the REPLICATION privilege.
Exercise
If archive_command fails for two hours, what happens to the WAL segments created in that period, and what can you recover?
Show answer
PostgreSQL keeps those segments in pg_wal and retries the command. They are not archived during the failure. Recovery cannot replay past the gap, so you can only restore to a time before the failure began or after archiving resumed, and the segments may fill the disk if the outage lasts long.