The WAL is the database. Every change is written to the write-ahead log and flushed before the data files are touched. On crash recovery PostgreSQL replays the WAL from the last checkpoint. Everything else in this module - backups, replication, point-in-time recovery - is a different way of using that same log.
Three kinds of backup, and they are not interchangeable.
pg_dump produces a logical dump: SQL or a custom-format archive. It is portable across versions and architectures, restores to a consistent snapshot of the moment it started, and is slow to restore at scale. It can dump a single table, which the others cannot.
pg_basebackup produces a physical copy of the data directory. It restores fast, must go back to a compatible major version and architecture, and is the foundation of both replication and PITR.
Point-in-time recovery is a base backup plus the archived WAL that follows it, replayed to a chosen moment. This is the only mechanism that recovers from logical damage - a DELETE without a WHERE at 14:05 - because it lets you stop at 14:04.
Know your RPO and RTO before the incident, and measure them. RPO is how much data you may lose; RTO is how long you may be down. These are numbers the business states and engineering verifies. An untested backup has an unknown RPO and an infinite RTO, and most organisations discover this during their first real restore.
Replication. Streaming replication ships WAL to a replica that replays it continuously. Asynchronous by default, so a failover can lose the last transactions; synchronous_commit = on with a synchronous standby trades write latency for a zero-loss promise. Logical replication decodes WAL into row changes and publishes selected tables, which is how you replicate between major versions, into a different schema, or to another system entirely.
Replicas are not backups. A DROP TABLE replicates faithfully and instantly.
Connection pooling. Each PostgreSQL connection is an OS process costing several megabytes. A few hundred is a lot. An application with a per-request connection will exhaust max_connections under load, and raising it makes things worse rather than better. PgBouncer in transaction mode multiplexes many client connections onto few server connections, and is close to mandatory for anything with real concurrency.
Laboratory exercise 5 - lose it and get it back.
In a disposable environment, set up WAL archiving and take a base backup. Load data, note the time, then cause logical damage: a DELETE or UPDATE with no WHERE, recorded with its timestamp.
Recover to the moment before the damage. Verify the data is correct and the damage is absent. Time the whole restore and compute the achieved RPO and RTO.
Then do it again with a different failure: stop the primary abruptly and promote a streaming replica. Measure what the asynchronous replica lost.
Deliverable: a recovery runbook somebody else could execute under pressure, the measured RPO and RTO for both scenarios, and evidence of verification - a count and a checksum that prove the data is right, not merely that the server started.
-- ================= Backups =================
--
-- Logical. Portable across versions; can dump one table; slow to
-- restore at scale.
-- pg_dump -Fc -d workshop -f workshop.dump # custom format
-- pg_dump -Fc -t ledger.entry -d workshop -f entry.dump
-- pg_restore -d workshop_restored -j 4 workshop.dump # parallel
--
-- Physical. Fast to restore; same major version and architecture only.
-- pg_basebackup -D /backup/base -Fp -Xs -P -c fast
--
-- Globals are NOT in pg_dump. Roles and tablespaces live here, and
-- forgetting them is the classic restore surprise:
-- pg_dumpall --globals-only -f globals.sql
-- ================= Point-in-time recovery =================
--
-- postgresql.conf, before you need it:
-- wal_level = replica
-- archive_mode = on
-- archive_command = 'test ! -f /archive/%f && cp %p /archive/%f'
-- archive_timeout = 300 # bound the RPO even when idle
--
-- Verify archiving is actually working. A failing archive_command is
-- silent apart from this view, and WAL then accumulates until the
-- disk fills:
SELECT archived_count, last_archived_wal, last_archived_time,
failed_count, last_failed_wal, last_failed_time
FROM pg_stat_archiver;
SELECT pg_current_wal_lsn(), pg_walfile_name(pg_current_wal_lsn());
-- Recovering to just before the damage:
-- 1. stop the server
-- 2. move the broken data directory aside - do NOT delete it, it is
-- evidence and it may be the only copy of something
-- 3. restore the base backup into place
-- 4. in postgresql.conf:
-- restore_command = 'cp /archive/%f %p'
-- recovery_target_time = '2026-11-30 14:04:00+00'
-- recovery_target_action = 'promote'
-- 5. touch recovery.signal
-- 6. start, and watch the log until it reports a consistent state
--
-- Then VERIFY, with a query rather than with optimism:
SELECT count(*), sum(amount_minor), max(created_at) FROM ledger.entry;
SELECT count(*) FROM ledger.account
WHERE balance_minor <> (SELECT coalesce(sum(amount_minor),0)
FROM ledger.entry e WHERE e.account_id = account.id);
-- Zero. The ledger reconciles, so the recovery is good.
-- ================= Replication =================
--
-- Streaming: WAL shipped and replayed continuously.
-- primary: wal_level=replica, max_wal_senders=10
-- CREATE ROLE replicator REPLICATION LOGIN PASSWORD '...';
-- replica: pg_basebackup -h primary -U replicator -D /data -R -Xs -P
-- (-R writes the standby configuration for you)
--
-- Lag, in bytes and in seconds. Watch both:
SELECT client_addr, state, sync_state,
pg_wal_lsn_diff(sent_lsn, replay_lsn) AS replay_lag_bytes,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication;
-- On the replica:
SELECT pg_is_in_recovery(),
now() - pg_last_xact_replay_timestamp() AS behind_by;
-- Zero data loss, if you will pay the latency:
-- synchronous_commit = on
-- synchronous_standby_names = 'ANY 1 (replica1, replica2)'
-- Every COMMIT now waits for a standby to confirm. With only one
-- standby configured and that standby down, writes STOP. Use ANY n
-- with more standbys than n.
-- Logical: selected tables, across major versions, into a different
-- schema if you want.
-- primary: wal_level = logical
CREATE PUBLICATION ledger_pub FOR TABLE ledger.account, ledger.entry;
-- subscriber:
-- CREATE SUBSCRIPTION ledger_sub
-- CONNECTION 'host=primary dbname=workshop'
-- PUBLICATION ledger_pub;
-- Promotion:
-- pg_ctl promote -D /data or SELECT pg_promote();
-- ================= Pooling =================
--
-- Each connection is an OS process costing several MB. Measure before
-- raising max_connections - the answer is almost always a pooler:
SELECT count(*), state FROM pg_stat_activity GROUP BY state;
SELECT setting FROM pg_settings WHERE name = 'max_connections';
-- pgbouncer.ini
-- [databases]
-- workshop = host=127.0.0.1 port=5432 dbname=workshop
-- [pgbouncer]
-- pool_mode = transaction # the useful one: a server connection
-- # is held only for a transaction
-- max_client_conn = 2000
-- default_pool_size = 25
--
-- transaction mode breaks anything relying on session state: prepared
-- statements, advisory locks, LISTEN/NOTIFY, temporary tables. Know
-- which of those your driver uses before you switch.
Discussion
No questions on this topic yet. Sign in to ask the first one.