Database Backup Strategies
Someone runs a migration against the wrong database, or an UPDATE goes out without a WHERE clause, and the orders table is now garbage. You go looking for last night's backup and find the cron job has been failing quietly for three weeks. Or the file is there, but nobody has ever tried restoring it, and you're about to find out whether it works while the site is down.
This post covers the backup types and how to combine them, concrete commands for MySQL, PostgreSQL and MongoDB, automating the whole thing with a script and cron, where to store the files, and the part most people skip: actually testing that you can restore.
Keep 3 copies of your data, on 2 different media types, with 1 copy offsite. That covers a dead disk, a fire in the data center, and ransomware that encrypts everything it can reach on the main server, including the local backups.
Understanding Backup Types
There are four backup types you'll run into. They trade storage space against how long a restore takes, and most setups mix two or three of them.
| Backup Type | What It Captures | Storage Size | Recovery Speed | Best For |
|---|---|---|---|---|
| Full Backup | Entire database snapshot | Large | Fastest | Weekly baseline |
| Incremental | Changes since last backup | Smallest | Slowest (chain) | Frequent daily backups |
| Differential | Changes since last full | Medium | Fast (full + one diff) | Daily with weekly full |
| Transaction Log | Individual transactions | Very Small | Point-in-time restore | High-frequency, PITR |
Choosing Your Backup Cadence
A common setup for a production database looks like this:
- Weekly full backups, taken during the lowest-traffic window (e.g., Sunday 2 AM)
- Daily differential backups that capture everything changed since the last weekly full
- Hourly transaction log backups, so you can recover to a point within the last hour
With this setup, the worst case is losing about an hour of data. Recovery requires applying the last full backup, then the latest differential, then the transaction logs up to the failure point.
Layered backup strategy: Full → Differential → Transaction Logs
MySQL Backup Strategies
For most MySQL setups you'll start with mysqldump, which writes a logical backup as plain SQL. Once the database gets big enough that a dump takes hours and a restore takes even longer, look at Percona XtraBackup, which copies the InnoDB files while the server keeps running.
Logical Backups with mysqldump
Basic Full Database Backup
Export all databases including stored procedures, triggers, and events to a compressed SQL file.
# Full backup of all databases
mysqldump \
--user=backup_user \
--password \
--all-databases \
--single-transaction \
--routines \
--triggers \
--events \
--flush-logs \
--master-data=2 \
| gzip > /backups/mysql/full-$(date +%Y%m%d-%H%M%S).sql.gz
# Single database backup
mysqldump \
--user=backup_user \
--password \
--databases myapp_production \
--single-transaction \
--routines \
--triggers \
| gzip > /backups/mysql/myapp-$(date +%Y%m%d-%H%M%S).sql.gz
Restore from mysqldump
Decompress and pipe the SQL file back into MySQL to restore the database.
# Restore all databases
gunzip -c /backups/mysql/full-20260520-020000.sql.gz \
| mysql --user=root --password
# Restore single database to a new database
mysql --user=root --password -e "CREATE DATABASE myapp_restored;"
gunzip -c /backups/mysql/myapp-20260520-020000.sql.gz \
| mysql --user=root --password myapp_restored
# Verify the restore
mysql --user=root --password -e "
SELECT table_name, table_rows
FROM information_schema.tables
WHERE table_schema = 'myapp_restored'
ORDER BY table_rows DESC
LIMIT 10;"
Binary Log for Point-in-Time Recovery
A dump only gets you back to the moment it was taken. To recover to, say, 14:29, one minute before someone dropped a table, you need the binary log, which records every data change. Turn it on in my.cnf:
[mysqld]
# Enable binary logging
log_bin = /var/log/mysql/mysql-bin.log
binlog_format = ROW
expire_logs_days = 7
max_binlog_size = 100M
server_id = 1
# Sync to disk on each commit for durability
sync_binlog = 1
innodb_flush_log_at_trx_commit = 1
On MySQL 8, expire_logs_days is deprecated in favour of binlog_expire_logs_seconds (7 days is 604800), and from 8.0.26 --master-data is renamed --source-data. The old names still work for now but print deprecation warnings. Also keep in mind that --single-transaction only gives you a consistent snapshot for InnoDB tables. Any leftover MyISAM tables can change mid-dump.
# Step 1: Restore the last full backup
gunzip -c /backups/mysql/full-20260520-020000.sql.gz | mysql --user=root --password
# Step 2: Apply binary logs up to the failure time
# For example, restore up to 14:30:00 on May 20, 2026
mysqlbinlog \
--start-datetime="2026-05-20 02:00:00" \
--stop-datetime="2026-05-20 14:30:00" \
/var/log/mysql/mysql-bin.000001 \
/var/log/mysql/mysql-bin.000002 \
| mysql --user=root --password
# Step 3: Verify data is at the expected point
mysql --user=root --password -e "SELECT COUNT(*) FROM myapp.orders WHERE created_at < '2026-05-20 14:30:00';"
PostgreSQL Backup Strategies
Postgres gives you three tools that map nicely onto the backup types above. pg_dump makes logical backups, pg_basebackup takes a physical copy of the whole cluster, and WAL (Write-Ahead Log) archiving ships every change off the server so you can do point-in-time recovery.
Good for smaller databases, and handy when you only need a few tables back:
# Full database dump in custom format (faster restore)
pg_dump \
--username=postgres \
--format=custom \
--compress=9 \
--file=/backups/pg/myapp-$(date +%Y%m%d-%H%M%S).dump \
myapp_production
# Restore from custom format dump
pg_restore \
--username=postgres \
--dbname=myapp_restored \
--jobs=4 \
--verbose \
/backups/pg/myapp-20260520-020000.dump
# Dump specific tables only
pg_dump \
--username=postgres \
--table=users \
--table=orders \
--format=custom \
myapp_production > /backups/pg/critical-tables.dump
A physical copy of the whole cluster, taken while it keeps serving traffic. This is what you want once the database is large:
# Create a physical base backup with WAL streaming
pg_basebackup \
--host=localhost \
--username=replication_user \
--pgdata=/backups/pg/basebackup-$(date +%Y%m%d) \
--format=tar \
--compress=9 \
--wal-method=stream \
--progress \
--verbose
# This creates:
# /backups/pg/basebackup-20260520/base.tar.gz (data files)
# /backups/pg/basebackup-20260520/pg_wal.tar.gz (WAL files)
Configure continuous WAL archiving in postgresql.conf for PITR:
# postgresql.conf settings for WAL archiving
wal_level = replica
archive_mode = on
archive_command = 'aws s3 cp %p s3://my-pg-backups/wal/%f'
archive_timeout = 300 # Archive every 5 minutes at minimum
# To restore to a specific time, create recovery.conf:
# (or recovery parameters in postgresql.conf for PG 12+)
restore_command = 'aws s3 cp s3://my-pg-backups/wal/%f %p'
recovery_target_time = '2026-05-20 14:30:00'
recovery_target_action = 'promote'
MongoDB Backup Strategies
For self-hosted MongoDB you've got mongodump for logical backups and filesystem snapshots for physical ones. If you're on Atlas, continuous backups with point-in-time recovery are already built in, so check what your tier includes before writing your own scripts. One thing to watch in the example below: the legacy mongo shell was removed in MongoDB 6.0, so on newer versions run those verify commands with mongosh.
# Full database backup
mongodump \
--uri="mongodb://backup_user:password@localhost:27017" \
--authenticationDatabase=admin \
--out=/backups/mongo/dump-$(date +%Y%m%d-%H%M%S) \
--gzip
# Backup specific database
mongodump \
--uri="mongodb://localhost:27017/myapp" \
--out=/backups/mongo/ \
--gzip \
--archive=/backups/mongo/myapp-$(date +%Y%m%d).archive
# Restore from backup
mongorestore \
--uri="mongodb://localhost:27017" \
--authenticationDatabase=admin \
--gzip \
--archive=/backups/mongo/myapp-20260520.archive \
--nsFrom="myapp.*" \
--nsTo="myapp_restored.*"
# Verify restore
mongo myapp_restored --eval "db.stats()"
mongo myapp_restored --eval "db.users.count()"
MongoDB Oplog for Point-in-Time Recovery
In a replica set, the oplog (operations log) records every write, which plays the same role as MySQL's binary log. Dump it along with your data:
# Backup with oplog (enables point-in-time restore)
mongodump \
--uri="mongodb://localhost:27017" \
--oplog \
--gzip \
--archive=/backups/mongo/full-with-oplog-$(date +%Y%m%d).archive
# Replay oplog to a specific point in time
mongorestore \
--oplogReplay \
--oplogLimit "1748000000:1" \
--gzip \
--archive=/backups/mongo/full-with-oplog-20260520.archive
Automating Backups with Shell Scripts
If a backup depends on someone remembering to run it, sooner or later it won't get run. Here's a script that dumps, checks the file, uploads to S3 and cleans up old copies, plus the cron entries to run it.
#!/bin/bash
set -euo pipefail
# Configuration
BACKUP_DIR="/backups/mysql"
S3_BUCKET="s3://my-db-backups/mysql"
DB_USER="backup_user"
DB_PASS_FILE="/etc/mysql/backup-password"
RETENTION_DAYS=30
DATE=$(date +%Y%m%d-%H%M%S)
LOG_FILE="/var/log/db-backup.log"
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"; }
log "Starting backup..."
# Create backup directory if missing
mkdir -p "$BACKUP_DIR"
# Perform mysqldump
BACKUP_FILE="$BACKUP_DIR/full-$DATE.sql.gz"
DB_PASS=$(cat "$DB_PASS_FILE")
mysqldump \
--user="$DB_USER" \
--password="$DB_PASS" \
--all-databases \
--single-transaction \
--routines \
--triggers \
--flush-logs \
| gzip > "$BACKUP_FILE"
log "Backup created: $BACKUP_FILE ($(du -sh "$BACKUP_FILE" | cut -f1))"
# Verify backup integrity
if gunzip -t "$BACKUP_FILE" 2>/dev/null; then
log "Integrity check PASSED"
else
log "ERROR: Integrity check FAILED, aborting upload"
exit 1
fi
# Upload to S3
aws s3 cp "$BACKUP_FILE" "$S3_BUCKET/$(basename "$BACKUP_FILE")" \
--storage-class STANDARD_IA
log "Uploaded to S3: $S3_BUCKET"
# Remove local backups older than retention period
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +"$RETENTION_DAYS" -delete
log "Cleaned up backups older than $RETENTION_DAYS days"
log "Backup complete!"
Make the Script Executable
Set the correct permissions and create a dedicated backup user with minimal privileges.
# Make script executable
chmod +x /usr/local/bin/db-backup.sh
# Create MySQL backup user with minimal privileges
mysql -u root -p < /etc/mysql/backup-password
chmod 600 /etc/mysql/backup-password
If you're on MySQL 8.0.21 or later and the dump fails with Access denied; you need (at least one of) the PROCESS privilege(s) for this operation, that's mysqldump trying to dump tablespace info. Either add PROCESS to the grant above or pass --no-tablespaces.
Schedule with Cron
Add the jobs with crontab. If you ever put a date +%Y%m%d straight into a crontab line, escape each % as \%. Cron treats a bare % as a newline and the command breaks in confusing ways.
# Full backup every Sunday at 2:00 AM
0 2 * * 0 /usr/local/bin/db-backup.sh >> /var/log/db-backup.log 2>&1
# Differential backup every day Mon-Sat at 2:00 AM
0 2 * * 1-6 /usr/local/bin/db-differential-backup.sh >> /var/log/db-backup.log 2>&1
# Binary log flush every hour (for PITR)
0 * * * * mysql -u backup_user -p$(cat /etc/mysql/backup-password) -e "FLUSH BINARY LOGS;" >> /var/log/db-backup.log 2>&1
# Alert if no backup file was created in the last 26 hours
0 4 * * * find /backups/mysql -name "*.sql.gz" -mmin -1560 | grep -q . || echo "BACKUP MISSING!" | mail -s "DB Backup Alert" admin@yourcompany.com
Cloud Storage and Retention Policies
A backup that lives on the same server as the database won't survive the same disk failure or ransomware attack. Push it to object storage (AWS S3, Google Cloud Storage, Backblaze B2). It's cheap, durable, and lives somewhere else. On S3 you can move older backups into cheaper storage classes automatically. Prices below are approximate us-east-1 list prices, so check current pricing for your region.
| Storage Class | Use Case | Retrieval Time | Approx. Cost/GB/mo |
|---|---|---|---|
| S3 Standard | Recent backups (last 7 days) | Milliseconds | $0.023 |
| S3 Standard-IA | Monthly backups (8-30 days) | Milliseconds | $0.0125 |
| S3 Glacier Instant | Quarterly backups (31-90 days) | Milliseconds | $0.004 |
| S3 Glacier Deep Archive | Long-term archive (90+ days) | Up to 12 hours | $0.00099 |
{
"Rules": [
{
"ID": "db-backup-lifecycle",
"Status": "Enabled",
"Filter": { "Prefix": "mysql/" },
"Transitions": [
{
"Days": 7,
"StorageClass": "STANDARD_IA"
},
{
"Days": 30,
"StorageClass": "GLACIER_INSTANT_RETRIEVAL"
},
{
"Days": 90,
"StorageClass": "DEEP_ARCHIVE"
}
],
"Expiration": {
"Days": 365
}
}
]
}
Encrypt anything you put in the cloud. Use S3 server-side encryption (SSE-S3 or SSE-KMS), or encrypt before uploading with something like openssl enc -aes-256-cbc or gpg. Someone who gets hold of an unencrypted dump has your whole database. And store the key somewhere other than the server you're backing up, or you won't be able to decrypt anything after losing it.
Testing Your Backups (The Most Skipped Step)
Until you've restored from a backup, you don't know whether it works. A file can look the right size and still be corrupt, cut off halfway through, or missing the database you added last month. The only way to find out is to restore it, on a schedule.
Automated Restore Testing Script
#!/bin/bash
# Weekly automated restore test (run in an isolated environment)
set -euo pipefail
BACKUP_DIR="/backups/mysql"
TEST_DB="restore_test_$(date +%Y%m%d)"
LATEST_BACKUP=$(ls -t "$BACKUP_DIR"/*.sql.gz | head -1)
ALERT_EMAIL="ops@yourcompany.com"
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"; }
log "Testing restore from: $LATEST_BACKUP"
# Create isolated test database
mysql -u root -p"$ROOT_PASS" -e "CREATE DATABASE $TEST_DB;"
# Attempt restore
if gunzip -c "$LATEST_BACKUP" | mysql -u root -p"$ROOT_PASS" "$TEST_DB"; then
log "Restore succeeded"
# Validate row counts match production
PROD_COUNT=$(mysql -u root -p"$ROOT_PASS" myapp_production \
-se "SELECT COUNT(*) FROM users;")
TEST_COUNT=$(mysql -u root -p"$ROOT_PASS" "$TEST_DB" \
-se "SELECT COUNT(*) FROM users;")
if [ "$PROD_COUNT" == "$TEST_COUNT" ]; then
log "Validation PASSED: user count matches ($PROD_COUNT rows)"
else
log "WARN: Row count mismatch: prod=$PROD_COUNT test=$TEST_COUNT"
echo "Row count mismatch in restore test" | mail -s "Backup Warning" "$ALERT_EMAIL"
fi
else
log "ERROR: Restore FAILED"
echo "Restore test failed for $LATEST_BACKUP" | mail -s "CRITICAL: Backup Restore Failed" "$ALERT_EMAIL"
fi
# Cleanup
mysql -u root -p"$ROOT_PASS" -e "DROP DATABASE $TEST_DB;"
log "Test database cleaned up"
Run this on a separate server, never against production. The script compares against the live users table, so expect small mismatches on a busy app (rows added since the dump). Treat a big gap as the warning sign, not an off-by-a-few. Also, time the restore. That number is your real recovery time, and it's usually longer than people guess.
RTO, RPO, and Disaster Recovery Planning
Before picking tools, get two numbers agreed with whoever owns the product. They decide almost everything else:
- Recovery Time Objective (RTO): The maximum acceptable downtime. "We can be down for at most 4 hours." A lower RTO requires more infrastructure (hot standbys, pre-staged restore environments).
- Recovery Point Objective (RPO): The maximum acceptable data loss measured in time. "We can lose at most 1 hour of data." A lower RPO requires more frequent backups and transaction log shipping.
| Business Tier | Target RTO | Target RPO | Strategy |
|---|---|---|---|
| Mission Critical | < 15 min | < 1 min | Hot standby replica, synchronous replication |
| Business Critical | < 1 hour | < 1 hour | Warm standby, hourly transaction log backups |
| Standard | < 4 hours | < 4 hours | Daily full + automated restore scripts |
| Development | < 24 hours | < 24 hours | Daily full backup to S3 |
Documenting Your Runbook
During an outage nobody wants to work out the restore steps from scratch. Write them down. Your runbook should answer:
- Where are backup files stored, and how do you access them (credentials, VPN)?
- What is the exact sequence of commands to restore each database system?
- How do you validate the restore was successful?
- Who gets paged and in what order? What is the escalation path?
- When is the application safe to cut traffic back over?
Keep the runbook somewhere you can reach when your own systems are down: a separate wiki, a Google Doc, even a printed copy. Not only on the server that just failed. At least once a year, simulate a failure and have someone follow the runbook from scratch while you time it.
Backup Monitoring and Alerting
Backup jobs fail silently. An expired AWS key, a full disk or a changed password, and cron keeps running a script that does nothing useful. Without alerts, you find out on the day you need to restore.
What to Monitor
- Backup job completion: Alert if a scheduled backup didn't complete within the expected window
- Backup file size anomaly: A backup that's much smaller than yesterday's may mean a truncated dump or a missing database
- S3 upload success: Check that the remote copy exists. A successful local write doesn't mean the upload worked
- Disk space: Alert when backup destination reaches 80% capacity before it fills and stops writing
- Restore test results: Weekly automated restore tests should report pass/fail to your monitoring system
- Backup age: Alert if the newest backup is older than your RPO. Someone may have disabled the cron job
How much of this you actually need
You don't need all of this on day one, and for a lot of projects you never will.
- Small app, few GB, can live with losing a day: a nightly
mysqldumporpg_dump, uploaded off the server and encrypted, plus a monthly restore test. Binlog or WAL archiving would mostly be extra moving parts here. - Managed database (RDS, Cloud SQL, Atlas): automated snapshots and PITR are already there. Don't rebuild them with cron. Do check the retention period, and keep an occasional logical dump somewhere outside that provider's account, because a deleted account or instance can take its automated backups with it.
- Large or busy database: this is where physical backups (XtraBackup,
pg_basebackup) and log archiving pay off. A logical dump of a few hundred GB can take hours to restore, and that's often what blows your RTO. - Replicas are not backups. A replica copies a
DROP TABLEwithin a second or so. It helps with hardware failure, not with mistakes.
The mistake I'd watch for most is a job that has run every night for a year and has never been restored. Pick one backup this week, restore it to a scratch server, and time it. That'll tell you more about your setup than any diagram here.