Your PostgreSQL Backup Might Be Useless. Here's How to Test It

Your PostgreSQL backup job reports success, but can you actually restore the database? Learn how to test PostgreSQL backups, verify recovered data, measure recovery time, and automate restoration checks before a real disaster strikes.

Share
PostgreSQL backup verification illustration featuring a database, backup file, restore checklist, and successful verification indicator.

Your PostgreSQL backup job runs every night. The script completes successfully, the logs report no errors, and the resulting backup files are safely stored on another server.

Everything looks fine.

But there is one question worth asking:

Have you actually restored that backup and verified that the database works?

A backup file existing on disk does not necessarily mean you can recover your database from it. The archive might be incomplete, corrupted, missing required dependencies, or incompatible with the environment where you need to restore it.

Worse, you might discover these problems during an actual production incident, when every minute of downtime matters.

For Linux administrators, database administrators, and DevOps engineers, backup verification should be part of the recovery strategy, not an optional maintenance task.

In this guide, we'll create a PostgreSQL backup, restore it into an isolated environment, verify the recovered database, measure recovery time, and establish a repeatable testing process.

The goal is simple: stop assuming your backups work and start proving that they do.

1. Why a successful backup does not guarantee recovery

Most backup systems report whether the backup operation completed successfully. That is useful, but it only confirms that the backup process reported success.

It does not necessarily prove that the resulting backup can be restored into a working database.

Consider a few scenarios:

  • A backup file exists, but its contents are damaged.
  • The database dump is available, but required roles are missing.
  • The database uses extensions that are unavailable on the recovery server.
  • The backup was created using a different PostgreSQL version.
  • A physical backup is missing the WAL files required for recovery.
  • The restoration process fails because of insufficient disk space.
  • The database restores successfully, but the application cannot authenticate or execute its queries.

These problems can remain invisible until someone attempts a restoration.

A reliable backup strategy must answer two separate questions:

  1. Can we create and retain a backup?
  2. Can we restore that backup and recover a usable service?

The second question is what this guide focuses on.

2. Understand your PostgreSQL backup type

Before testing a backup, identify how it was created. PostgreSQL supports several backup approaches, and each has a different restoration process.

Logical backups

Logical backups export database objects and data into a dump that can be restored using PostgreSQL utilities.

Common tools include:

  • pg_dump — creates a backup of an individual database.
  • pg_dumpall — exports all databases and global objects such as roles.
  • pg_restore — restores archives created in custom, directory, or tar formats.

Logical backups are useful when you need database-level portability, selective restoration, or a straightforward recovery workflow.

Physical backups

Physical backups contain the database files needed to recover a PostgreSQL cluster.

Common approaches include:

  • pg_basebackup
  • PostgreSQL-aware filesystem backup procedures
  • Backup solutions that manage base backups and WAL archiving

Physical backups are commonly used for larger databases and point-in-time recovery (PITR).

Unlike logical dumps, physical backups require a compatible PostgreSQL environment and the correct supporting files, including WAL data when required.

For this tutorial, we'll use a custom-format logical backup created with pg_dump -Fc. It provides a practical starting point for testing database restoration.

3. Create a PostgreSQL backup

Let's assume you have a PostgreSQL database named production_db.

Create a custom-format backup:

pg_dump -U postgres -d production_db \
  -Fc \
  -f production_db.dump

The -Fc option creates a custom-format archive that can be inspected and restored using pg_restore.

Check the resulting file:

ls -lh production_db.dump

Next, inspect the archive contents:

pg_restore --list production_db.dump

This displays the database objects recorded in the archive, including schemas, tables, indexes, and other objects.

If the command cannot read the archive, investigate the backup before proceeding.

However, successfully listing the archive does not prove that the entire database can be restored. It is only an initial inspection.

A real restoration test is still necessary.
PostgreSQL backup workflow showing a terminal running pg_dump to create a custom-format database backup, with a successful completion message and a .dump backup file.

Don't forget roles and global objects

One important detail about pg_dump is that it backs up an individual database, not the entire PostgreSQL cluster.

Roles and tablespaces are cluster-level objects. If your recovery procedure depends on them, back them up separately.

For example:

pg_dumpall -U postgres --globals-only \
  > postgres_globals.sql

Store this file securely alongside your database backup.

It may contain sensitive information, including role definitions and password hashes. Protect it accordingly.

4. Restore the backup in an isolated environment

Never use your production database as the first place to test a restoration.

Instead, create a separate PostgreSQL instance and restore the backup there.

For a convenient test environment, Docker works well.

Start a temporary PostgreSQL container:

docker run -d \
  --name postgres-restore-test \
  -e POSTGRES_PASSWORD='temporary_test_password' \
  -p 127.0.0.1:55432:5432 \
  postgres:16

This starts a PostgreSQL 16 instance and exposes its port only on the local machine.

Use a PostgreSQL image version appropriate for your source database and intended recovery environment. The example assumes PostgreSQL 16 is suitable; don't blindly use it for every backup.

For a real test, use temporary credentials rather than reusing production passwords. Avoid placing sensitive credentials directly in shell history.

Check whether the container is running:

docker ps

Wait until PostgreSQL is ready:

docker logs postgres-restore-test

Look for the message indicating that the database system is ready to accept connections.

Now create a separate database for restoration:

createdb \
  -h 127.0.0.1 \
  -p 55432 \
  -U postgres \
  -T template0 \
  restore_test

Restore the backup:

pg_restore \
  -h 127.0.0.1 \
  -p 55432 \
  -U postgres \
  -d restore_test \
  --exit-on-error \
  production_db.dump

The --exit-on-error option tells pg_restore to stop when it encounters an error rather than continuing through the archive.

This makes restoration failures easier to identify during automated testing.

If your backup contains ownership and permission definitions, the destination must have the corresponding roles and dependencies available.

You can restore the globals backup into the isolated PostgreSQL instance before restoring the database, provided the required environment and permissions are in place.

For a simplified test where ownership should be assigned to the destination user, pg_restore --no-owner may be appropriate. However, this changes ownership behavior and does not reproduce the original permission model.

Required extensions must also be installed and available on the destination server before restoring databases that depend on them.

PostgreSQL backup restoration in an isolated Docker container, showing pg_restore commands, a PostgreSQL database, a backup file, and a successful restore confirmation.

5. Verify that the restored database actually works

A successful pg_restore command is encouraging, but it should not be the end of the test.

You need to verify that the restored database contains the expected objects and usable data.

Connect to the restored database:

psql \
  -h 127.0.0.1 \
  -p 55432 \
  -U postgres \
  -d restore_test

Check the database name:

SELECT current_database();

List available tables:

\dt

Inspect important tables:

SELECT COUNT(*) FROM important_table;

Check the latest available record:

SELECT MAX(created_at) FROM important_table;

These checks help establish whether expected data is present.

For a more meaningful test, identify a few important application-level operations.

For example:

  • Can the application user authenticate?
  • Can the application read important records?
  • Can it execute a representative query?
  • Are expected schemas and extensions available?
  • Are required indexes and constraints present?
  • Can the application perform a controlled write in the test environment?

A database can contain tables and records but still fail when the application connects because of missing permissions, extensions, or incompatible settings.

The best verification process tests both database-level integrity and the operations your application depends on.

Remember that a row count alone is not a complete integrity check. For critical databases, compare known invariants, checksums, or application-specific validation results against trusted reference information.

If production is still receiving writes, account for the time at which the backup was taken. Legitimate changes made after the backup can otherwise look like missing data.

6. Measure how long recovery takes

Knowing that a backup restores successfully is only part of disaster recovery.

You also need to know how long recovery takes.

Two important concepts help define your recovery expectations.

Recovery Point Objective (RPO)

RPO describes how much data loss your organization can tolerate, measured in time.

For example, an RPO of one hour means your recovery strategy should limit potential data loss to approximately one hour of changes.

Recovery Time Objective (RTO)

RTO describes how long a service can remain unavailable before recovery needs to be completed.

For example, an RTO of 30 minutes means your recovery process should aim to restore service within that window.

These targets should influence your backup frequency, retention strategy, infrastructure, and restoration procedures.

During your test, record:

  • Time required to locate and retrieve the backup.
  • Time required to initialize the PostgreSQL environment.
  • Time required to restore the database.
  • Time required to verify the restored data.
  • Time required to make the application operational.

A 50 GB database might take significantly longer to restore on slower storage than on an SSD-backed server.

Don't measure only the database import. Measure the complete recovery workflow.

If your measured recovery time exceeds your RTO, your backup strategy may be technically functional but operationally insufficient.

7. Automate PostgreSQL restore testing

Manually testing backups is useful, but it is easy to forget.

A better approach is to automate restoration tests and run them on a regular schedule.

The following example is a starting point for testing a custom-format backup.

It assumes:

  • Docker is installed.
  • The backup file is available locally.
  • The PostgreSQL 16 image is appropriate for the test.
  • PostgreSQL client utilities are installed on the host.
  • A temporary test password is supplied through the environment.
#!/usr/bin/env bash

set -Eeuo pipefail

BACKUP="/backups/production_db.dump"
CONTAINER="postgres-restore-test"
PORT="55432"
DB="restore_test"
PGUSER="postgres"

: "${PGPASSWORD:?Set a temporary PostgreSQL test password}"

cleanup() {
    docker rm -f "$CONTAINER" >/dev/null 2>&1 || true
}

trap cleanup EXIT

if [[ ! -s "$BACKUP" ]]; then
    echo "ERROR: Backup file is missing or empty."
    exit 1
fi

START_TIME=$(date +%s)

echo "Starting temporary PostgreSQL instance..."

docker run -d \
    --name "$CONTAINER" \
    -e POSTGRES_PASSWORD="$PGPASSWORD" \
    -p "127.0.0.1:${PORT}:5432" \
    postgres:16 >/dev/null

echo "Waiting for PostgreSQL..."

for attempt in $(seq 1 30); do
    if docker exec "$CONTAINER" \
        pg_isready -U "$PGUSER" >/dev/null 2>&1; then
        break
    fi

    sleep 2
done

if ! docker exec "$CONTAINER" \
    pg_isready -U "$PGUSER" >/dev/null 2>&1; then
    echo "ERROR: PostgreSQL did not become ready."
    exit 1
fi

echo "Creating test database..."

export PGPASSWORD

createdb \
    -h 127.0.0.1 \
    -p "$PORT" \
    -U "$PGUSER" \
    -T template0 \
    "$DB"

echo "Restoring backup..."

pg_restore \
    -h 127.0.0.1 \
    -p "$PORT" \
    -U "$PGUSER" \
    -d "$DB" \
    --exit-on-error \
    "$BACKUP"

echo "Running basic verification..."

TABLE_COUNT=$(
    psql \
        -h 127.0.0.1 \
        -p "$PORT" \
        -U "$PGUSER" \
        -d "$DB" \
        -tAc \
        "SELECT COUNT(*) FROM information_schema.tables
         WHERE table_schema NOT IN
         ('pg_catalog', 'information_schema');"
)

if [[ "$TABLE_COUNT" -lt 1 ]]; then
    echo "ERROR: No user tables found."
    exit 1
fi

END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))

echo "Backup restore test PASSED."
echo "User table count: $TABLE_COUNT"
echo "Total test duration: ${DURATION} seconds"

This script performs a basic restoration test and confirms that user tables exist.

It is not a complete production-grade recovery validator. A stronger implementation should also verify expected tables, critical records, extensions, application credentials, and representative application queries.

For production use, also consider unique container names, port conflict handling, pinned image versions, secure secret injection, and explicit cleanup of any temporary resources.

The script should report failures to your monitoring system rather than relying only on terminal output.

You can schedule restore tests using cron or a systemd timer.

For important databases, test the newest backup regularly and periodically test older retained backups as well.

A backup that was tested six months ago is not proof that last night's backup is recoverable.

8. Build a practical backup verification routine

A reliable backup strategy should include more than a successful backup command.

Use this checklist as a starting point:

  • [ ] Verify that backup jobs complete successfully.
  • [ ] Check backup file size and availability.
  • [ ] Validate archive readability.
  • [ ] Store backups separately from production.
  • [ ] Encrypt sensitive backup files.
  • [ ] Maintain appropriate retention periods.
  • [ ] Preserve required roles, extensions, and configuration.
  • [ ] Restore backups into an isolated environment.
  • [ ] Verify important tables and application queries.
  • [ ] Measure restoration time against your RTO.
  • [ ] Test recovery from older retained backups.
  • [ ] Document the restoration procedure.
  • [ ] Alert when automated restoration tests fail.

For critical production databases, consider immutable backup storage and an off-site copy to reduce the impact of accidental deletion, infrastructure failure, or ransomware.

Also remember that a successful database restore does not automatically restore the entire application environment. Application configuration, secrets, certificates, external dependencies, and infrastructure may need separate recovery procedures.

Final thoughts: A backup is only as good as its recovery

Creating PostgreSQL backups is an important part of database administration. But the existence of a backup file should never be confused with the ability to recover a working database.

A backup job can report success while your actual recovery process remains untested.

The solution is to make restoration testing a regular part of your operational routine.

Create backups, restore them in isolated environments, verify the data, test application access, and measure recovery time. Automate these checks wherever possible and investigate every failed restoration.

Most importantly, document the process so recovery does not depend on someone remembering the correct commands during an incident.

Don't wait for a production failure to discover that your backups were never tested.

Test your PostgreSQL backups before you need them.