Docs / Surfaces / Databases / PostgreSQL

PostgreSQL

SafeGrd backs up PostgreSQL 13 and later from a read-only role. By default each backup uploads only what changed since the last one. Supabase, Amazon RDS and Neon each have a section at the end of this page.

# PostgreSQL 13 and later; the test suite runs 16
safegrd backup --database-url "$DATABASE_URL" --retention-days 14

The schema comes from pg_dump: types, tables, functions, views, indexes, constraints and triggers, exactly as Postgres describes them. The rows are copied over the wire with binary COPY, table by table, in chunks. A table larger than the host's memory backs up without staging anything on disk. Both are read from one snapshot, so if the database is written to during the backup, the rows, row counts and sequence positions still agree.

A drill on a database surface checks table counts, row counts, column counts and installed extensions, and that every role the schema names is in the backup. See Restore and Fire Drills.

Large objects (pg_largeobject, made with lo_import or lo_create) are in the backup, read under the same snapshot as the tables. A restore brings each one back under its own oid, with its bytes and its owner, so the rows that point at them work again. A Fire Drill checks every object's bytes against the digest the backup recorded. With --to-sql, each one becomes a lo_create file that load.sql runs after the tables. Grants on a large object (GRANT SELECT ON LARGE OBJECT) are not restored, so grant them again after a restore.

A database that uses pgvector backs up and drills like any other. SafeGrd's tests back up a table of vector columns and run a sandbox drill that restores every row. Install pgvector in the database you drill or restore into.

Roles, owners and grants

The schema is dumped with each object's owner, grants and default privileges, and each table's policies name the roles they apply to. SafeGrd backs up the roles these name (owners, grantees, policy roles) in roles.sql beside the schema, as pg_dumpall --roles-only writes them, with their password hashes. The cluster's other roles are not backed up.

Before the schema runs, a restore creates the roles the target does not have and prints Created role for each one. A created role is never a superuser or a replication role. Its login and password are as they were, so an application role logs in on the new cluster as it did on the old one.

safegrd restore --no-owner restores without owners and grants, so every object belongs to the restoring role. It still creates the roles, because a policy cannot be restored without them.

If the restoring role is not a superuser, the restore skips the owners and grants it may not set: an owner it is not a member of, or a grant on an object it does not own. It says how many it skipped and gives those objects to the restoring role. The roles it creates get no CREATEDB, CREATEROLE or BYPASSRLS, because only a role that holds them may set them. To keep every owner and attribute, restore as a superuser.

The daemon's sandbox drill creates the roles the same way and drops them with the sandbox. If the cluster does not have a role the schema names, the role the sandbox URL connects as needs CREATEROLE. verify --sandbox-target keeps what it restored, roles included, so you can look at it.

To leave the password hashes out, set roles_without_passwords: true on a surface or pass --roles-without-passwords to safegrd backup. A restore then creates the roles without a password. The same happens when the backup role cannot read pg_authid (an RDS master user, Supabase's postgres), and the backup says so. A surface SafeGrd backs up for you has no such switch and keeps the hashes.

The in-memory drill fails a snapshot whose schema names a role the snapshot does not carry, because no fresh cluster could load it. Snapshots taken before 5 October 2026 carry no roles. The next backup does.

pg_cron jobs

If the database has pg_cron, each backup records its jobs (name, schedule, command, user) in the snapshot, encrypted. The commands stay in the snapshot and never reach SafeGrd's server, because a command can hold a key.

Check the backups another tool makes

If Coolify, a cron pg_dump or another tool already backs up the database, SafeGrd can check those backups where that tool stores them, instead of taking its own:

surfaces:
- id: app-db
type: postgres
schedule: daily
watch:
url: s3://my-backups/data/coolify/backups/databases/team-0/app-db
endpoint: https://ACCOUNT.r2.cloudflarestorage.com
access_key: env:R2_KEY_ID
secret_key: env:R2_SECRET

Set schedule to how often the other tool writes. On that schedule the daemon lists the location and reads the newest backup once. It records the backup's SHA-256 and counts every table's rows from the dump, then reports that as a backup, dated when the other tool wrote it. If a check finds the same backup as last time, it reports nothing.

So the surface goes Overdue when the other tool has written nothing for twice its schedule, and Threat Shield compares each backup's rows and size with the last one. A dump that does not open, or ends early, is a failed backup.

A Fire Drill reads the backup again and checks that its SHA-256 is the one the check read. It loads the backup into the sandbox in one transaction with pg_restore or psql, and compares every table's rows. It leaves out the rows of pg_cron's job table, so nothing the backup scheduled runs. On the free plan the drill counts the backup again in memory.

The certificate names the tool that made the backup. It proves the backup restores and holds the rows it held when SafeGrd first read it. SafeGrd never read the database, so the certificate cannot show that the dump holds all of it.

Check them with no host

In the console, click Back up on SafeGrd, pick the database's engine and tick Check the backups another tool makes. Then give the bucket, the prefix and a key that can list and read it.

SafeGrd holds the key, encrypted, and uses it only on the machines it starts: a check on the surface's schedule, and the drills on your plan's cadence. A check that finds nothing new records nothing, so the surface still goes Overdue when the tool stops writing. The drill's machine gets the same key to read the backup again, and never a database credential. Every use of the key is in the key access log.

The erasure record

A backup taken on Monday holds the account a user deleted on Tuesday. Restore it on Wednesday and the account is back. Name the tables whose deleted rows are erasures, and a restore deletes them again before it commits:

surfaces:
- id: app-db
type: postgres
database_url: env:DATABASE_URL
erasures: [public.users, public.profiles]

How deletes are recorded

The next backup adds a safegrd schema to the database, with a table safegrd.erasures and a trigger on each named table. When a row is deleted, the trigger records its primary key, the transaction and the time. It does not record the row. Each table needs a primary key. The backup's role must be able to create a schema in the database and triggers on the tables, which the owner of both can do.

The daemon moves those records out of the database on every check-in, and every backup moves them first. They go to the surface's storage at <host>/erasures/<surface>/, encrypted to your key like the backups. Each one is locked for as long as a backup taken at that time could be kept. If a record cannot be moved, it stays in the table for the next try, and the console shows the storage as failing.

What a restore does

A restore reads the record before it writes anything. After it loads and counts the rows, it deletes every row erased after the backup was taken, along with whatever ON DELETE CASCADE removes with it. It prints how many rows it removed from each table. An erasure the backup already saw is not replayed, so a row inserted since with the same key is treated as a new row.

If the record cannot be read (another bucket, an export, a missing key), nothing is restored. The error names --without-erasures, which restores anyway and says erased rows may be back.

A sandbox drill replays the record after the counts are checked, and an in-memory drill opens it. If the record cannot be read, you find out from a drill before the day you restore.

Limits and storage

The record does not cover a TRUNCATE, tables you do not name, or copies of the data outside the database, such as files in Storage or logs. Do not name a table whose deletes are routine (sessions, carts), because every delete writes a record.

The record works on local storage, your own bucket or hosted storage, in the default repo format. On hosted storage, SafeGrd signs each object's write and read as it does for a backup, and sets its lock to the longest any of your backups could be kept. SafeGrd reads none of it, because the record is encrypted to your key. DROP SCHEMA safegrd CASCADE removes the trigger and the table.

An object of the record is deleted once its lock has ended and no backup of the surface is older than the newest erasure in it. safegrd prune deletes it in your own bucket and on local storage, and SafeGrd deletes it on hosted storage. If a bucket's policy refuses deletes, the bucket's lifecycle rule has to remove it.

Each backup uploads what changed

A PostgreSQL backup is a run of the surface's repository. Each table is one file of the run, cut into chunks of about 64 KiB. A later run in the same month uploads and locks only the chunks that changed. A table nobody wrote, or one that only grows at the end, adds almost nothing. A table updated at random rows all over can add its whole size on every run. The snapshot detail in the console shows what each table uploaded.

Three runs of one database in a month. The first run uploads every chunk of every table. In the next runs, orders, which only grows, uploads one new chunk at its end; users, updated at rows all over, uploads the chunks around the changed rows; countries, which nobody wrote, uploads nothing. 1st run of the month uploads 15 chunks orders users countries Next run uploads 4 chunks orders users countries The run after uploads 3 chunks orders users countries uploaded and locked already stored, reused
Each square is a chunk of about 64 KiB. Every run is still a full restore point: it lists every chunk of every table, and reuses the ones already stored.

Every run is a restore point: a restore brings the database back as that run read it. There is no restore point between two runs. For one archive per backup instead, pass --format tar or set format: tar on a surface. When you add a surface in the console, Backup type sets this: Incremental or Full.

On hosted storage, you can download a full backup as one file from the console. An incremental one restores on a host (hosted storage). MySQL, MongoDB and SQLite databases are incremental by default too.

# the whole database, into an empty one
safegrd restore --snapshot snap-20261004-091500-a1b2c3 --target "postgres://…/app_restored"
# one table: into an empty table of the same definition, or created if it was dropped
safegrd restore --snapshot snap-20261004-091500-a1b2c3 --table public.orders --target "postgres://…/app"
# every version of one table, by run
safegrd find --table public.orders

You can give --table more than once. The tables all come from one run, so they are consistent with each other. They load in one transaction, which commits only if every table matches its SHA-256 and its row count. The target's other tables stay as they are.

If the target no longer has a table, for example because an agent dropped it, the restore creates it as the run defined it, with its sequences, constraints and indexes. Its sequences are set to where the run left them. A table the target still has must be empty and defined as it was.

The command prints the run's time, the tables the restored ones point at that it did not load, and the sequences of an existing table that it did not move. restore --table public.orders --version 3 restores the third version that find --table lists.

To look at a table's backup beside the live one, use --as. restore --table public.orders --as public.orders_restored creates orders_restored with the live table's columns and no indexes, constraints or defaults, and loads the backup's rows into it. The live table stays as it is. It has to be defined as the backup recorded it. Compare the two with SQL, copy back what you need, and drop the copy. To put chosen rows straight back by primary key, use --rows.

--table works on a full backup (format: tar) too, with the same checks. The restore reads the archive twice, once for its definitions and once for the chosen tables' rows, and checks each read against the backup's SHA-256. A created table's foreign keys are added after the rows, so you can restore tables that point at each other together.

Skip tables nobody wrote

A run reads every table, because a database has no file times to compare. On a large database that read takes minutes and loads the server on every run. With --change-log, or change_log: true on a surface, a run skips each table that nothing has written to since the last run:

safegrd backup --database-url "$DATABASE_URL" --change-log
# [postgres-1a2b3c] 5 of 9 tables not read: the change log shows no write since the last run.

Restore to a point in time

A backup restores the database as it was when the run started. If you also archive its write-ahead log (WAL), you can restore a PostgreSQL you run yourself to any second inside a window, 7 days by default. Supabase, Neon and RDS do not let you set archive_command, so this is for self-hosted PostgreSQL 13 or newer. Give the surface a wal: block:

surfaces:
  - id: appdb
    type: postgres
    database_url: env:DATABASE_URL
    wal:
      window_days: 7
A timeline of the last 8 days. A base backup is taken every 7 days. The WAL is archived as it is written; each day's WAL is joined into one locked bundle, and the current day's stays unlocked until then. A restore to 14:52 four days ago starts from the base before that time and replays the WAL up to 14:52. Any second in the last 7 days can be the target. restore to any second in here base every 7 days WAL --to 14:52 replay from the base before it 8 days ago now a day of WAL, locked today, not yet locked
Each day's WAL is joined into one locked bundle, so up to a day of it is unlocked at any time. A restore starts from the newest base before the time you name and replays the WAL up to it.

Then set these in postgresql.conf and restart PostgreSQL:

wal_level = replica
archive_mode = on
archive_command = 'safegrd --config /etc/safegrd/config.yaml wal push --surface appdb %p'

How the WAL is stored

Each WAL file is compressed and encrypted on the host and written to your bucket unlocked. Once a day the daemon joins them into one locked bundle and deletes the unlocked copies, so up to a day of WAL is kept without a lock. Deleting them needs s3:DeleteObjectVersion on wal/. Without it, the copies stay beside the bundle and the daemon says so.

On hosted storage the window is 7 days on Growth and 30 on Scale. SafeGrd sets every lock and deletes the WAL files a bundle holds, so the host does not hold a storage key.

Base backups

The daemon takes a base backup with pg_basebackup every 7 days (base_every_days). The surface's role needs REPLICATION (ALTER ROLE safegrd_backup REPLICATION;), and pg_hba.conf needs a replication line for the host. safegrd wal base --surface appdb takes one now.

To spare the primary, point the surface's database_url at a standby. The base is taken there and its WAL comes from the primary's archive. The base records the standby and how far behind its primary it was.

A base backup of a cluster with a tablespace outside its data directory is refused before anything is uploaded, and the error names each tablespace. The surface's scheduled backups still cover every tablespace.

On a cluster with data checksums, a page that fails its checksum is read again before it is reported. A page that still fails does not fail the base. The host names the file and the page count, and wal status lists them under Damaged pages.

Incremental base backups

On PostgreSQL 17 and newer, the daemon can take an incremental base between the full ones. It holds only the blocks changed since the newest full, so a restore replays less WAL. Set summarize_wal = on in postgresql.conf (a reload is enough) and incremental_every_days: 1 under wal:.

Each incremental is taken from the newest full and locked until the same date as that full, so it never outlives the full it is rebuilt from. The daemon cannot take one on PostgreSQL 16 or older, with summarize_wal off, when the full is past its 7 days, when the window was raised since the full, or when this host did not take the full. Its log then says why, and the next base is a full one when it is due. wal base --full and wal base --incremental ask for one kind.

A restore from an incremental unpacks it and its full beside the target directory, then combines them with pg_combinebackup of the same major version. It needs room for both and for the result.

Run archive_command as the PostgreSQL user

archive_command runs as the user PostgreSQL runs as, so the config and the key file have to belong to that user, at mode 0600. With the bucket and its key in the config, a push never waits on SafeGrd. If the host uses a bucket or a key SafeGrd holds, it asks SafeGrd for it on each push, and the push waits while SafeGrd does not answer.

When a push fails

While a push fails, PostgreSQL keeps the WAL in pg_wal, which grows until the push works again. The daemon checks pg_stat_archiver on every pass and logs archive_command is failing, and SafeGrd alerts your team.

To keep a full disk from stopping the database, set queue_max: "8GB" under wal:. Once more WAL than that is waiting, the oldest is dropped without being archived. wal status lists it, and SafeGrd sends a wal_dropped alert. No restore can replay past it, so take a base backup once the archive is reachable.

Spool WAL on a busy cluster

A busy cluster can produce WAL faster than one upload per file can keep up. With spool: true under wal:, archive_command returns once the file is copied to the spool (spool_dir, default wal-spool in the state directory) and synced. The daemon uploads from the spool, parallel files at a time (4 by default). The user PostgreSQL runs as writes the spool, so the daemon's user needs to read and delete there. safegrd wal drain uploads it now. A restore fetches the same number of WAL files ahead.

Restore points and WAL drills

Before each daily bundle, the daemon marks a restore point and records each table's row count on both sides of it. To mark one now, before a migration for instance, run safegrd wal point --surface appdb. The role needs one more grant for it:

GRANT EXECUTE ON FUNCTION pg_create_restore_point(text) TO safegrd_backup;

Every 7 days (drill_every_days) the daemon tests the archive with the host's PostgreSQL server of the same major version. It restores into a throwaway cluster up to the newest restore point and counts each table against what the point recorded. Then it restores again to the end of the archive. safegrd wal drill --surface appdb runs it now. The console and the surface's certificate show the window and the last drill.

Restore to a moment

safegrd wal status --surface appdb shows the window a restore can reach, how much of it is locked, and any WAL file that is missing. Each base backup's record and each bundle's index is written twice, each copy with its checksum. If one copy is damaged, a restore reads the other. --check reads both copies of each and names any pair that differs.

To restore, run this as the PostgreSQL user, with the same major version the base backup came from:

safegrd wal restore --surface appdb --to "2026-10-17 14:52:00" --pgdata /var/lib/postgresql/restore
pg_ctl -D /var/lib/postgresql/restore start

The surface's Point in time tab in the console writes this command for a moment you pick.

PostgreSQL replays the WAL to that time (UTC) and promotes. To stop somewhere other than a time:

--exclusive stops just before the target. --timeline follows a timeline other than the newest. A numbered timeline is checked against the archive's history of it before anything is written.

If a restore would stop at a missing WAL file, it is refused before it unpacks anything, and the error names the file. Archiving is off on the restored cluster, so it does not write into the archive it came from. Turn it back on once this is the database you keep. On hosted storage, a host that replaces a lost one restores from the old host's archive with --node <old node id>.

To restore over the cluster's own data directory instead of an empty one, stop PostgreSQL and add --delta. The restore compares every file the base holds with the one on the target, byte for byte, and writes only those that differ. After a small fault, it does not write the whole cluster again. It refuses a directory PostgreSQL is running on, or one that belongs to another cluster.

Files the base does not have are removed if they are inside PostgreSQL's own directories (base, global, pg_wal and the other pg_* directories), because PostgreSQL would read them as data. Anything else, such as a log directory, is kept and listed. If a delta restore stops partway, run it again. PostgreSQL will not start on the directory until it finishes.

Keep the backup_label file the restore writes. The restore clears the checkpoint in pg_control, so PostgreSQL 13 to 17 start from the checkpoint the label names. They refuse to start if the label is deleted.

Give SafeGrd a read-only role

SafeGrd only reads your database. Give it a role of its own with no write permissions, so a leaked backup credential cannot change or delete your data.

# PostgreSQL 14 and later
CREATE ROLE safegrd_backup LOGIN PASSWORD 'a strong password';
GRANT pg_read_all_data TO safegrd_backup;

pg_read_all_data is built in from PostgreSQL 14. It grants SELECT on every table, view and sequence and USAGE on every schema, including ones created later, so you do not have to grant each new table. PostgreSQL 13 has no such role. Grant access explicitly and set the default for tables created later:

# PostgreSQL 13: repeat the last three lines for every schema
CREATE ROLE safegrd_backup LOGIN PASSWORD 'a strong password';
GRANT CONNECT ON DATABASE app TO safegrd_backup;
GRANT USAGE ON SCHEMA public TO safegrd_backup;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO safegrd_backup;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO safegrd_backup;

Run the ALTER DEFAULT PRIVILEGES statement too. Without it, the role cannot read tables created later, and they are left out of future backups. pg_dump runs as the same role. Before you go on, check that the role cannot write:

psql "postgres://safegrd_backup:…@db.internal/app" -c "CREATE TABLE sg_probe(i int);"
# expect: ERROR: permission denied for schema public

safegrd doctor checks this for every PostgreSQL surface the host can open, and safegrd claim checks the surfaces it adds. For a database SafeGrd backs up itself, the console checks it when you save the connection string and shows the same advice.

The line Surface <id> role warns when the role is a superuser, can create roles or databases, or can write to any table. It names up to three of those tables and prints the two lines above as the fix. A second line, Surface <id> row security, names the tables whose rows row-level security hides from the role. A role that is not a superuser cannot read password hashes, so roles are backed up without their passwords (roles).

A table the role cannot read does not fail the backup. The snapshot leaves it out, with its partitions and sequences, and the backup prints a warning that names the table and the grant that would include it. Views and row-level security policies that read a left-out table are left out too, and named in a second warning. A restore or restore --to-sql leaves out the foreign keys that point into those tables and says which ones. A Fire Drill of the snapshot passes. The snapshot records the list in left-out.json. Needs CLI v0.0.39.

Row-level security

To back up every row of a table with row-level security (RLS) policies, grant the role BYPASSRLS or back up as the tables' owner. pg_read_all_data does not bypass RLS by itself, so otherwise the backup holds only the rows the policies let the role see.

SafeGrd checks each table before it copies it. The backup prints every table RLS applied to, with the rows copied and the table's estimated size. The console marks the table Row-level security in the snapshot.

Large objects

pg_read_all_data does not reach large objects the role does not own. If a backup holds a large object it may not read, it says how many it left out, and its Fire Drill fails. Back up as their owner, or run GRANT SELECT ON LARGE OBJECT <oid> TO safegrd_backup for each one.

Read replicas

Point SafeGrd at a read replica to keep the backup's reads off your primary. It needs only read access. A backup of a standby holds what the standby had replayed, and the backup says how far behind it was: Read from: a standby, its newest transaction committed 4s before the backup on the primary. The snapshot's panel in the console shows the same. On a primary with no writes, that figure grows even though nothing is behind.

Replay can cancel a long backup on a standby. If it does, raise max_standby_streaming_delay on the standby.

A provider's own CA

If a provider signs its servers with a CA of its own (RDS, Aiven, DigitalOcean, Supabase), you need that CA to verify them. Without it, sslmode=require encrypts the connection but checks no certificate.

Supabase

Supabase runs PostgreSQL with pre-installed schemas for auth, storage and realtime. To back it up from GitHub Actions with no server of your own, follow Back up Supabase with GitHub Actions. Or let SafeGrd take the backup: click Back up on SafeGrd under Surfaces in the console (how it runs). Use the session pooler address below either way.

In that form, Sign in to Supabase signs you in at Supabase and lists your projects. Then choose one of two ways for SafeGrd to connect.

Sign in through Supabase for each backup

You type no password. SafeGrd holds the Supabase sign-in, encrypted. For each backup it asks Supabase for a read-only role whose password expires within minutes. The machine that takes the backup gets that role, and never the sign-in.

Where the project allows it, the backup reads as postgres through that role. A table it still cannot read is left out and named. The SafeGrd app asks Supabase for Projects read and Database read and write, because Supabase makes the role through a write call, even a read-only role.

SafeGrd opens the database with the role before it adds the surface and before each backup. If row-level security hides rows from the role, SafeGrd refuses the sign-in, or fails that backup, and names the tables. If the database's firewall lets the backup machines in but not SafeGrd's server, that check cannot run, so allow both.

Type the database password

SafeGrd holds the connection string, as for any other database. The project's postgres user reads every row.

Switch or reconnect

You can switch a surface between the two from its Details. Credential replaces the sign-in with a connection string, and Sign in through Supabase does the reverse.

If Supabase stops accepting the sign-in (you disconnected SafeGrd there, or removed the account's access to the project), the next backup fails before any machine starts and says so. Click Reconnect Supabase on the surface to sign in again.

Connection string

Connect to the direct host, db.[PROJECT-REF].supabase.co:5432. It has only an IPv6 address unless you buy Supabase's IPv4 add-on. A host with no IPv6, such as GitHub's runners, uses the session pooler instead: aws-0-[REGION].pooler.supabase.com:5432 with user postgres.[PROJECT-REF].

Do not use the transaction pooler on port 6543. It shares server connections between clients, which breaks binary COPY and the single snapshot the backup reads every table from. A backup through it, or through PgBouncer with pool_mode = transaction, is refused with an error that names the transaction pooler.

Add ?sslmode=require to the database URL. To verify the server too, download the CA certificate from the project's Database settings and set it as the surface's CA.

Row-level security

pg_read_all_data does not bypass RLS. Give the backup role BYPASSRLS, or grant explicit SELECT policies on tenant tables. Otherwise those tables back up with 0 rows. A project's own postgres user already has BYPASSRLS.

Restore

A Supabase project already holds Supabase's own schemas, and its postgres user is not a superuser, so you cannot restore into a project, even a new one. Restore into Supabase's PostgreSQL image as supabase_admin, following the guide's restore section. Stock postgres images do not have extensions such as supabase_vault.

Amazon RDS and Aurora (PostgreSQL)

RDS restricts superuser access, and SafeGrd does not need it. Create a read-only role with GRANT pg_read_all_data TO safegrd_backup;.

To keep dump traffic off your primary writer, point database_url at your read replica endpoint. SafeGrd only reads, so a replica is enough.

Download Amazon's root certificate bundle (global-bundle.pem) and add ?sslmode=verify-full&sslrootcert=/path/global-bundle.pem to the URL. For a database SafeGrd backs up for you, paste the bundle as the surface's CA.

Neon

Neon is serverless Postgres with compute autosuspend. Use the direct connection string without the -pooler suffix (for example ep-xyz.region.aws.neon.tech:5432), so binary streaming works. Neon requires TLS, so add ?sslmode=require to the URL.

If compute autosuspend is on, the first connection wakes the instance. Allow a few seconds for the cold start.