Console Login

Backups that restore: scheduled restore tests with restic and Borg

What breaks

The classic backup failure is not a failed backup. It is a backup job that has been exiting with status 0 every night for a year, a dashboard that is green, and a first restore attempt, on the worst possible day, that stops halfway with a checksum error, a missing key or a database file that will not open. Nobody saw it coming because nothing ever exercised the restore path.

Restic and Borg make this easy to miss, because their default integrity checks are cheap and answer a narrower question than the one you care about. Here I reproduce the gap on a clean Ubuntu container: I damage one repository file, show which checks notice, and build a scheduled restore test that does.

Root cause

A backup tool has to answer three different questions: did the backup run, is the repository structurally consistent, and can the data actually be read back and used. A zero exit code from backup answers only the first. The default restic check compares index and tree structure but does not read the packed data, so silent bit rot can leave it green.

The second cause is deduplication. Both tools store each chunk once and let later snapshots point at it. That saves space, and it also means that a damaged chunk is shared by every snapshot that contains the same data. Tonight's perfectly healthy backup run can therefore produce a snapshot that is unrestorable, because it reuses a chunk that was already damaged. I show this below with real output. The same reasoning applies to anything outside the repository, such as a lost key or a database copied mid-write: only a real restore exercises it.

What the docs say

The restic manual page on working with repositories says that by default check does not verify that the pack files on disk are unmodified, and that you must pass --read-data for that. It also offers --read-data-subset to check a fraction per run. It warns that as long as a repository is damaged, restoring some files will fail and new snapshots are not guaranteed to be restorable either.

The Borg documentation for borg check describes two steps. The repository step checks segment headers and the metadata and data of all objects by size and CRC, which can detect bit rot. The archive step checks metadata, and only with --verify-data does it cryptographically verify the file content, at the cost of reading and decrypting everything. Both pages are what I relied on for the behaviour I then tested.

Approaches compared

Structural check only

Run restic check or borg check on a schedule. It is cheap and catches broken repository structure. Restic's default does not read pack contents, so this is the weakest option, and it says nothing about keys, permissions or whether restored application data is usable.

Full or partial data verification

Use restic check --read-data or --read-data-subset, and borg check --verify-data or --max-duration for partial repository checks. This proves that the stored bytes are intact. It reads a lot of data, so on a large repository you rotate through subsets. It still does not prove that your restore procedure works end to end.

Scheduled restore into a scratch directory, then verify

Restore the newest snapshot to a temporary directory, compare it with a checksum manifest taken at backup time, check that the snapshot is recent, and run an application-level check such as a SQLite integrity check. This exercises key, repository, restore code path and result in one go.

Full disaster-recovery drill on another machine

Rebuild a service on a different host using only the credentials you would have in a real emergency. It is the most honest test and the most expensive to run often, so it suits an occasional exercise better than a nightly job.

Why this fix

I picked the scheduled restore test, with a cheaper repository check as a complement. It is the only option on the list that fails when the thing you will need on the bad day, an actual restored tree, is wrong. It is a short shell script, it works the same way for restic and Borg, and its exit status plugs into any scheduler.

The test has four assertions. The restore command must exit zero. Every restored file must match a SHA-256 manifest written at backup time. A canary file written at backup time must be younger than a limit, which catches a backup job that silently stopped. And the restored SQLite database must pass PRAGMA integrity_check. Each assertion catches a failure the others cannot.

Doing it in the sandbox

The environment

This is a clean container, not a production machine, with no particular location or hardware that I can vouch for. I started by printing what it actually is, so that every later result can be read against it, and nothing here should be read as a statement about other systems.

uname -a
Linux vm 6.18.44-fc-v1157 #1 SMP PREEMPT_DYNAMIC @0 x86_64 x86_64 x86_64 GNU/Linux
cat /etc/os-release
PRETTY_NAME="Ubuntu 24.04.5 LTS"
VERSION_CODENAME=noble

Installing both tools, and a Python snag

Both tools are packaged in Ubuntu 24.04, so I installed them from apt. The restic binary worked immediately, reporting version 0.16.4. The Borg command, however, crashed on start-up with a Python import error, so I looked into that before doing anything else.

apt-get update -qq 2>&1 | tail -3; apt-get install -y -qq restic borgbackup 2>&1 | tail -5
restic version; borg --version
restic 0.16.4 compiled with go1.22.2 on linux/amd64
ModuleNotFoundError: No module named 'borg.crypto.low_level'

The cause was in this container, not in Borg. The /usr/bin/python3 symlink points at Python 3.11, while the Ubuntu package ships its compiled extension for Python 3.12. Running the script with the 3.12 interpreter worked, so I added a two-line wrapper that does that. On a normal Ubuntu 24.04 install this should not be needed; I only report what I saw here.

readlink -f /usr/bin/python3
/usr/bin/python3.11
printf '#!/bin/sh\nexec /usr/bin/python3.12 /usr/bin/borg "$@"\n' > /usr/local/bin/borg && chmod +x /usr/local/bin/borg && hash -r && cat /usr/local/bin/borg && borg --version
#!/bin/sh
exec /usr/bin/python3.12 /usr/bin/borg "$@"
borg 1.2.8

A small dataset and two repositories

I generated 200 text files, five 3 MB random blobs and a SQLite database with 50,000 rows, 206 files and about 21 MB in total. Then I created one restic repository and one Borg repository on local disk, both encrypted with a lab-only passphrase file.

for i in $(seq 1 200); do head -c 20000 /dev/urandom | base64 > /srv/data/docs/note-$i.txt; done; for i in 1 2 3 4 5; do head -c 3000000 /dev/urandom > /srv/data/blobs/blob-$i.bin; done
export RESTIC_REPOSITORY=/srv/repo-restic RESTIC_PASSWORD_FILE=/etc/backup-lab/pass; restic init
export BORG_REPO=/srv/repo-borg BORG_PASSCOMMAND='cat /etc/backup-lab/pass'; borg init --encryption=repokey-blake2
restic backup /srv/data
Files:         206 new,     0 changed,     0 unmodified
processed 206 files, 20.302 MiB in 0:00
snapshot 08dcbffc saved

Baseline: both checks are green

restic check
no errors were found
borg check

Borg printed nothing and exited 0, which is how borg check reports success. Now I copied both repositories to a pristine location and damaged one file in each: 16 random bytes written into the middle of the largest restic pack, and 16 random bytes into the middle of the single Borg segment.

mkdir -p /srv/pristine && cp -a /srv/repo-restic /srv/repo-borg /srv/pristine/
chmod u+w /srv/repo-restic/data/b7/b773959d222cc9afa8364d77cb032b64f027929695a8e7c953df8157cfa35b2a && dd if=/dev/urandom of=/srv/repo-restic/data/b7/b773959d222cc9afa8364d77cb032b64f027929695a8e7c953df8157cfa35b2a bs=1 count=16 seek=5000000 conv=notrunc
dd if=/dev/urandom of=/srv/repo-borg/data/0/2 bs=1 count=16 seek=5000000 conv=notrunc

What the checks say about damaged repositories

The default restic check still passed, with no error at all. Borg's default check failed, because its repository step verifies the CRC of every segment entry. Reading all restic data with --read-data then found the damage, as the documentation predicts.

restic check
no errors were found
borg check 2>&1 | head -6
Data integrity error: Segment entry checksum mismatch [segment 2, offset 4986960]
Index object count mismatch.
restic check --read-data
Pack ID does not match, want b773959d222cc9afa8364d77cb032b64f027929695a8e7c953df8157cfa35b2a, got b608cd533434b478127f6e6546294810ccb096462737fca84ad41da2ac5ff581
Fatal: repository contains errors

Then I tried to restore, which is what actually matters. Both restores failed. Restic restored 209 of 210 items and named the one file it refused, while Borg stopped with an exception and a non-zero exit status, so neither tool let the damage pass silently.

rm -rf /srv/restore-lab/r1 && restic restore latest --target /srv/restore-lab/r1
Summary: Restored 209 / 210 files/dirs (19.633 MiB / 20.302 MiB) in 0:00
ignoring error for /srv/data/blobs/blob-5.bin: ciphertext verification failed
Fatal: There were 1 errors
rm -rf /srv/restore-lab/b1 && mkdir /srv/restore-lab/b1 && cd /srv/restore-lab/b1 && borg extract ::first
borg.helpers.errors.IntegrityError: Data integrity error: Segment entry checksum mismatch [segment 2, offset 4986960]

The restore test script

Two small scripts do the work. The backup script, which I do not reproduce here, writes a canary file with the current epoch time into the source tree, builds a SHA-256 manifest of that tree outside the repository, and then runs restic backup or borg create. The restore test restores the newest snapshot into a temporary directory, verifies it and cleans up. Below are the lines of that script that carry the work, selected from the output of cat; the rest is argument handling, a temporary directory and a fail function that writes a status file, calls logger and exits 1.

cat /usr/local/sbin/restore-test.sh
    restic restore latest --quiet --target "$T" || fail "restic restore exited non-zero"
    (cd "$T" && borg extract "::$a") || fail "borg extract of $a exited non-zero"
bad=$(cd "$R" && sha256sum --quiet -c "$STATE/manifest-$tool.sha256" 2>&1) || fail "checksum mismatch: $(echo "$bad" | head -3 | tr '\n' ' ')"
age=$((start - ts))
[ "$age" -le "$MAX_AGE" ] || fail "newest snapshot is ${age}s old, limit ${MAX_AGE}s"
db=$(python3 -c "import sqlite3,sys; print(sqlite3.connect(sys.argv[1]).execute('pragma integrity_check').fetchone()[0])" "$R/app.db") || fail "sqlite could not open app.db"
[ "$db" = ok ] || fail "sqlite integrity_check said: $db"

I reset both repositories from the pristine copies, ran each backup and then each test, and both tests passed. I then ran the restic test again with MAX_AGE=1, a limit of one second, to prove that the freshness check can fail on its own when a snapshot is older than allowed.

/usr/local/sbin/backup.sh restic
backup finished [restic]
/usr/local/sbin/restore-test.sh restic
Summary: Restored 211 files/dirs (20.302 MiB) in 0:00
RESTORE-TEST OK [restic]: 207 files match manifest, canary age 3s, sqlite ok, took 1s
/usr/local/sbin/restore-test.sh borg
RESTORE-TEST OK [borg]: 207 files match manifest, canary age 3s, sqlite ok, took 1s
MAX_AGE=1 /usr/local/sbin/restore-test.sh restic
RESTORE-TEST FAIL [restic]: newest snapshot is 13s old, limit 1s

The timings above come from a 21 MB dataset on local disk and say nothing about restore time at your scale. I then damaged the same pack and segment again. The restic test failed, and the Borg test failed too; both printed a FAIL line and wrote a status file for monitoring.

/usr/local/sbin/restore-test.sh restic
Summary: Restored 210 / 211 files/dirs (19.633 MiB / 20.302 MiB) in 0:00
RESTORE-TEST FAIL [restic]: restic restore exited non-zero

A green backup on top of damage

Next I ran a normal backup into the damaged restic repository. It exited 0 and printed its success line, a third snapshot appeared, and the restore test of that newest snapshot failed on the same blob. This is consistent with the deduplication effect described above and with the restic documentation's warning that new snapshots are not guaranteed to be restorable, although I did not inspect the snapshot's blob list to confirm the exact mechanism.

/usr/local/sbin/backup.sh restic
backup finished [restic]
/usr/local/sbin/restore-test.sh restic
Summary: Restored 210 / 211 files/dirs (19.633 MiB / 20.302 MiB) in 0:00
RESTORE-TEST FAIL [restic]: restic restore exited non-zero
ignoring error for /srv/data/blobs/blob-5.bin: ciphertext verification failed

Scheduling with cron

I put the pristine repositories back, installed cron from apt, started its daemon by hand and wrote a cron.d file with an every-minute schedule so that I could watch it fire. A real schedule would be weekly or nightly, not every minute.

cat /etc/cron.d/backup-lab
* * * * * root /usr/local/sbin/backup.sh restic >> /var/log/backup-lab.log 2>&1 && /usr/local/sbin/restore-test.sh restic >> /var/log/backup-lab.log 2>&1
* * * * * root /usr/local/sbin/backup.sh borg >> /var/log/backup-lab.log 2>&1 && /usr/local/sbin/restore-test.sh borg >> /var/log/backup-lab.log 2>&1

The restic jobs ran straight away. The Borg jobs did not, and the log showed a message I had caused: I had swapped in an older copy of the repository, and Borg refused to write because its local cache and security directory were newer than the repository. That is a useful safety check against a rolled-back repository, and I cleared the stale state for this lab repository by hand.

Cache, or information obtained from the security directory is newer than repository - this is either an attack or unsafe (multiple repos with same ID)
rm -rf /root/.config/borg/security/8b92a867471e70bade63c30b2f757edde2007d163e5acb634fea853444014dd9

After that, cron ran both tools without my involvement, and the log, which I read after waiting, shows scheduled restore tests passing for both tools. Once I had seen that, I stopped cron and deleted the cron.d file so that nothing kept running in the sandbox.

sleep 70; grep -E 'RESTORE|Cache' /var/log/backup-lab.log | cut -c1-100 | tail -n 6
RESTORE-TEST OK [borg]: 207 files match manifest, canary age 1s, sqlite ok, took 0s
RESTORE-TEST OK [restic]: 207 files match manifest, canary age 1s, sqlite ok, took 1s

The systemd timer variant

On a normal host I would use a systemd timer instead of cron, and the lines below are the schedule part of the timer file I wrote. In this container systemd is not running (systemctl is-system-running printed offline), so I could only write the units and validate them statically. I did not start the timer, so treat it as checked syntax, not as a tested schedule.

cat /etc/systemd/system/[email protected]
OnCalendar=Sun *-*-* 03:30:00
RandomizedDelaySec=15min
Persistent=true
systemd-analyze verify /etc/systemd/system/[email protected] /etc/systemd/system/[email protected]

The verify command printed nothing and exited 0. The service is a template unit that takes the tool name as its instance, so a timer instance for restic and another for borg would each run the matching test. The service unit, which I do not reproduce, runs the same script with the instance name as its argument.

Limits and alternatives

What worked: a restore test that fails on damage which the default restic check accepted, fails on a stale backup, and fails on a snapshot built on top of a damaged chunk. Borg's default check caught the same damage through CRCs, and the restore test caught it again.

What I did not test: remote repositories, large data, restore time at scale, real alerting delivery (I never checked that logger reached any log), the systemd timer itself, or restoring on a second machine with only the passphrase. My damage was 16 random bytes; other failures behave differently. The manifest is taken just before the backup, so a busy source tree needs a filesystem snapshot to avoid false alarms.

Choose another method when the repository is large: a full weekly restore can be too heavy, so restore a sample with --include and rotate --read-data-subset or --max-duration checks. Keep a disaster-recovery drill on a separate machine as an occasional exercise, since only that proves the passphrase, key and documentation work for someone with nothing else.