Sub topic 11
Backing up databases consistently
This chapter assumes you can run the restic or Borg commands from earlier chapters, that you have a working repository, and that you know basic SQL administration on your server's database. The chapter covers why copying live database files is unsafe, how to stream a dump into restic or Borg, and how to test that the result restores.
Why copying live database files is unsafe
A database server keeps its data in many files and changes them while it runs. It writes to a transaction log first, then updates data files later, and it keeps part of its state in memory. A file-level backup reads those files one after another over several seconds or minutes. The files it captures may come from different moments.
Suppose restic reads /var/lib/postgresql while a transaction commits. The data file may be read before the change and the log file after it. The copy then contains pages that do not agree with each other. The database may refuse to start from that copy, or it may start and hold damaged data. The backup command still exits with status 0, because restic and Borg only know they read the files.
Common symptoms of an inconsistent copy:
- The server fails at startup with messages about missing or corrupt WAL (write-ahead log) files, or about InnoDB recovery failing.
- Some tables restore fine while others contain torn pages or missing rows.
- The problem shows up only during a restore, long after the backup ran.
There are three safe approaches. This chapter focuses on the first.
| Approach | How it works | Trade-off |
|---|---|---|
| Logical dump | A tool such as `pg_dump` or `mysqldump` reads data through the database engine and writes SQL | Simple and portable, but slow to restore on large databases |
| Filesystem snapshot | LVM, ZFS, or Btrfs freezes a point-in-time view, and you back up the snapshot | Fast, but needs snapshot-capable storage and engine support for crash recovery |
| Physical backup tool | Tools such as `pg_basebackup` or Percona XtraBackup copy files with log coordination | Fast restores, but more setup and version coupling |
How a logical dump gives you consistency
A logical dump asks the database for its contents instead of reading its files. The database engine returns a consistent view, even while other clients write.
- PostgreSQL's
pg_dumpruns inside a single transaction with snapshot isolation. Every table in the dump reflects the same instant. mysqldump --single-transactiondoes the same for InnoDB tables. It does not protect MyISAM tables, which have no transactions.
The dump is a stream of SQL text. You can send that stream to a file, or straight to your backup tool through a pipe.
Streaming a dump into restic
Both restic and Borg avoid a temporary file on disk, which matters when the dump is larger than the free space on the server. Restic reads from standard input with --stdin.
sudo -u postgres pg_dumpall | restic backup --stdin --stdin-filename pg_dumpall.sqlHere is what each part does:
sudo -u postgres pg_dumpallruns the dump as thepostgresoperating system user. That user can connect over the local socket without a password.pg_dumpalldumps every database in the cluster, plus roles and tablespace definitions. Per-database tools such aspg_dumpdo not include roles.--stdintells restic to read the data from the pipe instead of from paths.--stdin-filenamesets the name of the file inside the snapshot. Without it, the name defaults tostdin.
The dump appears in the snapshot as a single file, and you list and restore it like any other file. Deduplication still works on text dumps. Unchanged regions of consecutive dumps share chunks, so daily dumps cost much less than their full size. Dumps compressed with gzip defeat this, because a small change shifts the whole compressed stream. Pipe the plain text to restic and let the repository compress it.
Handling pipeline failures
A pipe has a trap. In a shell, the exit status of a pipeline is by default the status of the last command. If pg_dumpall fails halfway, restic still sees the end of the input, saves a truncated dump, and exits 0. You then hold a snapshot that looks fine and restores to half a database.
Bash fixes this with set -o pipefail, which makes the pipeline fail if any command in it fails. The script from the automation chapter already sets set -euo pipefail. Extend it to include the database dump:
#!/bin/bash
set -euo pipefail
export RESTIC_REPOSITORY=sftp:[email protected]:/srv/restic/myserver
export RESTIC_PASSWORD_FILE=/etc/restic/password
sudo -u postgres pg_dumpall | restic backup --stdin --stdin-filename pg_dumpall.sql
restic backup --exclude-file=/etc/restic/excludes.txt /etc /home /var/www
restic forget --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --pruneBe aware that pipefail cannot undo a snapshot restic has already written. If pg_dumpall dies near the end, restic may have committed a partial snapshot before the script stops. This leaves a bad snapshot in the repository. Two defenses help:
- Dump to a temporary file first, check that the dump command succeeded, then back up the file. This costs disk space but guarantees you only back up complete dumps.
- Tag the snapshot (
--tag db) so you can find and remove a bad one withrestic forget <snapshot-id>.
A newer restic option, --stdin-from-command, runs the command itself and discards the snapshot if the command fails. Check that your installed version supports it with restic backup --help before relying on it.
Streaming a dump into Borg
Borg can also read from a pipe. In Borg 1.x you use - as the path with --stdin-name, and with Borg 1.2 and later you can use borg create --content-from-command.
sudo -u postgres pg_dumpall | borg create --stdin-name pg_dumpall.sql '::{hostname}-db-{now:%Y-%m-%dT%H:%M:%S}' -Borg stores a dump from stdin as one archive with one file. The same caution about truncated dumps applies, and pipefail does not remove an archive Borg has already created. Use a separate archive name prefix, such as -db- above, so you can apply a different borg prune --glob-archives policy to database archives if you want one.
MySQL and MariaDB
The pattern is the same. Use --single-transaction for a consistent InnoDB view, and --routines --events so stored code is included.
mysqldump --single-transaction --routines --events --all-databases \
| restic backup --stdin --stdin-filename mysqldump.sqlCredentials need care. Do not put a password on the command line, because other users can read it in the process list. Put it in ~/.my.cnf under [client] for the user running the script, and make that file mode 0600. For a root-run script, /root/.my.cnf works.
Which files to exclude from the file backup
If you dump the database, you should exclude the live data directory from your file-level backup. Backing up both wastes space and produces a second, inconsistent copy that someone may restore by mistake. Add the data directory to /etc/restic/excludes.txt:
/var/lib/postgresql
/var/lib/mysqlKeep the configuration files, such as /etc/postgresql or /etc/mysql. A restore needs them, and they are small.
Testing the dump, not just the backup
A successful backup command tells you the bytes reached the repository. It does not tell you the SQL inside will load. Restore the dump into a throwaway database now and then.
restic dump latest pg_dumpall.sql > /tmp/pg_dumpall.sql
sudo -u postgres psql -f /tmp/pg_dumpall.sql postgresThe first command writes one file from the latest snapshot to standard output. Run the load on a scratch machine, never on the production server, because pg_dumpall output recreates roles and databases and can collide with live ones. Check the end of the dump too: a complete pg_dump file ends with a line such as -- PostgreSQL database dump complete, and a truncated one does not.
restic dump latest pg_dumpall.sql | tail -n 3Putting it together
The workflow below shows the order of operations in the backup script.
Common mistakes
- Backing up
/var/lib/mysqlor/var/lib/postgresqlas the only database protection. - Forgetting
pipefail, which hides dump failures. - Compressing the dump before it reaches the repository, which hurts deduplication.
- Putting database passwords in command arguments or world-readable files.
- Never loading a dump into a test database, so the first restore happens during an outage.
- Using
pg_dumpfor one database and forgetting roles, which the restored cluster then lacks.
Exercise
Your script runs pg_dumpall | restic backup --stdin without set -o pipefail. The database crashes midway through the dump. What does restic do, what exit status does the script see, and how would you protect against this?
Show answer
Restic reads whatever arrived before the pipe closed, stores it as a snapshot, and exits 0. Because the pipeline status is the status of its last command, the script sees success and you hold a truncated dump. Protect against it by setting set -euo pipefail so the script fails, by dumping to a temporary file and backing up only after the dump command succeeds (or using restic backup --stdin-from-command where available), and by testing restores so a bad dump is found early.
Exercise
Why should you leave the dump uncompressed when sending it to restic or Borg?
Show answer
Both tools split data into chunks and store each unique chunk once, and they compress the chunks themselves. A small change in a gzip-compressed stream alters most of the bytes after it, so consecutive dumps share few chunks and deduplication saves little. Plain text keeps unchanged regions identical between runs.