Sub topic 13
Scheduling, Retention, Encryption, and Offsite Copies
Assume you know basic SQL, psql, PostgreSQL roles, and Linux command-line tools. This chapter focuses on turning a backup command into a recovery process that runs regularly and protects copies from local failures.
Schedule backups with a controlled job
A backup is useful only if it runs consistently and produces a usable file. Schedule it with cron, a systemd timer, or an operations platform. The scheduler should run a script that:
- Uses a lock so two copies cannot run at once.
- Writes logs and returns a failure status.
- Sets restrictive file permissions.
- Creates a timestamped output file.
- Removes files older than the retention period.
- Uploads a copy to separate storage.
This example creates a custom-format logical dump and keeps local files for 14 days:
#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
backup_dir=/srv/pg-backups
database=mydb
stamp=$(date -u +%Y%m%dT%H%M%SZ)
output="$backup_dir/${database}_${stamp}.dump"
mkdir -p "$backup_dir"
exec 9>"$backup_dir/.backup.lock"
flock -n 9 || {
echo "Another backup is running"
exit 0
}
pg_dump --format=custom --dbname="$database" --file="$output"
sha256sum "$output" > "$output.sha256"
find "$backup_dir" -type f \
\( -name "${database}_*.dump" -o -name "${database}_*.dump.sha256" \) \
-mtime +14 -delete
echo "Created $output"A cron entry runs this script every day at 02:15 UTC:
15 2 * * * /usr/local/sbin/backup-mydb >> /var/log/backup-mydb.log 2>&1The schedule must leave enough time for a backup to finish before the next one starts. Monitor duration and failure output rather than assuming that a successful process start means a successful backup.
Choose retention deliberately
Retention is the length of time that backup copies remain available. It should reflect the period for which you may need to investigate corruption, accidental deletion, or an unnoticed security incident.
A simple policy might keep:
| Copy type | Example retention | Purpose |
|---|---|---|
| Daily logical dumps | 14 days | Recent object-level recovery |
| Weekly full copies | 8 weeks | Recovery from older mistakes |
| Monthly copies | 12 months | Long-term records |
Retention should account for recovery point objective (RPO), which is the maximum acceptable data loss. If the business can lose only one hour of changes, a daily dump cannot meet that goal. Continuous WAL archiving or frequent backups are required.
Encrypt and copy backups off site
Encryption protects a backup if its storage or transfer path is exposed. Use client-side encryption when the storage provider should not receive plaintext. Store the decryption key separately from the backup location, preferably in a managed secret system with restricted access.
For example, age can encrypt a dump with a recipient’s public key:
pg_dump --format=custom --dbname=mydb \
| age --encrypt --recipient age1examplepublicrecipient \
> /srv/pg-backups/mydb_20261127T021500Z.dump.ageThe matching private key is required to restore it:
age --decrypt --identity /secure/keys/backup-recovery-key \
/srv/pg-backups/mydb_20261127T021500Z.dump.age \
| pg_restore --dbname=mydb_restored --no-ownerUpload encrypted files to a different account, region, or provider. Configure object storage with restricted credentials, versioning where appropriate, and server-side encryption as an additional layer. Test that the restore host can retrieve both the backup and its decryption key.
flowchart TD
A[Scheduled job] --> B[Acquire lock]
B --> C[Create backup]
C --> D[Encrypt and checksum]
D --> E[Upload off site]
E --> F[Verify upload]
F --> G[Apply retention policy]
G --> H[Alert on failure]Use backup management tools when needed
pgBackRest and Barman automate many details of physical backups, WAL archiving, retention, encryption, repositories, and verification. They are often safer than maintaining a growing collection of shell scripts. Choose one when you need multiple PostgreSQL servers, point-in-time recovery, compression policies, or centralized monitoring.
Regardless of the tool, document the retention policy, encryption-key location, restore procedure, and person responsible for responding to failures.
Exercise
A team stores seven nightly dumps on the same PostgreSQL server and wants protection from disk failure. What should it change first?
Show answer
It should copy encrypted backups to storage outside the server, then test that the copies can be downloaded and restored. Keeping more local files does not protect against loss of the server.