Automated Offsite Backups and Drills
A few years back, a client called me at 6:40 AM because a botched plugin update had dropped three tables from their production CMS database. No problem, their team said—they'd run a nightly mysqldump cron job since 2021, and /var/backups held months of neatly dated .sql.gz files. I SSHed in and checked the latest archive. It was 20 bytes long. Every archive from the past four months was 20 bytes long. A routine MySQL password rotation had broken authentication in the script, cron had mailed stderr to a local root mailbox nobody read, and gzip had compressed an empty error stream into a valid 20-byte header every night at 02:00.
That failure mode is painfully common. When you're self-hosting web stacks on bare metal without a managed cloud control plane watching your disks, an untested nightly dump script is basically a placebo. Real disaster recovery isn't measured by how many archives sit in a folder. It's measured by whether you can turn cold offsite bytes back into a consistent, queryable database under pressure—and how recently you proved it.
Why Vanilla mysqldump Cron Jobs Fail Silently
Even when a naive cron job exits zero and writes a multi-gigabyte file, it often produces an archive you can't safely restore. Default mysqldump flags were designed for MyISAM and behave badly on live InnoDB workloads.
By default, mysqldump grabs global or per-table LOCK TABLES locks. On an active storefront or editorial CMS taking steady writes, locking tables for five minutes stalls PHP-FPM workers, fills your reverse proxy queue, and triggers 502s at 2:03 AM. Usually someone strips the lock flags to silence the alerts, trading downtime for a logically torn snapshot. Table orders dumps at 02:00:05 while order_items dumps at 02:01:22. Foreign keys drift apart, totals stop matching, and your app chokes on orphaned rows days after recovery.
Three other silent killers show up constantly in self-hosted audits:
- Half-written exports from disk pressure or
max_allowed_packeterrors, leaving truncated SQL files that still look plausible inls -lh. - Dropped database logic, because
mysqldumpskips stored routines and scheduled events unless explicitly requested. - Shared blast radius from writing dumps to another partition on the same NVMe drive or an attached NFS volume, which dies alongside primary data during a root compromise or stray recursive delete.
A backup you haven't restored into an isolated database engine in the last seven days is just an unverified hypothesis sitting on someone else's hard drive.
These cracks surface fastest before risky maintenance. Anyone practicing strict pre-migration database snapshot discipline ahead of a major CMS upgrade knows a bad rollback artifact turns a routine cutover into an all-night salvage job. The same applies when pairing backups with blue-green CMS deployments done right: instant traffic switching only saves you if the data underneath rolls back cleanly.
Consistent InnoDB Dumps Without Stalling Traffic
For databases under roughly 40 GiB, logical exports via mysqldump (or mariadb-dump on MariaDB 11+) remain my preferred offsite format. They travel cleanly across minor engine versions and are easy to inspect. Past 40 to 50 GiB, SQL replay times push past an hour and you should switch to physical hot backups with Percona XtraBackup or mariadb-backup. Below that line, a disciplined logical dump is hard to beat.
Start with a dedicated read-only MySQL user instead of embedding root credentials in a script. Following the least-privilege habits we use when hardening self-hosted Linux CMS nodes, run the job under a locked-down system account with credentials stored at mode 0600 in /etc/backup-agent/mysql.cnf:
CREATE USER 'backup_ro'@'127.0.0.1' IDENTIFIED BY '32-char-random-secret';
GRANT SELECT, SHOW VIEW, TRIGGER, EVENT, PROCESS, RELOAD ON *.* TO 'backup_ro'@'127.0.0.1';
Next, capture an MVCC snapshot on local NVMe storage and verify its completion footer before touching offsite object storage:
#!/usr/bin/env bash
set -euo pipefail
SPOOL="/var/spool/db-backups"; DUMP="${SPOOL}/cms_prod.sql"
mkdir -p "${SPOOL}" && chmod 0700 "${SPOOL}"
mysqldump --defaults-extra-file=/etc/backup-agent/mysql.cnf \
--single-transaction --quick --routines --triggers --events --hex-blob \
--default-character-set=utf8mb4 --set-gtid-purged=OFF \
--result-file="${DUMP}.tmp" cms_prod
tail -n 5 "${DUMP}.tmp" > "${SPOOL}/footer.txt"
if ! grep -q "Dump completed on" "${SPOOL}/footer.txt"; then
rm -f "${DUMP}.tmp"; exit 1
fi
mv "${DUMP}.tmp" "${DUMP}"
Each flag earns its place. --single-transaction opens a REPEATABLE READ transaction so InnoDB serves a consistent point-in-time view without blocking live web traffic. --quick streams rows directly instead of buffering a 6 GiB table into RAM until the Linux OOM killer intervenes. --hex-blob keeps binary columns intact across character-set parsing.
One honest trade-off: --single-transaction aborts with MySQL error 1412 if concurrent DDL (ALTER TABLE, DROP TABLE, TRUNCATE) hits a table mid-export. Freeze schema migrations during the 02:00 dump window, or run exports off a local asynchronous replica.
Notice two deliberate choices above. First, we spool to local NVMe instead of streaming across the WAN, so a stalled upload can't hold an InnoDB snapshot open for twenty minutes and bloat undo logs. Second, we skip gzip completely—which sounds backwards until you pair it with deduplicating object storage.
Encrypted Deduplication to Object Storage With Restic
Compressing a 6.4 GiB SQL dump with gzip every night wrecks deduplication. One new row near the top shifts the deflate bit stream for everything after it, turning two dumps that are 98% identical into completely different blobs. Shipping sixty nights of those to S3 or Backblaze B2 burns 120+ GiB of redundant storage.
restic solves this at the chunk layer. It slices raw SQL using content-defined chunking (Rabin fingerprints), skips chunks already in the bucket, compresses new chunks internally with zstd, and encrypts everything client-side with AES-256 and Poly1305 authentication before bytes leave the host. On my own 6.4 GiB CMS database plus 18 GiB of uploaded site media, sixty nightly snapshots occupy just 24.8 GiB total in B2.
set -a; source /etc/backup-agent/restic.env; set +a
restic backup --password-file /etc/backup-agent/restic.pass \
--compression auto --tag cms-prod \
/var/spool/db-backups/cms_prod.sql /var/www/cms/shared/files
A normal weeknight run finishes fast and barely touches upstream bandwidth:
Files: 1 new, 1 changed, 41208 unmodified
Added to the repository: 118.420 MiB (31.605 MiB stored)
processed 41210 files, 24.412 GiB in 0:38 — snapshot 7f3c91a4 saved
Overwriting the exact same spool path (/var/spool/db-backups/cms_prod.sql) nightly lets restic find its parent snapshot automatically and ship only changed chunks—31.6 MiB stored for 24.4 GiB of live state in 38 seconds.
Append-Only Buckets and Separated Pruning
Never grant the production server's S3 key DeleteObject permission so it can run restic forget --prune itself. If an attacker compromises your CMS host, they'll read restic.env, wipe every historical snapshot, and ransom the live database.
Give the production node write-only credentials backed by S3 Object Lock (or Backblaze Bucket Lock) with a 14-day retention window. Execute your backup rotation strategy from a separate, locked-down admin box holding the pruning key:
restic forget --password-file /etc/backup-admin/restic.pass \
--keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune
restic check --password-file /etc/backup-admin/restic.pass --read-data-subset=10%
That weekly 10% read check verifies every pack file across roughly ten weeks, catching silent bitrot or missing objects without blowing your egress budget.
Automated Weekly Restore Drills in a Throwaway Container
Writing encrypted chunks to S3 only proves your upload keys work. It doesn't prove the SQL imports without syntax errors, broken view definers, or missing foreign-key targets.
Every Sunday at 04:00 UTC, a systemd timer on a cheap $10/month verification VPS pulls the latest snapshot, boots an ephemeral MariaDB container backed by RAM-speed tmpfs, replays the dump, and checks real data freshness:
#!/usr/bin/env bash
set -euo pipefail
set -a; source /etc/backup-drill/restic.env; set +a
WORK="/var/tmp/restore-drill"; CTR="cms-drill"; PASS="drill-pass"
cleanup() { set +e; podman rm -f "${CTR}" >/dev/null 2>&1; rm -rf "${WORK}"; }
trap cleanup EXIT
rm -rf "${WORK}" && mkdir -p "${WORK}"
restic restore latest --password-file /etc/backup-drill/restic.pass \
--tag cms-prod --target "${WORK}" --include /var/spool/db-backups/cms_prod.sql
podman run -d --name "${CTR}" --tmpfs /var/lib/mysql:rw,noexec,nosuid,size=12g \
-e MARIADB_ROOT_PASSWORD="${PASS}" -e MARIADB_DATABASE=cms_verify \
docker.io/library/mariadb:11.4 --innodb-flush-log-at-trx-commit=0 --skip-log-bin
for i in $(seq 1 30); do
if podman exec "${CTR}" mariadb-admin ping -uroot -p"${PASS}" --silent; then break; fi
sleep 2
done
podman exec -i "${CTR}" mariadb -uroot -p"${PASS}" cms_verify < "${WORK}/var/spool/db-backups/cms_prod.sql"
ROWS=$(podman exec "${CTR}" mariadb -N -B -uroot -p"${PASS}" cms_verify -e "SELECT COUNT(*) FROM pages;")
AGE_H=$(podman exec "${CTR}" mariadb -N -B -uroot -p"${PASS}" cms_verify -e "SELECT TIMESTAMPDIFF(HOUR, MAX(updated_at), NOW()) FROM content_versions;")
if [ "${ROWS}" -lt 500 ]; then exit 1; fi
if [ "${AGE_H}" -gt 30 ]; then exit 1; fi
curl -fsS -m 10 --retry 3 "https://hc-ping.com/replace-with-your-uuid" >/dev/null
Two details make this cheap enough to run weekly. First, pairing tmpfs with --innodb-flush-log-at-trx-commit=0 and --skip-log-bin cuts a 6.4 GiB replay from twelve minutes to 45 seconds—we're verifying logical integrity, not crash durability inside a disposable container. Second, checking AGE_H catches the nastiest silent failure: a broken dump script that stops updating the spool file while restic happily backs up the same month-old SQL file every night.
The trailing curl hits a dead-man's-switch monitor (Healthchecks.io or a Prometheus alert watching last-success age). If the VPS dies, the timer fails to fire, or any query exits non-zero, silence itself pages you Sunday morning.
Five Checks Before You Trust the Pipeline
Nightly snapshots give you a 24-hour Recovery Point Objective (RPO). For most editorial CMS nodes and internal apps, that's plenty. If you run an e-commerce checkout where losing 18 hours of orders isn't survivable, keep this pipeline as your baseline and layer continuous MySQL binary log archiving on top for point-in-time recovery.
Before calling the setup done, verify five things by hand:
- Kill a test dump mid-run and confirm the footer check refuses to hand a truncated file to
restic. - Run
restic forgetfrom the production node and confirm object storage returns403 AccessDenied. - Escrow the
resticpassphrase off-box in your password manager and an offline copy—losing the key turns encrypted backups into expensive data deletion. - Time a cold rebuild from fresh OS to HTTP 200 so your Recovery Time Objective (RTO) is a measured number, not a guess.
- Break the weekly drill intentionally once with a bogus table name and confirm the dead-man's-switch alert actually reaches your phone.
You don't need enterprise backup appliances or bloated SaaS agents to sleep well. Eighty lines of boring shell script, an append-only object bucket costing a few dollars a month, and a throwaway container proving recoverability every Sunday beat blind hope every single time—especially at 6:40 AM on a Tuesday.
Comments
Post a Comment