Tools Hub / Blueprints / Linux & DevOps
⚙️ Linux & DevOps

Automated PostgreSQL Streaming Backup to Cloudflare R2 / S3 with SHA256 Checksum & GFS Retention

Stream pg_dump custom-format output directly into S3/R2 via multipart upload while computing SHA256 on the fly, then enforce GFS (daily/weekly/monthly) retention with a SQLite ledger and verified restore checks.

Stack: Python 3 / pg_dump custom format / boto3 S3-R2 / RAM: 96 MB RAM Intermediate
📄 pg_stream_backup.py
#!/usr/bin/env python3
"""Stream pg_dump (custom format) to S3/R2 with SHA256 + GFS retention.

Env:
  PG_DSN            e.g. postgresql://backup:pw@127.0.0.1:5432/appdb
  S3_ENDPOINT       e.g. https://<account>.r2.cloudflarestorage.com
  S3_BUCKET         bucket name
  S3_ACCESS_KEY / S3_SECRET_KEY
  S3_REGION         default 'auto' (R2) or 'us-east-1'
  BACKUP_PREFIX     default 'pg/appdb'
  RETENTION_DAILY / RETENTION_WEEKLY / RETENTION_MONTHLY  default 7/4/6
  STATE_DB          default '/var/lib/pgbackup/state.sqlite3'
"""
import hashlib, logging, os, sqlite3, subprocess, sys, time
from datetime import datetime, timezone

import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError

LOG = logging.getLogger("pgbackup")
CHUNK = 8 * 1024 * 1024


def env(key, default=None, required=False):
    v = os.environ.get(key, default)
    if required and not v:
        raise SystemExit(f"missing env {key}")
    return v


def init_state(path):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    con = sqlite3.connect(path, timeout=30)
    con.execute("PRAGMA journal_mode=WAL")
    con.execute("""CREATE TABLE IF NOT EXISTS backups(
        key TEXT PRIMARY KEY, kind TEXT, size INTEGER, sha256 TEXT,
        created_at TEXT, verified INTEGER DEFAULT 0)""")
    con.commit()
    return con


def s3_client():
    return boto3.client(
        "s3",
        endpoint_url=env("S3_ENDPOINT"),
        aws_access_key_id=env("S3_ACCESS_KEY", required=True),
        aws_secret_access_key=env("S3_SECRET_KEY", required=True),
        region_name=env("S3_REGION", "auto"),
        config=Config(signature_version="s3v4", retries={"max_attempts": 5, "mode": "standard"},
                      connect_timeout=10, read_timeout=60),
    )


def stream_dump(dsn, key, bucket, client):
    """Run pg_dump, stream stdout into multipart upload, hash on the fly."""
    proc = subprocess.Popen(
        ["pg_dump", "--format=custom", "--compress=6", "--no-owner", "--no-privileges", dsn],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0,
    )
    upload = client.create_multipart_upload(Bucket=bucket, Key=key, ContentType="application/octet-stream")
    uid = upload["UploadId"]
    parts, buf, part_no, sha, total = [], b"", 1, hashlib.sha256(), 0
    try:
        while True:
            chunk = proc.stdout.read(CHUNK)
            if not chunk:
                break
            sha.update(chunk)
            total += len(chunk)
            buf += chunk
            while len(buf) >= CHUNK:
                body, buf = buf[:CHUNK], buf[CHUNK:]
                r = client.upload_part(Bucket=bucket, Key=key, UploadId=uid, PartNumber=part_no, Body=body)
                parts.append({"ETag": r["ETag"], "PartNumber": part_no})
                part_no += 1
        if buf:
            r = client.upload_part(Bucket=bucket, Key=key, UploadId=uid, PartNumber=part_no, Body=buf)
            parts.append({"ETag": r["ETag"], "PartNumber": part_no})
        rc = proc.wait(timeout=30)
        if rc != 0:
            raise RuntimeError(f"pg_dump exit {rc}: {proc.stderr.read().decode(errors='replace')[:500]}")
        client.complete_multipart_upload(Bucket=bucket, Key=key, UploadId=uid,
                                         MultipartUpload={"Parts": parts})
        return total, sha.hexdigest()
    except Exception:
        client.abort_multipart_upload(Bucket=bucket, Key=key, UploadId=uid)
        proc.kill()
        raise


def gfs_kind(now):
    if now.day == 1:
        return "monthly"
    if now.weekday() == 6:
        return "weekly"
    return "daily"


def prune(con, client, bucket, prefix):
    limits = {"daily": int(env("RETENTION_DAILY", "7")),
              "weekly": int(env("RETENTION_WEEKLY", "4")),
              "monthly": int(env("RETENTION_MONTHLY", "6"))}
    for kind, keep in limits.items():
        rows = con.execute(
            "SELECT key FROM backups WHERE kind=? ORDER BY created_at DESC LIMIT -1 OFFSET ?",
            (kind, keep)).fetchall()
        for (key,) in rows:
            try:
                client.delete_object(Bucket=bucket, Key=key)
                con.execute("DELETE FROM backups WHERE key=?", (key,))
                LOG.info("pruned %s %s", kind, key)
            except (BotoCoreError, ClientError) as e:
                LOG.error("prune failed %s: %s", key, e)
    con.commit()


def main():
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
    dsn = env("PG_DSN", required=True)
    bucket = env("S3_BUCKET", required=True)
    prefix = env("BACKUP_PREFIX", "pg/appdb")
    con = init_state(env("STATE_DB", "/var/lib/pgbackup/state.sqlite3"))
    client = s3_client()
    now = datetime.now(timezone.utc)
    kind = gfs_kind(now)
    key = f"{prefix}/{kind}/{now:%Y%m%dT%H%M%SZ}.dump"
    t0 = time.time()
    size, digest = stream_dump(dsn, key, bucket, client)
    con.execute("INSERT OR REPLACE INTO backups VALUES (?,?,?,?,?,0)",
                (key, kind, size, digest, now.isoformat()))
    con.commit()
    LOG.info("uploaded %s size=%d sha256=%s in %.1fs", key, size, digest, time.time() - t0)
    prune(con, client, bucket, prefix)


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        LOG.exception("backup failed: %s", e)
        sys.exit(1)

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:

sql
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:

code
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.sqlite3

Step 3: Systemd unit. Load credentials via EnvironmentFile, restrict writes with ProtectSystem=strict + ReadWritePaths=/var/lib/pgbackup, and block privilege escalation with NoNewPrivileges=yes:

ini
[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=yes

Pair 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:

bash
sudo -u pgbackup time /usr/bin/python3 /opt/pgbackup/pg_stream_backup.py

Watch connections and locks during pg_dump:

sql
SELECT pid, state, query_start, left(query, 60) FROM pg_stat_activity WHERE datname='appdb';

Cross-check object sizes against the ledger:

bash
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:

bash
aws s3 cp s3://pg-backups/pg/appdb/daily/xxx.dump - --endpoint-url $S3_ENDPOINT | sha256sum

A 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.

Want the full multi-workflow production repo with REST API & ops dashboard?
All blueprints are bundled inside the B2B AI Automation MVP Pack with Docker, Systemd & test suite.
Get Full MVP Pack $499 →
PARTNER ECOSYSTEM

Recommended Cloud & AI Infrastructure

Hand-picked developer infrastructure we use to run 24/7 workflows. Partner links help keep all browser tools free.
📬 WEEKLY BRIEF · ZERO SPAM

Get the Yevrix Indie Dev & AI Digest

One weekly email with new browser-local dev tools, cloud & LLM pricing benchmarks, ready-to-install Agent Skills, and rising OSS repos. 1-click unsubscribe anytime.