DEV Community

Mango Developer
Mango Developer

Posted on Originally published at mangodeveloper.com

How to Automate Database Backups: The 2 AM Phone Call You'll Never Get

The first time I got the "we lost prod" phone call, it was 3 AM on a Tuesday. Someone had run DROP TABLE users against the production database - wrong terminal, wrong tab, you know the story. The Postgres backups were running. They had been running for two years. They'd never been tested. When we tried to restore, we discovered the nightly pg_dump had been silently failing for six weeks because the dump user's password had expired. We had zero usable backups. We rebuilt the table from a stale dev export and a week of application logs. It took 19 hours.

That's the lesson this article exists to teach: a backup you haven't restored is a hypothesis, not a backup. The automated backup itself is the easy part - it's 30 lines of bash or one Ansible role. The hard part, the part that actually saves you at 3 AM, is the architecture around it: what type of backup for what workload, where the copies live, how often you test, how you alert on silent failures, and what your RPO/RTO actually are. This article walks through the full stack, from pg_dump basics to a tested, encrypted, off-site, monitored, restore-verified backup pipeline.

This is the article I wish I'd had before someone dropped that table.

What "Database Backup" Actually Means

A database backup is one of three things, and conflating them gets people fired:

Type What it is Speed Size Restores
Logical SQL dump of schema + data Slow to back up, slow to restore Small (compressed) Any version, any OS
Physical Copy of data files Fast Large Same major version, same arch
PITR WAL/binlog stream + base backup Continuous Medium Point-in-time, seconds of RPO

Logical backups (pg_dump, mysqldump, mongodump) are the simplest: connect to the DB, dump SQL or BSON, write to a file. They're portable across versions and architectures, work for migrations, and are easy to inspect. They're also slow - a 500 GB Postgres database takes 4-8 hours to dump and 8-12 hours to restore. Use them for small databases (<50 GB) and as a secondary "human-readable" backup.

Physical backups (pgBackRest, Percona XtraBackup, file-level snapshots) copy the data files directly. Much faster - a 500 GB physical backup takes 30-60 minutes, restore is similar. They're version-locked: a Postgres 14 physical backup restores only to Postgres 14.x. Use them for medium-to-large databases where logical backup is too slow.

Point-in-time recovery (PITR) streams the database's WAL (Postgres) or binlog (MySQL) continuously to a backup server, plus a periodic base backup. Restore to any second. RPO (Recovery Point Objective - how much data you can lose) of seconds to minutes. RTO (Recovery Time Objective - how long to restore) of minutes to hours. This is the gold standard for production databases; everything else is a fallback.

A real backup strategy layers all three: PITR for fast point-in-time recovery, daily physical backups for "restore to this morning," weekly logical backups for portability and cross-version migration, and quarterly restore tests to prove it all works.

Prerequisites

  • A database you care about. Could be Postgres, MySQL, MongoDB, SQLite, or any of a dozen others.
  • A backup destination with at least 2x your database size in free space, ideally off-site.
  • A user with backup privileges (pg_dump needs SELECT on all tables; physical backups need filesystem access to the data directory).
  • A monitoring channel (Slack, email, PagerDuty) for backup success/failure alerts.
  • A test environment where you can practice restores. If you've never restored a backup, you don't have a backup.
  • A written RPO/RTO. "We can lose 1 hour of data and be back online in 4 hours" is a target. "We need backups" is not.

For this article I'll cover Postgres (the most common in modern stacks), MySQL/MariaDB, and MongoDB. SQLite gets a section at the end. The principles transfer to anything.

Postgres: pg_dump for Logical Backups

pg_dump is the Swiss Army knife of Postgres backups. It connects to the DB, dumps schema and data as SQL (or a custom binary format), and writes to stdout or a file.

BashCopy

Enter fullscreen mode Exit fullscreen mode

Basic dump, custom format (compressed, parallelizable)

pg_dump -Fc -h localhost -U backup_user -d myapp -f /backups/myapp_$(date +%Y%m%d_%H%M%S).dump

Plain SQL (human-readable, slow to restore)

pg_dump -h localhost -U backup_user -d myapp -f /backups/myapp_$(date +%Y%m%d_%H%M%S).sql

Dump all databases (use pg_dumpall for globals + per-DB pg_dump for data)

pg_dumpall -h localhost -U backup_user --globals-only -f /backups/globals_$(date +%Y%m%d).sql

Enter fullscreen mode Exit fullscreen mode

-Fc is the custom format - compressed, supports parallel restore, and is what you want 95% of the time. Plain SQL (-f file.sql) is human-readable but 3-5x slower to restore and doesn't support parallel restore.

For automation, here's a wrapper script that handles the common failure modes:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

!/usr/bin/env bash

/usr/local/bin/pg_backup.sh

set -euo pipefail

DB_NAME="${DB_NAME:-myapp}"
DB_HOST="${DB_HOST:-localhost}"
DB_USER="${DB_USER:-backup_user}"
BACKUP_DIR="${BACKUP_DIR:-/var/backups/postgres}"
RETENTION_DAYS="${RETENTION_DAYS:-14}"
SLACK_WEBHOOK="${SLACK_WEBHOOK:-}"

mkdir -p "$BACKUP_DIR"
TS=$(date +%Y%m%d_%H%M%S)
OUT="$BACKUP_DIR/${DB_NAME}_${TS}.dump"
LOG="/var/log/pg_backup.log"

Use .pgpass for credentials, never inline passwords

export PGPASSFILE="/etc/postgresql/backup.pass"

if pg_dump -Fc -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -f "$OUT" 2>>"$LOG"; then
SIZE=$(stat -c%s "$OUT")
SHA=$(sha256sum "$OUT" | awk '{print $1}')
echo "$(date -Iseconds) OK db=$DB_NAME file=$OUT size=$SIZE sha=$SHA" >> "$LOG"

# Prune old backups
find "$BACKUP_DIR" -name "${DB_NAME}_*.dump" -mtime +${RETENTION_DAYS} -delete

# Heartbeat to monitoring
if [[ -n "$SLACK_WEBHOOK" ]]; then
curl -fsS -X POST -H 'Content-Type: application/json' \
-d "{\"text\":\"✅ pg_dump OK: ${DB_NAME} ($((SIZE/1024/1024))MB)\"}" \
"$SLACK_WEBHOOK" || true
fi
else
echo "$(date -Iseconds) FAIL db=$DB_NAME" >> "$LOG"
if [[ -n "$SLACK_WEBHOOK" ]]; then
curl -fsS -X POST -H 'Content-Type: application/json' \
-d "{\"text\":\"🚨 pg_dump FAILED: ${DB_NAME} - check $LOG\"}" \
"$SLACK_WEBHOOK" || true
fi
exit 1
fi

Enter fullscreen mode Exit fullscreen mode


markdown

Two details matter. First, set -euo pipefail makes the script fail loudly on any error - without it, a pg_dump failure would silently produce an empty file and the script would exit 0. Second, .pgpass for credentials instead of inline passwords - PGPASSWORD=... shows up in ps and shell history; .pgpass (chmod 600) does not.

pg_dumpall --globals-only captures roles, tablespaces, and cluster config - pg_dump doesn't. Run it daily; without globals, restoring users and permissions after a cluster loss is a pain.

Postgres: pgBackRest for Physical + PITR

pg_dump is fine for small databases. For anything >50 GB or anything where RPO < 24 hours, you want pgBackRest. It does physical backups (full, incremental, differential), WAL archiving for PITR, parallel processing, compression, and S3-compatible storage - all in one tool.

BashCopy

Enter fullscreen mode Exit fullscreen mode


conf

Install

sudo apt install pgbackrest

Configure /etc/pgbackrest.conf

[db]
pg1-path=/var/lib/postgresql/15/main
pg1-port=5432
pg1-user=postgres
pg1-host=localhost

[global]
repo1-path=/var/lib/pgbackrest
repo1-retention-full=4
repo1-retention-diff=4
repo1-retention-incr=30
repo1-bundle=y
repo1-cipher-type=aes-256-cbc
repo1-cipher-pass=$(openssl rand -base64 32)
process-max=4
log-level-console=info
log-level-file=debug
compress-type=lz4

For S3 backend instead of local:

repo1-type=s3

repo1-s3-endpoint=s3.us-east-1.amazonaws.com

repo1-s3-bucket=my-pgbackrest-repo

repo1-s3-region=us-east-1

repo1-s3-key=AKIA...

repo1-s3-key-secret=...

Enter fullscreen mode Exit fullscreen mode


plaintext

Enable WAL archiving in Postgres (postgresql.conf):

CodeCopy

Enter fullscreen mode Exit fullscreen mode


conf
archive_mode = on
archive_command = 'pgbackrest --stanza=db archive-push %p'
wal_level = replica

Enter fullscreen mode Exit fullscreen mode


plaintext

Initialize the stanza and run the first backup:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo -u postgres pgbackrest --stanza=db stanza-create
sudo -u postgres pgbackrest --stanza=db --type=full backup

Schedule via cron or systemd:

Daily incremental, weekly differential, monthly full

0 2 * * * postgres pgbackrest --stanza=db --type=inc backup
0 3 * * 0 postgres pgbackrest --stanza=db --type=diff backup
0 4 1 * * postgres pgbackrest --stanza=db --type=full backup

Enter fullscreen mode Exit fullscreen mode


plaintext

PITR restore example - "restore to 2024-03-15 14:30:00":

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

Stop Postgres

sudo systemctl stop postgresql

Move the existing data dir aside

sudo mv /var/lib/postgresql/15/main /var/lib/postgresql/15/main.broken

Restore

sudo -u postgres pgbackrest --stanza=db \
--type=time --target="2024-03-15 14:30:00" \
--target-action=promote restore

Start Postgres - it will replay WAL up to the target time and stop

sudo systemctl start postgresql

Enter fullscreen mode Exit fullscreen mode


markdown

pgBackRest replays WAL up to the target timestamp, then promotes (makes the DB writable). --target-action=pause instead leaves the DB in recovery mode so you can verify before promoting. Always use pause first; verify data; then pg_ctl promote manually. Promoting too early means you can't roll back.

MySQL: mysqldump and Percona XtraBackup

mysqldump is MySQL's logical backup tool. Same trade-offs as pg_dump: portable, slow, fine for small DBs.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

Single-transaction dump (consistent snapshot, doesn't lock tables)

mysqldump --single-transaction --quick --routines --triggers --events \
--set-gtid-purged=OFF \
-h localhost -u backup_user -p"$MYSQL_PWD" myapp | gzip > /backups/myapp_$(date +%Y%m%d).sql.gz

All databases

mysqldump --single-transaction --all-databases ... | gzip > /backups/all_$(date +%Y%m%d).sql.gz

Enter fullscreen mode Exit fullscreen mode


plaintext

--single-transaction is the magic flag for InnoDB - it dumps from a consistent snapshot without locking tables. Without it, mysqldump locks each table while dumping, which is unusable on a production DB. --quick prevents buffering the whole dump in memory (matters for large DBs).

For physical backups with PITR, Percona XtraBackup is the standard:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

Install

sudo apt install percona-xtrabackup-80

Full backup

xtrabackup --backup --target-dir=/backups/full_$(date +%Y%m%d) \
--user=backup_user --password="$MYSQL_PWD"

Prepare the backup (apply redo logs)

xtrabackup --prepare --target-dir=/backups/full_$(date +%Y%m%d)

Incremental backup

xtrabackup --backup --target-dir=/backups/inc_$(date +%Y%m%d_%H%M) \
--incremental-basedir=/backups/full_$(date +%Y%m%d) \
--user=backup_user --password="$MYSQL_PWD"

Enter fullscreen mode Exit fullscreen mode


plaintext

For PITR, enable binlog streaming to a remote location. The pattern: a daily full XtraBackup + continuous binlog streaming via mysqlbinlog --read-from-remote-server --raw to a backup server. Restore is: restore the full backup, replay binlogs to the target timestamp.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

Stream binlogs to backup server

mysqlbinlog --read-from-remote-server --host=localhost --raw \
--stop-never --stop-never-slave-server-id=99999 \
--user=repl --password="$REPL_PWD" \
mysql-bin.000123

Enter fullscreen mode Exit fullscreen mode


markdown

The --stop-never flag keeps the stream open, picking up new binlogs as they're written. This gives you RPO of seconds - you have every transaction up to the moment of failure.

MongoDB: mongodump and oplog

mongodump produces BSON dumps:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
mongodump --uri="mongodb://backup_user:$MONGO_PWD@localhost:27017" \
--db=myapp --out=/backups/mongo_$(date +%Y%m%d_%H%M%S) \
--gzip --numParallelCollections=4

Restore

mongorestore --uri="mongodb://localhost:27017" \
--gzip --drop /backups/mongo_20240315_020000/

Enter fullscreen mode Exit fullscreen mode


plaintext

For PITR on MongoDB, the pattern is continuous oplog backup. MongoDB's oplog is a capped collection of recent operations; you stream it to a backup server and replay on restore:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

Stream oplog continuously (run as a service)

while true; do
mongodump --uri="mongodb://..." \
--collection=oplog.rs --db=local \
--query='{ts:{$gte:Timestamp(1710460800,1)}}' \
--out=/backups/oplog_$(date +%Y%m%d_%H%M%S)
sleep 60
done

Enter fullscreen mode Exit fullscreen mode


markdown

For production MongoDB, the better path is MongoDB Atlas Cloud Backup or Percona Backup for MongoDB - both handle oplog streaming, point-in-time restores, and retention automatically. Hand-rolling MongoDB PITR is fragile; the managed tools are worth the cost.

Scheduling: systemd Timers Over Cron

Cron is fine for "run this daily." systemd timers are better for everything else: they support dependencies (run after the network is up), they have native logging (journalctl), they handle missed runs (Persistent=true runs the missed job on boot), and they don't pile up if a job runs long.

iniCopy

Enter fullscreen mode Exit fullscreen mode


systemd

/etc/systemd/system/pg-backup.service

[Unit]
Description=PostgreSQL logical backup
After=postgresql.service
Requires=postgresql.service

[Service]
Type=oneshot
User=postgres
EnvironmentFile=/etc/postgresql/backup.env
ExecStart=/usr/local/bin/pg_backup.sh
ExecStopPost=/usr/local/bin/notify_backup_result.sh %i

Enter fullscreen mode Exit fullscreen mode


plaintext

iniCopy

Enter fullscreen mode Exit fullscreen mode


systemd

/etc/systemd/system/pg-backup.timer

[Unit]
Description=Run PostgreSQL backup daily at 2 AM

[Timer]
OnCalendar=--* 02:00:00
Persistent=true
RandomizedDelaySec=300

[Install]
WantedBy=timers.target

Enter fullscreen mode Exit fullscreen mode


plaintext

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo systemctl enable --now pg-backup.timer
systemctl list-timers pg-backup.timer
journalctl -u pg-backup.service -f # watch live

Enter fullscreen mode Exit fullscreen mode


markdown

RandomizedDelaySec=300 adds up to 5 minutes of jitter, which prevents the "every backup job in the fleet fires at exactly 02:00:00" thundering herd. Persistent=true means if the machine was off at 2 AM, the job runs on next boot. Cron has neither of these.

Off-Site: Don't Keep All Backups in One Place

A backup that lives on the same machine as the database dies when the machine dies. Off-site copy is non-optional. Three patterns:

Restic to B2/S3 (covered in another article in this series - but the pattern):

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
restic -r b2:my-bucket:db-backups backup /var/backups/postgres/
restic -r b2:my-bucket:db-backups forget --keep-daily 7 --keep-weekly 4 --keep-monthly 12 --prune

Enter fullscreen mode Exit fullscreen mode


markdown

pgBackRest direct to S3 (skip the local copy entirely):

iniCopy

Enter fullscreen mode Exit fullscreen mode


properties
repo1-type=s3
repo1-s3-endpoint=s3.us-east-1.amazonaws.com
repo1-s3-bucket=my-db-backups

Enter fullscreen mode Exit fullscreen mode


markdown

Rclone for any cloud:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
rclone sync /var/backups/postgres/ b2:my-bucket/db-backups/ --transfers 4 --checkers 8

Enter fullscreen mode Exit fullscreen mode


markdown

The 3-2-1 rule: 3 copies of the data, on 2 different media, with 1 off-site. For databases, that means: live data + local backup + off-site backup. If the live data and local backup are on the same physical host (a VM with a local disk for backups), you have 2 copies on 1 medium - not enough. Either back up to a separate host, or use a cloud target.

Encryption

If your backups contain user data (and they do), they must be encrypted at rest. Two layers:

Transport-layer: S3 / B2 / GCS all support TLS in transit. Use HTTPS endpoints, never HTTP.

At-rest encryption:

  • pgBackRest has built-in AES-256-CBC encryption (repo1-cipher-type=aes-256-cbc).
  • For files (pg_dump output, mongodump output), use age or gpg:
BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

age (modern, simple)

age -r age1ql3z7hjy54pw3hyzm5xc... -o backup.dump.age backup.dump
age -d -i key.txt backup.dump.age > backup.dump

gpg (legacy, everywhere)

gpg --symmetric --cipher-algo AES256 backup.dump
gpg --decrypt backup.dump.gpg > backup.dump

Enter fullscreen mode Exit fullscreen mode


markdown

The encryption key must NOT live on the database server. If the DB is compromised and the key is sitting next to the backups, the attacker gets everything. Store keys in a separate secrets manager (HashiCorp Vault, AWS KMS, AWS Secrets Manager, 1Password with the CLI), and have the restore procedure fetch the key separately.

A pattern I use: a small "restore VM" with the age private key on it, in a different AWS account than the database. To restore, you copy the encrypted backup from S3 to the restore VM, decrypt locally, and apply. The database server never sees the private key.

Restore Testing: The Backup You Can Actually Use

This is the part most teams skip. A backup you haven't restored is a hypothesis. Automate restore testing:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

!/usr/bin/env bash

/usr/local/bin/test_restore.sh

set -euo pipefail

BACKUP_FILE="${1:-$(ls -t /var/backups/postgres/myapp_*.dump | head -1)}"
TEST_DB="myapp_restore_test"

echo "$(date -Iseconds) Testing restore from $BACKUP_FILE"

Drop and recreate the test DB

sudo -u postgres dropdb --if-exists "$TEST_DB"
sudo -u postgres createdb "$TEST_DB"

Restore

if sudo -u postgres pg_restore -d "$TEST_DB" --no-owner --no-privileges -j 4 "$BACKUP_FILE"; then
# Verify: count rows in critical tables
EXPECTED_USERS=$(sudo -u postgres psql -d myapp -t -c "SELECT count() FROM users")
ACTUAL_USERS=$(sudo -u postgres psql -d "$TEST_DB" -t -c "SELECT count(
) FROM users")

if [[ "$EXPECTED_USERS" == "$ACTUAL_USERS" ]]; then
echo "$(date -Iseconds) RESTORE OK users=$ACTUAL_USERS"
sudo -u postgres dropdb "$TEST_DB"
exit 0
else
echo "$(date -Iseconds) RESTORE MISMATCH expected=$EXPECTED_USERS actual=$ACTUAL_USERS"
exit 1
fi
else
echo "$(date -Iseconds) RESTORE FAILED"
exit 1
fi

Enter fullscreen mode Exit fullscreen mode


plaintext

Schedule weekly:

iniCopy

Enter fullscreen mode Exit fullscreen mode


systemd

/etc/systemd/system/restore-test.timer

[Timer]
OnCalendar=weekly
Persistent=true

Enter fullscreen mode Exit fullscreen mode


markdown

Alert if restore test fails - that's the only signal that catches "backups are running but unusable" before you need them. The two failure modes this catches: corruption (the backup file is broken) and schema drift (the backup can't restore because the schema changed and the dump is from before the migration).

For physical backups, the restore test should restore to a separate host (a fresh VM or container) and run smoke tests against the restored DB. This catches "the backup works on the original host but not on a clean host" issues that file-level restores sometimes have.

Monitoring: Catching Silent Failures

Silent failure is the killer. The backup job ran, exit 0, the file exists, but the file is corrupt or empty. Monitoring needs to check:

  1. Did the job run? Heartbeat to healthchecks.io or equivalent - if no heartbeat in 25 hours, page.
  2. Did the file get written? Check file exists and size > 0.
  3. Is the file recent? mtime within last 24h.
  4. Is the file growing? Compare today's size to yesterday's - a sudden 90% drop means the DB lost data or the dump is incomplete.
  5. Can the file be restored? Weekly restore test.
BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

healthchecks.io heartbeat

curl -fsS --retry 3 https://hc-ping.com//$?

File checks (run hourly)

LATEST=$(ls -t /var/backups/postgres/myapp_*.dump | head -1)
SIZE=$(stat -c%s "$LATEST")
MTIME=$(stat -c%Y "$LATEST")
NOW=$(date +%s)
AGE=$((NOW - MTIME))

if [[ $AGE -gt 90000 ]]; then # > 25 hours
echo "BACKUP STALE: $LATEST is $AGE seconds old" >&2
exit 1
fi

if [[ $SIZE -lt 1024 ]]; then
echo "BACKUP TOO SMALL: $LATEST is $SIZE bytes" >&2
exit 1
fi

Enter fullscreen mode Exit fullscreen mode


markdown

Wire these into Prometheus with the node_exporter textfile collector, or just shell out to a webhook. The point is: alert on absence, alert on size anomaly, alert on restore test failure. If you only alert on job exit code, you'll miss the silent-corruption cases.

Production Considerations

RPO and RTO: define them. "RPO 1 hour, RTO 4 hours" means: worst case, you lose 1 hour of data; recovery takes 4 hours. Design the backup strategy to meet these. PITR gives RPO of seconds; daily logical backup gives RPO of 24 hours. If your business can tolerate 24 hours of data loss, a daily pg_dump is sufficient; if not, you need PITR.

Impact on production: pg_dump and physical backups consume resources. Run them during off-peak hours. pg_dump from a replica (not primary) eliminates the impact entirely. pgBackRest can also back up from a standby.

Storage growth: backups accumulate. Without retention, you'll fill your backup storage in months. Set retention: 7 daily, 4 weekly, 12 monthly is a common baseline. Adjust based on compliance requirements (some regulations require 7 years).

Network: off-site backups consume bandwidth. A 100 GB daily backup over a 100 Mbps link takes 2.5 hours. Schedule around peak traffic, use compression, and consider incremental backups (pgBackRest incremental is ~10% of full size).

Security: backup files contain all your data. Restrict filesystem permissions, encrypt at rest, audit access. The backup server is a high-value target - compromise it and the attacker has everything.

Common Mistakes (and How to Spot Them)

No restore test. Symptom: you discover at 3 AM that the backup is corrupt. Fix: weekly automated restore test with alerting.

Backups on the same host. Symptom: host dies, you lose data and backups together. Fix: off-site replication to a different host or cloud.

Cron without set -e. Symptom: backup job silently produces empty file, exit 0. Fix: set -euo pipefail in every backup script; check exit codes.

No monitoring on backup success. Symptom: backups fail for weeks before anyone notices. Fix: alert on missing heartbeat, alert on size anomaly, alert on restore test failure.

Single backup type. Symptom: logical backup can't restore because of version mismatch. Fix: layer logical + physical + PITR; each is a fallback for the others.

Storing credentials next to backups. Symptom: if the backup server is compromised, the attacker gets data + keys. Fix: encrypt with keys stored elsewhere (KMS, Vault).

Backing up to a single cloud region. Symptom: AWS us-east-1 goes down, you can't restore. Fix: replicate backups across regions or cloud providers.

Not testing partial restores. Symptom: full restore works, but "restore one dropped table" doesn't, because nobody practiced it. Fix: test partial restores (specific tables, specific points in time) quarterly.

Troubleshooting, From Real Production

"pg_dump hangs forever". Usually a long-running transaction blocking the snapshot. Check pg_stat_activity for queries older than the dump start time. Fix: kill the long transaction, or use a replica for dumps.

"pgBackRest: could not access file". Postgres data directory permissions. pgBackRest runs as postgres user; the data dir must be owned by postgres. Common after a chown -R mistake.

"Restore fails: schema mismatch". The backup is from an older Postgres version. Logical backups handle this (mostly); physical don't. Always restore to the same major version for physical; for major upgrades, dump and restore.

"xtrabackup: operation not permitted". Backup user lacks BACKUP_ADMIN privilege or filesystem permissions on the data directory. Grant BACKUP_ADMIN, PROCESS, RELOAD, LOCK TABLES, REPLICATION CLIENT.

"Backup file is 0 bytes". Disk full, permissions error, or the dump user's password expired. Check df -h, check the log, check the user can connect: psql -U backup_user -d myapp -c "SELECT 1".

"Restore is slow". For pg_restore, add -j 4 (4 parallel jobs) and --no-indexes (rebuild indexes after). For XtraBackup, ensure --prepare ran (without it, restore does the redo log replay on first start, which is slow).

"Off-site copy fails intermittently". Network bandwidth or cloud rate limits. Add retry logic (rclone --retries 5 --low-level-retries 10), use incremental sync (not full re-upload), and consider multipart uploads for large files.

SQLite: The Often-Forgotten Case

SQLite is the database for lots of small apps - and people forget it needs backups. The naive approach (cp app.db app.db.bak) can corrupt if a write is in progress. The right way:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

Method 1: sqlite3 .backup (online, consistent)

sqlite3 /var/lib/myapp/app.db ".backup /backups/app_$(date +%Y%m%d).db"

Method 2: VACUUM INTO (creates a clean, compacted copy)

sqlite3 /var/lib/myapp/app.db "VACUUM INTO '/backups/app_$(date +%Y%m%d).db'"

Method 3: Use the SQLite backup API from Python

import sqlite3
src = sqlite3.connect("/var/lib/myapp/app.db")
dst = sqlite3.connect("/backups/app_$(date).db")
src.backup(dst)
dst.close()
src.close()

Enter fullscreen mode Exit fullscreen mode

.backup is the canonical method - it uses SQLite's online backup API, which copies the database atomically while writes continue. Never cp a live SQLite file.

Cost Considerations

Scale Tooling Storage Total/mo
Small (10 GB DB) pg_dump + rclone to B2 7 daily × 5 GB = 35 GB @ $0.005/GB ~$1
Medium (200 GB DB) pgBackRest to S3 4 full × 200GB + 30 inc × 20GB = 1.4 TB ~$35
Large (2 TB DB) pgBackRest + cross-region 4 full × 2TB + 30 inc × 200GB = 14 TB ~$350
Enterprise (20 TB) Multiple regions, encrypted 50 TB+ ~$1500

B2 at $6/TB/month is 4x cheaper than S3 Standard ($23/TB) and doesn't charge egress. For backup workloads (write once, rarely read, restore on demand), B2 or Wasabi are the right answers. S3 Glacier Deep Archive ($1/TB) is cheaper but restore takes 12 hours - fine for "archive" backups (yearly retention), not for "restore yesterday" backups.

For self-hosted: a 4 TB Synology as a backup target is ~$500 upfront, $0/month. Worth it if you have multiple databases to back up and want them in one place.

Alternatives Comparison

Tool Database Type Cost When
pg_dump Postgres Logical Free Small DBs, portability
pgBackRest Postgres Physical + PITR Free Production Postgres
Barman Postgres Physical + PITR Free Alternative to pgBackRest
mysqldump MySQL Logical Free Small DBs
Percona XtraBackup MySQL Physical + PITR Free Production MySQL
mongodump MongoDB Logical Free Small MongoDB
Percona Backup for MongoDB MongoDB Physical + PITR Free Production MongoDB
Cloud-native snapshots Any Block-level Provider RDS, Aurora, Cloud SQL
restic + dump Any Logical + dedup Free + storage Cross-DB unified pipeline

For RDS/Aurora/Cloud SQL: use the cloud provider's automated snapshots + manual snapshots for cross-region. Don't run pg_dump against a managed DB unless you need portability (migrating off the managed service). The native snapshots are faster, transactional, and PITR is built-in.

Real-World Use Cases

  • SaaS startup Postgres: pgBackRest to B2, daily full + continuous WAL, 30-day retention. Weekly restore test. RPO < 1 minute, RTO 1 hour. Total cost: $20/mo.
  • E-commerce MySQL: Percona XtraBackup daily + binlog streaming to a standby server in a different region. Restore test monthly. RPO < 5 seconds (binlog stream), RTO 2 hours.
  • Analytics MongoDB: mongodump nightly to S3, 7-day retention. No PITR (analytics can tolerate 24h data loss). Restore test quarterly.
  • Multi-tenant SaaS: per-tenant pg_dump (each tenant gets their own backup file). Customers can self-restore via a "restore from yesterday" button in the admin panel. Annual restore drill for the largest tenants.
  • Compliance-heavy (HIPAA/SOX): encrypted at rest with KMS-managed keys, 7-year retention, immutable storage (S3 Object Lock in compliance mode), quarterly restore tests with documented attestation.

Conclusion

A database backup is a hypothesis until you've restored it. The patterns that actually save you are the boring ones: logical backups for portability, physical backups for speed, PITR for low RPO, off-site copies for disaster recovery, encryption for security, automated restore tests for proof, and monitoring on all of it for catch-the-silent-failure. Layer them, schedule them, alert on them, and practice restoring. The 3 AM phone call you'll never get is the one where the backup worked because you tested it last Tuesday.


Originally published on Mango Developer.

Top comments (0)