StackPilot

How to Back Up a Postgres Database to Object Storage

By The StackPilot Team 7 min read

Some links on this page are affiliate links. If you sign up through them we may earn a commission at no extra cost to you. We only link to services we have actually used, and commission never decides what we recommend.

You got pg_dump | gzip | aws s3 cp - working, the cron job runs, and the bucket has files in it. Then you tried to restore one and found a 40-byte gzip that pg_restore rejects, or a dump from three weeks ago that was never overwritten because the job has been failing quietly since a credential rotated. The wall you hit next is almost never the upload — it is verification and retention.

Quick verdict

For a single VPS running Postgres up to a few tens of gigabytes, use pg_dump -Fc written to a local temp file, checked with pg_restore -l, then uploaded with the AWS CLI or rclone, on a timer, with a bucket lifecycle rule for retention and a monthly restore test. That is the cheapest thing that works and it has no lock-in. The tradeoff is recovery point: you lose everything since the last dump. If you cannot accept that, stop reading the pg_dump section and set up pgBackRest or WAL-G for continuous WAL archiving instead — pgBackRest if you want incrementals and a repo you control, WAL-G if you want the shortest config that still does point-in-time recovery.

What you are actually choosing between

OptionCost shapeOps burden, ceiling, lock-in
pg_dump + aws s3 cp or rcloneCheapest tier: storage and request charges only, no extra computeLow burden, low ceiling. Fine into the low tens of GB; no PITR; portable custom-format dumps, zero lock-in
pgBackRestStorage plus a little compute for the repo hostMedium burden, high ceiling. Full/incremental/differential, parallel compression, PITR; repo layout is pgBackRest-specific but restores are plain Postgres
WAL-GStorage plus computeMedium burden, high ceiling. Fewer knobs than pgBackRest, good fit if your bucket is the only place you want backups to live
Managed provider PITR (your database host's built-in)Premium: bundled into the instance price, usually the most expensive per GB-monthLowest burden, ceiling set by the vendor, highest lock-in — you cannot take the backup with you when you leave

Step by step

1. Decide dump or WAL before you touch a bucket. A logical dump gives you a consistent snapshot at one point in time. WAL archiving gives you the ability to restore to any second. Most small deployments need the first and think they need the second. If your recovery objective is measured in hours, a dump every hour is cheaper and simpler than a WAL repo.

2. Create the bucket and a credential scoped to it. Do not use an account-wide key. Make an IAM user or service account with s3:PutObject, s3:GetObject, s3:ListBucket, and s3:DeleteObject on that one bucket prefix and nothing else. Turn on bucket versioning so an accidental overwrite or a compromised key does not destroy history, and add Object Lock if your compliance story needs immutability.

3. Set the retention rule on the bucket, not in your script. A lifecycle rule that expires objects under daily/ after 30 days and under monthly/ after 12 months keeps working when your cron job does not. Scripts that aws s3 rm old backups fail in exactly the situation where you need them most — the box is down and nothing is running.

4. Write the dump to disk first, then upload. This is the step people skip and it is the one that prevents the silent-truncation failure. In a pipe, the exit status you check is the last command's, so a pg_dump that dies halfway still produces a successful upload of a broken file.

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

DB=appdb
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
TMP=$(mktemp -d)
OUT="$TMP/$DB-$STAMP.dump"

# --no-owner/--no-privileges makes restores into a fresh cluster trivial.
# Drop them if you rely on role grants surviving the restore.
pg_dump -Fc --no-owner --no-privileges -d "$DB" -f "$OUT"

# Read the archive's table of contents. Fails loudly on a truncated file.
pg_restore -l "$OUT" > /dev/null

aws s3 cp "$OUT" "s3://my-pg-backups/daily/$DB-$STAMP.dump" \
  --storage-class STANDARD_IA

rm -rf "$TMP"

If you must stream, keep set -o pipefail in the script and check $? after the pipeline. That catches the failure but still leaves you without a local copy to inspect, so prefer the temp file on anything under a few tens of GB.

5. Rotate the credential before it expires, and alert on failure. The most common cause of a dead backup pipeline is an access key with a 90-day policy that nobody renewed. Wrap the script so a non-zero exit sends you a message — cron mail, a healthcheck ping, whatever you already read. A backup job that fails silently is worse than no backup job, because you stop worrying.

6. Test the restore on a schedule, not in an emergency. Once a month, pull the newest object and restore it into a scratch database on the same or a newer major version:

aws s3 cp s3://my-pg-backups/daily/latest.dump .
createdb restore_test
pg_restore -d restore_test --clean --if-exists latest.dump
psql -d restore_test -c 'select count(*) from your_biggest_table;'

Compare the row count against production. A dump that restores without errors but is missing a table is a failure you will only find this way.

7. If you chose WAL, wire up archiving and watch it. With pgBackRest, archive_mode = on and archive_command = 'pgbackrest --stanza=main archive-push %p' in postgresql.conf, then pgbackrest stanza-create and a first pgbackrest backup --type=full. The failure mode here is specific and nasty: when archive_command fails, Postgres keeps retrying and pg_wal grows until the disk fills and the database stops accepting writes. Monitor pg_stat_archiver.failed_count and set archive_timeout so idle clusters still ship segments.

Where this falls short

pg_dump is a logical backup and it does not give you point-in-time recovery. If someone drops a table at 14:02 and your last dump was 13:00, you have lost an hour of writes and there is no way around that with this method.

Large databases are a poor fit. Dump time scales with database size and index count, restores are single-threaded unless you use pg_restore -j, and a dump that takes longer than your interval means you are permanently behind. Past a few tens of GB, switch to physical backups.

Object storage in the same account as your VPS is one failure domain, not two. A compromised account, a lapsed card, or a misconfigured bucket policy takes out the server and the backups together. Push a copy to a second provider or a second account, or at minimum enable Object Lock so a stolen key cannot delete history.

Restores are where version drift bites. A dump from Postgres 15 restores cleanly into 15 and usually into 16, but not backwards, and extensions must be installed on the target before pg_restore runs. Note the server version in the object key or a sidecar file so you know what you are restoring.

If your database is managed by a provider that already does PITR, and you are not legally required to hold your own copies, use theirs and spend your time on the restore drill instead. Running your own WAL repo against a managed instance is usually duplicated effort.

FAQ

How do I back up a Postgres database to S3 without running out of disk?

Write the dump to a temp file, upload it, then delete it in the same script — never accumulate dumps locally. Size the volume so one dump plus the database fits with headroom, or stream with pg_dump -Fc | aws s3 cp - and accept that you cannot inspect the file before upload.

Is pg_dump safe to run on a production database?

Yes. pg_dump takes a consistent snapshot in a single transaction and does not block writes, though it holds an ACCESS SHARE lock that will queue behind DDL. Long dumps do keep an old snapshot alive, which delays vacuum cleanup, so run them off-peak on busy systems.

How often should I back up Postgres to object storage?

As often as your tolerance for lost writes allows, and no more often than a restore can be verified. Hourly dumps with 30 days of retention are a common starting point for small deployments; anything that needs minutes of recovery should use WAL archiving.

Can I restore a pg_dump from S3 into a different Postgres version?

Usually upward, rarely downward. Restoring a dump into a newer major version works in most cases; going backwards does not. Install any extensions the dump references on the target first, and use --no-owner --no-privileges if roles differ between clusters.

Related reading: How to Test That a Backup Actually Restores, Not Just Runs, Offsite Backup Provider for a One Person SaaS: Picks

Bottom line

For most self-managed Postgres on a VPS, pg_dump -Fc to a local file, verified with pg_restore -l, uploaded to a versioned bucket with a lifecycle rule, plus a monthly restore into a scratch database, is the right answer. It is cheap, portable, and you can read the whole pipeline in one screen. Reach for pgBackRest or WAL-G the moment you need point-in-time recovery or the dump starts taking longer than the interval between dumps.

Today, do one thing: run the script in step 4 by hand, restore the resulting file into a scratch database, and count rows. You will either find your pipeline already works or find the problem while it is still cheap.