A Backup Is Not Valid Until You Can Restore It

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

A backup file is not a backup

A backup script finishing without errors proves only one thing: a file was created. It does not prove that the file actually contains your data, nor that you can recover it when you need to. That difference is usually discovered at the worst possible moment: with the server down and the client on the phone.

In the previous article, we looked at how to make cron alert you when a task fails. This is the next step. Having the backup job run is not enough: you must verify that it actually works.

The ladder of confidence

A backup earns your trust in stages. Each level demonstrates something the previous one cannot guarantee:

  1. It exists. The file was created and has a reasonable size.
  2. It is intact. It was not corrupted during copying, moving, or storage.
  3. It is readable. The restore tooling can parse its contents.
  4. It is restorable. It can be loaded into an actual database and the data is there.
  5. It is recoverable on time. You can get operations back up within a timeframe your business tolerates.

Most teams stop at the first step. The rest of this article walks through the others, from the cheapest checks to the most comprehensive ones.

1. Verify file integrity

The first check is verifying whether the file you have is identical to the one generated. That is what a checksum is for: a content fingerprint that changes if a single byte is altered. Calculate it immediately after generating the backup:

sha256sum mibase_2026-11-23.dump > mibase_2026-11-23.dump.sha256

Before restoring it, or after copying it to another server, verify that it matches:

sha256sum -c mibase_2026-11-23.dump.sha256

If the result is OK, the file preserves the exact same content it had when the fingerprint was generated.

There is an important precaution: store the checksum in an independent location as well. If the file and its checksum are stored together and both become corrupted or altered, the check might still appear valid. For critical backups, keep a copy of the checksums on another server or in protected storage.

If the backup is compressed, the compression tool itself can validate its internal structure:

gzip -t respaldo.sql.gz              # comprueba la integridad del gzip
tar -tzf respaldo.tar.gz > /dev/null # lista el contenido sin extraerlo

Also add a file size check. If today’s backup is half the size of yesterday’s, something happened, even if no command failed. File size does not prove that the data is complete, but it can catch anomalies that warrant investigation.

The limitation: a checksum only proves that the file hasn’t changed since the hash was generated. If the backup was created empty or truncated, the checksum will match an utterly useless file. That is why you need to climb to the next step.

2. Verify that PostgreSQL and MySQL dumps are complete

A database dump can cut off halfway through due to disk exhaustion, a timeout, or a dropped connection. Fortunately, both database engines provide tools and signals to detect many of these issues.

PostgreSQL custom format (-Fc). pg_restore can inspect the file without modifying any database:

pg_restore --list mibase.dump > /dev/null  # lee el índice del archivo
pg_restore -f /dev/null mibase.dump        # procesa el contenido

The first command is fast, but it only verifies that the table of contents can be read. The second parses the contents and generates the restore statements, discarding the output. It is a much deeper check, though it is not equivalent to executing those statements against a running PostgreSQL server.

PostgreSQL plain-text format. A complete dump generated by pg_dump ends with a completion marker. You can check it like this:

tail -n 5 mibase.sql | grep -Fq "PostgreSQL database dump complete"

If it does not appear, the process might have been interrupted before finishing. This marker is a helpful indicator, but it does not prove that all expected tables and records are present.

MySQL and MariaDB. Dumps generated by mysqldump usually end with a comment that includes the completion timestamp:

tail -n 1 mibase.sql | grep -q "^-- Dump completed"

This comment might not appear if you use flags like --skip-comments or --skip-dump-date, so check the options used to generate your backups before relying on it.

If the dump is compressed, you can inspect the marker directly:

set -o pipefail
gzip -t mibase.sql.gz &&
  zcat mibase.sql.gz | tail -n 5 | grep -q "^-- Dump completed"

pipefail ensures that a decompression error is not masked by the exit status of tail or grep.

These checks help confirm that the dump finished writing and that its contents are readable. They do not confirm that the data is logically valid or that the engine can restore it. For that, you need to climb another step.

3. Automate test restores

The only way to know a backup can be restored is by actually restoring it. The good news is you do not have to do this manually: a script can load the latest dump into a temporary database, run a few sanity checks, and only alert you if something looks wrong.

This PostgreSQL example reuses the log and alerta functions from the previous article:

#!/usr/bin/env bash
set -Eeuo pipefail

source /opt/scripts/comun.sh   # log() y alerta()

# Conectar exclusivamente al servidor de pruebas.
export PGHOST="${PGHOST_PRUEBA:?Define PGHOST_PRUEBA}"
export PGPORT="${PGPORT_PRUEBA:-5432}"
export PGUSER="${PGUSER_PRUEBA:?Define PGUSER_PRUEBA}"

DUMP_DIR="/backups"
PATRON="mibase_*.dump"

# Evitar ejecuciones simultáneas.
exec 9>/var/lock/prueba_restauracion.lock
flock -n 9 || {
    log WARN "Ya existe una prueba de restauración en ejecución"
    exit 1
}

# Localizar el respaldo más reciente.
mapfile -t ARCHIVOS < <(
    find "$DUMP_DIR" -maxdepth 1 -type f -name "$PATRON" \
        -printf '%T@ %p\n' | sort -nr
)

if [ "${#ARCHIVOS[@]}" -eq 0 ]; then
    log ERROR "No se encontraron respaldos en $DUMP_DIR"
    alerta || true
    exit 1
fi

DUMP="${ARCHIVOS[0]#* }"

# Nombre único para evitar conflictos entre ejecuciones.
PRUEBA="restore_test_$(date +%s)_$$"

LIMPIAR="${LIMPIAR:-1}"   # LIMPIAR=0 conserva la base para depurar

limpieza() {
    local rc=$?
    if [ "$LIMPIAR" -eq 1 ]; then
        dropdb --if-exists --maintenance-db=postgres "$PRUEBA" \
            >/dev/null 2>&1 || true
    fi
    return "$rc"
}

fallo() {
    local rc=$?
    # Con set -E el trap también salta dentro de $(...): evita alertas duplicadas.
    [ "$BASH_SUBSHELL" -gt 0 ] && exit "$rc"
    log ERROR "Prueba de restauración falló en la línea $1 (código $rc)"
    alerta || true
    exit "$rc"
}

trap limpieza EXIT
trap 'fallo "$LINENO"' ERR

INICIO=$SECONDS

log INFO "Restaurando $DUMP en $PRUEBA"

createdb --maintenance-db=postgres "$PRUEBA"

pg_restore \
    --no-owner \
    --exit-on-error \
    --single-transaction \
    --dbname="$PRUEBA" \
    "$DUMP"

# Comprobaciones de plausibilidad.
# Adapta tabla, columna y umbrales a tu aplicación.
FILAS=$(psql -X -v ON_ERROR_STOP=1 -d "$PRUEBA" -tAc \
    "SELECT count(*) FROM pedidos")

RECIENTE=$(psql -X -v ON_ERROR_STOP=1 -d "$PRUEBA" -tAc \
    "SELECT COALESCE(max(creado_en) >= now() - interval '2 days', false)
     FROM pedidos")

if [ "$FILAS" -lt 1000 ] || [ "$RECIENTE" != "t" ]; then
    log ERROR "Datos sospechosos: $FILAS filas, registros recientes: $RECIENTE"
    alerta || true
    exit 1
fi

log OK "Restauración verificada: $FILAS filas en $((SECONDS - INICIO))s"

# La limpieza se realizará mediante el trap EXIT.

There are several important design choices in this example:

  • --exit-on-error forces pg_restore to halt on the first error, rather than continuing through errors that might go unnoticed.
  • --single-transaction runs the restore inside a transaction. If it fails, PostgreSQL rolls back the changes made during that attempt.
  • trap ensures error alerts are sent and the temporary database is dropped even if execution terminates unexpectedly.
  • The database name includes a timestamp and the process PID, preventing name collisions across runs.
  • flock prevents two test runs from running at the same time.
  • The script requires explicitly defining the test server and test user: if either is missing, it exits rather than connecting to a default that might accidentally be production.

A security note: the PostgreSQL user must have privileges strictly limited to the test environment. Do not use production superuser credentials. Never store passwords directly in the script either: use .pgpass with 0600 permissions or a secure secrets management mechanism.

Validation queries are just as critical as the restore itself. In this example, we check that pedidos (orders) has a minimum number of records and contains recent activity. Adapt these queries to your system: a table that always grows, a sensible minimum row count, or referential integrity checks between tables.

These checks catch obvious anomalies, but they don’t prove every single record is accurate. For that, application-specific validations are required, such as reconciling totals, relationships, and known reference records.

The two-day threshold is illustrative: adjust it to your backup frequency and actual system traffic.

$((SECONDS - INICIO)) measures how long the restore took, excluding the time spent finding the file and waiting for the lock. That metric will help you spot whether restore durations are steadily drifting upward.

The concept is identical for MySQL and MariaDB: create an empty database on a test server, load the dump via mysql test < mydb.sql, and execute equivalent queries. Here too, use a user with limited privileges and ensure the temporary database is dropped even if the restore fails.

4. Define retention and rotation

Keeping older backups is not hoarding junk: it is what saves you when an issue takes days to be discovered. If data corruption goes undetected for ten days and you only keep seven daily backups, all of them might be corrupted.

A typical grandfather-father-son scheme combines multiple frequencies to cover different recovery horizons without exhausting storage space:

  • 7 daily backups for recent errors.
  • 4 weekly backups for issues that take days to surface.
  • 12 monthly backups for audits or changes that went unnoticed for weeks.

When it comes to where to store them, the classic reference is the 3-2-1 rule: three copies of your data, across two different storage media, with one copy offsite.

Today, this is often extended to 3-2-1-1-0: one additional immutable or offline copy (which ransomware cannot encrypt) and zero errors during verification checks.

Rotate only after verifying. First confirm that the new backup exists, passes integrity checks, and, where applicable, has passed an automated test restore. Only then apply your retention policy.

A script that deletes the oldest backup before verifying the new one can leave you with one broken backup too many and one good backup too few.

To manage retention safely, consider dedicated backup tools like restic or borg, which let you enforce retention policies without relying on risky manual deletion scripts.

For example, using restic:

restic forget \
  --keep-daily 7 \
  --keep-weekly 4 \
  --keep-monthly 12

forget removes references to snapshots that no longer match the retention policy. To reclaim the underlying storage space used by data that is no longer referenced, you must also run prune.

restic can also verify its own repository. restic check checks structural metadata, and restic check --read-data reads all underlying stored data. On large repositories this can be slow; --read-data-subset=10% verifies a different fraction on each run.

Remember that retention and verification are distinct concerns: keeping twelve months of snapshots does not prove those snapshots can actually be restored.

5. Run periodic disaster recovery drills

Automated restores prove that data can be loaded. A recovery drill tests everything else: the runbook, access permissions, documentation, and the human team.

A flawless backup file is useless if nobody remembers where the encryption key is, how to provision the server, or where the configuration files required to run the application are kept.

Once a quarter, or at least twice a year, simulate a real outage:

  1. Choose a specific scenario. For example: “the database server vanished and needs to be rebuilt from scratch.”
  2. Have someone other than the author execute it, following only the written documentation. Every time they have to ask a question, you have found a gap.
  3. Test all necessary dependencies. Not just the database: verify encryption keys, TLS certificates, configurations, application builds, and operational credentials.
  4. Measure actual timings. Record how long it took to bring the service back up and how much data was lost. These are the values you will compare against your RTO (Recovery Time Objective), the maximum acceptable downtime, and your RPO (Recovery Point Objective), the maximum acceptable data loss measured as a timeframe.
  5. Compare results with business requirements. If the business expects recovery within an hour and the restore took four, that is an actionable finding, not a minor detail.
  6. Document what went wrong and fix it before the next drill.

RPO does not necessarily have to match the timestamp of the last full backup. For example, PostgreSQL allows combining full backups with WAL archives for Point-In-Time Recovery (PITR), dramatically cutting potential data loss for transactions occurring after the backup.

The execution times tracked by the script in step 3 provide a clear week-over-week baseline. If restores take longer over time as the database grows, you will see it coming before it becomes a crisis during an incident.

Putting it all together

Each check covers a different level, and none of them replaces the others:

CheckWhat it provesSuggested frequency
Checksum and sizeThe file matches its original content and has no obvious anomaliesEvery backup
Dump inspectionThe dump completed cleanly and can be parsedEvery backup
Automated restoreData loads successfully and passes sanity checksWeekly or daily
Retention and rotationMulti-tier historical copies exist per policyAfter verifying new backups
Recovery drillThe team can restore operations within target SLAsQuarterly or biannually

You don’t have to implement everything all at once. If today you only generate the raw dump file, start with checksums and dump inspection: they are straightforward to set up. Next, introduce weekly automated restores—that single change will give you the most peace of mind.

A backup you have never restored is just a promise, not a guarantee. The difference between the two only becomes apparent on the day you need it, and by then, it’s too late to check.