Skip to main content

PostgreSQL Deep Dive

Learning objectives
  • Describe Postgres's process architecture and memory layout, and what each background process does
  • Explain how WAL, checkpoints and shared buffers interact on the write path
  • Read MVCC tuple headers and explain why VACUUM exists, what causes bloat, and how XID wraparound is prevented
  • Design replication (streaming, synchronous, logical) and HA with Patroni for a stated RPO and RTO
  • Plan backups and point-in-time recovery, and know which extensions and tuning knobs matter first

TL;DR​

  • Postgres is process-per-connection: a postmaster forks a backend for each client; background processes (checkpointer, background writer, WAL writer, autovacuum, archiver, WAL senders) share a memory segment containing shared buffers.
  • Commit = WAL flushed. Data pages are written later by the checkpointer and background writer. Checkpoints bound crash recovery time; full-page images protect against torn pages.
  • MVCC in the heap: an UPDATE writes a new tuple version (xmin/xmax mark validity). VACUUM reclaims dead versions, maintains the visibility map, and freezes old tuples.
  • Bloat comes from vacuum falling behind or being blocked by anything that holds an old snapshot: long transactions, idle-in-transaction sessions, stale replication slots, hot_standby_feedback, orphaned prepared transactions.
  • XID wraparound: transaction ids are 32-bit; if tables are not frozen in time, Postgres eventually refuses new writes to protect data. Monitor age(datfrozenxid).
  • Streaming replication ships WAL to byte-identical standbys (async or sync); logical replication ships row changes per table (upgrades, CDC, selective sync).
  • Patroni + etcd (or Consul/Kubernetes) is the common open-source HA stack; pgBackRest/WAL-G + WAL archiving give PITR. Test restores, not just backups.

Why it matters​

Postgres is the default relational database for new banking and e-commerce systems, and many outages trace back to its internals rather than to the application: autovacuum unable to keep up with a high-churn payment_status table, a forgotten replication slot filling the disk with WAL, a transaction ID wraparound emergency on a large ledger, a failover that lost the last seconds of payments because replication was asynchronous. An architect who can explain these mechanisms designs schemas, retention, HA and runbooks that avoid them, and can hold their own with DBAs and auditors.

Core concepts​

Process architecture​

ProcessRole
postmasterListens for connections, forks backends, restarts children after a crash
backendRuns one client's queries; has private memory for sorts and hashes (work_mem)
checkpointerPerforms checkpoints: flushes all dirty buffers and writes a checkpoint record
background writerTrickles dirty buffers to the OS ahead of need, so backends rarely write themselves
WAL writerFlushes WAL buffers periodically (important for asynchronous commits)
autovacuum launcher / workersSchedule and run VACUUM and ANALYZE per table
archiverCopies completed WAL segments to the archive (archive_command or archive_library)
WAL sender / receiverStream WAL to standbys / receive it on standbys
logical replication launcher / workersApply logical replication on subscribers

Version notes: cumulative statistics moved into shared memory in Postgres 15 (the separate stats collector process is gone); Postgres 18 introduced asynchronous I/O (io_method), with I/O worker processes by default. Because each connection is a process, connection counts in the thousands hurt; use pooling (see Query Optimization).

Shared buffers and the OS page cache​

shared_buffers (default 128 MB, commonly set to around 25% of RAM as a starting point) caches 8 KB pages, with clock-sweep eviction. Postgres also relies on the OS page cache: a page evicted from shared buffers may still be served from OS memory. effective_cache_size does not allocate anything; it tells the planner how much total cache to assume, which makes index scans look cheaper. The pg_buffercache extension shows what is in shared buffers; pg_stat_database.blks_hit / blks_read give a hit ratio (keep in mind "read" may still be a page-cache hit).

WAL, checkpoints and durability​

  • Every change is first described in the WAL (16 MB segment files in pg_wal). A commit is durable when its WAL is flushed (synchronous_commit = on); group commit lets concurrent transactions share one flush.
  • A checkpoint writes all dirty pages and records a redo point; after a crash, replay starts there. Triggers: checkpoint_timeout (default 5 min) or WAL reaching max_wal_size (default 1 GB). checkpoint_completion_target (0.9 by default since 14) spreads the writes. If the log shows "checkpoints are occurring too frequently", raise max_wal_size.
  • After each checkpoint, the first change to a page writes a full-page image to WAL (full_page_writes), so WAL volume spikes right after checkpoints. Longer checkpoint intervals mean less WAL but longer recovery.
  • wal_level controls what is logged: replica (default; enough for physical replication and archiving) or logical (adds information for logical decoding).
  • synchronous_commit levels trade latency for safety: off (may lose recent commits on crash, never corrupts), local, remote_write, on (flushed on sync standbys too), remote_apply (visible on sync standbys).

MVCC tuples​

Each heap tuple carries a header with, among others:

  • xmin: the transaction that created this version.
  • xmax: the transaction that deleted or updated it (or locked it), 0 if none.
  • ctid: the tuple's physical location; for an updated tuple it points to the newer version.
  • Hint bits caching whether xmin/xmax committed or aborted (looked up in the commit log, pg_xact).
CREATE TABLE account (id int PRIMARY KEY, balance_minor bigint);
INSERT INTO account VALUES (1, 100);
SELECT xmin, xmax, ctid, * FROM account; -- e.g. xmin=750, xmax=0, ctid=(0,1)
UPDATE account SET balance_minor = 80 WHERE id = 1;
SELECT xmin, xmax, ctid, * FROM account; -- new version: xmin=751, ctid=(0,2)
-- the old version (0,1) still exists with xmax=751 until vacuum removes it

A snapshot lists which transactions were in progress when it was taken; a tuple is visible if its xmin committed before the snapshot and its xmax did not. Consequences: readers never block writers; rollback is instant (the aborted versions are simply never visible); but every update leaves a dead tuple and every index entry pointing to it must eventually be cleaned (unless the update was HOT, see Indexing).

VACUUM and autovacuum​

VACUUM (plain, concurrent with reads and writes):

  • removes dead tuples and their index entries, recording free space in the free space map for reuse (it does not shrink the file, except truncating empty pages at the end);
  • updates the visibility map (pages where all tuples are visible to everyone), which enables index-only scans and lets later vacuums skip pages;
  • freezes old tuples so their xmin no longer needs comparing against the moving XID horizon.

VACUUM FULL rewrites the table compactly but takes an ACCESS EXCLUSIVE lock for the duration; on a live system use pg_repack (online rebuild via triggers and a brief lock at the end) instead (see Zero-Downtime Schema Migrations).

Autovacuum triggers on a table when dead tuples exceed autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor × reltuples (defaults 50 and 0.2, so about 20% of the table) and, since 13, also after enough inserts. For a 1-billion-row table, 20% means 200 million dead tuples before cleanup starts: far too late. Tune per table:

ALTER TABLE payment SET (
autovacuum_vacuum_scale_factor = 0.01,
autovacuum_analyze_scale_factor = 0.005,
autovacuum_vacuum_cost_limit = 2000
);

Globally, the defaults are conservative for modern SSDs: autovacuum_max_workers 3, cost limit 200 shared among workers, cost delay 2 ms. Raising the cost limit and workers is common on busy OLTP systems; watch I/O.

What blocks vacuum from removing dead tuples (the "xmin horizon"):

-- Oldest snapshots held by sessions
SELECT pid, state, backend_xmin, now() - xact_start AS xact_age, left(query, 60) AS query
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY age(backend_xmin) DESC
LIMIT 5;

-- Replication slots pin xmin and WAL
SELECT slot_name, active, xmin, catalog_xmin, restart_lsn,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots;

-- Forgotten two-phase transactions
SELECT gid, prepared, owner FROM pg_prepared_xacts;

Typical culprits: a reporting query running for hours on the primary, an application session left idle in transaction, an abandoned logical slot (a CDC connector that was decommissioned), and hot_standby_feedback = on with long queries on a replica. Guardrails: idle_in_transaction_session_timeout, statement_timeout for application roles, max_slot_wal_keep_size (13+) to cap WAL retained by slots, and alerts on slot lag and oldest transaction age.

Transaction ID wraparound​

XIDs are 32-bit and compared modulo 2³², so each transaction can see about 2 billion XIDs "in the past". A tuple whose xmin is older than that would suddenly appear to be in the future and become invisible. Freezing prevents this by marking old tuples as visible to all.

  • Each table tracks relfrozenxid; each database datfrozenxid. When a table's age exceeds autovacuum_freeze_max_age (default 200 million), autovacuum runs an aggressive anti-wraparound vacuum that scans all pages not already frozen, even if autovacuum is disabled for that table.
  • Since Postgres 14, vacuum_failsafe_age (default 1.6 billion) makes vacuum skip index cleanup and throttling to finish freezing as fast as possible.
  • If the age approaches the hard limit anyway, Postgres warns, then refuses to assign new XIDs, so writes fail until a vacuum completes. On a multi-terabyte table that can mean hours of write outage. Several well-known public post-mortems describe exactly this (for example Sentry's "Transaction ID Wraparound in Postgres").
  • MultiXact IDs (used when several transactions lock the same row, for example via foreign key checks) have the same problem and their own freeze settings.

Monitor:

SELECT datname, age(datfrozenxid) AS xid_age FROM pg_database ORDER BY 2 DESC;
SELECT c.oid::regclass AS table_name, age(c.relfrozenxid) AS xid_age,
pg_size_pretty(pg_total_relation_size(c.oid)) AS size
FROM pg_class c WHERE c.relkind IN ('r', 'm', 't')
ORDER BY 2 DESC LIMIT 10;

Alert well before trouble (for example at several hundred million, a rough but common threshold), and investigate why autovacuum is not keeping up: blocked horizon, too little throttle budget, or huge tables that need partitioning so each partition can be frozen independently (old monthly partitions, once frozen, stay frozen).

Replication​

Physical streaming replication sends WAL records to standbys, which replay them into a byte-identical copy of the whole cluster.

  • Standbys can serve read-only queries (hot standby). Queries can conflict with replay (for example vacuum removing rows a standby query still needs): max_standby_streaming_delay (default 30 s) delays replay before cancelling the query; hot_standby_feedback avoids cancellations by holding back vacuum on the primary (and so causes bloat there).
  • Asynchronous by default: the primary does not wait; on failover, the last moments of commits may be lost (RPO > 0, equal to replication lag).
  • Synchronous: synchronous_standby_names = 'ANY 1 (replica_a, replica_b)' (quorum) or 'FIRST 1 (…)' (priority). Commits wait for the standby's acknowledgement at the level chosen by synchronous_commit. Cost: every commit pays a network round trip; with one sync standby and no quorum, losing it stalls writes, so run at least two candidates.
  • Replication slots make the primary retain WAL until a standby has consumed it. Without them, a lagging standby may need re-cloning; with them, a dead standby can fill the primary's disk unless max_slot_wal_keep_size is set.
  • Cascading replication lets standbys feed other standbys, for cross-region copies.

Logical replication (10+) decodes WAL into row-level changes per table and applies them on a subscriber via publications and subscriptions.

  • Uses: major-version upgrades with minimal downtime, replicating a subset of tables to another service or region, consolidating databases, feeding CDC tools (Debezium uses the pgoutput plugin through logical decoding, see Transactional Outbox & CDC).
  • Limitations to plan for (version-dependent): DDL is not replicated, so schema changes must be applied on both sides; sequence values are not replicated in most versions; tables need a replica identity (usually the primary key) for updates and deletes; very large transactions are buffered unless streaming of in-progress transactions is enabled (14+).
  • Recent versions improve failover of logical slots to standbys (17+), important when CDC must survive primary failover.

High availability with Patroni​

How it works:

  • Each node runs a Patroni agent that manages its local Postgres and talks to a distributed configuration store (etcd, Consul, ZooKeeper, or the Kubernetes API).
  • The primary holds a leader key with a TTL (default 30 s) and renews it every loop (default 10 s). If it cannot renew (crash, network partition), it demotes itself to avoid split brain, and a watchdog can reset the machine as extra fencing.
  • When the key expires, healthy replicas race to acquire it; Patroni refuses to promote a replica lagging more than maximum_lag_on_failover. In synchronous_mode, only a synchronous replica may be promoted, giving RPO 0 for acknowledged commits.
  • The old primary rejoins as a replica, using pg_rewind if its timeline diverged.
  • Clients find the primary through HAProxy (health checks on Patroni's REST endpoints such as /primary), a DNS/VIP callback, or Kubernetes services.

Rough expectations: failover in tens of seconds, mostly TTL and detection time; RPO zero only with synchronous replication. Alternatives: CloudNativePG (Kubernetes operator), repmgr, and managed services (Amazon RDS Multi-AZ and Aurora, Google Cloud SQL, Azure Database for PostgreSQL), which hide the mechanism but have the same trade-offs. Design and test failover as part of High Availability & Disaster Recovery.

Backups and point-in-time recovery​

MethodWhatRestoreUse
pg_dump / pg_dumpallLogical SQL or custom-format dump of one database at a consistent snapshotSlow for large databases (reload + reindex); no PITRSmall databases, migrations, per-table exports
Base backup + WAL archivePhysical copy of the data directory (pg_basebackup or a tool) plus every WAL segment sinceRestore base, replay WAL to any point in timeProduction standard
pgBackRest / WAL-G / BarmanTools implementing the above with parallelism, compression, encryption, object storage, incremental or delta backups, verificationFast parallel restore, PITRProduction standard
Storage or cloud snapshotsVolume-level snapshotFastComplement, not replacement; must be crash-consistent and combined with WAL for PITR

PITR in outline: restore a base backup, create recovery.signal, set restore_command to fetch archived WAL and recovery_target_time (or recovery_target_lsn / _xid), start the server; it replays to the target and pauses or promotes depending on recovery_target_action. Postgres 17 added native incremental backups (pg_basebackup --incremental with pg_combinebackup, requiring summarize_wal).

Banking-grade practices: backups in a separate account or region with immutability (object lock) against ransomware; encryption with managed keys; automated restore tests that measure restore time against the RTO and validate data (row counts, checksums, application smoke tests); documented PITR runbooks for "someone ran a bad UPDATE" scenarios.

Extensions worth knowing​

ExtensionUse
pg_stat_statementsPer-query execution statistics; the first thing to enable
auto_explainLogs plans of slow queries
pgauditDetailed session and object audit logging, often required in banks
pgcryptoHashing and encryption functions (prefer application-side encryption for secrets and key management)
pg_trgmTrigram similarity and LIKE '%…%' indexing
btree_gistScalar equality inside GiST, enabling exclusion constraints with ranges
pg_partmanAutomated partition creation and retention
pg_cronCron-style jobs inside the database
pg_repackOnline table and index rebuilds to remove bloat
pgstattuple, pg_buffercacheInspect bloat and buffer contents
postgisGeospatial types and indexes (store locators, delivery zones)
pgvectorVector similarity search for embeddings
citus, timescaledbDistributed tables; time-series features

Managed services support a curated subset; check before designing around an extension.

Tuning knobs: where to start​

Starting points only (rough; validate with your workload and monitoring):

SettingDefaultTypical starting pointNotes
shared_buffers128 MB≈ 25% of RAMLarger rarely helps beyond a point because of the OS cache
effective_cache_size4 GB≈ 50–75% of RAMPlanner hint only
work_mem4 MB16–64 MB for OLTP, more per session for reportsPer sort or hash node, per connection: multiply before raising
maintenance_work_mem64 MB1–2 GBSpeeds vacuum and index builds
max_connections100As low as possible, with a poolerEach connection is a process
random_page_cost41.1–2 on SSDMakes index scans more attractive
effective_io_concurrencyVersion-dependentHigher on SSDAffects bitmap heap scans and prefetching
max_wal_size1 GBSeveral to tens of GBFewer, smoother checkpoints
checkpoint_timeout5 min10–30 minLonger recovery, less WAL
autovacuum_max_workers, autovacuum_vacuum_cost_limit3, 200 (shared)More workers, cost limit 1000–2000Keep vacuum ahead of churn
statement_timeout, idle_in_transaction_session_timeout, lock_timeoutOffSeconds for API rolesProtect the server from runaway sessions
log_min_duration_statementOff250 ms–1 sFind slow queries
huge_pagestryon (with OS configuration)Reduces page-table overhead for large shared buffers

Trade-offs​

OptionStrengthsWeaknessesChoose when
Async streaming replicaNo commit latency cost; read scalingRPO equals lag; stale readsMost read replicas, cross-region DR
Sync replication (quorum)RPO 0 for acknowledged commitsCommit latency includes network RTT; needs 2+ candidatesLedgers and payments within a region
Logical replicationSelective, cross-version, feeds CDCNo DDL, sequences need handling, more overheadUpgrades, data distribution, CDC
Patroni (self-managed)Control, portable, open sourceYou operate etcd, fencing, upgradesOn-prem banks, multi-cloud
Managed HA (RDS, Cloud SQL, Aurora)Less operational workLess control, vendor-specific behavior, extension limitsCloud-native teams
pg_dumpSimple, portableSlow restore, no PITRSmall databases, exports
Physical backup + WAL (pgBackRest)PITR, fast parallel restoreSetup and storage costEvery production database

In practice​

  • Dashboards every Postgres deployment needs: connections by state, transaction rate and rollbacks, cache hit ratio, replication lag (bytes and seconds), slot retained WAL, oldest transaction age, age(datfrozenxid), dead tuples and last autovacuum per big table, checkpoint frequency and duration, disk usage of pg_wal, locks waiting.
  • Partition high-churn and very large tables so vacuum and freezing work on manageable pieces (see Partitioning & Sharding in Practice).
  • Keep transactions short and keep analytics off the primary: long queries hold the xmin horizon. Use a replica (accepting either query cancellations or hot_standby_feedback bloat) or a warehouse fed by CDC.
  • Major upgrades: pg_upgrade --link (minutes of downtime, after testing), or logical replication to a new-version cluster and a controlled switchover (seconds of downtime, more work).
  • Security for banks: TLS everywhere, SCRAM authentication, least-privilege roles (separate migration, application and read-only roles), pgaudit for privileged actions, encryption at rest at the storage layer, RLS for multi-tenant isolation (see Schema Patterns).

Common pitfalls​

  • Leaving autovacuum at defaults on billion-row tables. Symptom: bloat, slow index scans, and an anti-wraparound vacuum that runs for a day at the worst moment.
  • Abandoned replication slots. Symptom: pg_wal grows until the disk fills and the primary stops.
  • idle in transaction sessions from application bugs. Symptom: vacuum cannot clean anything newer than that session's snapshot; bloat across the cluster.
  • Assuming asynchronous replicas are up to date during failover. Symptom: payments acknowledged to customers are missing after promotion.
  • Single synchronous standby without quorum. Symptom: the standby restarts and every commit on the primary hangs.
  • VACUUM FULL on a live table. Symptom: the table is locked for the whole rewrite; checkout down.
  • Backups never restored. Symptom: discovering during an incident that the archive has gaps or restore takes 14 hours against a 1-hour RTO.
  • Raising max_connections to thousands instead of pooling. Symptom: memory pressure and lower throughput under load.

Interview angle​

  • Prompts: "How does Postgres implement MVCC and what does vacuum do?", "What is transaction ID wraparound?", "Design HA for a payments database with RPO 0", "How would you do a major version upgrade with minimal downtime?", "Your Postgres disk is filling up, what do you check?"
  • A strong answer connects mechanism to symptom: dead tuples → bloat → slow scans; long transactions → vacuum blocked; slots → WAL retention; async replication → RPO.
  • For HA, discuss the consensus store, fencing, sync vs async, client routing, and how you test failover; relate to Replication and Consensus & Raft.
  • Follow-ups: "Why not just use VACUUM FULL?", "What does hot_standby_feedback trade off?", "How do you know your backups work?"
  • Red flags: "Postgres doesn't need maintenance", confusing logical and physical replication, claiming RPO 0 with async replicas.

Self-check​

1. Why does Postgres need VACUUM when InnoDB does not have an equivalent user-facing process?

Postgres stores old row versions in the table itself: each update leaves a dead tuple and stale index entries until something removes them, and old tuples must be frozen before XIDs wrap around. VACUUM does both, plus maintaining the visibility map. InnoDB keeps old versions in a separate undo log, which background purge threads trim automatically, so the cleanup is internal (though long transactions still cause undo growth).

2. List four things that can prevent vacuum from removing dead tuples, and how to detect each.

Long-running transactions and idle in transaction sessions (pg_stat_activity.backend_xmin, xact_start); replication slots with an old xmin or catalog_xmin (pg_replication_slots); hot_standby_feedback from replicas running long queries (standby queries, feedback xmin in pg_stat_replication); orphaned prepared transactions (pg_prepared_xacts). All hold the xmin horizon back.

3. Explain XID wraparound and the mechanisms that prevent it.

XIDs are 32-bit and compared circularly, so only about 2 billion past transactions are distinguishable; older tuples would appear to be from the future. Vacuum freezes tuples older than a threshold so they are visible to everyone regardless of XID. Autovacuum forces aggressive freezing at autovacuum_freeze_max_age, the failsafe (14+) speeds it up near danger, and as a last resort Postgres stops assigning XIDs to protect data, which blocks writes.

4. What happens to commits and to RPO with synchronous_standby_names = 'ANY 1 (a, b)' and synchronous_commit = on?

Each commit waits until at least one of standbys a or b has flushed the commit's WAL to disk, so acknowledged commits survive the loss of the primary as long as one of them is promoted; RPO for acknowledged transactions is zero. Commit latency includes a network round trip, and if both standbys are unavailable, commits wait, so monitor and keep both healthy.

5. How does Patroni avoid split brain?

Leadership is a key with a TTL in a consensus store (etcd, Consul, ZooKeeper or Kubernetes). Only the holder may run as primary; it must renew the key every loop, and if it cannot reach the store it demotes itself before the TTL expires. Replicas only promote after acquiring the key. A watchdog device can additionally reset a node that fails to demote, providing fencing.

6. Scenario: an engineer ran UPDATE payment SET status = 'REFUNDED' without a WHERE clause at 14:03. How do you recover?

Do not fail over (replicas have the change). Restore the latest base backup before 14:03 to a separate instance, replay archived WAL with recovery_target_time just before the statement (or the transaction's XID from logs), and pause there. Extract the correct payment rows and repair production with a reviewed script, considering changes made after 14:03. Then add guardrails: no direct write access, reviewed scripts, pgaudit, and require WHERE checks in tooling.

7. When would you choose logical replication over physical streaming replication?

When you need to replicate only some tables, replicate between different major versions (upgrades), feed a different schema or system, or provide change streams to CDC consumers. Physical replication is simpler and complete for HA and read replicas, but only to identical major versions and for the whole cluster.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Watch MVCC and vacuum, then perform a point-in-time recovery.

docker run --name pg-deep -e POSTGRES_PASSWORD=pg -d postgres:17 \
-c wal_level=replica -c archive_mode=on \
-c archive_command='test ! -f /var/lib/postgresql/archive/%f && cp %p /var/lib/postgresql/archive/%f'
docker exec -u postgres pg-deep mkdir -p /var/lib/postgresql/archive
docker exec -it pg-deep psql -U postgres

Part A: MVCC and vacuum

  1. Create account, insert a row, update it three times, and inspect xmin, xmax, ctid after each update.
  2. Insert 1 million more rows (INSERT INTO account SELECT g, 100 FROM generate_series(2, 1000001) g;), update all of them, and check n_dead_tup in pg_stat_user_tables and pgstattuple('account') (after CREATE EXTENSION pgstattuple;).
  3. In a second session run BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM account; and leave it open. Run VACUUM VERBOSE account; in the first session and read how many dead tuples it could not remove. Commit the second session and vacuum again.
  4. Check age(datfrozenxid) for your database, run VACUUM FREEZE account; and check age(relfrozenxid) for the table.

Part B: PITR

docker exec -u postgres pg-deep pg_basebackup -D /var/lib/postgresql/base -Fp -Xs
docker exec -it pg-deep psql -U postgres -c "CREATE TABLE important (id int); INSERT INTO important SELECT generate_series(1, 1000);"
docker exec -it pg-deep psql -U postgres -c "SELECT now();" # note this timestamp as T
docker exec -it pg-deep psql -U postgres -c "DROP TABLE important; SELECT pg_switch_wal();"

Then restore into a second data directory inside the container and start it on port 5433 (replace T):

docker exec -u postgres pg-deep bash -c '
cp -r /var/lib/postgresql/base /var/lib/postgresql/restore &&
touch /var/lib/postgresql/restore/recovery.signal &&
echo "restore_command = '"'"'cp /var/lib/postgresql/archive/%f %p'"'"'" >> /var/lib/postgresql/restore/postgresql.auto.conf &&
echo "recovery_target_time = '"'"'T'"'"'" >> /var/lib/postgresql/restore/postgresql.auto.conf &&
pg_ctl -D /var/lib/postgresql/restore -o "-p 5433" -l /tmp/restore.log start'
docker exec -it pg-deep psql -U postgres -p 5433 -c "SELECT count(*) FROM important;"

Done when the restored instance shows 1,000 rows in important, you can explain why vacuum could not clean up in step A3, and you have written a one-page PITR runbook including how you would find the exact target time from logs.

Further reading​

  • PostgreSQL documentation: "Routine Vacuuming", "Write-Ahead Logging", "High Availability, Load Balancing, and Replication", "Continuous Archiving and Point-in-Time Recovery" (postgresql.org/docs/current).
  • Hironobu Suzuki, The Internals of PostgreSQL (online book, interdb.jp).
  • Egor Rogov, PostgreSQL 14 Internals (free e-book from Postgres Professional).
  • Patroni documentation (patroni.readthedocs.io).
  • pgBackRest user guide (pgbackrest.org).
  • Sentry engineering blog, "Transaction ID Wraparound in Postgres".
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).