Database backups – that can actually be restored

A backup only counts once someone has restored it. These are the scripts we would set up today: a nightly dump with clean-up, a copy outside the building in the EU, a restore test that writes its own log, and the rules Danish bookkeeping law sets when the books live in your own system.

Last checked:

ChecklistDanish bookkeeping law: when your own system holds the books
  • A full backup at least weekly
  • Kept by an unrelated party
  • On a server in an EU or EEA country
  • For 5 years from the end of the financial year
  • The copy may be compressed and encrypted, but you must always be able to hand over the data in readable form

3-2-1 for a database

The rule is simple: three copies of the data, on two kinds of storage, one of them away from the server. For a database that usually means the live database, last night’s local dump and an encrypted copy at another provider in the EU. Add a fourth rule: the offsite copy must not be deletable from the database server. Otherwise whoever gets into the server can remove your backups too.

We learnt this the hard way. Our control panel kept a local copy only when the upload to Google Drive failed, and its retention setting applied to Drive, not the disk. The result was no offsite copy and disks that filled up; on one server the clean-up freed 208 GB. Since 25.10.2026 every backup leaves the server and project dumps stay there for at most 2 days. That day we found about 300 GB of leftover local copies on 12 servers.

Logical or physical backup?

  • Logical (pg_dump, mysqldump): SQL or a compressed archive of tables and data. Restores onto a newer version and another server, and lets you pull out a single table. Slow to restore for large databases, and you lose everything since the last dump.
  • Physical (pg_basebackup + WAL): a copy of the data directory plus the running WAL files. Restores to a specific minute (point-in-time recovery). Tied to the same major version and platform. From PostgreSQL 17, pg_basebackup can also take incremental backups.

For a small-business database of a few GB, a nightly logical dump is enough. If losing a day of orders is unacceptable, add WAL archiving. Our own release practice on bkg.dk is a nightly database backup with an offsite copy, plus a dump before every deploy and a one-command rollback script.

Recipe 1: nightly pg_dump with clean-up and an offsite copy

The script dumps roles separately, dumps each database in PostgreSQL’s custom format, checks that each file can be read, writes checksums, copies to an rclone remote and cleans up only after the upload has been verified. On Sundays the copy also goes into a weekly folder kept for about 6 years.

#!/usr/bin/env bash
# /usr/local/bin/pg-backup.sh – nightly logical backup of all databases
# Run from the postgres user's own crontab (crontab -u postgres -e):
#   15 2 * * * /usr/local/bin/pg-backup.sh >> /var/log/pg-backup.log 2>&1
set -euo pipefail

BACKUP_DIR=/var/backups/pg
LOCAL_DAYS=2                 # local copies: 2 days at most
REMOTE=offsite-crypt:db      # rclone crypt on top of e.g. a Storage Box in the EU
DAILY_KEEP=14d               # daily copies offsite
WEEKLY_KEEP=2200d            # weekly copies ~6 years (5 years after financial year end)
HEARTBEAT_URL=${HEARTBEAT_URL:-}   # e.g. a self-hosted healthchecks URL
STAMP=$(date +%F)
HOST=$(hostname -s)

mkdir -p "$BACKUP_DIR/$STAMP"
cd "$BACKUP_DIR/$STAMP"

# 1. Roles and grants are not in pg_dump
pg_dumpall --globals-only > globals.sql

# 2. Each database separately, compressed, so one table can be restored alone
while read -r db; do
  pg_dump -Fc -Z 6 -f "$db.dump" "$db"
  pg_restore --list "$db.dump" > /dev/null     # readable = not truncated
done < <(psql -AtX -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate")
sha256sum ./* > SHA256SUMS

# 3. Offsite: daily folder, on Sundays also weekly/
rclone copy "$BACKUP_DIR/$STAMP" "$REMOTE/daily/$HOST/$STAMP"
if [ "$(date +%u)" = 7 ]; then
  rclone copy "$BACKUP_DIR/$STAMP" "$REMOTE/weekly/$HOST/$STAMP"
fi
rclone cryptcheck "$BACKUP_DIR/$STAMP" "$REMOTE/daily/$HOST/$STAMP" --one-way

# 4. Clean-up – only reached if upload and check succeeded (set -e)
rclone mkdir "$REMOTE/weekly/$HOST"     # does not exist before the first Sunday
rclone delete "$REMOTE/daily/$HOST" --min-age "$DAILY_KEEP" --rmdirs
rclone delete "$REMOTE/weekly/$HOST" --min-age "$WEEKLY_KEEP" --rmdirs
find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type d -mtime +"$LOCAL_DAYS" -exec rm -rf {} +

# 5. Heartbeat: if it does not arrive, monitoring must raise an alarm
[ -n "$HEARTBEAT_URL" ] && curl -fsS -m 10 "$HEARTBEAT_URL" > /dev/null
echo "$(date -Is) OK $STAMP"

Step 5 comes from our own experience: a backup that fails silently is discovered when you need it. The script only reports “OK” when everything went through, and monitoring reacts when the report does not arrive. Our hub runs 39 automated maintenance routines, and several of them watch backups. We ran both scripts on this page end to end in a PostgreSQL 18 container on 19.11.2026 – including the Sunday branch and a restore.

Run the script from the postgres user’s own crontab, not with su - postgres from root. On Debian and Ubuntu, systemd’s RemoveIPC deletes shared memory when the last login session of a regular user ends. We have seen PostgreSQL show as running while every query failed. The PostgreSQL docs explain that system users are exempt and that the risk mainly applies to installs where postgres is not created as a system user.

Set up the remotes once. Keep the encryption password somewhere other than the server, for example in your password manager. Without it the backup is worthless.

# Once: SFTP remote to a Storage Box (port 23) with an encrypted layer on top
rclone config create storagebox sftp host "$SB_HOST" user "$SB_USER" port 23 key_file /var/lib/postgresql/.ssh/storagebox
rclone config create offsite-crypt crypt remote storagebox:backups password "$(rclone obscure "$CRYPT_PASS")"

Recipe 2: monthly restore test with a log

The test fetches the newest copy from offsite storage – not the local one – checks the checksum, restores into a temporary database, counts tables and rows and writes one line to a CSV log. The log is your evidence that the backup works.

#!/usr/bin/env bash
# /usr/local/bin/pg-restore-test.sh <database> [check_table]
set -euo pipefail
REMOTE=offsite-crypt:db
HOST=$(hostname -s)
DB=${1:?usage: pg-restore-test.sh <database> [check_table]}
TABLE=${2:-}                       # only table names you type yourself
WORK=$(mktemp -d)
TEST_DB="restoretest_${DB}_$(date +%Y%m%d)"
LOG=/var/log/pg-restore-tests.csv
trap 'rm -rf "$WORK"; dropdb --if-exists "$TEST_DB"' EXIT

LATEST=$(rclone lsf "$REMOTE/daily/$HOST" --dirs-only | sort | tail -n 1)
rclone copy "$REMOTE/daily/$HOST/$LATEST" "$WORK" --include "$DB.dump" --include SHA256SUMS
(cd "$WORK" && grep " ./$DB.dump\$" SHA256SUMS | sha256sum -c -)

START=$(date +%s)
createdb "$TEST_DB"
pg_restore -d "$TEST_DB" -j 4 --no-owner --exit-on-error "$WORK/$DB.dump"
SECS=$(( $(date +%s) - START ))

TABLES=$(psql -AtX -d "$TEST_DB" -c "SELECT count(*) FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog','information_schema')")
ROWS=n/a
[ -n "$TABLE" ] && ROWS=$(psql -AtX -d "$TEST_DB" -c "SELECT count(*) FROM $TABLE")
echo "$(date -Is),$DB,${LATEST%/},$SECS,$TABLES,$ROWS,OK" >> "$LOG"
echo "Restored $DB from ${LATEST%/}: $TABLES tables, $ROWS rows, $SECS seconds"

Compare the numbers with production. If yesterday’s orders count is zero in the restored copy, the backup is the problem. Time it too: that number tells you how long you are down if things go wrong.

Why it matters: in 2024 the Danish Data Protection Agency proposed a DKK 50,000 fine for an IT provider. After a ransomware attack a chiropractic clinic could not get its data back, because the provider had encrypted the backups without securing the key, and no one had tested a restore. GDPR Article 32 requires the ability to restore access to personal data in a timely manner and regular testing of the measures.

Recipe 3: MySQL and MariaDB

--single-transaction gives a consistent snapshot without locking, but only for InnoDB tables. The script therefore lists any MyISAM tables at the end, which are not covered.

#!/usr/bin/env bash
# /usr/local/bin/mysql-backup.sh – MySQL 8 / MariaDB, one file per database
set -euo pipefail
BACKUP_DIR=/var/backups/mysql/$(date +%F)
CNF=/root/.my-backup.cnf     # [client] user=… password=…  (mode 600)
DUMP=$(command -v mariadb-dump || command -v mysqldump)
mkdir -p "$BACKUP_DIR"

mysql --defaults-extra-file="$CNF" -N -e "SHOW DATABASES" \
  | grep -Ev '^(information_schema|performance_schema|sys)$' \
  | while read -r db; do
      "$DUMP" --defaults-extra-file="$CNF" --single-transaction --quick \
        --routines --triggers --events --hex-blob \
        --default-character-set=utf8mb4 "$db" | gzip -6 > "$BACKUP_DIR/$db.sql.gz"
    done

# MyISAM is NOT consistent with --single-transaction
mysql --defaults-extra-file="$CNF" -N -e "SELECT table_schema, table_name FROM information_schema.tables WHERE engine='MyISAM' AND table_schema NOT IN ('mysql','information_schema','performance_schema','sys')"

Upload and clean-up are the same rclone steps as in recipe 1. Use --default-character-set=utf8mb4: our control panel created databases in utf8mb3, and a user’s first emoji caused error 1366.

WAL archive for point-in-time recovery

To restore to 14:32 yesterday you need the WAL files archived continuously and a physical base backup to start from. The minimum that works:

# postgresql.conf
wal_level = replica
archive_mode = on
archive_command = 'test ! -f /var/lib/pg-wal-archive/%f && cp %p /var/lib/pg-wal-archive/%f'
archive_timeout = 300        # at most 5 minutes between archived WAL files
# Weekly physical base backup: compressed tar with WAL included
pg_basebackup -D "/var/backups/pg-base/$(date +%F)" -Ft -z -X stream -c fast -P

In production we would use a dedicated tool such as pgBackRest, WAL-G or Barman instead of cp, because they handle encryption, compression, retention and upload. The setup above is for understanding the principle.

Danish bookkeeping law: when your own system holds the books

If you use a registered standard system such as e-conomic or Dinero, the provider takes the backups: a full backup at least weekly and an incremental one daily, on a server in the EU or EEA. If the bookkeeping lives in your own or a customised system – a self-hosted Odoo Community, or your own shop database with invoices – the system is unregistered and the responsibility is yours. Who is covered at all, and which systems are registered, is explained on regnskab.best-choice.dk.

For an unregistered system the Danish Business Authority (Erhvervsstyrelsen) requires:

  • A full backup at least weekly of all posted transactions and vouchers, unless nothing was posted since the last one.
  • Kept by an unrelated party (“ikke nærtstående part”) presumed to meet recognised IT-security standards – not a company in the same group or a related person.
  • On a server in an EU or EEA country.
  • For 5 years from the end of the financial year the material relates to.
  • The copy may be compressed and encrypted, but you must always be able to hand over the data in readable form.

Exempt are businesses with backup rules in other legislation, for example DORA and NIS2. Breaches are punished with a fine; the law sets no amount.

Recipe 1 meets this if the remote storage is with an independent provider with servers in the EU – for example a Storage Box in Germany or Finland, for which Hetzner offers a data processing agreement. The Sunday copy in weekly/ is kept for 2,200 days, just over 6 years, so the latest financial year is covered too. Choose storage where you can document the server’s country; an ordinary cloud drive without a chosen data region is hard to document to an auditor. Keep the encryption key safe for the whole period – without it you cannot hand over the data.

Files and servers outside the database – documents, vouchers as PDFs, whole machines – are covered on backup.best-choice.dk. Here we stay with the database.

Sources

Last reviewed: 2026-12-03

Questions about database backups

Is pg_dump a real backup?

Yes, a logical dump is a full copy of the database at that moment. It does not cover changes after the dump; for that you add WAL archiving.

How often should we test a restore?

At least monthly for every important database, and always after changing the backup setup. Write the result to a log so you can show the test was done.

Is our managed provider’s backup enough for Danish bookkeeping law?

Hardly on its own. Provider backups are kept for days, not years – Aiven 2–30 days, RDS at most 35. Take a weekly copy to another provider in the EU and keep it for 5 years.

Should the backup be encrypted?

Yes, once it leaves the server. But keep the key separate and safe, or you cannot restore – that was exactly the failure in the Danish DPA case.

Fixed price, no commitment

Get a fixed price for your database task

Tell us briefly what you use today and what you want to achieve. A person answers by e-mail with a proposal and a fixed price before any work starts.

  • A fixed price before we start
  • An answer by e-mail, no calls
  • Your details are used only to answer you

Fields marked with * are required.

What is it about?