HomeBlogHow to Set Up Automated Backups...

Engineering Guide · 8 min read · June 28, 2026

How to Set Up Automated Backups for PostgreSQL

A nightly pg_dump cron job is not a disaster recovery strategy once your database grows past a few gigabytes or an engineer drops a table at 2:15 PM. Learn how to configure pgBackRest physical base backups, continuous WAL archiving to immutable object storage, and automated weekly restore verification.

Author
Smit Desai
Published
June 28, 2026
Read time
8 min read
Topic
Cloud & DevOps
Services
Custom Web · Mobile Apps · All Services

Almost every team thinks they have database backups until the day an engineer runs a migration against production without a WHERE clause at 2:14 PM. If your backup strategy is a nightly pg_dump script writing .sql.gz files to the same server disk, you are looking at up to 24 hours of lost customer transactions—and a multi-hour index rebuild while your application stays offline.

Real PostgreSQL disaster recovery rests on three pillars: continuous Write-Ahead Log (WAL) archiving for Point-in-Time Recovery (PITR), physical base backups that restore at disk-copy speed, and automated restore drills that prove the files are actually readable. Having maintained production Linux databases across 170+ shipped systems and managed 300+ live client sites at server level for a Finnish partner, I treat an untested backup the same way I treat an untested deployment: it does not exist.

Choose the Right Backup Method for Your Database Size

Logical dumps (pg_dump) and physical continuous archiving (pgBackRest or WAL-G) solve different problems. Mixing them up leaves businesses exposed to slow recoveries or silent corruption.

Backup Strategy Typical RPO Restore Speed (100 GB DB) Point-in-Time Recovery Best Use Case
pg_dump nightly cron Up to 24 hours Slow (replays SQL & rebuilds indexes) No Small DBs (<5 GB), logical schema/table exports
Cloud VM / EBS snapshots Snapshot interval Fast volume attach No (crash-consistent unless quiesced) Quick environment cloning, coarse infra recovery
Physical base + WAL (pgBackRest) Seconds to ~1–5 min Fast (parallel file copy + WAL replay) Yes (exact timestamp or LSN) Production SaaS and transactional business databases

Keep pg_dump around for portable logical archives or restoring a single accidentally truncated lookup table into a scratch database. For primary production continuity, use physical backups with continuous WAL archiving.

Configure Continuous WAL Archiving With pgBackRest

pgBackRest handles parallel compression, checksums, incremental backups, retention expiration, and direct S3-compatible object storage encryption out of the box.

Step 1: Set PostgreSQL Archiving Parameters

In postgresql.conf, enable WAL archiving and ensure wal_level is at least replica:

wal_level = replica
archive_mode = on
archive_command = 'pgbackrest --stanza=prod_db archive-push %p'
archive_timeout = 300
max_wal_senders = 4

Setting archive_timeout = 300 forces PostgreSQL to switch and archive a WAL segment every 5 minutes even during quiet overnight traffic, capping your worst-case data loss window (RPO) at five minutes.

Step 2: Configure the pgBackRest Stanza and S3 Repository

Create /etc/pgbackrest.conf with encryption enabled and an explicit retention policy (full weekly + diff daily):

[global]
repo1-type=s3
repo1-s3-bucket=company-pg-backups-prod
repo1-s3-region=eu-central-1
repo1-s3-endpoint=s3.eu-central-1.amazonaws.com
repo1-path=/pgbackrest
repo1-cipher-type=aes-256-cbc
repo1-cipher-pass=REPLACE_WITH_KMS_OR_VAULT_SECRET
repo1-retention-full=4
repo1-retention-diff=14
process-max=4
start-fast=y

[prod_db]
pg1-path=/var/lib/postgresql/16/main

Initialize and verify the stanza before trusting any schedule:

sudo -u postgres pgbackrest --stanza=prod_db stanza-create
sudo -u postgres pgbackrest --stanza=prod_db check

If pgbackrest check fails, PostgreSQL will keep accumulating unarchived WAL segments inside pg_wal/ until the root disk fills up and crashes the database. Always alert on archive_command failures and pg_wal directory growth.

Step 3: Schedule Full and Differential Backups

Run a weekly full backup and daily differential backups via systemd timers (preferable to plain cron because systemd logs exit statuses cleanly to journald):

# /etc/systemd/system/pgbackrest-diff.service
[Unit]
Description=PostgreSQL Differential Backup via pgBackRest

[Service]
Type=oneshot
User=postgres
ExecStart=/usr/bin/pgbackrest --stanza=prod_db --type=diff backup

Pair that unit with a daily OnCalendar=02:15 timer, and run a separate --type=full unit every Sunday at 01:00.

Isolate Backup Credentials and Enable Immutability

If an attacker—or a misconfigured cleanup script—gains root access to your database server and that server holds s3:DeleteObject permissions on the backup bucket, your backups can be wiped in seconds.

Follow three strict boundary rules:

  1. Append-only IAM policy on the DB host: Grant the database backup role s3:PutObject, s3:GetObject, and s3:ListBucket, and explicitly deny s3:DeleteObject and s3:DeleteObjectVersion.
  2. S3 Object Lock: Enable bucket versioning and Object Lock in Governance (or Compliance) mode for 14–30 days so even root credentials in the backup account cannot purge recent recovery points early.
  3. Cross-account replication: Copy backups into a locked-down security/audit AWS account separate from production workloads.

More cloud resiliency patterns for stateful workloads are documented in the AWS Architecture Center.

Automate Weekly Restore Drills (Don't Trust Exit Code 0)

A backup job exiting with status 0 only confirms bytes were uploaded; it does not prove your encryption passphrase works, your WAL chain has zero gaps, or your team knows the exact restore commands under stress.

Spin up an ephemeral restore-verification instance weekly via CI or a scheduled job:

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

# Restore latest backup + WAL to a temporary isolated directory
pgbackrest --stanza=prod_db \
  --pg1-path=/var/lib/postgresql/restore-verify \
  --delta \
  restore

# Start isolated PostgreSQL on port 5433 and run sanity queries
pg_ctlcluster 16 restore-verify start
psql -p 5433 -U postgres -d app_prod -c "SELECT count(*) FROM users; SELECT max(created_at) FROM orders;"
pg_ctlcluster 16 restore-verify stop

Record the elapsed duration of that script as your real, measured RTO. If restoring 120 GB takes 42 minutes in a drill, you know your exact recovery SLA before an incident happens. Pair these checks with alerting on stale backups, which we cover alongside service metrics in monitoring production applications with Prometheus and Grafana.

Practising Point-in-Time Recovery Before an Incident

Document a two-step runbook for your on-call engineer so nobody has to guess recovery_target_time flags at 3 AM:

pgbackrest --stanza=prod_db \
  --type=time \
  --target="2026-01-20 14:13:45+00" \
  --target-action=promote \
  restore

Always restore to a fresh volume or staging node first, inspect the dropped table or corrupted rows, and either promote the restored instance or dump just the affected table back into production. Never overwrite your only remaining primary data directory blindly before inspecting the recovered state.

If you are inheriting legacy servers with undocumented cron scripts or fragile database storage, our upgrade old software and infrastructure hardening services bring your backups up to audit-ready reliability.

Hardening Your PostgreSQL Reliability With SmitDev

At SmitDev, we build production database backup, replication, and disaster-recovery pipelines that pass real restore drills—not just checkbox audits. You can engage a senior infrastructure engineer at $55/day for 8–9 hours of dedicated engineering work or $1,999/month for dedicated delivery, with remote software engineering across US, UK, EU, UAE, Australian, and Singapore time zones.

Need an end-to-end PostgreSQL backup, S3 immutability, and PITR drill setup this week? Contact our team with your current Postgres version and database size, and we will scope a clean implementation and runbook for your stack.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

cloud & devops

Why is pg_dump alone risky for production PostgreSQL databases?

pg_dump creates a logical snapshot at a single point in time, meaning everything written between last night's dump and an outage is lost. On large databases, restoring from pg_dump also takes hours because every index and foreign key must be rebuilt sequentially.

What is the difference between RPO and RTO in PostgreSQL backups?

RPO (Recovery Point Objective) is the maximum amount of recent data you can afford to lose—typically seconds to minutes with continuous WAL archiving. RTO (Recovery Time Objective) is how long it takes to bring a restored database back online.

How do you protect PostgreSQL backups against ransomware or accidental deletion?

Write backups to a separate cloud account or dedicated IAM user that has permission to PutObject but cannot delete or overwrite existing backup objects, and enable S3 Object Lock in Governance or Compliance mode for your retention window.

Do managed databases like RDS still need separate backup verification?

Yes. Automated cloud snapshots protect against disk loss, but they do not prevent logical corruption, bad migrations, or compromised credentials inside the same AWS account. Exporting periodic logical snapshots or cross-account backups and running automated restore tests closes that gap.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.