Backup, PITR & Disaster Recovery
"To recover successfully using continuous archiving (also called “online backup” by many database vendors), you need a continuous sequence of archived WAL files that extends back at least as far as the start time of your backup." — PostgreSQL 19 documentation, Chapter 25.3, Continuous Archiving and Point-in-Time Recovery (PITR)
Summary: A backup is only real once you have restored it; point-in-time recovery turns a base backup plus an unbroken WAL archive into any minute you choose, and disaster recovery adds distance, immutability and rehearsed procedures. Focus: Logical and physical backups, continuous archiving, recovery targets and timelines, incremental backups, RPO/RTO arithmetic, 3-2-1, encryption, ransomware, restore drills, and the PostgreSQL, MySQL, RDS/Aurora and Laravel/Go tooling around them. Learning goal: Design a backup chain for a stated RPO and RTO, recover a database to the second before a mistake, and prove on a schedule that the chain still restores.
This page is the complete reference for getting data back. It covers file system snapshots and cloud snapshots, backup verification and restore drills, the backup catalog and retention rules, encryption of backups, immutable storage against ransomware, multi-database consistency, and logical replication for migrations, in addition to logical backups (pg_dump formats, --jobs, pg_dumpall, pg_restore, MySQL mysqldump --single-transaction, mydumper), physical backups (pg_basebackup, file system and cloud snapshots, Percona XtraBackup), continuous archiving with archive_command and restore_command, the four recovery targets (time, LSN, name, xid), timelines, incremental backups (pgBackRest, PostgreSQL 17 pg_combinebackup), catalogs and retention, verification and restore drills, checksums, RPO and RTO with the arithmetic, the 3-2-1 rule, offsite copies, encryption, immutable storage, large objects and TOAST, multi-database consistency, logical replication for migrations, RDS and Aurora PITR, the GitLab 2017 outage, and working code in Go and Laravel. It deliberately does not re-teach three neighbours: how the WAL itself is written, flushed and replayed after a crash is in Durability, WAL & Crash Recovery; streaming replication, lag and failover tooling are in Replication, Read Replicas & Failover; and encryption of data at rest, in transit and in use has its own page, Encryption at Rest, in Transit & in Use. Migrations that change what a restore means are in Zero-Downtime Schema Migrations.
Page map
| If you are looking for | Go to |
|---|---|
| A table you can memorise in one minute | Everything in one minute |
| Why backups fail and what a backup must prove | Why backups exist |
| GitLab 2017 and what it teaches | Where the lessons come from |
| One concept with a timeline and code | The concepts, one by one |
pg_dump, pg_restore, mysqldump, mydumper | Logical backups |
pg_basebackup, snapshots, XtraBackup | Physical backups |
archive_command, restore_command, recovery targets | Continuous archiving and PITR |
Timelines and .history files | Timelines after PITR |
Full, differential, incremental, pg_combinebackup | Incremental and differential backups |
| Catalog, retention, expiry | Backup catalog and retention |
| RPO, RTO, the formulas | RPO, RTO and the math |
| 3-2-1, offsite, immutability, encryption, ransomware | DR design |
| Per-product behaviour | What each product offers |
| Knobs, files, error messages | Mechanics |
| Classic problems with SQL, Go and Laravel | Solving the classic problems |
| Which strategy for which workload | Choosing a strategy |
| Replicas, microservices, regions | In architecture |
| Reproduce a recovery on one machine | Lab |
| Beliefs, cheat sheet, terms | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The backup families. Every row is unpacked below.
| Family | Tools | What you get | Restores | Point in time? |
|---|---|---|---|---|
| Logical | pg_dump, pg_dumpall, mysqldump, mydumper, mongodump | SQL or an archive of rows and DDL | One table, one schema, or a different major version | Only the moment the dump started |
| Physical | pg_basebackup, XtraBackup, snapshots, rsync of a stopped cluster | The data files | The whole cluster, fast | Only the moment the backup ended |
| Continuous archiving | base backup + WAL archive (PostgreSQL), base + binlog (MySQL) | Files plus every change since | The whole cluster to any point in the archive | Yes: time, LSN, name, xid |
| Replica | streaming replication, Aurora replicas | A live copy | A failover target | No: it copies mistakes too |
The four recovery targets (PostgreSQL; at most one may be set):
| Parameter | Meaning | Tiny example | Good for |
|---|---|---|---|
recovery_target_time | Stop at a commit timestamp | '2026-11-25 14:03:09+00' | "Just before 14:03" |
recovery_target_lsn | Stop at a WAL position | '0/5000060' | Exact, found with pg_waldump |
recovery_target_name | Stop at a named restore point | 'before_migration' | Planned risky changes |
recovery_target_xid | Stop at a transaction id | '8731' | You know the bad transaction |
recovery_target = 'immediate' | Stop when the backup is consistent | n/a | Restoring a backup as-is |
The numbers.
| Term | Definition | Driven by |
|---|---|---|
| RPO | How much recent data you can lose | archive_timeout, shipping lag, synchronous replication |
| RTO | How long you can be down | Restore throughput, WAL volume to replay, people, DNS |
| 3-2-1 | 3 copies, 2 media/types, 1 offsite | Policy |
| 3-2-1-1-0 | plus 1 immutable or offline, 0 errors after verification | Policy plus drills |
The three things to do.
| Situation | Do this |
|---|---|
| You have a backup job | Restore it on a schedule into a scratch database and check a known value |
| You need minutes of RPO | Base backups plus WAL archiving, monitored with pg_stat_archiver |
| You fear ransomware or a stolen admin key | Keep one copy in another account under Object Lock, with write-only credentials |
Why backups exist
Redundancy and backup solve different problems. A replica protects you from a dead machine. A backup protects you from a living one that is doing the wrong thing: a bad DELETE, a buggy migration, a corrupted page, a ransomware actor with valid credentials. The fundamental trade-off is between recovery distance and recovery speed.
| Closer and faster | Farther and safer |
|---|---|
| Replica in another AZ (seconds, but copies mistakes) | Offsite, immutable archive (hours, survives anything) |
| Snapshot on the same host (fast, dies with the host) | Encrypted copy in another account and region |
| Latest base backup plus little WAL (short RTO) | Many generations and long WAL history (long RTO, deep rewind) |
| Synchronous standby (RPO about 0) | Asynchronous archive (RPO of seconds to minutes, cheaper) |
An everyday picture. A shop keeper photographs the whole shop floor once a month (the base backup) and writes every change in a dated diary (the WAL archive). When something breaks you set the photo on the table and read the diary forward to the minute before the mistake. The photo alone is a month stale; the diary alone has no starting picture; and the photo can be slightly blurred, because the diary corrects the blur. A second shop with the same stock (a replica) copies the mistake the instant you make it.
Three common misunderstandings, up front
| Belief | Reality |
|---|---|
| "We have a replica, so we have a backup." | A replica applies the bad DELETE as fast as the good data. GitLab's own postmortem calls its replication "primarily used for failover purposes and not for disaster recovery." |
| "The backup job ran, so the backup exists." | A job exit code proves the scheduler ran something. Only a restore proves the bytes are usable. |
| "PITR is a faster dump." | PITR needs a base backup and an unbroken WAL archive from that base forward; one missing segment cuts the chain at that point. |
Where the lessons come from
PostgreSQL's manual names three "fundamentally different approaches": the SQL dump, the file system level backup, and continuous archiving. MySQL's manual draws the same line: "Physical backups consist of raw copies of the directories and files that store database contents", while "Logical backup tools include the mysqldump program and the SELECT ... INTO OUTFILE statement."
The lesson most engineers learn from is GitLab's outage of 31 January 2017. The postmortem opens: "This incident caused the GitLab.com service to be unavailable for many hours. We also lost some production data that we were eventually unable to recover." An engineer working on replication removed the production data directory believing it was the secondary; the postmortem says "around 300 GB of data had already been removed" before it stopped. Five backup mechanisms existed on paper and none could be used the way the plan assumed.
| Mechanism on paper | What the postmortem found | Lesson |
|---|---|---|
Daily pg_dump to S3 | "The S3 bucket was empty"; the job used pg_dump 9.2 against a 9.6 server, and "A difference in major versions results in pg_dump producing an error" | Match client and server major versions; alert on absence |
| Failure notifications | Emails were rejected by the receiver, so "we were never aware of the backups failing" | Monitor the artifact, not the sender |
| Azure disk snapshots | Enabled for NFS servers, not for the databases "as we assumed that our other backup procedures were sufficient enough" | Never assume another layer covers you |
| LVM snapshots | "not really meant to be used for disaster recovery"; the usable one was about 6 hours old | A convenience copy is not a DR copy |
| Replication | "primarily used for failover purposes and not for disaster recovery" | A replica is not a backup |
Recovery then meant copying the staging data directory back, which "took around 18 hours" because the network disks were "throttled to a really low number (around 60Mbps)". The data lost covered 17:20 to 00:00 UTC, roughly 5,000 projects, 5,000 comments and 700 new user accounts (GitLab's own estimate). Its answer to "Why was the backup procedure not tested on a regular basis?" was: "Because there was no ownership, as a result nobody was responsible for testing this procedure." The follow-ups include "Investigate Point in time recovery & continuous archiving for PostgreSQL" and "Automated testing of recovering PostgreSQL database backups". These are GitLab's words and numbers, not an independent audit.
Two lessons beyond the headline. First, RTO is a copy-speed problem: 18 hours came from disk throughput, not from any database setting. Second, the restore path is a product: it needs an owner, a schedule and an alert, exactly like the service.
The concepts, one by one
Logical backup Must-know
In plain words: A logical backup is a recipe: the CREATE TABLE statements and the rows, written as SQL or as an archive that a restore tool replays.
Common misunderstanding: "A dump is a copy of the database files." It is a description of the data; restoring it re-inserts every row and rebuilds every index, which is why it is slow, and why it can restore into a newer PostgreSQL major version while a file copy cannot.
Definition: A logical backup extracts schema and data through the database's query interface (pg_dump uses a single snapshot transaction) into a portable representation.
pg_dump session Other sessions
1 BEGIN ISOLATION LEVEL REPEATABLE READ; INSERT INTO orders ... -- keeps running
2 -- snapshot fixed here UPDATE orders ...
3 COPY customers TO stdout; -- not visible to the dump
4 COPY orders TO stdout; -- same snapshot as customers
5 COMMIT;
-- the dump equals the database at step 2, even if it took an hourReal scenario: Seeding a staging database with one tenant's data; upgrading PostgreSQL 15 to 17 by dump and restore; restoring one dropped table without touching the rest; a nightly dump of a 20 GB internal tool.
What provides it:
| Product | Tool | Consistency mechanism |
|---|---|---|
| PostgreSQL | pg_dump | One snapshot transaction; -j workers share it through synchronized snapshots |
| MySQL InnoDB | mysqldump --single-transaction | START TRANSACTION WITH CONSISTENT SNAPSHOT at REPEATABLE READ; InnoDB only |
| MySQL, many tables | mydumper / myloader | Parallel chunked dump with a global consistent snapshot |
| MongoDB | mongodump --oplog | Oplog slice to make a point-in-time view |
| SQLite | .backup, VACUUM INTO | Online backup API / copy under a read lock |
| SQL Server | BACKUP DATABASE (not a SQL dump) | Native page-level backup, closer to physical |
Fix / how to use it:
-- PostgreSQL: what a restore needs to see to be sure the dump is whole
SELECT count(*) FROM orders; -- compare with the number at dump time
SELECT pg_size_pretty(pg_database_size('shop')); -- sanity-check dump size against thisThe Go runner that dumps, hashes, restores into a scratch database and counts rows is the "After" snippet further down. The Laravel equivalent is backup:run-style Artisan code.
Physical backup Must-know
In plain words: A physical backup copies the files the database itself uses. Restoring means putting the files back and starting the server.
Common misunderstanding: "Copying the data directory with cp while the server runs is a physical backup." Without pg_backup_start/pg_backup_stop (or pg_basebackup), the copy is torn: files are read at different moments and there is no backup_label telling recovery where to start. It may start, and be silently wrong.
Definition: A physical backup is a copy of the cluster's files plus the WAL needed to bring them to a consistent state. PostgreSQL states the property that makes it work: "We do not need a perfectly consistent file system backup as the starting point" (the manual's words), because replaying WAL corrects it.
1 pg_backup_start('nightly') -- checkpoint; WAL start LSN recorded
2 copy data files (can be torn) -- server keeps running and writing
3 pg_backup_stop() -- end LSN; returns backup_label contents
4 archive every WAL segment from the start segment through the stop segment
5 restore: files + backup_label + WAL replay -> consistent clusterReal scenario: A 3 TB OLTP cluster where a logical restore would take two days; seeding a new streaming replica; cloning production to a rehearsal environment with pg_basebackup.
What provides it:
| Product | Tool |
|---|---|
| PostgreSQL | pg_basebackup, low-level pg_backup_start/pg_backup_stop, pgBackRest, Barman, WAL-G |
| MySQL InnoDB | Percona XtraBackup, MySQL Enterprise Backup, Clone plugin (CLONE LOCAL DATA DIRECTORY) |
| Oracle | RMAN |
| SQL Server | native full/differential/log backups |
| Redis | RDB snapshot file, AOF |
| Any | LVM, ZFS, EBS or Azure disk snapshots (see snapshots) |
Fix / how to use it: see the pg_basebackup runner and the lab.
Continuous archiving Must-know
In plain words: Every time the server fills a 16 MB WAL segment, it hands the file to a command you wrote, which copies it somewhere safe. Together with a base backup, that archive can replay history.
Common misunderstanding: "Archiving is on, so I am protected." Archiving that fails keeps retrying while WAL piles up in pg_wal until the disk fills and the primary stops. A failing archive is both a recovery risk and an availability risk.
Definition: WAL archiving sets wal_level = replica (or higher), archive_mode = on, and archive_command (or archive_library). The command runs on completed segments; it must return zero only when the file is durably stored.
1 segment 00000001000000000000000A fills (16 MB, or archive_timeout fires)
2 server runs archive_command with %p=pg_wal/...0A and %f=...0A
3 command copies to the archive, exits 0 -> server marks .ready as .done
4 non-zero exit -> server retries, WAL accumulates in pg_wal
5 pg_stat_archiver.failed_count rises, last_failed_wal names the fileReal scenario: A quiet database where the last transaction sits in a half-empty segment for an hour: without archive_timeout, the RPO is an hour. A bucket policy change that makes uploads fail at 3 am: pg_wal fills and the primary stops by 6.
What provides it:
| Product | Mechanism |
|---|---|
| PostgreSQL | archive_command / archive_library, archive_timeout, pg_switch_wal(), pg_stat_archiver |
| MySQL | binary log shipping (mysqlbinlog --read-from-remote-server, --raw) |
| SQL Server | transaction log backups |
| Oracle | archived redo logs (ARCHIVELOG mode) |
| MongoDB | oplog (Atlas continuous backup) |
Fix / how to use it:
-- postgresql.conf (reload for archive_command; wal_level needs a restart)
-- wal_level = replica
-- archive_mode = on
-- archive_timeout = 60
-- archive_command = 'test ! -f /archive/%f && cp %p /archive/%f'
SELECT archived_count, failed_count, last_archived_wal, last_archived_time,
last_failed_wal, last_failed_time
FROM pg_stat_archiver;PostgreSQL's own example is explicitly "an example, not a recommendation"; production archives use pgBackRest, WAL-G or Barman, which add compression, parallelism, retries and checksums. The Laravel monitor for this view is ArchiveHealth.
Point-in-time recovery (PITR) Must-know
In plain words: You restore an old base backup, then let PostgreSQL replay archived WAL only up to a moment you choose, and stop there.
Common misunderstanding: "I can recover to any time since yesterday's backup." The stop point "must be after the ending time of the base backup", and every archived segment from the base's start to the target must exist. To reach a time while a base backup was in progress you must go back to the previous base backup.
Definition: PITR is archive recovery with a recovery target. PostgreSQL begins when recovery.signal exists, reads restore_command to fetch segments, and stops at the target.
1 stop the broken server; keep the data directory aside as evidence
2 restore the chosen base backup into an empty data directory
3 touch recovery.signal
4 postgresql.conf: restore_command, recovery_target_time = '2026-11-25 14:03:09+00'
5 start: replay segments ...09 ... until the next commit would pass the target
6 recovery_target_action = pause (default): query, verify, then promote
7 promote: new timeline starts, server accepts writesReal scenario: A migration drops the wrong column at 14:03 and a customer reports it at 14:40; a developer runs an unscoped UPDATE in production; a bug zeros every price for 8 minutes.
What provides it:
| Product | PITR |
|---|---|
| PostgreSQL | base backup + WAL archive + recovery target |
| MySQL | full backup + mysqlbinlog --stop-datetime / --stop-position replay |
| SQL Server | RESTORE LOG ... WITH STOPAT |
| Oracle | RMAN SET UNTIL TIME |
| Amazon RDS / Aurora | restore to a new instance at a chosen second inside the retention window |
| Redis, SQLite | none built in (Litestream adds it for SQLite) |
| MongoDB | oplog replay, or Atlas continuous backup |
Fix / how to use it: the full procedure is in the lab; the knobs are in recovery targets.
Timeline Important
In plain words: Each time you recover and start accepting writes, PostgreSQL starts a new branch of history so the new writes cannot be confused with the old ones that were thrown away.
Common misunderstanding: "After PITR I am back on the same history." You are on timeline 2. Old WAL for timeline 1 after the target still exists in the archive but belongs to an abandoned branch.
Definition: A timeline id is the first eight hex digits of a WAL segment name (00000002 00000000 0000003A). Promotion after recovery writes a 00000002.history file recording where the branch left its parent.
TLI 1: ... 0/5000000 ---- 0/5000060 ---- 0/5000200 ----> (damage continues)
\
TLI 2: +---- 0/5000060 ----> new writes, 00000002... segments
00000002.history: "1 0/5000060 no recovery target specified"Real scenario: You recovered to 14:03:09, then discover 14:03:09 was too early: you can recover again from the same base, aiming for the right branch with recovery_target_timeline.
What provides it: PostgreSQL only; MySQL has no timeline concept (GTIDs and binlog positions play a related role); Aurora and RDS create a new instance instead of a branch.
Fix / how to use it: see Timelines after PITR.
Base backup, differential and incremental Important
In plain words: A full backup copies everything. A differential copies what changed since the last full. An incremental copies what changed since the last backup of any kind.
Common misunderstanding: "Incrementals are free storage savings." They shrink storage and backup time, but a restore needs the whole chain valid, and PostgreSQL itself "has no built-in mechanism to figure out which backups are still needed as a basis for restoring later incremental backups."
Definition: pgBackRest: a differential "copies only those database cluster files that have changed since the last full backup"; an incremental "copies only those database cluster files that have changed since the last backup". PostgreSQL 17 pg_basebackup --incremental=<old_manifest> goes down to block level using WAL summaries, and pg_combinebackup reassembles a synthetic full backup.
Sun F (full, 2 TB)
Mon I1 -> depends on F
Tue I2 -> depends on I1 -> F
Wed D -> depends on F only (differential)
Thu I3 -> depends on D -> F
restore I3 = F + D + I3Real scenario: A 5 TB database where 2% of blocks change a day: daily incrementals move 100 GB instead of 5 TB.
What provides it:
| Product | Mechanism |
|---|---|
| pgBackRest | --type=full, diff, incr, optional block incremental (repo-block) |
| PostgreSQL 17+ | pg_basebackup --incremental, summarize_wal = on, pg_combinebackup |
| XtraBackup | --incremental-basedir (changed pages by LSN) |
| Barman | incremental via rsync or block-level (version dependent) |
| SQL Server | differential backups (changed extents since last full) |
Fix / how to use it: see Incremental and differential backups.
Backup verification Must-know
In plain words: Verification is everything between "the file exists" and the application works against the restored copy.
Common misunderstanding: "pg_verifybackup passed, so the backup is fine." It checks files against the manifest and checks the WAL it needs is readable. It does not start the server, run recovery, or look at your data.
Definition: A ladder: (1) exit code of the tool; (2) file checksums and manifest (pg_verifybackup); (3) restore into scratch and start the server; (4) query a known value; (5) an application smoke test. Each rung catches failures the one below cannot.
1 pg_basebackup exit 0 -- the tool finished
2 pg_verifybackup <dir> -- files match backup_manifest
3 pg_ctl start on the restored copy -- recovery reached consistency
4 SELECT count(*), max(created_at) ... -- freshness and plausibility
5 application smoke test against it -- schema + extensions + roles usableReal scenario: A backup that restores cleanly but was taken from a replica that was 4 hours behind; a dump that restores but lost the extension needed by the app; a base backup that is whole but the WAL after it has a gap.
What provides it: pgBackRest verify and restore with --delta; pg_verifybackup; pg_checksums; XtraBackup --prepare; and your own drill job, shown in the Go runner.
Fix / how to use it: see Restore drills.
RPO and RTO Must-know
In plain words: RPO asks how much recent data can we lose? and RTO asks how long can we be down?.
Common misunderstanding: "Daily backups mean a 24-hour RPO and a short RTO." A daily dump gives a 24-hour RPO, and the RTO is the dump's restore time, which for a large database is longer than the dump took.
Definition: Neither the PostgreSQL nor the MySQL manual defines these; the working definitions are: RPO is the gap between the last recoverable point and the failure; RTO is the time from failure to a working service. They pull against each other and against cost.
failure at 14:03:09
last archived WAL ends at 14:02:40 -> RPO achieved = 29 s
service back at 15:41 -> RTO achieved = 98 minReal scenario: A payments ledger with RPO 0 (synchronous standby plus archive) and RTO 15 min (hot standby); an internal wiki with RPO 24 h and RTO 1 day (nightly dump).
What provides it: see RPO, RTO and the math.
Fix / how to use it: the Go calculator below prints both from measurable inputs.
// Package main turns the RPO and RTO arithmetic into a calculator, so the
// numbers in a runbook come from inputs that can be measured and re-measured.
package main
import (
"flag"
"fmt"
"time"
)
func main() {
var (
dataGB = flag.Float64("data-gb", 2000, "size of the base backup to copy back, in GB")
restoreMBps = flag.Float64("restore-mbps", 400, "sustained restore throughput, MB/s")
walGBPerDay = flag.Float64("wal-gb-per-day", 200, "WAL generated per day, GB")
daysSince = flag.Float64("days-since-base", 1, "age of the base backup at the failure, days (worst case: backup interval)")
replayMBps = flag.Float64("replay-mbps", 100, "WAL replay speed, MB/s (measure it; replay is often slower than copy)")
fetchMBps = flag.Float64("wal-fetch-mbps", 200, "restore_command fetch speed, MB/s")
overhead = flag.Duration("overhead", 25*time.Minute, "detection, decision, provisioning, DNS and smoke tests")
archiveSec = flag.Float64("archive-timeout-sec", 60, "archive_timeout: worst-case age of unarchived WAL")
shipSec = flag.Float64("ship-lag-sec", 30, "archive_command or upload lag")
)
flag.Parse()
copyBack := seconds(*dataGB * 1024 / *restoreMBps)
walMB := *walGBPerDay * 1024 * *daysSince
fetch := seconds(walMB / *fetchMBps)
replay := seconds(walMB / *replayMBps)
rto := *overhead + copyBack + max(fetch, replay) // fetch and replay overlap, the slower one dominates
rpo := seconds(*archiveSec + *shipSec)
fmt.Printf("copy base backup back : %s\n", copyBack.Round(time.Second))
fmt.Printf("fetch WAL : %s (%.0f GB)\n", fetch.Round(time.Second), walMB/1024)
fmt.Printf("replay WAL : %s\n", replay.Round(time.Second))
fmt.Printf("estimated RTO : %s\n", rto.Round(time.Minute))
fmt.Printf("estimated RPO (async) : %s (worst case, archive-only, no synchronous standby)\n", rpo.Round(time.Second))
}
func seconds(s float64) time.Duration { return time.Duration(s * float64(time.Second)) }3-2-1 and immutable copies Important
In plain words: Keep three copies, on two kinds of storage, with one somewhere else; today add one copy nobody can change.
Common misunderstanding: "Three copies on the same cloud account is 3-2-1." If one set of credentials can delete all three, you have one copy with three names.
Definition: 3 copies of the data (production plus two backups), on 2 different media or storage systems, 1 offsite. The extended form 3-2-1-1-0 adds 1 immutable or offline copy and 0 errors after verification.
1 production disk (copy 1, media A)
2 archive in bucket, region A (copy 2, media B)
3 replicated bucket, region B (copy 3, offsite)
4 locked bucket, other account (immutable, ransomware-proof)
5 attacker with prod admin key can delete 1-3; cannot delete 4Real scenario: A compromised CI token deletes every backup bucket in the production account; the locked copy in a separate account is the only survivor.
What provides it: S3 Object Lock (governance or compliance mode, retention, legal hold) with versioning; Azure immutable blob storage; Google Cloud bucket retention policy and Bucket Lock; tape; restic or borg in append-only mode.
Fix / how to use it: see DR design.
Logical backups in depth
pg_dump formats and options Must-know
pg_dump dumps one database. The PostgreSQL manual says it "makes consistent exports even if the database is being used concurrently" and that "except in simple cases, pg_dump is generally not the right choice for taking regular backups of production databases".
| Format | Flag | Compressed by default | Parallel dump (-j) | Selective, reorderable restore | Restores with |
|---|---|---|---|---|---|
| Plain SQL | -Fp (default) | No | No | No (edit the text) | psql -f |
| Custom | -Fc | Yes (gzip) | No | Yes, pg_restore --list / --use-list | pg_restore, can use -j |
| Directory | -Fd | Yes | Yes: "the only format that supports parallel dumps" | Yes | pg_restore, can use -j |
| Tar | -Ft | No | No | Partly (order of data fixed) | pg_restore |
Parallel dumps work because of synchronized snapshots: the leader exports a snapshot and each worker adopts it, so every table is read at the same logical instant. "pg_dump -j uses multiple database connections", so plan connections and load. Other options a practitioner meets: --schema-only and --data-only; --table / --schema / --exclude-table; --no-owner and --no-acl for restoring into another role setup; --serializable-deferrable (wait for a safe snapshot so the dump cannot fail with a serialization failure); --snapshot=<name> to share a snapshot with another tool; --compress=zstd:level; --statistics (include optimizer statistics); and --large-objects.
pg_dump --format=directory --jobs=4 --file=/backups/shop-20261125 shop
pg_dump --format=custom --file=/backups/shop.dump shop
pg_dumpall --globals-only > /backups/globals.sql # roles and tablespaces: pg_dump does not include thempg_dumpall and what pg_dump leaves out Important
In plain words: pg_dump saves one database; roles and tablespaces live in the cluster, so a restore needs them first.
Common misunderstanding: "A dump contains users." Roles are global objects. The manual: "To export an entire cluster, or to export global objects that are common to all databases in a cluster (such as roles and tablespaces), use pg_dumpall."
1 pg_dumpall --globals-only > globals.sql -- roles, tablespaces
2 for db in $(list databases): pg_dump -Fc $db > $db.dump
3 restore: psql -f globals.sql; createdb each; pg_restore -d each
-- caveat: steps 1-2 are separate snapshots, see multi-database consistencypg_restore Important
pg_restore reads custom, directory and tar archives. Key switches:
| Switch | Effect | Caveat |
|---|---|---|
--jobs=N | Parallel restore of data and index builds | Custom/directory only; input must be a file or directory, not a pipe; not with --single-transaction |
--list / --use-list=file | Print the table of contents; restore only chosen items | Edit the list to skip or reorder |
--clean --if-exists | Drop objects before recreating | Dangerous on a live database |
--create | Create the database first | Cannot combine with --single-transaction |
--single-transaction | All or nothing | Implies --exit-on-error; may exhaust the lock table on big schemas |
--transaction-size=N | Commit every N objects | Middle ground, PostgreSQL 17+ |
--exit-on-error | Stop at the first error | Default is to continue and report |
--section (pre-data, data, post-data) | Phase control | Use to load data before building indexes |
Restore time is dominated by index builds and constraint validation, so after a restore run ANALYZE, and re-check that sequences are at the right value.
-- after pg_restore: sanity checks you can script
SELECT last_value FROM orders_id_seq;
SELECT max(id) FROM orders; -- the sequence must not be behind
SELECT schemaname, relname, n_live_tup FROM pg_stat_user_tables ORDER BY n_live_tup DESC LIMIT 5;MySQL: mysqldump and mydumper Important
mysqldump --single-transaction starts a consistent snapshot in REPEATABLE READ and dumps InnoDB tables without blocking writers. It does nothing for MyISAM tables (they need --lock-all-tables, which blocks writes), and DDL during the dump can break the snapshot. Other flags: --routines --triggers --events (not dumped by default for routines/events), --source-data=2 (MySQL 8.4 name; older --master-data) writes the binlog coordinates so the dump can be the base of a binlog PITR; --set-gtid-purged; --hex-blob; --quick to stream rows instead of buffering. mydumper and myloader dump and load many tables and chunks in parallel, and are the usual choice above roughly a few hundred GB for logical dumps. The MySQL manual page for mysqldump could not be fetched raw (HTTP 403); these flag descriptions are from the author's working knowledge and should be checked against your version.
1 mysqldump --single-transaction --source-data=2 --routines --triggers shop > shop.sql
2 header of shop.sql: -- CHANGE REPLICATION SOURCE TO SOURCE_LOG_FILE='binlog.000042', SOURCE_LOG_POS=157;
3 PITR: restore shop.sql, then mysqlbinlog binlog.000042 --start-position=157 --stop-datetime='...' | mysqlBackup of large objects, TOAST and logical dumps Good to know
TOASTed values (big text, bytea, jsonb) are stored out of line in a TOAST table, but pg_dump reads rows through COPY, so they are detoasted and dumped inline with the row. The dump gets larger than the on-disk table when the data compresses well. Large objects (the lo_* API, pg_largeobject) are a separate storage area: pg_dump includes them by default, but "except when --schema, --table, --schema-only, --statistics-only, or --no-data is specified"; add --large-objects (older --blobs) when you dump a single table and still need them. In directory format each large object becomes its own file. A physical backup copies TOAST tables and pg_largeobject as ordinary files, so nothing special is needed. For multi-gigabyte blobs prefer object storage with a reference in the row, and back up the bucket on its own schedule.
Physical backups in depth
pg_basebackup Must-know
pg_basebackup "is used to take a base backup of a running PostgreSQL database cluster." It connects over the replication protocol, so the role needs the REPLICATION attribute and pg_hba.conf needs a replication line.
| Option | Meaning | Note |
|---|---|---|
--format=plain or tar | Directory copy or tar files | -Ft compresses with --compress |
--wal-method=stream (-X stream) | Stream WAL alongside the copy | Default; fetch collects WAL at the end; none leaves WAL to your archive |
--checkpoint=fast or spread | Start with an immediate or paced checkpoint | spread is polite; the tool "will appear to be idle" until it finishes |
--max-rate=RATE | Throttle the copy | Protect production I/O |
--slot / --create-slot | Keep WAL for a replication slot | Use for seeding replicas |
--manifest-checksums=SHA256 | Per-file checksums in backup_manifest | CRC32C default; SHA family "provides a cryptographically secure digest" |
--incremental=old_manifest | Incremental backup (PostgreSQL 17+) | Needs summarize_wal = on |
--no-verify-checksums | Skip page checksum verification | Leave it on |
Compatibility from the manual: it "works with servers of the same or older major version, down to 9.1"; the restore itself needs the same major version and architecture. Output is verified with pg_verifybackup. The low-level alternative is pg_backup_start('label') and pg_backup_stop(): you copy the files with your own tool and write the returned backup_label byte for byte; "The connection calling pg_backup_start must be maintained until the end of the backup, or the backup will be automatically aborted."
1 pg_basebackup -h primary -U replicator -D /backups/base-20261125 -X stream --checkpoint=spread --manifest-checksums=SHA256
2 pg_verifybackup /backups/base-20261125
3 cat /backups/base-20261125/backup_label
START WAL LOCATION: 0/3000028 (file 000000010000000000000003)
CHECKPOINT LOCATION: 0/3000060
LABEL: base-20261125File system and cloud snapshots
In plain words: LVM, ZFS, EBS and Azure disk snapshots freeze a block device instantly; PostgreSQL can recover from one as it would from a crash.
Common misunderstanding: "A snapshot is a backup." A snapshot on the same host or the same storage account is a convenience copy, and restoring it across accounts can be very slow: GitLab recorded a restore that "took over a week" across storage accounts and called its LVM snapshots "not really meant to be used for disaster recovery".
The PostgreSQL requirement is that the snapshot is atomic across all files (data, tablespaces and WAL). If WAL is on another volume you need a consistent group snapshot (EBS multi-volume snapshots, a ZFS dataset covering both), or you bracket the snapshot with pg_backup_start/pg_backup_stop. Add WAL archiving to a snapshot to get PITR. Cloud snapshots are incremental at the block level, which makes them cheap to take often and slow to move.
XtraBackup and MySQL physical backups
Percona XtraBackup is a hot backup tool for MySQL and Percona Server. It copies InnoDB data files while the server runs, tracks redo log changes during the copy, and then needs xtrabackup --prepare to apply them before the backup is consistent. Incrementals use --incremental-basedir and the LSN; --copy-back restores. MySQL Enterprise Backup does the same for Oracle's edition, and the Clone plugin copies a running instance for replica seeding. Pair a physical MySQL backup with archived binary logs for PITR.
Continuous archiving and PITR
The archive side Must-know
Requirements from the manual: set wal_level to replica or higher, archive_mode to on, and archive_command or archive_library. %p is the path of the file, %f its name. The command runs only on completed segments, so on a quiet server "there could be a long delay between the completion of a transaction and its safe recording in archive storage"; set archive_timeout ("settings of a minute or so are usually reasonable") or call pg_switch_wal() by hand. Forced switches still produce full-size 16 MB files, so a very short archive_timeout bloats storage (compress with WAL-G or pgBackRest). To pause archiving, set archive_command = '': WAL accumulates in pg_wal until a working command returns.
Rules for a correct archive command: it must return zero only when the file is safe; it must not overwrite an existing file with different content (hence test ! -f); it must be idempotent on retry; it should copy to a temporary name and rename; and it should fsync. PostgreSQL 15 added archive_library so a loadable module can do this without forking a shell for each segment. archive_mode = always also archives from a standby.
The restore side and recovery targets
To recover: restore the base backup into an empty data directory, create recovery.signal, and set restore_command. The manual: "The one thing that you absolutely must specify is the restore_command". The server will also ask for .history files, and %p differs from %f.
| Parameter | Value | Behaviour |
|---|---|---|
restore_command | 'cp /archive/%f "%p"' or pgbackrest --stanza=main archive-get %f "%p" | Fetches WAL segments and history files |
recovery_target_time | timestamptz with offset | Stops at a commit time; always give the time zone |
recovery_target_lsn | '0/5000060' | Stops at a WAL position |
recovery_target_name | restore point name | Created by pg_create_restore_point('name') |
recovery_target_xid | transaction id | "transactions can complete in a different numeric order" than they start, so this is not a time proxy |
recovery_target = 'immediate' | n/a | Stops when the backup is consistent |
recovery_target_inclusive | on (default) or off | Stop just after or just before the target |
recovery_target_timeline | latest (default), current, or an id | Which branch to follow |
recovery_target_action | pause (default), promote, shutdown | After the target; pause lets you query, then pg_wal_replay_resume() |
recovery_end_command / archive_cleanup_command | shell | Run at the end / to trim a standby's archive |
"At most one of recovery_target, recovery_target_lsn, recovery_target_name, recovery_target_time, or recovery_target_xid can be used"; more than one is an error. Finding the target is the hard part: for time, use an application log or pg_xact_commit_timestamp() if track_commit_timestamp was on; for xid, use log_statement, pgaudit, or pg_waldump; for LSN, use pg_waldump -p /archive -s <start> -r Transaction; for planned changes, create a restore point first.
SELECT pg_create_restore_point('before_pricing_migration'); -- run just before a risky change
SELECT pg_is_in_recovery(), pg_last_wal_replay_lsn(), pg_last_xact_replay_timestamp();
SELECT pg_wal_replay_resume(); -- after verifying a paused recovery, finish and promoteTimelines after PITR
When recovery ends and the server is promoted, it creates a new timeline ("a new timeline is created to identify the series of WAL records generated after that recovery"), writes <newid>.history to the archive, and names new segments with the new id. The history file lists parent timeline, switch LSN and reason. The default recovery_target_timeline = latest follows the newest branch found; set current to stay on the branch that was current at the base backup, or an explicit id to return to a state "that was itself generated after a recovery attempt". "You cannot recover into timelines that branched off earlier than the base backup." Timelines also stop a revived old primary from overwriting archive files: its segments carry the old id.
1 base backup on TLI 1; WAL 000000010000000000000003 ...
2 recover to 14:03:09, promote -> 00000002.history, WAL 00000002...
3 later disaster; recover from the same base with recovery_target_timeline = 2 to follow the TLI 2 branch
4 or recovery_target_time = earlier + recovery_target_timeline = current to branch again from TLI 1The picture shows one recovery: the dashed bracket is the archive that must have no gap, the black bar is the recovery target, and the new timeline branches off at that point.
Incremental and differential backups
pgBackRest Important
pgBackRest's guide defines a backup as "a consistent copy of a database cluster that can be restored to recover from a hardware failure, to perform Point-In-Time Recovery, or to bring up a new standby". Types: full; differential ("changed since the last full backup", needs the full valid); incremental ("changed since the last backup", needs the chain valid). Files are compared by timestamp and size, or by checksum with --delta. Useful options straight from the guide: process-max (default 1, "almost never the appropriate value"), archive-async with a spool path, repo-block and bundling (block incremental stores "only the portions of files that have changed"), repo1-cipher-type=aes-256-cbc for repository encryption, and repo1-retention-full, repo1-retention-diff. pgbackrest verify "verify contents of a repository"; restore --type=time --target=... runs PITR; info prints the catalog.
# pgbackrest.conf (excerpt)
[global]
repo1-path=/var/lib/pgbackrest
repo1-retention-full=2
repo1-cipher-type=aes-256-cbc
process-max=4
start-fast=y
[main]
pg1-path=/var/lib/postgresql/17/main
# crontab: full on Sunday, differential Monday to Saturday
30 06 * * 0 pgbackrest --type=full --stanza=main backup
30 06 * * 1-6 pgbackrest --type=diff --stanza=main backupPostgreSQL 17 incremental backup and pg_combinebackup Important
Server setup: summarize_wal = on (the summarizer writes pg_wal/summaries; wal_summary_keep_time defaults to 10 days, "comfortably higher than the time that could pass between a backup and a later incremental backup"). Take a full backup, then pg_basebackup --incremental=<previous backup_manifest>. Relation files may be replaced by incremental files containing only changed blocks. To restore, "pg_combinebackup must first be used to combine it with the previous backups upon which it depends", producing a synthetic full backup.
1 postgresql.conf: summarize_wal = on -- then reload
2 pg_basebackup -D /b/full -X stream -- full, writes backup_manifest
3 pg_basebackup -D /b/incr1 --incremental=/b/full/backup_manifest
4 pg_basebackup -D /b/incr2 --incremental=/b/incr1/backup_manifest
5 pg_combinebackup /b/full /b/incr1 /b/incr2 -o /restore/data
6 touch /restore/data/recovery.signal; set restore_command; startCaveats from the manual: "For a small database, it's simpler to ignore the existence of incremental backups"; a heavily modified database gains little; WAL summaries must cover the whole range between the two backups or the incremental fails; on a standby an incremental can fail when no new restartpoint exists; changing the checksum status between backups limits pg_combinebackup. Incremental backups do not remove the need for WAL archiving to reach a point in time.
The matrix reads left to right: the further right, the more you can recover to and the more you must keep (files plus a WAL or binlog stream); only the logical column can cross major versions or restore a single table.
Backup catalog and retention
In plain words: The catalog is the list of which backups exist, what they cover, and what each depends on; retention is the rule for deleting old ones.
Common misunderstanding: "Retention is a bucket lifecycle rule." A blind age rule deletes a full backup that later incrementals still need, or the WAL between two kept backups. Retention must be expressed in backups and WAL together.
| Tool | Catalog | Retention knobs |
|---|---|---|
| pgBackRest | pgbackrest info | repo1-retention-full, -full-type (count or time), -diff; incrementals expire with their parent; WAL expires with backups |
| Barman | barman list-backups, barman show-backup | retention_policy = RECOVERY WINDOW OF 7 DAYS or REDUNDANCY 3, barman cron |
| WAL-G | wal-g backup-list | wal-g delete retain FULL 5, delete before |
Plain pg_basebackup | your own file | the Go runner below writes catalog.jsonl |
| spatie/laravel-backup | backup:list | backup:clean, cleanup.default_strategy |
| RDS / Aurora | console, describe-db-snapshots | automated backup retention 1 to 35 days (verify current limits) |
A recovery window policy keeps whatever is needed to restore to any point in the last N days; a redundancy policy keeps N backups. With pgBackRest by count, "if repo1-retention-full-type=count and repo1-retention-full=2 then there will be three full backups stored before the oldest one is expired" (the new one completes before expiry runs), so budget space for count plus one.
Restore drills and automatic verification
Testing restores automatically means a restore drill: a scheduled, automated job that restores the latest backup (and, weekly, a PITR to a recent timestamp) on disposable infrastructure, runs checks, records the measured time as the real RTO, and pages on failure.
| Check | What it proves | Failure it catches |
|---|---|---|
| Tool exit code | Backup process finished | Crash, timeout |
pg_verifybackup | Files match manifest, WAL parses | Truncated or altered files |
| Restore + start + reach consistency | Recovery works end to end | Missing backup_label, WAL gap, wrong version |
pg_amcheck / pg_checksums --check | No corrupt pages | Silent corruption copied into backups |
| Row-count and max-timestamp query | Data is present and recent | Backup of a lagging replica, empty schema |
| Application smoke test | Roles, extensions, grants, schema usable | Missing global objects (pg_dumpall --globals-only) |
| Measured wall time | Real RTO | RTO assumptions rotting as data grows |
Data checksums protect against silent corruption: initdb --data-checksums (on by default from PostgreSQL 18) stores a checksum per page; pg_checksums --check verifies an offline cluster; pg_basebackup verifies checksums of the pages it reads unless told not to; MySQL InnoDB has innodb_checksum_algorithm. A backup of a corrupt page is a corrupt backup, and logical dumps (which read through the executor) catch a different class of corruption than physical ones; pg_amcheck checks B-tree structure.
RPO, RTO and the math
RPO for archive-based recovery is bounded by the longest time WAL can exist only on the primary: RPO <= archive_timeout + archive lag + upload time, so with archive_timeout = 60, 30 seconds of upload lag the worst case is about 90 seconds. A synchronous standby (synchronous_commit = on with synchronous_standby_names) makes RPO zero for a node loss, at a write-latency price, but still not for a logical mistake. Sharing the same bucket region adds replication lag for cross-region copies.
RTO is a sum:
RTO = detect + decide + provision + copy_back + fetch/replay_WAL + validate + cutover
copy_back = backup_size / restore_throughput
replay_WAL = WAL_since_base / replay_speed (fetch and replay overlap: take the larger)Worked example (illustrative inputs, not measurements): 2 TB base backup at 400 MB/s is 2,000 x 1,024 / 400, about 5,120 s, or 85 minutes. One day of WAL at 200 GB/day replayed at 100 MB/s is about 2,050 s, or 34 minutes. Add 25 minutes of human and DNS time and the RTO is about 2 hours 24 minutes: the Go calculator above prints exactly this. To cut it: take base backups more often (less WAL), use incrementals plus pg_combinebackup, restore in parallel (process-max, pg_restore -j), use faster disks (GitLab's 60 Mbps staging disks cost 18 hours), or keep a warm standby that is already in recovery.
Storage budget: retention days x daily WAL volume (compressible by 3 to 5 times) plus base backups kept. 14 days x 200 GB is 2.8 TB raw, about 700 GB at 4:1, plus two full backups of 2 TB at, say, 3:1 compression is about 1.3 TB. The point is to compute it from your own pgbackrest info numbers.
| Strategy | Typical RPO | Typical RTO | Cost |
|---|---|---|---|
Nightly pg_dump | up to 24 h | hours to days (restore + indexes) | Low |
| Base backup + WAL archive, cold restore | minutes | tens of minutes to hours | Medium |
| Hot standby (async) + archive | seconds | minutes | Medium to high |
| Synchronous standby + archive | about 0 for node loss | minutes | High (latency) |
| Multi-region warm standby | seconds to minutes | minutes | High |
DR design: offsite, immutable, encrypted
Read the picture from the inside out: the replica and the archive live in region A; the archive is copied to region B for a standby; and the locked copy in a separate account is the only one that survives stolen production credentials.
Topology: primary region, replica, cold standby Important
| Tier | What it is | RPO | RTO | Notes |
|---|---|---|---|---|
| Hot standby, same region | Streaming replica in another AZ | about 0 if sync, seconds if async | seconds to minutes | Node/AZ loss only. See Replication & Failover |
| Warm standby, other region | Replica following WAL from the cross-region archive | seconds to minutes | minutes | Regional outage |
| Cold standby | No server running; restore base + WAL on demand (IaC ready) | archive lag | tens of minutes to hours | Cheapest; needs rehearsal |
| Backup-only | Offsite immutable archive | archive lag | hours | The last line: survives credential theft |
DR drills choose a target region, account and runbook; failing over a database also means failing over the secrets, DNS, queues and anything else that was in region A.
3-2-1 and offsite copies Important
Cross-region replication of the archive bucket (S3 Cross-Region Replication, GCS dual-region, Azure GRS) gives a second failure domain, but replication copies deletes unless versioning and delete-marker rules say otherwise. Replication lag becomes part of the RPO. Egress, data residency law, and key location all change with the region, so decide them on purpose.
Immutable storage and ransomware Must-know
In plain words: Immutable means write once, read many, no deletion until a retention date, enforced by the storage service rather than by good behaviour.
Common misunderstanding: "Our backups are in a private bucket, so ransomware cannot reach them." An attacker with production admin credentials, or a compromised CI role, can delete or encrypt the bucket. The protection must be independent of those credentials.
| Control | What it gives | Product |
|---|---|---|
| Object Lock, compliance mode | No one, including root, can delete before retention ends | AWS S3 |
| Object Lock, governance mode | Deletion needs a special permission | AWS S3 |
| Legal hold | Indefinite lock until released | S3, Azure |
| Versioning + MFA delete | Old versions recoverable | S3 |
| Immutable blob / time-based retention | WORM policy | Azure Blob Storage |
| Retention policy + Bucket Lock | Locks the policy itself | Google Cloud Storage |
| Separate account / project | Different credentials and blast radius | all clouds |
| Write-only credentials from production | Production can add, never delete | IAM policy |
| Pull-based copy | The backup host fetches; production holds no key to it | restic, borg append-only, rclone |
| Offline or tape | Air gap | physical |
Also protect the catalog and the keys: a deleted pgbackrest repository config or a lost encryption key makes immutable bytes useless. Alert on unexpected deletions, on archive silence, and on backup size dropping to near zero (ransomware encrypting, or an empty dump).
Encryption of backups Important
| Layer | How | Key custody |
|---|---|---|
| Client-side, in the tool | pgBackRest repo1-cipher-type=aes-256-cbc and repo1-cipher-pass; WAL-G libsodium or PGP; XtraBackup --encrypt | You hold the passphrase; the cloud sees ciphertext |
| Stream filter | pg_dump ... | gpg --encrypt -r backup@example.com, age | Public key on the backup host, private key offline |
| Server-side | S3 SSE-S3, SSE-KMS, SSE-C; Azure and GCS equivalents | Cloud KMS, IAM policy decides who can decrypt |
| Volume level | EBS encryption, LUKS | Protects stolen disks, not a stolen mount |
| Application archive | spatie/laravel-backup password and encryption (zip) | App config |
Rules: encrypt before the data leaves the trust boundary when the cloud account is part of the threat model; store keys separately from the backups (a key in the same bucket is no key); rotate keys with retained backups in mind (you need old keys to read old backups); test restore with the key retrieval procedure, not with a cached key. The wider topic (TDE, envelope encryption, KMS) is in Encryption at Rest, in Transit & in Use.
Multi-database consistency Important
In plain words: One backup is consistent inside itself; two backups of two databases are consistent with each other only if you make them so.
Common misunderstanding: "pg_dumpall gives a consistent snapshot of the whole cluster." It dumps databases one after another, each with its own snapshot, so a transaction that spanned nothing but moved on between dumps can leave them inconsistent. A physical base backup, by contrast, is consistent across every database in the cluster.
1 cluster A (orders) dump starts 02:00:00, snapshot A
2 cluster B (billing) dump starts 02:00:07, snapshot B
3 an order paid at 02:00:03 is in B but not in A -> invoice without order after restoreOptions: (1) one physical backup per cluster and a shared recovery point: call pg_create_restore_point('nightly_2026_11_25') in each cluster (or pick a common timestamp with synchronised clocks) and recover each to it; (2) keep cross-service invariants repairable: outbox, idempotency keys and a reconciliation job (see Outbox and Saga); (3) accept the skew and document it. Across services there is no global snapshot, only close enough plus reconciliation.
Logical replication for migrations Good to know
Logical replication (CREATE PUBLICATION on the source, CREATE SUBSCRIPTION on the target) streams row changes and can cross major versions, which makes it the tool for near-zero-downtime upgrades and moving a database to another provider. It is a migration tool, not a backup: it does not replicate DDL, sequences' current values, or large objects, it copies deletes, and a mistake replicates. The sequence is: copy schema (pg_dump --schema-only), create the subscription (initial table copy, then streaming), wait for lag to reach zero, stop writes, advance sequences, switch the application. pg_createsubscriber (PostgreSQL 17) converts a physical standby into a logical subscriber. Details of slots and lag are in Replication & Failover.
Cloud snapshots, RDS and Aurora PITR Important
Managed services expose PITR as an API, not as files. Amazon RDS keeps automated backups (daily snapshot plus transaction logs) for a retention period you choose, and the restore-to-point-in-time action always creates a new instance at a second you choose within the window; the latest restorable time usually trails real time by a few minutes. Aurora backs up the cluster volume continuously (no backup window impact), supports restore to a new cluster, cloning, and, for Aurora MySQL, Backtrack (rewind in place). Manual snapshots survive the instance; automated backups are deleted with it unless a final snapshot or retained backups are configured, which is a classic way to lose a backup together with the database. Cross-Region and cross-account snapshot copy, AWS Backup vault lock, and KMS key policy are the managed equivalents of the offsite and immutable controls above. These behaviours come from AWS documentation that was not fetched for this page; check current retention limits (about 1 to 35 days) and Region support before relying on them. Azure Database for PostgreSQL and Google Cloud SQL expose the same idea as point-in-time restore to a new server.
What each product offers
| Product | Logical | Physical | PITR | Incremental | Notes |
|---|---|---|---|---|---|
| PostgreSQL | pg_dump, pg_dumpall, pg_restore | pg_basebackup, snapshots | Base + WAL, 4 targets | pg_basebackup --incremental (17+), pg_combinebackup | Tools: pgBackRest, Barman, WAL-G |
| MySQL / InnoDB | mysqldump, mydumper, SELECT ... INTO OUTFILE | XtraBackup, Enterprise Backup, Clone plugin | Full + binlog replay | XtraBackup incremental | --single-transaction for InnoDB only |
| SQL Server | bcp, scripts | BACKUP DATABASE full | RESTORE LOG ... STOPAT | Differential | Recovery models: FULL, BULK_LOGGED, SIMPLE |
| Oracle | Data Pump expdp/impdp | RMAN | RMAN until time, ARCHIVELOG | Level 1 incremental | Flashback features |
| SQLite | .dump, VACUUM INTO | .backup API, file copy at rest | Litestream (WAL shipping) | None built in | Copy only when no writer, or use the API |
| MongoDB | mongodump | Filesystem snapshot, Atlas | Oplog / Atlas continuous | Atlas | --oplog for consistency |
| CockroachDB | BACKUP/RESTORE (SQL, to cloud storage) | n/a (distributed) | AS OF SYSTEM TIME restore | Incremental backups | Managed or self-hosted |
| Redis | redis-cli --rdb | RDB snapshot, AOF | AOF replay | None | Replication is not backup either |
| RDS / Aurora | n/a | Automated snapshots | New instance at any second in window | Block level | Retention in days |
Mechanics
Files and settings you must know Must-know
| Name | Where | Meaning |
|---|---|---|
backup_label | root of a base backup | Start WAL location, checkpoint, label; must be written "byte for byte"; its presence tells recovery to start from the backup checkpoint |
backup_manifest | root of a pg_basebackup | Per-file size, mtime, checksum; input to pg_verifybackup and --incremental |
tablespace_map | root | Maps tablespace symlinks |
recovery.signal | data directory | Targeted archive recovery; removed after promotion |
standby.signal | data directory | Standby mode; wins if both signals exist |
*.history | archive and pg_wal | Timeline switch records |
*.backup | archive | Backup history file next to the WAL segment |
pg_wal/summaries | data directory | WAL summaries for incremental backups |
wal_level, archive_mode, archive_command, archive_library, archive_timeout | postgresql.conf | Archiving; wal_level and archive_mode need a restart |
restore_command, recovery_target_*, recovery_target_action | postgresql.conf | Recovery; only at server start |
max_wal_senders, wal_keep_size, max_slot_wal_keep_size | postgresql.conf | Replication protocol and WAL retention; max_slot_wal_keep_size stops a stuck slot from filling the disk |
summarize_wal, wal_summary_keep_time | postgresql.conf | Incremental backup support |
full_page_writes | postgresql.conf | Why a torn file-level copy can be repaired by replay |
WAL file name anatomy: 24 hex digits are timeline (8), log (8), segment (8): 00000002 00000001 0000003A. With 16 MB segments each log id holds 256 segments. The Go checker below uses this to find gaps.
Errors and messages you will meet
| Message or symptom | Meaning | Fix |
|---|---|---|
archive command failed with exit code 1 in the log, failed_count rising | The archive command returned non-zero | Fix the destination; WAL accumulates until it works |
pg_wal full, primary stops | Archive or slot is stuck | Fix archiving; cap slots with max_slot_wal_keep_size; do not delete pg_wal files by hand |
FATAL: requested timeline 2 is not a child of this server's history | Wrong recovery_target_timeline for this base backup | Use current/latest or the right id |
FATAL: recovery ended before configured recovery target was reached | Archive ends before the target time or a segment is missing | Check for gaps and the target; run the Go gap checker |
FATAL: invalid checkpoint record or could not locate required checkpoint record | backup_label missing or WAL for the start checkpoint absent | Restore the base backup's WAL and backup_label intact |
pg_dump: error: aborting because of server version mismatch | Client older than server (GitLab 2017) | Use pg_dump from the server's major version |
pg_restore: error: ... already exists | Restoring into a non-empty database | Use an empty database, or --clean --if-exists knowingly |
Incremental fails: WAL summaries are required on timeline ... | summarize_wal was off, or summaries expired | Take a new full backup; raise wal_summary_keep_time |
| Hang at "waiting for checkpoint" | --checkpoint=spread | Wait, or use fast off-peak. GitLab's postmortem records a pg_basebackup that "will sit and wait silently" until the primary starts sending data |
ERROR 1356 / ERROR 1146 on MySQL restore | Views or tables referencing missing objects | Restore in order, include routines and views |
Solving the classic problems
The nightly backup that silently fails
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Verify by restore | Restore to scratch, count rows, write a manifest | Proves usability | Needs scratch capacity |
| Dead-man's switch | Alert when no success arrives in N hours | Catches missing runs and broken mail | One more integration |
| Version-match the tool | pg_dump from the server's major version | Avoids GitLab's failure | Pin in image |
| Own the job | Named owner and a runbook | "no ownership" was the root cause | Process |
Go backup runner: dump, hash, restore, verify
The "Before" is a cron loop that never checks anything.
// Package main is a "cron in a loop" backup job. It shells out to pg_dump
// and never checks the result.
package main
import (
"log"
"os/exec"
"time"
)
func main() {
ticker := time.NewTicker(24 * time.Hour)
defer ticker.Stop()
for range ticker.C {
file := "/backups/app-" + time.Now().Format("20060102") + ".sql"
// No timeout, no checksum, no manifest, no restore test. A failed
// pg_dump is logged and forgotten until someone needs the backup.
cmd := exec.Command("pg_dump", "--format=plain", "--dbname=app", "--file="+file)
if err := cmd.Run(); err != nil {
log.Println("backup failed:", err)
}
}
}The "After" runs the dump under a 30-minute deadline, hashes the stream while writing, restores into a scratch database with psql, counts rows, and only then writes a manifest with restore_verified: true.
// Package main is a nightly PostgreSQL backup job. It dumps under a deadline,
// hashes the stream while writing it, writes a manifest, and proves the dump
// restores by loading it into an empty scratch database and counting rows.
//
// This file uses only the standard library. The binary must register a
// PostgreSQL driver for database/sql, for example with a blank import of
// github.com/jackc/pgx/v5/stdlib; that choice belongs to the deployment.
package main
import (
"bytes"
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"time"
)
const (
driverName = "pgx" // registered by the binary, see the package comment
dumpTimeout = 30 * time.Minute
// The sanity table and query are fixed constants, not user input.
sanityTable = "orders"
countQuery = "SELECT count(*) FROM " + sanityTable
)
type manifest struct {
Database string `json:"database"`
File string `json:"file"`
Bytes int64 `json:"bytes"`
SHA256 string `json:"sha256"`
SourceRowCount int64 `json:"source_row_count"`
RestoreVerified bool `json:"restore_verified"`
CreatedAt time.Time `json:"created_at"`
}
func main() {
dir := os.Getenv("BACKUP_DIR")
dbName := os.Getenv("BACKUP_DATABASE")
scratchName := os.Getenv("SCRATCH_DATABASE")
if dir == "" || dbName == "" || scratchName == "" {
log.Fatal("BACKUP_DIR, BACKUP_DATABASE and SCRATCH_DATABASE must be set")
}
// Connection details for the source and the scratch database come from
// the environment. pg_dump and psql read PGHOST, PGUSER and PGPASSWORD.
src, err := sql.Open(driverName, os.Getenv("SOURCE_DSN"))
if err != nil {
log.Fatal(err)
}
defer src.Close()
scratch, err := sql.Open(driverName, os.Getenv("SCRATCH_DSN"))
if err != nil {
log.Fatal(err)
}
defer scratch.Close()
ctx, cancel := context.WithTimeout(context.Background(), dumpTimeout)
defer cancel()
if err := run(ctx, src, scratch, dir, dbName, scratchName); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context, src, scratch *sql.DB, dir, dbName, scratchName string) error {
// Row count before the dump. The dump is a consistent snapshot taken a
// moment later, so the restored table should hold at least this many rows.
var sourceRows int64
if err := src.QueryRowContext(ctx, countQuery).Scan(&sourceRows); err != nil {
return fmt.Errorf("count source rows: %w", err)
}
createdAt := time.Now().UTC()
name := fmt.Sprintf("%s-%s.sql", dbName, createdAt.Format("20060102T150405Z"))
path := filepath.Join(dir, name)
sum, size, err := dumpTo(ctx, dbName, path)
if err != nil {
return fmt.Errorf("dump: %w", err)
}
if err := restoreAndVerify(ctx, scratch, scratchName, path, sourceRows); err != nil {
return fmt.Errorf("restore verification failed for %s: %w", path, err)
}
m := manifest{
Database: dbName,
File: name,
Bytes: size,
SHA256: sum,
SourceRowCount: sourceRows,
RestoreVerified: true,
CreatedAt: createdAt,
}
return writeManifest(path+".manifest.json", m)
}
// dumpTo streams pg_dump's stdout into a file and a SHA-256 hash in one pass,
// so the checksum describes exactly the bytes on disk.
func dumpTo(ctx context.Context, dbName, path string) (string, int64, error) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err != nil {
return "", 0, err
}
defer f.Close()
cmd := exec.CommandContext(ctx, "pg_dump", "--format=plain", "--no-owner", "--dbname="+dbName)
var stderr bytes.Buffer
cmd.Stderr = &stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", 0, err
}
if err := cmd.Start(); err != nil {
return "", 0, err
}
h := sha256.New()
n, copyErr := io.Copy(io.MultiWriter(f, h), stdout)
waitErr := cmd.Wait() // Wait after the pipe is drained; it also reaps the process.
if copyErr != nil {
return "", 0, copyErr
}
if waitErr != nil {
// A non-zero exit means the file is not a complete dump. Never keep it.
_ = os.Remove(path)
return "", 0, fmt.Errorf("pg_dump failed: %w: %s", waitErr, stderr.String())
}
if err := f.Sync(); err != nil {
return "", 0, err
}
return hex.EncodeToString(h.Sum(nil)), n, nil
}
// restoreAndVerify loads the dump into scratchName, which must be an empty
// database, then runs a row-count query. Passing it proves the file is a
// usable backup, not just a file that exists.
func restoreAndVerify(ctx context.Context, scratch *sql.DB, scratchName, dumpPath string, minRows int64) error {
var stderr bytes.Buffer
cmd := exec.CommandContext(ctx, "psql",
"--no-psqlrc", "--quiet", "-v", "ON_ERROR_STOP=1",
"--dbname="+scratchName, "--file="+dumpPath,
)
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("psql restore: %w: %s", err, stderr.String())
}
var restored int64
if err := scratch.QueryRowContext(ctx, countQuery).Scan(&restored); err != nil {
return fmt.Errorf("count restored rows: %w", err)
}
if restored < minRows {
return fmt.Errorf("restored %d rows from %s, expected at least %d", restored, sanityTable, minRows)
}
return nil
}
func writeManifest(path string, m manifest) error {
data, err := json.MarshalIndent(m, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, append(data, '\n'), 0o600)
}database/sql has no backup API and the standard library has no PostgreSQL driver, so the binary registers one (for example a blank import of github.com/jackc/pgx/v5/stdlib). The sql.Open documentation warns that "Open may just validate its arguments without creating a connection to the database", so the first query is where a bad DSN shows up. exec.CommandContext makes the deadline kill the child; read the pipe to EOF, then Wait, and treat a non-zero exit as a failed backup however many bytes arrived.
For physical backups the second runner executes pg_basebackup, then pg_verifybackup, then appends a catalog entry built from backup_label; with PREVIOUS_BACKUP_DIR set it takes a PostgreSQL 17 incremental backup.
// Package main runs a physical backup: pg_basebackup with a manifest, then
// pg_verifybackup, then a catalog entry built from backup_label. It exits
// non-zero when any step fails, so a scheduler can alert on the exit code.
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
const backupTimeout = 6 * time.Hour
// catalogEntry is one line of the backup catalog: enough to pick the right
// base backup for a recovery target without opening the backup itself.
type catalogEntry struct {
Label string `json:"label"`
Dir string `json:"dir"`
StartWAL string `json:"start_wal_location"`
StartSegment string `json:"start_wal_file"`
StartedAt string `json:"start_time"`
FinishedAt time.Time `json:"finished_at"`
ManifestSHA string `json:"manifest_checksums"`
Verified bool `json:"verified"`
ReferenceDir string `json:"incremental_base,omitempty"`
WALMethod string `json:"wal_method"`
}
func main() {
root := os.Getenv("BACKUP_ROOT")
if root == "" {
log.Fatal("BACKUP_ROOT must be set; PGHOST, PGUSER and a password file are read by pg_basebackup itself")
}
ctx, cancel := context.WithTimeout(context.Background(), backupTimeout)
defer cancel()
entry, err := runBackup(ctx, root, os.Getenv("PREVIOUS_BACKUP_DIR"))
if err != nil {
log.Fatal(err)
}
if err := appendCatalog(filepath.Join(root, "catalog.jsonl"), entry); err != nil {
log.Fatal(err)
}
log.Printf("backup %s verified, starts at WAL %s", entry.Label, entry.StartSegment)
}
func runBackup(ctx context.Context, root, previous string) (catalogEntry, error) {
label := time.Now().UTC().Format("20060102T150405Z")
dir := filepath.Join(root, label)
args := []string{
"--pgdata=" + dir,
"--format=plain",
"--wal-method=stream", // the WAL needed for consistency travels with the backup
"--checkpoint=spread", // do not hammer the I/O of a busy primary
"--manifest-checksums=SHA256",
"--label=" + label,
"--no-password",
}
entry := catalogEntry{Label: label, Dir: dir, WALMethod: "stream", ManifestSHA: "SHA256"}
if previous != "" {
// PostgreSQL 17 incremental backup: needs summarize_wal = on on the server.
args = append(args, "--incremental="+filepath.Join(previous, "backup_manifest"))
entry.ReferenceDir = previous
}
if out, err := run(ctx, "pg_basebackup", args...); err != nil {
_ = os.RemoveAll(dir) // a partial backup directory must never look like a backup
return entry, fmt.Errorf("pg_basebackup: %w: %s", err, out)
}
// pg_verifybackup checks every file against the manifest and checks that
// the WAL needed to reach consistency is present and parseable. It does
// not replace a restore drill, but it catches truncated and altered files.
if out, err := run(ctx, "pg_verifybackup", dir); err != nil {
return entry, fmt.Errorf("pg_verifybackup: %w: %s", err, out)
}
entry.Verified = true
fields, err := readBackupLabel(filepath.Join(dir, "backup_label"))
if err != nil {
return entry, err
}
entry.StartWAL = fields["START WAL LOCATION"]
entry.StartedAt = fields["START TIME"]
if i := strings.Index(entry.StartWAL, "(file "); i >= 0 {
entry.StartSegment = strings.TrimSuffix(entry.StartWAL[i+len("(file "):], ")")
entry.StartWAL = strings.TrimSpace(entry.StartWAL[:i])
}
entry.FinishedAt = time.Now().UTC()
return entry, nil
}
func run(ctx context.Context, name string, args ...string) (string, error) {
cmd := exec.CommandContext(ctx, name, args...)
var buf bytes.Buffer
cmd.Stdout = &buf
cmd.Stderr = &buf
err := cmd.Run()
return strings.TrimSpace(buf.String()), err
}
// readBackupLabel parses "KEY: value" lines such as
// "START WAL LOCATION: 0/3000028 (file 000000010000000000000003)".
func readBackupLabel(path string) (map[string]string, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("backup_label missing, this is not a usable online backup: %w", err)
}
defer f.Close()
out := map[string]string{}
sc := bufio.NewScanner(f)
for sc.Scan() {
if k, v, ok := strings.Cut(sc.Text(), ": "); ok {
out[k] = v
}
}
return out, sc.Err()
}
func appendCatalog(path string, e catalogEntry) error {
line, err := json.Marshal(e)
if err != nil {
return err
}
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return err
}
defer f.Close()
if _, err := f.Write(append(line, '\n')); err != nil {
return err
}
return f.Sync()
}Laravel: an Artisan backup and verification
Laravel has no built-in backup (the 13.x scheduling, filesystem, artisan, migrations and container pages have no backup chapter, and schema:dump dumps structure only). The usual package is spatie/laravel-backup: "The backup is a zipfile that contains all files in the directories you specify along with a dump of your database." Its introduction page says the package can run a backup (php artisan backup:run), "clean up old backups, monitor the health of the backups, and show an overview of all backups"; the exact command names backup:clean, backup:monitor and backup:list, and the config keys below, come from the author's working knowledge, because the deeper documentation pages could not be fetched as text: verify them against the version you install. A zip of files plus a SQL dump is a logical, application-level backup: it has no PITR. Pair it with server-side WAL archiving if the RPO is minutes. Its configuration excerpt:
<?php
// config/backup.php (excerpt) for spatie/laravel-backup. Check the keys
// against the version you install; the package is configured in this file.
use Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumAgeInDays;
use Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumStorageInMegabytes;
return [
'backup' => [
'name' => env('APP_NAME', 'app'),
'source' => [
'files' => [
'include' => [base_path()],
'exclude' => [base_path('vendor'), base_path('node_modules')],
],
'databases' => ['pgsql'],
],
// Encrypt the zip with a password kept outside the backup destination.
'password' => env('BACKUP_ARCHIVE_PASSWORD'),
'encryption' => 'default',
'destination' => [
// A second disk in another account or region gives offsite copies.
'disks' => ['s3', 's3_offsite'],
],
],
'monitor_backups' => [
[
'name' => env('APP_NAME', 'app'),
'disks' => ['s3', 's3_offsite'],
'health_checks' => [
MaximumAgeInDays::class => 1,
MaximumStorageInMegabytes::class => 50_000,
],
],
],
];A custom command is the right tool when you need a specific format. The "Before" calls mysqldump through exec() with the password on the command line:
<?php
// app/Console/Commands/BackupDatabase.php, the way many projects start.
namespace App\Console\Commands;
use Illuminate\Console\Command;
class BackupDatabase extends Command
{
protected $signature = 'backup:database';
protected $description = 'Dump the database to a local file';
public function handle(): int
{
$user = config('database.connections.mysql.username');
$pass = config('database.connections.mysql.password');
$db = config('database.connections.mysql.database');
$file = storage_path('backups/'.$db.'-'.date('Ymd').'.sql');
// Credentials end up in the shell command line, visible in `ps` and
// in shell history. The exit status is ignored, and nothing checks
// that the file is complete or restorable.
exec("mysqldump -u {$user} -p{$pass} {$db} > {$file}");
$this->info('Backup written to '.$file);
return self::SUCCESS;
}
}The "After" uses Symfony Process with an argument array (no shell), PGPASSWORD in the environment, setTimeout(1800) ("By default, processes have a timeout of 60 seconds"), mustRun() so a failed dump never reaches the upload, and Storage::disk('s3')->putFileAs(...) streaming ("Streaming files to storage offers significantly reduced memory usage"):
<?php
// app/Console/Commands/BackupDatabase.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\Process\Process;
final class BackupDatabase extends Command
{
protected $signature = 'backup:database';
protected $description = 'Dump the PostgreSQL database and upload the dump to S3';
public function handle(): int
{
$conn = config('database.connections.pgsql');
$name = sprintf('%s-%s.sql', $conn['database'], now()->utc()->format('Ymd\THis\Z'));
$dir = storage_path('app/backups');
@mkdir($dir, 0700, true);
$localPath = $dir.DIRECTORY_SEPARATOR.$name;
// An argument array runs pg_dump without a shell. The password goes in
// PGPASSWORD, so it is not on the command line. 1800 s is the timeout:
// Symfony's default is 60 s.
$process = new Process(
[
'pg_dump',
'--format=plain',
'--no-owner',
'--host='.$conn['host'],
'--port='.$conn['port'],
'--username='.$conn['username'],
'--file='.$localPath,
'--dbname='.$conn['database'],
],
null,
['PGPASSWORD' => (string) $conn['password']],
);
$process->setTimeout(1800);
// mustRun() throws ProcessFailedException on a non-zero exit, so a
// failed dump never reaches the upload step.
$process->mustRun();
// putFileAs() streams the file to S3 instead of loading it into memory.
Storage::disk('s3')->putFileAs('backups/postgres', new File($localPath), $name);
unlink($localPath);
$this->info('Uploaded backups/postgres/'.$name);
return self::SUCCESS;
}
}The libpq documentation says of PGPASSWORD: "Use of this environment variable is not recommended for security reasons, as some operating systems allow non-root users to see process environment variables via ps; instead consider using a password file" The verification command restores a dump into a scratch database and checks a row count:
<?php
// app/Console/Commands/VerifyBackup.php
// Restores a dump into the empty scratch database named by the "scratch"
// connection in config/database.php, then checks a row count.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process;
final class VerifyBackup extends Command
{
protected $signature = 'backup:verify {file : Local dump file to restore} {--min-rows=1 : Minimum rows expected in orders}';
protected $description = 'Restore a dump into a scratch database and sanity-check the row count';
public function handle(): int
{
$file = (string) $this->argument('file');
$conn = config('database.connections.scratch');
// ON_ERROR_STOP makes psql exit non-zero on the first failing statement.
$process = new Process(
[
'psql',
'--no-psqlrc',
'--quiet',
'--set=ON_ERROR_STOP=1',
'--host='.$conn['host'],
'--port='.$conn['port'],
'--username='.$conn['username'],
'--dbname='.$conn['database'],
'--file='.$file,
],
null,
['PGPASSWORD' => (string) $conn['password']],
);
$process->setTimeout(1800);
$process->mustRun();
// A sanity check, not a checksum: the table must exist and hold rows.
$count = DB::connection('scratch')->table('orders')->count();
$min = (int) $this->option('min-rows');
if ($count < $min) {
$this->error("Restored {$count} rows, expected at least {$min}.");
return self::FAILURE;
}
$this->info("Restore verified: {$count} rows in orders.");
return self::SUCCESS;
}
}The schedule uses withoutOverlapping because "By default, scheduled tasks will be run even if the previous instance of the task is still running."
<?php
// routes/console.php
// Global-namespace code, so it lives in its own file. The scheduler is driven
// by one cron entry that runs `php artisan schedule:run` every minute.
use Illuminate\Support\Facades\Schedule;
Schedule::command('backup:database')
->daily()
->withoutOverlapping()
->emailOutputOnFailure(config('backup.alert_email'));A dump includes the migrations table, so restoring an old dump gives an old schema: deploy matching code or run migrations forward (Zero-Downtime Schema Migrations).
A broken archive cuts PITR
| Solution | How | Advantage | Cost |
|---|---|---|---|
Monitor pg_stat_archiver | Alert on failed_count growth and age of last_archived_time | Catches silent failure | Needs a scheduler |
| Gap check | Parse segment names between base start and now | Catches deletion and partial sync | Custom or pgBackRest verify |
| Archive to two places | pgBackRest multi-repo, or archive + replica | Single failure tolerated | Cost |
Alert on pg_wal size | Disk usage on the WAL volume | Early warning for the availability risk | n/a |
SELECT now() - last_archived_time AS since_last_archive,
failed_count, last_failed_wal, last_failed_time
FROM pg_stat_archiver;Go: find gaps between the base backup and now
// Package main checks a WAL archive directory for the one thing that breaks
// point-in-time recovery: a missing segment between the base backup and the
// recovery target. It parses 24-hex-digit segment names (timeline, log, seg).
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
// segmentsPerLog is 256 for the default 16 MB WAL segment size: the low
// 32 bits of an LSN hold 0x100 segments of 16 MB each.
const segmentsPerLog = 256
type segment struct {
Timeline uint32
Number uint64 // log*segmentsPerLog + seg, a linear segment number
Name string
ModTime time.Time
}
// parseSegment accepts "000000010000000000000003" and the same name with a
// compression suffix such as ".gz", ".zst" or ".lz4". Partial and history
// files return ok=false.
func parseSegment(file string) (segment, bool) {
name := file
if i := strings.IndexByte(name, '.'); i >= 0 {
if strings.HasSuffix(name, ".history") || strings.HasSuffix(name, ".partial") || strings.Contains(name, ".backup") {
return segment{}, false
}
name = name[:i]
}
if len(name) != 24 {
return segment{}, false
}
tli, err1 := strconv.ParseUint(name[0:8], 16, 32)
logID, err2 := strconv.ParseUint(name[8:16], 16, 32)
seg, err3 := strconv.ParseUint(name[16:24], 16, 32)
if err1 != nil || err2 != nil || err3 != nil {
return segment{}, false
}
return segment{Timeline: uint32(tli), Number: logID*segmentsPerLog + seg, Name: name}, true
}
func main() {
if len(os.Args) != 3 {
log.Fatalf("usage: %s <archive-dir> <first-needed-segment-from-backup_label>", os.Args[0])
}
first, ok := parseSegment(os.Args[2])
if !ok {
log.Fatalf("not a WAL segment name: %q", os.Args[2])
}
segs, err := readArchive(os.Args[1], first.Timeline)
if err != nil {
log.Fatal(err)
}
if segs[len(segs)-1].Number < first.Number {
log.Fatalf("newest archived segment %s is older than the first needed segment %s", segs[len(segs)-1].Name, first.Name)
}
gaps := findGaps(segs, first.Number)
if len(gaps) > 0 {
for _, g := range gaps {
fmt.Printf("GAP on timeline %d: missing %d segment(s) starting at linear number %d\n", first.Timeline, g[1], g[0])
}
os.Exit(1)
}
newest := segs[len(segs)-1]
fmt.Printf("archive is continuous up to %s; newest segment is %s old\n",
newest.Name, time.Since(newest.ModTime).Round(time.Second))
}
func readArchive(dir string, timeline uint32) ([]segment, error) {
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
var segs []segment
for _, e := range entries {
s, ok := parseSegment(e.Name())
if !ok || s.Timeline != timeline {
continue
}
info, err := e.Info()
if err != nil {
return nil, err
}
s.ModTime = info.ModTime()
segs = append(segs, s)
}
if len(segs) == 0 {
return nil, fmt.Errorf("no segments for timeline %d in %s", timeline, filepath.Clean(dir))
}
sort.Slice(segs, func(i, j int) bool { return segs[i].Number < segs[j].Number })
return segs, nil
}
// findGaps returns [start, count] pairs for holes at or after firstNumber.
func findGaps(segs []segment, firstNumber uint64) [][2]uint64 {
var gaps [][2]uint64
expect := firstNumber
for _, s := range segs {
if s.Number < expect {
continue // older than the base backup needs
}
if s.Number > expect {
gaps = append(gaps, [2]uint64{expect, s.Number - expect})
}
expect = s.Number + 1
}
return gaps
}Laravel: page when archiving fails
<?php
declare(strict_types=1);
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* Fails when PostgreSQL WAL archiving is behind or failing. Run it every
* minute from the scheduler and page on a non-zero exit: a broken archive
* silently cuts the PITR chain.
*/
class ArchiveHealth extends Command
{
protected $signature = 'db:archive-health {--max-lag=300 : seconds since the last archived segment}';
protected $description = 'Check pg_stat_archiver for failures and lag';
public function handle(): int
{
$row = DB::selectOne(
'SELECT archived_count, failed_count, last_archived_wal,
EXTRACT(EPOCH FROM (now() - last_archived_time))::int AS archived_age,
EXTRACT(EPOCH FROM (now() - last_failed_time))::int AS failed_age
FROM pg_stat_archiver'
);
if ($row === null || $row->archived_age === null) {
$this->error('Nothing has ever been archived: archive_mode may be off.');
return self::FAILURE;
}
$maxLag = (int) $this->option('max-lag');
$stuck = $row->failed_age !== null && $row->failed_age < $row->archived_age;
$this->line(sprintf(
'last archived %s, %ds ago; failed_count=%d',
$row->last_archived_wal,
$row->archived_age,
$row->failed_count,
));
// Idle databases switch segments only on archive_timeout, so allow for it.
if ($stuck || $row->archived_age > $maxLag) {
$this->error('WAL archiving is failing or behind; the PITR chain is at risk.');
return self::FAILURE;
}
return self::SUCCESS;
}
}Recover from a mistaken DROP or DELETE
Choose by what you know: you know the time (recovery_target_time), you made a restore point (recovery_target_name), you know the transaction (recovery_target_xid), or you read the WAL (recovery_target_lsn). Do not recover on top of production: build a side instance at the target, verify with recovery_target_action = pause, then copy only the lost rows back with pg_dump --table (or INSERT ... SELECT through postgres_fdw/dblink), or promote it as the new primary if the damage was wide. This preserves everything written after the mistake. The full procedure is in the lab.
-- on the recovered side instance (paused at the target), export just what was lost
\copy (SELECT * FROM orders WHERE created_at >= '2026-11-25') TO '/tmp/orders-recovered.csv' CSV
-- on production: load it into a staging table, reconcile, INSERT ... ON CONFLICT DO NOTHINGGo: build the recovery settings for the side instance, refusing anything but exactly one target.
// excerpt: imports fmt, sort, strings
var targetKeys = map[string]bool{
"recovery_target_time": true,
"recovery_target_lsn": true,
"recovery_target_name": true,
"recovery_target_xid": true,
}
// recoveryConf renders the settings for a side instance. PostgreSQL accepts at
// most one recovery_target_* parameter, so exactly one must be supplied.
func recoveryConf(archiveDir string, targets map[string]string) (string, error) {
keys := make([]string, 0, len(targets))
for k, v := range targets {
if !targetKeys[k] || strings.ContainsAny(v, "'\n") {
return "", fmt.Errorf("invalid recovery target %q", k)
}
keys = append(keys, k)
}
if len(keys) != 1 {
return "", fmt.Errorf("exactly one recovery target is required, got %d", len(keys))
}
sort.Strings(keys)
var b strings.Builder
fmt.Fprintf(&b, "restore_command = 'cp %s/%%f \"%%p\"'\n", archiveDir)
fmt.Fprintf(&b, "%s = '%s'\n", keys[0], targets[keys[0]])
b.WriteString("recovery_target_action = 'pause'\n") // verify before promoting
b.WriteString("archive_mode = off\n") // a side instance must not write into the archive
return b.String(), nil
}Laravel: record a named restore point automatically before every migration run, so just before the migration is always a valid target.
// app/Providers/AppServiceProvider.php (excerpt)
use Illuminate\Database\Events\MigrationsStarted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
public function boot(): void
{
// A named restore point before every migration run: PITR can stop exactly here.
// Needs superuser or EXECUTE on pg_create_restore_point for the app role.
Event::listen(MigrationsStarted::class, function (): void {
if (DB::connection()->getDriverName() !== 'pgsql') {
return;
}
DB::selectOne('SELECT pg_create_restore_point(?)', ['before_migrate_'.now()->format('Ymd_His')]);
});
}Restoring a logical dump fast
pg_restore --jobs=8 --dbname=shop --no-owner /backups/shop-20261125 # directory format
# postgresql.conf for the restore window only: fsync stays on, but relax
# max_wal_size = 32GB, maintenance_work_mem = 2GB, checkpoint_timeout = 30min, autovacuum = off
# afterwards: ANALYZE; re-enable autovacuum; reset sequencesThe same restore from Go and from Laravel:
// excerpt: imports context, fmt, os/exec
// restoreParallel loads a directory-format dump with eight jobs.
func restoreParallel(ctx context.Context, db, dir string) error {
cmd := exec.CommandContext(ctx, "pg_restore", "--jobs=8", "--no-owner", "--dbname="+db, dir)
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("pg_restore: %w: %s", err, out)
}
return nil
}// app/Console/Commands/RestoreDump.php (excerpt): parallel restore of a directory-format dump
use Symfony\Component\Process\Process;
$process = new Process(['pg_restore', '--jobs=8', '--no-owner', '--dbname='.$database, $dumpDir]);
$process->setTimeout(7200); // the 60-second default would kill a real restore
$process->mustRun(); // throws on a non-zero exit instead of pretending it workedRetries and failure handling
| Failure | Retry? | Rule |
|---|---|---|
archive_command non-zero | Automatic | Server retries forever; fix the cause |
| Upload to object storage times out | Yes, with backoff | Idempotent keys; check the checksum on completion |
pg_dump fails midway | No | Delete the partial file; never ship it |
pg_basebackup interrupted | Restart from scratch | The directory is not resumable; pgBackRest can resume a backup |
| Recovery interrupted by an external error | Yes: "the server can simply be restarted and it will continue recovery" | Keep recovery.signal and the archive |
| Verification restore fails | Page a human | Never auto-delete the previous good backup on a failed verification |
Retention must run only after the new backup has been verified, never before.
Choosing a strategy
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Small internal tool, RPO 24 h | Nightly pg_dump -Fc + weekly restore test | Offsite copy | Simple and cheap |
| Production OLTP, RPO minutes | pgBackRest/WAL-G full+diff + WAL archive | pg_stat_archiver alert, monthly PITR drill | Real PITR |
| 5 TB+, mostly cold data | Incrementals (pgBackRest or PG 17) | Block incremental, process-max | Backup window and storage |
| Payments / ledger | Synchronous standby + archive + immutable copy | RPO 0 for node loss, PITR for mistakes | Two different failure classes |
| Major version upgrade | Logical replication or pg_upgrade | Dump --schema-only first | Short cutover |
| Multi-tenant, restore one tenant | Logical dump of the tenant schema + PITR side instance | pg_dump --schema=tenant_42 | Selective restore |
| Managed RDS/Aurora | Automated backups + cross-Region copy + vault lock | Test restore to new instance | Provider handles WAL |
| SQLite on a single host | Litestream or .backup API | Offsite bucket | Embedded model |
| Ransomware in the threat model | Separate account + Object Lock + write-only keys | Offline copy | Credentials are the weak link |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One PostgreSQL primary, one application. The simplest correct setup is a base backup weekly, a WAL archive, archive_timeout = 60, an alert on pg_stat_archiver, one offsite bucket, and a restore drill monthly. Example: a Laravel shop with 80 GB uses pgBackRest to S3 with repo1-retention-full=2, runs pgbackrest verify nightly, and restores into a scratch VM on the first of the month while the Laravel backup:monitor watches the file-level backup of uploads.
Modular monolith and multiple databases
Several schemas or databases in one cluster are backed up consistently by one physical backup, but pg_dump per database is not mutually consistent (see multi-database consistency). Per-module restores use pg_dump --schema=billing on a PITR side instance. Ownership matters: each module owns the restore test for its tables.
Microservices: no global snapshot
Each service owns its database and its backup, and there is no single timestamp across them. After restoring billing to 14:03, orders may still contain orders billing has forgotten. Make the recovery safe by design: the outbox pattern (Outbox) so events can be republished, idempotent consumers so replays do not double-apply (Idempotent Consumers), sagas (Saga) to compensate, and a reconciliation job comparing the services. Coordinate restore points: run pg_create_restore_point('release_2026_11_25') in every database at a deploy fence and restore all to that name.
1 orders-db: restore point 'fence_1400' at 14:00:00
2 billing-db: restore point 'fence_1400' at 14:00:01
3 incident at 14:03 in billing-db only
4 restore billing to fence_1400; replay orders -> billing events from the outbox since the fence
5 reconcile: invoices without order, orders without invoiceDistributed data: replicas, caches and multi-region
Replicas are for failover, not recovery; a replica can be promoted to a new primary and then seed a PITR chain by taking a new base backup. A delayed replica (recovery_min_apply_delay) gives a cheap few-hours undo window. Take backups from a standby to spare the primary, remembering the standby's lag defines the freshness of the base, and pg_backup_stop on a standby needs archive_mode = always to wait for archiving. Redis and other caches are rebuilt, not restored; after a PITR flush caches that held data from the discarded future. Multi-region: cross-region archive replication, a warm standby that follows WAL, and a DR exercise that moves secrets and DNS as well. CockroachDB and Spanner use their own backup and AS OF SYSTEM TIME restore; consensus does not remove the need for backups (Distributed SQL & Consensus).
Scaling path: 1x, 10x, 100x
| Scale | Data | Strategy | What changes |
|---|---|---|---|
| 1x | 10 to 100 GB | pg_dump -Fd -j, nightly; or pgBackRest full | Dump is fine; verify weekly |
| 10x | 1 TB | pgBackRest + WAL archive, diff daily | Restore minutes become hours; rehearse |
| 100x | 10+ TB | Incrementals/block incremental, parallel, snapshots + WAL, standby warm | Copy time dominates RTO; shard or partition so recovery units are smaller (Partitioning & Sharding) |
Lab
Everything runs on one machine with PostgreSQL 17 binaries on the path; no containers. Ports 5433 (primary) and 5434 (recovered copy).
# 0. Setup
export LAB=/tmp/pitrlab; rm -rf $LAB; mkdir -p $LAB/archive
initdb -D $LAB/primary >/dev/null
cat >> $LAB/primary/postgresql.conf <<CONF
port = 5433
wal_level = replica
archive_mode = on
archive_timeout = 30
archive_command = 'test ! -f $LAB/archive/%f && cp %p $LAB/archive/%f'
CONF
pg_ctl -D $LAB/primary -l $LAB/primary.log start
createdb -p 5433 shop
psql -p 5433 shop -c "CREATE TABLE orders(id serial PRIMARY KEY, total int); INSERT INTO orders(total) SELECT g FROM generate_series(1,1000) g;"# 1. Base backup, verified
pg_basebackup -p 5433 -D $LAB/base -X stream --checkpoint=fast --manifest-checksums=SHA256
pg_verifybackup $LAB/base # expected: "backup successfully verified"
grep -E "START WAL|LABEL" $LAB/base/backup_label-- 2. More work, a restore point, then the "accident" (psql -p 5433 shop)
INSERT INTO orders(total) SELECT 5000 + g FROM generate_series(1,500) g; -- 1500 rows now
SELECT pg_create_restore_point('before_drop'); -- note the returned LSN
SELECT now(); -- note this time too
DROP TABLE orders; -- the accident
SELECT pg_switch_wal(); -- force the segment into the archive
-- psql: \dt shows no orders; the replica of this would show none either# 3. Check the archive before trusting it
ls $LAB/archive | head # 0000000100000000000000NN files; the segment holding DROP must be there
psql -p 5433 shop -Atc "SELECT archived_count, failed_count FROM pg_stat_archiver;" # failed_count = 0# 4. Recover to the restore point, on a new directory and port
pg_ctl -D $LAB/primary stop
cp -R $LAB/base $LAB/restore && chmod 700 $LAB/restore
cat >> $LAB/restore/postgresql.conf <<CONF
port = 5434
archive_mode = off
restore_command = 'cp $LAB/archive/%f "%p"'
recovery_target_name = 'before_drop'
recovery_target_action = 'pause'
CONF
touch $LAB/restore/recovery.signal
pg_ctl -D $LAB/restore -l $LAB/restore.log start
sleep 3; tail -5 $LAB/restore.log
# expected: log lines about stopping at the restore point and pausing at the end of recovery-- 5. Verify while paused, then finish (psql -p 5434 shop)
SELECT pg_is_in_recovery(); -- t
SELECT count(*) FROM orders; -- 1500: the table exists, rows from step 2 included
SELECT pg_wal_replay_resume(); -- ends recovery and promotes
SELECT timeline_id FROM pg_control_checkpoint(); -- 2: a new timeline started# 6. Look at the artifacts, and try a wrong target
ls $LAB/restore/pg_wal | grep history # 00000002.history (archive_mode is off here, so it is not in $LAB/archive)
cat $LAB/restore/pg_wal/00000002.history # one line: parent TLI 1, switch LSN, "at restore point "before_drop""
# Repeat step 4 on a fresh copy with: recovery_target_time = '<time from step 2 minus 1 minute>'
# -> if that time is before the base backup ended, startup fails: the stop point must be after the base backup
# Remove a middle segment from $LAB/archive and repeat: recovery stops short; run the Go gap checker to see whyCleanup: pg_ctl -D $LAB/restore stop; rm -rf $LAB.
Common misconceptions
| Belief | Reality |
|---|---|
| "A replica is a backup." | It replicates the bad write; GitLab: replication is "not for disaster recovery". |
| "The cron job succeeded, so the backup is good." | Only a restore proves it; GitLab's job produced nothing for a long time. |
"cp -r of PGDATA while running is a backup." | Needs pg_backup_start/pg_backup_stop or pg_basebackup, plus WAL. |
"pg_dump includes roles." | Roles are global; use pg_dumpall --globals-only. |
"pg_dumpall is consistent across databases." | Each database is dumped with its own snapshot. |
| "A snapshot on the same host is DR." | It dies with the host and may restore slowly (GitLab: over a week across accounts). |
| "I can PITR to any time after any backup." | The target must be after the base backup ended and the WAL must be unbroken. |
| "Archiving errors are only a backup problem." | A failing archive_command fills pg_wal and can stop the primary. |
| "Incrementals are always cheaper to restore." | They need the whole chain valid and pg_combinebackup; restore is more work. |
| "Encryption at rest on the cloud covers backups." | The provider's key and an attacker with your IAM role can both read them. |
| "A backup in the same account is offsite." | One compromised credential deletes both; use a separate account and Object Lock. |
| "RPO and RTO are the same thing." | RPO is data loss; RTO is downtime; they are tuned by different mechanisms. |
Cheat sheet
| Topic | What to remember |
|---|---|
| Backup vs replica | Replica for failover, backup for mistakes and attacks |
| Dump formats | -Fd for parallel dump; -Fc/-Fd for selective, parallel restore |
| Globals | pg_dumpall --globals-only for roles and tablespaces |
| MySQL | mysqldump --single-transaction --source-data=2; mydumper for big; XtraBackup for physical |
| Base backup | pg_basebackup -X stream --manifest-checksums=SHA256 then pg_verifybackup |
| Archive | wal_level=replica, archive_mode=on, archive_command, archive_timeout=60; watch pg_stat_archiver |
| Recovery | restore base, recovery.signal, restore_command, one recovery_target_*, pause then verify |
| Targets | time, LSN, name (pg_create_restore_point), xid, immediate |
| Timelines | Promotion starts a new TLI and writes .history; default follows latest |
| Incremental | PG 17: summarize_wal, --incremental, pg_combinebackup; pgBackRest full/diff/incr |
| Retention | Express in backups plus WAL; verify before expiring |
| RPO | about archive_timeout + ship lag; 0 only with a synchronous standby (for node loss) |
| RTO | detect + provision + copy + replay + validate; measure it in drills |
| 3-2-1-1-0 | 3 copies, 2 media, 1 offsite, 1 immutable, 0 verification errors |
| Immutable | Separate account, Object Lock/WORM, write-only credentials |
| Large objects | Included by default only in full-database dumps; TOAST dumps inline |
| Multi-DB | pg_dumpall is not one snapshot; use restore points across services |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why is a streaming replica not a backup? Name the failure it does not protect against. Must-know
Answer
Answer: It applies every committed change, including a mistaken DELETE, within seconds. It protects against node or AZ loss, not logical errors or attacks.
2 — List the three things a PITR needs and what makes it fail. Must-know
Answer
Answer: A base backup, an unbroken WAL archive from its start through the target, and a restore_command/recovery target. A missing segment, a target before the base backup ended, or a wrong timeline ends or prevents recovery.
3 — Which recovery_target_* would you use before a planned risky migration, and how do you create it? Important
Answer
Answer: recovery_target_name, created with SELECT pg_create_restore_point('name') just before the change. It is exact and needs no clock reading.
4 — What does recovery_target_action = pause give you? Good to know
Answer
Answer: Recovery stops at the target with the server readable; you can query to confirm it is the right point, then pg_wal_replay_resume() to finish, or restart with a later target.
5 — After PITR what is a timeline and why does PostgreSQL create one? Important
Answer
Answer: A numbered branch of WAL history (first 8 hex digits of segment names). It separates new writes from the discarded future and prevents a revived old primary from overwriting archive files; a .history file records the branch point.
6 — A nightly job exits 0 and S3 has a 2 KB file. What went wrong and what check would have caught it? Must-know
Answer
Answer: The dump failed or produced an empty/partial file and was not treated as failure. A restore into scratch with a row-count check, plus a size and age alert, would have caught it.
7 — Compute RTO: 3 TB base at 300 MB/s, 100 GB WAL replayed at 100 MB/s, 20 minutes of overhead. Important
Answer
Answer: Copy: 3,072,000 MB / 300 = 10,240 s (about 171 min). Replay: 102,400 / 100 = 1,024 s (about 17 min), overlapping fetch. Total about 171 + 17 + 20 = 208 minutes, about 3.5 hours.
8 — What does 3-2-1-1-0 add to 3-2-1? Must-know
Answer
Answer: One immutable or offline copy and zero errors after verification (restore tests).
9 — Why is pg_dumpall not consistent across databases, and what is? Must-know
Answer
Answer: It dumps each database with a separate snapshot sequentially. A physical base backup of the cluster is consistent across all of its databases.
10 — What do you need besides the latest incremental to restore it? Important
Answer
Answer: Every earlier backup it depends on, back to the full, combined with pg_combinebackup (or pgBackRest restore), plus the WAL from the backup onward.
11 — Name two things that make a backup bucket survive stolen production credentials. Important
Answer
Answer: An Object Lock/WORM copy in a separate account, and write-only credentials from production (no delete permission).
12 — Why can a failing archive_command take the primary down? Important
Answer
Answer: The server keeps unarchived segments in pg_wal; if archiving keeps failing the directory fills the disk and the server stops.
Glossary
| Term | Meaning |
|---|---|
| Logical backup | Schema and rows exported as SQL or an archive (pg_dump, mysqldump) |
| Physical backup | Copy of the data files (pg_basebackup, XtraBackup, snapshots) |
| Base backup | A physical backup that serves as the start of archive recovery |
| WAL (write-ahead log) | Sequential record of changes, split into 16 MB segments by default |
| WAL archive | Storage holding completed WAL segments for recovery |
archive_command | Shell command run for each completed WAL segment; zero exit means stored |
restore_command | Shell command that fetches an archived file during recovery |
archive_timeout | Forces a WAL switch after N seconds to bound archive delay |
| PITR | Point-in-time recovery: base backup plus WAL replay to a target |
| Recovery target | Stop point: time, LSN, name, xid or immediate |
recovery.signal | Empty file that makes the server start archive recovery |
| Restore point | Named WAL position made with pg_create_restore_point |
| Timeline (TLI) | Branch of WAL history; first 8 hex digits of segment names |
.history file | Records where a timeline branched from its parent |
backup_label | File naming the start checkpoint and WAL of a base backup |
backup_manifest | Per-file list with sizes and checksums, input to pg_verifybackup |
pg_verifybackup | Checks a base backup against its manifest and WAL |
pg_combinebackup | Combines a full and incremental backups into a synthetic full (PostgreSQL 17+) |
| WAL summarization | summarize_wal; tracks changed blocks for incremental backups |
| Differential backup | Changes since the last full backup |
| Incremental backup | Changes since the last backup of any type |
| Retention policy | Rule deciding which backups and WAL to keep (redundancy or recovery window) |
| Backup catalog | Inventory of backups and their dependencies (pgbackrest info, barman list-backups) |
| RPO | Recovery point objective: tolerable data loss |
| RTO | Recovery time objective: tolerable downtime |
| 3-2-1 rule | Three copies, two media, one offsite |
| Immutable backup | Cannot be altered or deleted until retention ends (Object Lock, WORM) |
| Object Lock | S3 feature for WORM retention (governance or compliance mode) |
| Synchronized snapshot | Exported snapshot that parallel pg_dump workers share |
| TOAST | Out-of-line storage of large values; dumped inline by pg_dump |
| Large object | pg_largeobject storage accessed with lo_*; included in full dumps |
| Data checksums | Per-page checksums that detect silent corruption |
| Restore drill | Scheduled, automated restore and check of a backup |
| pgBackRest / Barman / WAL-G | PostgreSQL backup and archive managers |
| XtraBackup | Percona's hot physical backup tool for MySQL |
mydumper | Parallel logical dumper for MySQL |
| Cold / warm / hot standby | Not running / following WAL / accepting failover |
| Logical replication | Publication/subscription of row changes; usable for migrations |
| RDS / Aurora PITR | Managed restore to a new instance at a chosen second |
pg_stat_archiver | View with archive success, failure and last file |
References
- PostgreSQL 19 documentation, Chapter 25. Backup and Restore.
- PostgreSQL 19 documentation, 25.3. Continuous Archiving and Point-in-Time Recovery (PITR).
- PostgreSQL 19 documentation, pg_basebackup, pg_dump and pg_restore.
- PostgreSQL 19 documentation, libpq environment variables and runtime configuration: write-ahead log.
- MySQL 8.4 Reference Manual, Types of Backup.
- GitLab, Postmortem of database outage of January 31, 10 February 2017.
- pgBackRest, User Guide.
- Barman, documentation.
- Percona, XtraBackup documentation.
- Go documentation:
os/exec,database/sql. - Symfony, Process component.
- Laravel 13 documentation: Task Scheduling, Filesystem, Migrations.
- spatie, laravel-backup introduction.