Sub topic 13
Scheduling, retention, encryption, and offsite copies
A backup command that you run by hand protects nothing once you forget to run it. This chapter turns the dump and base-backup commands from earlier chapters into an unattended routine. The routine runs on a schedule, keeps a bounded number of copies, encrypts them, and stores a copy away from the database host.
It assumes you can run pg_dump, pg_restore, pg_basebackup, and WAL archiving as covered earlier. It also assumes you have basic shell scripting skills and a Linux host with cron or systemd.
Decide the schedule from your RPO
Your recovery point objective (RPO) is the most data you can afford to lose. It sets how often each kind of backup must run.
| Backup type | What limits data loss | Typical schedule |
|---|---|---|
| Logical dump (`pg_dump`) | Time since the last dump | Nightly, or more often for small databases |
| Base backup (`pg_basebackup`) | Not the limit, because WAL fills the gap | Weekly or nightly |
| Continuous WAL archiving | Time since the last archived WAL segment | Continuous, bounded by `archive_timeout` |
A nightly dump alone means up to 24 hours of lost data. Base backups plus WAL archiving shrink that to minutes. The base backup frequency then controls recovery time (RTO), because less WAL has to be replayed after restoring a newer base backup.
Schedule backups for a quiet period. A dump holds a snapshot transaction open for its whole run. On a busy database, a long dump delays cleanup of dead rows by autovacuum. Parallel dumps (-j) shorten that window, but they use more connections and more I/O.
A complete backup script
The script below dumps one database, checks that the dump is readable, encrypts it, uploads it, and prunes old local files. Save it as /usr/local/bin/pg_backup.sh.
#!/usr/bin/env bash
set -euo pipefail
umask 077
DB=mydb
DEST=/var/backups/postgres
BUCKET=s3://example-backups/postgres/mydb
[email protected]
KEEP_DAYS=7
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
TMP="$DEST/${DB}_${STAMP}.dump.partial"
FILE="$DEST/${DB}_${STAMP}.dump.gpg"
mkdir -p "$DEST"
trap 'rm -f "$TMP"' EXIT
pg_dump -U postgres -Fc -f "$TMP" "$DB"
pg_restore --list "$TMP" > /dev/null
gpg --batch --yes --trust-model always \
--encrypt --recipient "$RECIPIENT" --output "$FILE" "$TMP"
aws s3 cp "$FILE" "$BUCKET/" --only-show-errors
find "$DEST" -name "${DB}_*.dump.gpg" -mtime +"$KEEP_DAYS" -deleteSeveral details in this script matter:
set -euo pipefailstops the script at the first failure. The prune step comes last on purpose. If the dump or upload fails, the script exits before deleting anything, so a run of failed backups cannot erase the last good ones.umask 077makes every file readable only by its owner.- The dump is written to a
.partialname and only the encrypted result gets the final name. A half-written file is never mistaken for a finished backup. pg_restore --listis the cheap readability check from the verification chapter. It does not replace a real test restore.--trust-model alwayslets gpg encrypt without an interactive trust prompt. Use it only with a public key you imported yourself.
Run the script as the postgres operating system user so peer authentication works without a password. If you must connect over TCP, put credentials in a ~/.pgpass file with mode 0600. Never put a password in the script or on a command line, where ps can show it.
Scheduling with cron
A file in /etc/cron.d names the user to run as.
[email protected]
30 2 * * * postgres /usr/local/bin/pg_backup.sh >> /var/log/pg_backup.log 2>&1Cron mails any output to MAILTO, but only if the host can send mail. Do not rely on that alone. A silent failure is the worst case, because nobody notices until a restore is needed. Add an external check. Either ping a dead-man's-switch service after a successful run, or alert when the newest object in the bucket is older than 26 hours.
A literal % in a crontab line is treated as a newline, so escape it as \% if a command uses date +%Y. Keeping the logic in a script avoids the problem.
A systemd timer is an alternative to cron. It has two advantages: Persistent=true runs a missed job after the host was down, and the journal keeps the output and exit status.
Retention
Retention is the rule for how long each backup is kept. The usual shape is a tiered one, such as 7 daily, 4 weekly, and 6 monthly copies. Pick the numbers from two questions: how far back could you discover a problem, and how much storage you can pay for. Silent corruption or an accidental DELETE may go unnoticed for weeks, so a week of dailies is often too short.
Logical dumps are independent files, so you can delete any of them freely. Physical backups are not independent:
- A base backup is only usable together with the WAL from its start to its end. For point-in-time recovery, you need all WAL from the base backup forward to the recovery target.
- Delete a base backup and its WAL together. Never delete WAL that the oldest base backup you keep still needs.
pg_archivecleanupremoves WAL older than a given segment. When you point it at a.backuphistory file, it treats that file's start position as the cutoff.
pg_archivecleanup -d /mnt/archive 00000001000000000000001A.00000028.backupThe .backup file appears in the archive each time a base backup finishes. Pass the one belonging to the oldest base backup you still keep.
Watching the WAL archive
A failing archive_command does not stop the database right away. PostgreSQL keeps retrying and keeps the unarchived segments in pg_wal, and the disk slowly fills. Check the archiver's own counters.
SELECT archived_count, last_archived_time,
failed_count, last_failed_time
FROM pg_stat_archiver;Alert when last_failed_time is later than last_archived_time, or when last_archived_time is older than your RPO allows.
Encryption
pg_dump and pg_basebackup do not encrypt their output. Anyone who reads the file reads your data, including password hashes stored in pg_authid for a globals dump. Encrypt every backup before it leaves the host.
Public-key encryption suits backups. The server holds only the public key, so a compromised server cannot decrypt old backups. Keep the private key somewhere separate, such as an offline vault, and keep at least two copies of it. A backup you cannot decrypt is the same as no backup.
To restore from the script above, decrypt first.
gpg --decrypt mydb_20261127T023000Z.dump.gpg > mydb.dump
createdb -U postgres mydb_restored
pg_restore -U postgres -d mydb_restored -j 4 --no-owner mydb.dumpThe decrypted file goes to disk because parallel restore (-j) needs a seekable file. It cannot read from a pipe. Without -j, you can pipe gpg --decrypt straight into pg_restore and avoid writing plaintext.
Encrypt after compressing, not before. Encrypted data looks random and does not compress. The custom format already compresses, so the order in the script is right.
Also protect data in transit and at rest in the destination. Cloud tools use TLS by default. Turn on server-side encryption on the bucket as a second layer, but treat it as a complement. With client-side gpg, the storage provider never sees plaintext.
Offsite copies
A backup stored on the database host is lost together with the host in a disk failure, a fire, a ransomware attack, or a mistaken rm -rf. The common rule is 3-2-1: three copies, on two kinds of storage, with one copy offsite.
Options for the offsite copy:
- Object storage such as Amazon S3, using
aws s3 cporrclone. - A second server reached with
rsyncorscpover SSH. - A backup host that pulls files, so the database host holds no credentials able to delete them.
Protect the offsite copy from the database host itself. If the host's credentials can delete backups, an attacker who controls the host can delete them. Give the upload credentials write-only access. Then enable bucket versioning or object lock, so deleted or overwritten objects can be recovered for a set period. A bucket lifecycle rule can expire old objects and move older ones to cheaper storage, which implements your retention tiers without any script.
Common mistakes
- Pruning before confirming success. Always delete old backups after the new one is verified and uploaded.
- Keeping the private key only on the database host. If the host is lost, the encrypted backups are unreadable.
- Never testing a restore. Schedule a periodic test restore of the newest offsite copy, including the decryption step.
- Ignoring globals. Run
pg_dumpall --globals-onlyon a schedule too, or roles will be missing after a rebuild. - Backups that grow without alerts. A sudden change in backup size, up or down, often signals a problem. Log the file size on every run.
When this script grows to cover many databases, base backups, WAL, parallelism, and encrypted repositories, a purpose-built tool such as pgBackRest or Barman handles retention and expiry for you. The next chapter compares them.
Exercise
Your retention policy keeps the two newest base backups. The oldest one you keep has the history file 00000001000000000000001A.00000028.backup. Which WAL segments can you delete from the archive, and which command does it?
Show answer
You can delete every WAL segment older than the start position recorded in that history file, meaning segments before 00000001000000000000001A. The command is pg_archivecleanup /mnt/archive 00000001000000000000001A.00000028.backup. Segments from that point forward must stay, because the oldest kept base backup needs them for recovery.
Exercise
A teammate changes the script so that the find ... -delete line runs first, before pg_dump. Why is this risky, and what does the original order protect against?
Show answer
If the dump later fails, the cleanup has already removed old backups, so fewer good copies remain, and repeated failures can leave none. With the original order, set -e stops the script on any failed step, so pruning only happens after a new backup was created, checked, encrypted, and uploaded.