Database Backup and Recovery: A Practical Pattern for Reliable PostgreSQL Operations

Learn how to design reliable PostgreSQL backups with remote storage, automation, retention, monitoring, and tested database recovery.

Cloud Infrastructure•~15 min read•November 23, 2026•By QZ-L Editorial
#PostgreSQL#Database Backup#DevOps#Cloud Infrastructure#Disaster Recovery
Looking for related guides? Start with the qz-l Learning Center and explore more tutorials in this topic cluster.

A production database can run perfectly for months without anyone thinking about backups. Until something goes wrong.

A failed disk, an accidental SQL statement, a corrupted database, or an unsuccessful deployment can turn a normal day into a recovery exercise. Having a backup command available is not enough. The important question is whether the data can actually be recovered when it is needed.

For a small application, running pg_dump every night and uploading the result to cloud storage may seem sufficient. It is a reasonable starting point, but a reliable backup strategy requires more than scheduling a command.

The real objective is to establish a repeatable process that creates consistent backups, stores them independently, verifies their integrity, retains historical versions, and provides a tested recovery procedure.

This article explores that pattern, explains why each part matters, and discusses how to implement it correctly without introducing unnecessary operational complexity.

1. Understand the Difference Between Backup and Recovery

Backup and recovery are two related but different responsibilities.

Backup is the process of creating and preserving a recoverable copy of data.

Recovery is the process of using that copy to bring a database back to a usable state.

A successful pg_dump execution only proves that a dump operation completed. It does not prove that:

  • The backup contains all the required data.
  • The backup file is valid.
  • The backup can be downloaded.
  • The database can be restored.
  • The restored application can use the database successfully.

A backup that cannot be restored is not a reliable backup.

This distinction should influence the design from the beginning. Instead of building a scheduled backup command first and thinking about recovery later, design both processes as parts of the same system.

2. Separate Production Data from Backup Storage

One of the most important principles is that production data and its backups should not depend on the same storage failure domain.

Consider this architecture:

              Production Environment
              -----------------------

                Application Server
                        |
                        v
                   PostgreSQL
                        |
                        v
                    pg_dump
                        |
                        v
                  Backup Script
                        |
                        v
                Remote Object Storage
                        |
                        v
                 Historical Backups


              Recovery Environment
              --------------------

                Remote Object Storage
                        |
                        | Download
                        v
                  Backup Archive
                        |
                        v
                 Isolated PostgreSQL
                        |
                        v
                  Restore and Test

Keeping a backup on the same VPS as the production database provides limited protection.

If the VPS is deleted, the disk fails, or the entire machine becomes unavailable, both the database and its local backups may disappear together.

Remote object storage provides an independent copy that can be accessed even when the original server is unavailable.

Examples include:

  • Oracle Cloud Infrastructure Object Storage.
  • Amazon S3.
  • Google Cloud Storage.
  • Azure Blob Storage.

The specific provider is less important than the architectural principle:

Production data and production backups should not depend on the same storage failure domain.

For stronger protection, consider using a separate cloud account or administrative boundary. This reduces the risk of losing both production data and backups through the same compromised account.

3. Choose the Right PostgreSQL Backup Strategy

PostgreSQL provides several backup approaches. The right choice depends on database size, recovery requirements, and operational complexity.

Logical Backup with pg_dump

pg_dump creates a logical backup of a PostgreSQL database.

For example:

pg_dump -Fc -d myapp_prod > myapp.dump

The -Fc option produces a custom-format archive.

This format is particularly useful for application databases because it supports selective restoration and works with pg_restore.

Advantages include:

  • Straightforward implementation.
  • Support for selective restoration.
  • Portability across supported PostgreSQL environments.
  • No requirement to copy the entire database directory.
  • Suitability for many small and medium-sized applications.

Inspect the archive:

pg_restore -l myapp.dump

Restore it into a separate database:

pg_restore -d myapp_restore_test myapp.dump

There is one important limitation: pg_dump backs up a single database. It does not automatically include cluster-wide roles and tablespaces.

If those objects are required for recovery, back them up separately. For example:

pg_dumpall --globals-only > globals.sql

Physical Backup

A physical backup copies PostgreSQL's underlying database files.

Common approaches include:

  • pg_basebackup.
  • Filesystem-level snapshots.
  • Storage-level snapshots.
  • Dedicated PostgreSQL backup solutions.

Physical backups are useful for larger databases and recovery strategies that need to preserve the database cluster.

However, they require more careful handling of PostgreSQL versions, filesystem consistency, WAL files, and recovery procedures.

Point-in-Time Recovery

A daily logical backup provides a recovery point at the time the dump was created.

It does not automatically provide recovery to an arbitrary moment between two backups.

For example, if a database is backed up at 02:00 and accidental deletion occurs at 16:00, restoring the previous night's dump may lose up to 14 hours of changes.

PostgreSQL supports Point-in-Time Recovery (PITR) using a base backup together with archived Write-Ahead Log (WAL) files.

This allows recovery to a particular point in time, subject to the backup and WAL archive configuration.

For applications with stricter recovery requirements, WAL archiving and PITR may be more appropriate than relying exclusively on daily logical dumps.

4. Define Recovery Objectives Before Choosing a Schedule

Two important concepts help determine how frequently backups should run and how quickly recovery must happen.

Recovery Point Objective (RPO)

RPO describes how much data loss an application can tolerate, measured in time.

For example:

Backup frequency Approximate maximum data loss
Every 24 hours Up to 24 hours
Every 12 hours Up to 12 hours
Every 6 hours Up to 6 hours
Every hour Up to 1 hour

These are simplified estimates assuming the most recent scheduled backup succeeded.

Recovery Time Objective (RTO)

RTO describes how long an application can remain unavailable while recovery is performed.

A personal application might tolerate several hours of downtime, while a business-critical application may require recovery within minutes.

These objectives influence the backup design.

A daily pg_dump may be perfectly reasonable for a personal application with modest data changes. It may be insufficient for an application that processes financial transactions continuously.

The goal is not to build the most complicated backup system. It is to build one that meets the application's actual recovery requirements.

5. Build a Reliable Backup Pipeline

Once the backup method and schedule are established, the next step is automation.

A typical automated workflow consists of several stages:

       Start Backup Job
              |
              v
       Create Database Dump
              |
              v
       Validate Local Archive
              |
              v
       Upload to Remote Storage
              |
              v
       Verify Uploaded Object
              |
              v
       Apply Retention Policy
              |
              v
       Record Execution Result
              |
              v
       Report Success or Failure

Each stage should have a clear success or failure condition.

Create the Backup

For a local PostgreSQL installation on Linux:

sudo -u postgres pg_dump \
  -Fc \
  -d myapp_prod \
  > /tmp/myapp.dump

Using the PostgreSQL system account avoids unnecessarily exposing database credentials in the backup script.

The output redirection is performed by the calling shell, so the resulting file belongs to the user running the script.

This is useful when the backup script runs as a dedicated system user.

Validate the Archive

Before uploading the file, check that it exists and is not empty:

test -s /tmp/myapp.dump

Inspect the archive:

pg_restore -l /tmp/myapp.dump > /dev/null

This confirms that PostgreSQL can read the archive's table of contents.

It is a useful validation step, although it does not prove that every database object can be successfully restored.

Upload to Remote Storage

Upload the generated archive using the cloud provider's CLI or SDK.

For example, with OCI Object Storage:

oci os object put \
  --auth instance_principal \
  --namespace YOUR_NAMESPACE \
  --bucket-name myapp-db-backups \
  --name backups/daily/myapp-backup.dump \
  --file /tmp/myapp.dump

The example uses OCI Instance Principal authentication.

This is preferable to storing long-lived API keys on an OCI compute instance when the instance identity can be used.

For other cloud providers, use the equivalent instance identity, workload identity, or managed identity mechanism where available.

The principle is to avoid embedding long-lived credentials in scripts or source repositories.

Verify the Uploaded Object

A successful CLI upload should not be treated as the only verification.

At minimum, check that the remote object exists and that its size matches the local file.

For example:

stat -c '%s' /tmp/myapp.dump

Then inspect the remote object's metadata using the cloud provider's CLI.

For stronger verification, calculate a cryptographic checksum before upload and compare it with a checksum obtained from the downloaded object.

For example:

sha256sum /tmp/myapp.dump

A matching SHA-256 checksum provides stronger evidence that the downloaded object is byte-for-byte identical to the original archive.

Do not assume an object storage ETag is always a SHA-256 checksum. Its meaning can vary depending on the provider and upload method.

6. Implement a Retention Policy

Keeping every backup forever is usually unnecessary and can eventually increase storage costs.

A retention policy defines how many backups should remain available.

For example:

backups/
  daily/
    myapp-2026-11-20.dump
    myapp-2026-11-21.dump
    myapp-2026-11-22.dump
    myapp-2026-11-23.dump

A simple policy might keep the latest 14 successful daily backups.

The backup process should:

  1. List existing backup objects.
  2. Identify valid backup filenames.
  3. Sort them by timestamp.
  4. Keep the newest 14.
  5. Delete older backups.

There is an important distinction between retaining 14 backups and retaining 14 calendar days of history.

If a scheduled job fails for several days, keeping the latest 14 successful backups may preserve a longer period of history.

For production systems, retention should also consider:

  • Weekly backups.
  • Monthly backups.
  • Long-term archival requirements.
  • Regulatory requirements.
  • Protection against accidental deletion.
  • Immutable or object-locked backups.

A useful strategy is to maintain short-term daily backups and separate longer-term recovery points.

Never delete older backups before confirming that the new backup has been uploaded and verified.

A failed backup should never cause the last known-good backup to be deleted.

7. Schedule Backups with an Operating System Scheduler

A backup process should run automatically without requiring someone to remember to execute it.

On a Linux VPS, systemd timers provide a convenient way to schedule recurring jobs.

They offer several advantages:

  • Integration with the operating system.
  • Centralized execution logs.
  • Clear service status.
  • Automatic execution after a missed schedule when configured appropriately.

A service unit can look like this:

[Unit]
Description=PostgreSQL Backup
Wants=network-online.target
After=network-online.target postgresql.service

[Service]
Type=oneshot
User=backup
Group=backup
ExecStart=/opt/myapp-backup/backup.sh

The timer:

[Unit]
Description=Daily PostgreSQL Backup Timer

[Timer]
OnCalendar=*-*-* 02:00:00 UTC
Persistent=true
Unit=myapp-backup.service

[Install]
WantedBy=timers.target

Enable the timer:

sudo systemctl daemon-reload

sudo systemctl enable --now myapp-backup.timer

Check the next execution:

systemctl list-timers myapp-backup.timer

Inspect execution logs:

sudo journalctl -u myapp-backup.service

The Persistent=true option is useful because systemd can trigger a missed execution when the timer becomes active again.

However, it does not replace monitoring. A timer being active only proves that the schedule is enabled, not that every backup completed successfully.

8. Protect Backup Data and Credentials

Database backups often contain more sensitive information than application source code.

They may include:

  • User records.
  • Email addresses.
  • Authentication-related data.
  • Business transactions.
  • Application configuration stored in database tables.
  • Other private information.

Treat backup archives as sensitive production data.

Private Storage

Do not make backup buckets or objects publicly accessible.

Use narrowly scoped IAM policies that grant only the permissions required by the backup process.

Identity-Based Authentication

Prefer instance or workload identities over long-lived access keys where supported.

Avoid putting credentials directly in shell scripts, Git repositories, or command history.

Encryption

Use encryption in transit and at rest.

Cloud object storage commonly provides server-side encryption, but applications with stricter requirements may also consider client-side encryption.

Access Separation

The backup process should not automatically have broad administrative permissions over the entire cloud account.

Where possible, separate the permissions required to upload backups from those required to delete or administer them.

Protection Against Deletion

Consider object versioning, retention locks, or immutable storage where appropriate.

This helps protect backups from accidental deletion and certain compromised-account scenarios.

A backup stored in the same cloud account with unrestricted deletion permissions is not fully protected against an attacker who gains administrative access to that account.

9. Test Recovery in an Isolated Environment

This is arguably the most important part of the entire process.

Do not use the production database as your first restore target.

Instead, create a separate recovery environment.

For example:

Production PostgreSQL
        |
        | Backup
        v
Remote Object Storage
        |
        | Download
        v
Local Recovery Environment
        |
        v
Isolated PostgreSQL
        |
        v
myapp_restore_test

This allows recovery testing without affecting production data.

Download a Backup

Download one of the stored backup archives to the recovery machine.

For example:

oci os object get \
  --namespace YOUR_NAMESPACE \
  --bucket-name myapp-db-backups \
  --name backups/daily/YOUR_BACKUP_FILENAME \
  --file ~/Downloads/myapp-restore-test.dump

Create a Separate Database

Using DBeaver or createdb, create a new empty database:

myapp_restore_test

Make sure the database belongs to the local recovery PostgreSQL instance.

Restore the Archive

For command-line restoration:

pg_restore \
  --no-owner \
  --no-privileges \
  -d myapp_restore_test \
  ~/Downloads/myapp-restore-test.dump

The --no-owner and --no-privileges options are useful when the original production roles and permissions do not exist in the local environment.

Alternatively, DBeaver provides a graphical restore workflow:

  1. Select the test database.
  2. Open Tools → Restore.
  3. Select the downloaded custom-format archive.
  4. Configure the PostgreSQL native client.
  5. Set the appropriate restore options.
  6. Start the restore.

DBeaver uses PostgreSQL's native pg_restore utility behind the scenes.

Verify the Restored Database

A restore command completing successfully is not the final verification.

Check:

  • Expected tables exist.
  • Important indexes and constraints exist.
  • Row counts are reasonable.
  • Important relationships remain intact.
  • Application queries execute successfully.
  • Required database roles and permissions are available.

For example:

SELECT COUNT(*) FROM users;

SELECT COUNT(*) FROM orders;

SELECT COUNT(*) FROM transactions;

The table names are illustrative; use the important tables in your own application.

For a more complete test, connect a staging copy of the application to the restored database and exercise critical application workflows.

The objective is to prove that the database is not only restorable but also usable.

10. Monitor Backup Jobs

Automation without monitoring can create a false sense of security.

A scheduled backup may fail because of:

  • Database connection problems.
  • Insufficient disk space.
  • Network failures.
  • IAM permission changes.
  • Object storage service issues.
  • Invalid credentials.
  • Script errors.

At a minimum, monitor the following:

Check What it tells you
Latest backup timestamp Whether a recent backup exists
Backup job exit status Whether the last execution succeeded
Backup file size Whether the archive is unexpectedly small
Remote object existence Whether the upload completed
Storage usage Whether retention is working
Restore test result Whether recovery is possible

A practical monitoring system should alert you when a scheduled backup fails or when no successful backup has appeared within the expected time window.

Do not rely solely on checking the timer's status.

A useful distinction is that a scheduled job being active, a backup command completing successfully, and a database being recoverable are three different things.

11. Common Mistakes to Avoid

A few mistakes can undermine an otherwise good backup strategy.

Keeping Backups Only on the Same VPS

A backup on the same disk does not protect against disk failure or VPS deletion.

Use independent storage.

Assuming Upload Success Means Backup Success

An upload command completing does not prove that the archive is restorable.

Validate the archive and periodically perform actual restoration tests.

Storing Credentials in Scripts

Hardcoded credentials create unnecessary security risks.

Use workload identity or managed identity where supported.

Deleting Old Backups Too Early

Retention cleanup should happen only after the new backup has been uploaded and verified.

A failed backup should never cause the last known-good backup to be deleted.

Ignoring Database Roles and Global Objects

A database dump does not automatically include all cluster-wide PostgreSQL roles and tablespaces.

Understand which database-level and cluster-level objects your recovery process needs.

Confusing Daily Backups with Point-in-Time Recovery

A daily dump cannot recover changes made after its creation.

If the application requires a smaller recovery point, consider WAL archiving and PITR.

Never Testing Recovery

This is the most dangerous mistake.

A backup process that has never been tested through restoration is an assumption, not a verified recovery strategy.

12. A Practical Implementation Checklist

For a small PostgreSQL application, the following checklist is a reasonable starting point.

  • Define acceptable RPO and RTO.
  • Choose a suitable PostgreSQL backup method.
  • Create a private remote storage bucket.
  • Configure identity-based authentication.
  • Implement automated backup generation.
  • Validate the generated archive.
  • Upload the backup to remote storage.
  • Verify the uploaded object.
  • Configure a retention policy.
  • Schedule the job using systemd or an equivalent scheduler.
  • Monitor execution failures.
  • Download a backup to a separate environment.
  • Restore it into an isolated database.
  • Verify database structure and important data.
  • Document the recovery procedure.
  • Repeat recovery testing periodically.

13. The Practical Takeaway

A reliable database backup strategy is not simply a command that runs every night.

It is a complete operational pattern:

Create → Validate → Upload → Verify → Retain → Monitor → Restore → Test

Each stage addresses a different failure scenario.

For a small application, PostgreSQL custom-format dumps, private object storage, identity-based authentication, automated scheduling, and a tested restore process can provide a practical balance between reliability and operational complexity.

As the application grows, its recovery requirements may change. More frequent backups, WAL archiving, point-in-time recovery, immutable storage, and separate disaster recovery environments may become necessary.

The most important principle remains unchanged:

Do not measure your backup strategy by how many backup files you have. Measure it by whether you can recover your application when something goes wrong.

References

Related Posts

Back Up a Live SQLite Database Without Copying the Wrong File

Learn why live SQLite file copies can fail, and when to use the Backup API, VACUUM INTO, or sqlite3_rsync instead.

GitHub Desktop Multiple Accounts: Keep Sign-In and Commit Identity Separate

Use GitHub Desktop's per-repository account selection without confusing remote authentication with the Git name and email recorded in commits.

GitHub Actions Workflow Logs: Detect and Respond to Leaked Secrets

Enable GitHub workflow log secret scanning carefully, review preview gaps, and revoke leaked credentials with a practical response checklist.