1. Production Pain Points & Architecture Trade-offs
The classic pg_dump | gzip > /backup/x.sql.gz script fails in production for three reasons: local disk fills up on multi-hundred-GB databases, corrupted dumps go unnoticed until a real restore is needed, and retention via find -mtime +7 -delete cannot distinguish daily/weekly/monthly tiers or audit what was deleted.
This blueprint's core trade-off is zero-disk streaming upload: pg_dump --format=custom stdout feeds directly into an S3/R2 multipart upload, keeping only an 8 MB buffer in memory while incrementally computing a SHA256 digest with hashlib.sha256. Even a 500 GB database keeps the process under 100 MB RSS.
The second trade-off is using SQLite as a ledger instead of relying on object-store list operations. R2/S3 list_objects_v2 is eventually consistent and awkward to paginate; a local SQLite ledger in WAL mode atomically records key, size, SHA256, GFS tier, and creation time, turning retention into a single SQL statement.
The third trade-off is deciding GFS tier at write time, not inferring it later. gfs_kind() classifies at backup start based on UTC date: the 1st of the month is monthly, Sunday is weekly, everything else is daily. This keeps tier semantics stable even if the job is delayed or re-run.
2. Step-by-Step Deployment & Permission Hardening
Step 1: Create a dedicated backup role. Never run pg_dump as superuser:
CREATE ROLE backup LOGIN PASSWORD 'strong-pw';
GRANT CONNECT ON DATABASE appdb TO backup;
GRANT USAGE ON SCHEMA public TO backup;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO backup;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO backup;Add GRANT SELECT ON ALL SEQUENCES if sequences or large objects exist.
Step 2: Configure R2 credentials. Create an API token scoped to Object Read & Write on the specific bucket. Write credentials to /etc/pgbackup/env with chmod 600 and root:root ownership:
PG_DSN=postgresql://backup:pw@127.0.0.1:5432/appdb
S3_ENDPOINT=https://<account>.r2.cloudflarestorage.com
S3_BUCKET=pg-backups
S3_ACCESS_KEY=...
S3_SECRET_KEY=...
S3_REGION=auto
BACKUP_PREFIX=pg/appdb
STATE_DB=/var/lib/pgbackup/state.sqlite3Step 3: Systemd unit. Load credentials via EnvironmentFile, restrict writes with ProtectSystem=strict + ReadWritePaths=/var/lib/pgbackup, and block privilege escalation with NoNewPrivileges=yes:
[Unit]
Description=PostgreSQL streaming backup
[Service]
Type=oneshot
User=pgbackup
EnvironmentFile=/etc/pgbackup/env
ExecStart=/usr/bin/python3 /opt/pgbackup/pg_stream_backup.py
ProtectSystem=strict
ReadWritePaths=/var/lib/pgbackup
NoNewPrivileges=yes
PrivateTmp=yesPair with pgbackup.timer firing daily at 02:00 UTC.
Step 4: Verify restores. An unverified backup is not a backup. Periodically download the latest daily dump, run pg_restore --list to check TOC integrity, and restore into a scratch database to run SELECT count(*) sampling.
3. Key Parameter Tuning & Load-Test Commands
Part size. CHUNK = 8 * 1024 * 1024. R2 enforces a 5 MB minimum part size; 8 MB balances throughput against retry cost. On flaky networks drop to 5 MB to reduce per-part retransmit cost; on fat pipes with huge databases raise to 16 MB to cut request count.
pg_dump compression. --compress=6 is the CPU/volume sweet spot. Drop to 3 on IO-bound hosts, raise to 9 when storage cost dominates—but note compression runs inside pg_dump and consumes CPU.
Timeouts and retries. Config(connect_timeout=10, read_timeout=60, retries={'max_attempts': 5}) covers connection setup, per-read/write, and overall retry. botocore backs off exponentially on transient R2 500s.
Load-test commands. Wrap a single run in time to observe end-to-end duration:
sudo -u pgbackup time /usr/bin/python3 /opt/pgbackup/pg_stream_backup.pyWatch connections and locks during pg_dump:
SELECT pid, state, query_start, left(query, 60) FROM pg_stat_activity WHERE datname='appdb';Cross-check object sizes against the ledger:
aws s3 ls s3://pg-backups/pg/appdb/daily/ --endpoint-url $S3_ENDPOINT
sqlite3 /var/lib/pgbackup/state.sqlite3 'SELECT kind,count(*),sum(size) FROM backups GROUP BY kind;'4. Troubleshooting & Safe Rollback
Failure 1: pg_dump non-zero exit. The code checks rc != 0 after proc.wait() and raises with the first 500 chars of stderr, while abort_multipart_upload cleans up incomplete parts. Debug by running pg_dump --format=custom --no-owner <dsn> > /dev/null manually—common causes are insufficient grants or version mismatch (pg_dump must be ≥ server version).
Failure 2: orphaned multipart uploads. If the process is SIGKILLed, abort_multipart_upload never runs and R2 keeps billing incomplete parts. Add a bucket lifecycle rule for AbortIncompleteMultipartUpload after 7 days as a safety net.
Failure 3: ledger/storage drift. If prune deletes an object but the SQLite write fails, the ledger keeps a stale row. Run a reconciliation script periodically: diff storage object keys against ledger keys, then backfill or delete orphans.
Failure 4: SHA256 mismatch. Before restoring, download and recompute:
aws s3 cp s3://pg-backups/pg/appdb/daily/xxx.dump - --endpoint-url $S3_ENDPOINT | sha256sumA mismatch means a corrupted upload—fall back to the weekly/monthly tier immediately.
Safe rollback. Accidental prune is the biggest risk. Before going live, set RETENTION_DAILY=30 for a week, confirm tier classification in the ledger, then tighten to 7. The prune function only deletes keys present in the ledger—never blind prefix deletes. Enable R2 versioning or Object Lock at the bucket level and give the monthly tier a 30-day retention as a final guard. Every deletion logs LOG.info("pruned ...") for journald traceability.