Running Postgres in production: backups, replication, vacuum, upgrades, pooling

What to know before you are on call for a PostgreSQL database, on the chat product's data; every command output is real, from local PostgreSQL 16 and 17 servers and PgBouncer. A child of Topic: databases. Data as of October 2026. Reading: 43 min, plus 17 in closed details.

The idea in one screen

A Postgres server is one process per connection writing every change first to the write-ahead log (WAL) and leaving old row versions behind. Running it in production is three jobs: ship the WAL somewhere safe (backups, replicas, failover), clean up what it leaves behind (vacuum, freezing), and never let anything pin either in place: an open transaction, an abandoned replication slot, a flood of connections.

Fig. 1, step by step: one server, and the orange pins that page you

  1. One process per connection. The postmaster starts a backend process for every client that connects, and it serves only that client until it disconnects. That is why connections are expensive and poolers exist (sections 1 and 7).
  2. Every change goes to the WAL first. A backend changes 8 KB pages in shared buffers and appends a record of the change to the WAL in pg_wal/. A checkpoint later writes the pages to the table files, and only then is the old WAL recycled (section 1).
  3. Ship the WAL. The WAL is a complete history of every change: archived next to a base backup it is point-in-time recovery (section 2); streamed to another server it is a replica that can take over (sections 3 and 4).
  4. Clean up what it leaves. An update or delete leaves the old row version behind in the table files. VACUUM reclaims the dead versions and freezes old rows so the 32-bit transaction counter can wrap safely (sections 5 and 6).
  5. The two pins. An open transaction stops vacuum and ages transaction IDs; an inactive replication slot keeps WAL until the disk is full. These two, plus a flood of connections, are what pages you.
  6. What a fresh install lacks. No archive, no replica, no pooler and no alerts: a fresh install has none of the blue additions, and adding them is most of this page (sections 2, 3, 7 and 9).

One server, drawn, not to scale; drag to turn it.

You need: what MVCC row versions and snapshots are (Transactions and concurrency) and what the WAL, pages and checkpoints do inside the engine (Storage engines and indexes). Slow queries and EXPLAIN are Query planning and performance; read replicas for load and sharding are Scaling a database; migrations as schema design are SQL and data modelling; replication theory and consensus are Distributed systems fundamentals.

Backend
the operating-system process the postmaster starts for each client connection.
WAL, LSN
the write-ahead log, stored as 16 MB segment files in pg_wal/; an LSN (log sequence number, like 0/2209DC60) is a position in it.
Checkpoint
the moment every changed page is on disk, after which older WAL can be recycled.
RPO, RTO
how much data you may lose, and how long you may be down.
PITR
point-in-time recovery: a base backup plus archived WAL, replayed to any chosen moment.
Replication slot
a bookmark on the primary that keeps WAL until one consumer confirms it.
Dead tuple
a row version no transaction can see any more; VACUUM reclaims it.
XID, freezing
the 32-bit transaction ID; freezing marks old rows so the counter can wrap safely.
Transaction pooling
a pooler lends a server connection for one transaction at a time.

What pages you, and the first thing to look at

FailureHow it showsFirst thing to look atWhat prevents it
Disk fullcould not extend file, No space left on device; at 100% Postgres shuts down (it cannot write WAL)pg_replication_slots, size of pg_wal/, pg_stat_archiver, biggest tablesSlot cap, archive alert, disk alert at 80% (sections 3, 5)
Data deleted by a person or a bugUsers report missing dataWhen exactly? (application logs, pg_waldump)Point-in-time recovery, least privilege (2, 11)
Lost instanceConnections refused; host or disk goneIs a replica healthy, how far behind?Replica, automated failover, fencing (4)
Replication lagStale replica reads; a failover would lose datapg_stat_replication: write_lag, flush_lag, replay_lagLag alert, replica sized like the primary (3)
BloatTables far bigger than their datan_dead_tup, sessions with an old backend_xminAutovacuum tuned per hot table, idle-transaction timeout (5)
Transaction ID wraparoundWarnings, then database is not accepting commandsage(datfrozenxid), what holds the oldest XIDAlert at a quarter of the limit (6)
Connection exhaustiontoo many clients already, remaining connection slots are reservedpg_stat_activity by state and applicationA pooler, small app pools, timeouts (7)
A migration hangs every queryEvery query on one table waitspg_blocking_pids(), wait_eventlock_timeout and retry (8)
Runaway queryCPU or IO at 100%pg_stat_activity by query_startstatement_timeout per role (9)

Only one row is the hardware failure people imagine; the rest are slow accumulations (dead rows, retained WAL, transaction age, connections) or human mistakes, and every accumulation shows days ahead in one number you can alert on (section 9). The Incident lab walks each one with real output.

The five rules that prevent most database outages
  1. Backups are continuous and restores are tested: a base backup plus archived WAL, restored on a schedule by a machine, with the restore time written down (section 2).
  2. A replica is not a backup: it copies your mistakes within milliseconds (sections 2 and 3).
  3. Every replication slot has a cap and an alert (max_slot_wal_keep_size), or one dead replica fills the primary's disk (section 3).
  4. Every session has timeouts (statement_timeout, idle_in_transaction_session_timeout), so one forgotten transaction cannot block vacuum and pile up locks (sections 5, 7, 8).
  5. Applications connect through a pooler and max_connections stays in the hundreds, not thousands (section 7).
How the evidence on this page was made (provenance)

Every command output is real. Numbers marked measured were measured for this page on a laptop (Apple M1 Pro, 16 GB, macOS) with PostgreSQL 16.2 from the pgserver wheel, PostgreSQL 17.11 from conda-forge and PgBouncer 1.24.1 built from source; every run takes under 20 minutes and its script is in this page's src/lab/. illustrative marks anything made up to show a shape. A laptop is not a server: absolute timings are small, so read them as orders of magnitude and look at the ratios. The data is the root's chat product at one tenth of its size: 10,000 users, 100,000 chats, 1,000,000 messages (about 220 MB on disk), made by the same generator with the same seeds. Being on call means you are the person paged when it breaks, and you are expected to stop the bleeding within minutes; the page is organised around what pages you.

1. The server: processes, memory, WAL and checkpoints

One process per connection. The postmaster is the parent process; for every client that connects it starts a new operating-system process, a backend, which serves that one connection until it closes (how connections are established). Background processes do the housekeeping: the checkpointer, the WAL writer, the autovacuum launcher and its workers, and WAL senders if you replicate. This one design decision is why connections are expensive and poolers exist (section 7). Everything served by one postmaster from one data directory (often /var/lib/postgresql/18/main, holding every table and index as files, postgresql.conf, pg_hba.conf and the log) is a cluster in Postgres's words: one server, possibly many databases, not a cluster of machines.

Memory: one shared cache, and memory per operation

Two kinds of memory matter (resource settings). shared_buffers is the cache of 8 KB table and index pages shared by every backend: 128 MB by default, about 25% of RAM on a dedicated server is the documented starting point (the operating system's file cache holds much of the rest). work_mem (default 4 MB) is the budget of each sort or hash operation in each running query, and a hash may use hash_mem_multiplier (2.0) times more; past it the operation spills to temporary files. So the server-wide setting multiplies: a query with one sort and one hash join can take three times work_mem, in every active backend at once. Predict: with 100 active connections, what server-wide work_mem takes this 64 GB host past its RAM? Then drag.

The usual answer is a modest server default and a larger work_mem set per role or per session for reports and batch jobs (ALTER ROLE reports SET work_mem = '256MB'; illustrative); how a spill changes a plan, and the temp_files it leaves, is on Query planning and performance. Two more settings round out the memory picture: maintenance_work_mem (default 64 MB) is what VACUUM and CREATE INDEX use, once per autovacuum worker, and effective_cache_size allocates nothing at all: it only tells the planner how much data is likely cached.

work_mem is per operation, per backend: the server-wide value multiplies

Worst case = shared_buffers + active backends × (one sort + one hash × 2.0) × work_mem, from the documented per-operation rule. The 64 GB host, shared_buffers at 25% and the query shape are illustrative; real queries rarely all peak at once, which is why this is the ceiling, not the expectation. Measured here: one backend kept MB after a single 64 MB sort, until it exited.

WAL and checkpoints: why pg_wal/ grows

Before any change touches a table file, a record describing it is appended to the WAL and flushed; after a crash, Postgres replays the WAL to redo what the table files missed. A checkpoint writes every changed page in memory to the table files; it starts every checkpoint_timeout (5 minutes) or after max_wal_size (1 GB) of WAL, whichever comes first (WAL settings), and after it the WAL before that point is no longer needed for crash recovery, so its segments are recycled. On a healthy server pg_wal/ therefore stays near max_wal_size. For operations, the point is: the WAL is a complete history of every change, so shipping it elsewhere gives you both backups (section 2) and replicas (section 3), and anything that still needs old WAL (a failing archive command, a replica that is behind, a slot) stops the recycling, which is the mechanism behind most disk-full pages. Why the first change to a page after a checkpoint writes the whole page, and what longer checkpoint intervals cost in recovery time, is on Storage engines and indexes.

2. Backups and point-in-time recovery

Two numbers define what "backed up" means, and the product owner agrees them before anyone picks a tool. The recovery point objective (RPO) is how much recent data you may lose, measured in time: "RPO 24 hours" accepts losing a day of writes, which a chat product cannot. The recovery time objective (RTO) is how long the restore may take, from "we need to restore" to "users are back", set by database size, disk and network speed and how practised the procedure is.

Logical against physical

A logical backup (pg_dump) asks the database for its contents: CREATE TABLE statements and the rows. A physical backup (pg_basebackup, or a tool on the same mechanism) copies the data directory's files while the server runs, plus the WAL needed to make that copy consistent. On the 221 MB chat database:

Logical (pg_dump)Physical (base backup + WAL)
What you getThe database at the one moment the dump startedThe database at any moment since the base backup, if the WAL is archived
Size here measured33.9 MB (compressed rows; indexes are rebuilt on restore)258 MB (every file, indexes included, plus the WAL written during the copy)
RestoreReplays SQL and rebuilds every index: slow for big databasesCopy files, replay WAL: speed of the disk and network
Portable?Yes: across major versions, machines, one table at a timeNo: same major version, same platform, whole cluster only
Good forCopying data elsewhere, upgrades, a second safety netDisaster recovery and point-in-time recovery
Real run: last night's dump and a base backup of the same database (measured output)

Fig. 2 · the same DELETE, recovered two ways

Point-in-time recovery: the most important picture on this page

Because the WAL records every change, a base backup plus every WAL segment written since lets Postgres rebuild the database at any moment you choose. You switch it on with three settings: wal_level = replica (the default), archive_mode = on, and an archive_command that copies each finished 16 MB segment somewhere safe and returns success only once the file is stored (WAL settings). To recover, restore the base backup, tell Postgres where the archive is (restore_command) and when to stop (recovery_target_time), and start it. Below, a nightly backup at midnight, a normal day of messages, and at 14:03 a cleanup that lost its WHERE clause, recovered both ways. Predict how many of the day's messages each method keeps, then watch both (the toggle swaps the method).

  1. 00:00 Nightly backup. pg_dump writes the whole database to one file (33.9 MB here). That file is the database as of midnight, and nothing after.
  2. Morning: messages arrive. Users write messages all morning. None of them is in last night's file, and no WAL is kept.
  3. 14:02:59 The last good moment. 1,012,000 messages: 12,000 of them written today.
  4. 14:03:00 DELETE FROM messages; A cleanup meant for one chat runs without its WHERE clause. Every message is gone, and the replica deleted them too, milliseconds later.
  5. 14:05 Alert; two more messages arrive. Users notice. Two new messages are written to the now empty table.
  6. Restore into a new server. pg_restore loads the midnight file into a fresh server: 1,000,000 messages (2.18 s here, measured).
  7. Replay. Nothing to replay: a dump is one moment. The recovered server stays at midnight.
  8. Result: 12,000 messages lost. Everything written since midnight; the RPO was 14 hours.

Row counts, segment names, the recovery log line and the recovery times are from the real run; the clock times are illustrative (the run compressed "the day" into ten seconds: six batches of 2,000 messages, then the DELETE).

The recovered server stops replaying just before the DELETE's commit record (recovery stopping before commit of transaction), so the delete simply never happened. Three details decide a real incident:

  • Finding the moment. pg_waldump prints each WAL record; the bad transaction shows up as a million heap delete records followed by one COMMIT with a timestamp. Recover to just before it, or name it with recovery_target_xid and recovery_target_inclusive = false.
  • A new timeline. The recovered server says selected new timeline ID: 2: a branch of history whose WAL files carry the new timeline in their names, so they never mix with the old ones in the archive.
  • Writes after the mistake. Recovering to 14:02:59 also drops everything written after 14:03 (two messages in the run), so you usually recover into a separate server and copy the deleted rows back with SQL. That is a product decision: say it in the incident channel.

A replica is no help here: it applied the DELETE milliseconds later. A delayed replica (recovery_min_apply_delay = '1h') gives you an hour to stop it, a useful extra, never a substitute for archived WAL.

Real run: the bad DELETE, pg_waldump, then both recoveries (measured output)

Tools, and what managed services do

Nobody writes cp archive commands in production. Three open-source tools take base backups, archive WAL, keep retention, compress, encrypt and restore against object storage such as S3: pgBackRest (the common choice for self-managed Postgres: full, differential and incremental backups, parallel compression, asynchronous archiving, verification; user guide), WAL-G (one Go binary, popular in Kubernetes and cloud setups, delta backups to S3, GCS or Azure) and Barman (EDB's backup server, pulling from many Postgres servers). Amazon RDS keeps automated backups for up to 35 days and uploads transaction logs to S3 every five minutes, so its point-in-time restore can lose up to about five minutes (RDS PITR docs).

A minimal pgBackRest setup, and the tool versions (reference, versions dated)

PostgreSQL 17's built-in incremental backups (pg_basebackup --incremental, merged with pg_combinebackup: release notes) do not manage retention or object storage. The setup below follows the pgBackRest user guide (bucket and paths are illustrative). Latest releases when read: pgBackRest 2.59.3, 2026-10-04; WAL-G v3.0.9, 2026-08-20 (also backs up MySQL and others); Barman 3.20.1, 2026-09-29.

# /etc/pgbackrest/pgbackrest.conf
[global]
repo1-type=s3
repo1-s3-bucket=chat-db-backups
repo1-s3-region=eu-west-1
repo1-path=/pgbackrest
repo1-retention-full=4            # keep four full backups and the WAL they need
repo1-cipher-type=aes-256-cbc     # encrypted before it leaves the machine
process-max=4
archive-async=y
start-fast=y

[main]
pg1-path=/var/lib/postgresql/18/main

# postgresql.conf
archive_mode = on
archive_command = 'pgbackrest --stanza=main archive-push %p'

# weekly full, daily differential (cron); restore to a moment:
pgbackrest --stanza=main --type=full backup
pgbackrest --stanza=main --type=diff backup
pgbackrest --stanza=main --type=time "--target=2026-10-04 14:02:59+00" --target-action=promote restore

A backup you have not restored is not a backup

GitLab.com lost about six hours of data in January 2017 with every backup method in place and none ever restored (the story is below). A restore that runs on a schedule is the only proof a backup works:

What "tested restores" means in practice
  • A scheduled job (weekly at least) restores the latest backup to a scratch server, replays WAL to a recent moment, and checks that the server starts, key row counts are close to production's and a smoke query works. It alerts if any step fails.
  • It records how long the restore took: that number, not a guess, is your RTO. Here 221 MB took under two seconds; at a realistic 200 MB/s a 2 TB database takes about three hours before any WAL replay (2,000,000 MB / 200 MB/s = 10,000 s; illustrative speed).
  • Backups go to another account or project with delete protection (object lock), so a compromised production account or a bad script cannot delete them too.
  • Alert when the archiver fails (pg_stat_archiver.failed_count rising) and when the newest backup is older than its schedule.
The GitLab 2017 outage (case)

On 31 January 2017 GitLab.com lost about six hours of database changes: an engineer fighting replication lag deleted the data directory on the primary instead of the replica, and then the team found the nightly pg_dump had been failing silently (its major version did not match the server's) and disk snapshots had never been enabled; the best copy was a manual snapshot six hours old that took about 18 hours to copy back (GitLab postmortem, 2017-02-10; the full case is in the SWE topic's Case files tab). Every backup method existed; none had been restored.

3. Replication: a live copy on another machine

A backup gets the data back after hours. A replica (or standby) is a second server kept within milliseconds of the primary, so it can take over in seconds and serve read-only queries meanwhile. In streaming replication a WAL sender process on the primary streams WAL records over an ordinary connection to a WAL receiver on the replica, which writes them, flushes them and replays them into its table files exactly as crash recovery would (high availability docs). The replica starts as a base backup; pg_basebackup -R also writes the connection settings and a standby.signal file that keeps it a replica.

  1. Commit on the primary. The backend's WAL record is flushed to the primary's own pg_wal/. With asynchronous replication (the default) the client is told "committed" now.
  2. Streamed and written: write_lag ends. The WAL sender sends the record over an ordinary connection and the replica's WAL receiver writes it: the network part (0.000247 s in the run below).
  3. Flushed: flush_lag ends. The receiver flushes it to the replica's disk, so it survives a replica crash (0.000248 s).
  4. Replayed: replay_lag ends. The startup process applies it to the replica's table files exactly as crash recovery would; only now does a query on the replica see the row. Normally this is about 1 ms (median 1.27 ms with 8 writers, measured).
  5. Replay stalls, WAL piles up. Pause replay (or run a long replica query that conflicts with it): records still arrive and are flushed in milliseconds, but wait unapplied. 9.5 s into the pause: replay_lag 00:00:09.355926 and 79 MB not yet replayed.

The primary reports each replica's progress in pg_stat_replication (monitoring docs): write_lag (received and written, not yet flushed), flush_lag (on the replica's disk, survives a replica crash), replay_lag (applied, visible to queries there). They separate the network, the replica's disk, and its single replay process.

Real run: a replica of the chat database (measured output)

Replication lag, measured

The chart is the whole run behind Fig. 3, sampled every 250 ms. Pausing replay (pg_wal_replay_pause()) stands in for the most common real cause: a long query on the replica that needs rows the replay is about to remove. Replay waits up to max_standby_streaming_delay (30 s) and then cancels the query; hot_standby_feedback = on instead tells the primary not to remove those rows, which moves the bloat to the primary (section 5). Lag also comes from a replica on smaller hardware, a saturated network, or a write burst such as a big UPDATE or an index build. What lag means for the application (which reads may go to a replica, read-your-writes, Jepsen's Long Fork) is Scaling a database, section 3.

Real run: pg_stat_replication while replay is paused (measured output)

When replay stalls, only replay_lag climbs: one second per second

write_lagflush_lagreplay_lagMB not yet replayed (right axis)

Replication slots, and why they fill disks

If a replica disconnects, the primary may recycle WAL the replica still needs. A replication slot prevents that: a bookmark on the primary that keeps all WAL from its position until the consumer confirms it. The other side of the promise: if the replica never comes back, the primary keeps WAL until its disk is full and it stops. Measured with the replica stopped and ordinary updates running, the slot held 1091 MB (wal_status extended) and pg_wal/ reached 1120 MB:

Since PostgreSQL 13 max_slot_wal_keep_size caps what a slot may hold (default -1, unlimited: replication settings); past it the slot is marked lost and the replica must be rebuilt from a fresh base backup (here 2.3 s for 774 MB on one laptop; hours for terabytes over a network). Since PostgreSQL 18 idle_replication_slot_timeout can also invalidate slots inactive too long. wal_status says how close you are: reserved (within max_wal_size), extended (beyond it, still kept), unreserved (removed at the next checkpoint), lost (pg_replication_slots).

Rule
Set max_slot_wal_keep_size to what your disk can afford, alert on slots where active is false or retained WAL exceeds a few GB, and drop slots for replicas that are gone. A slot that carries an xmin (logical slots always do) also holds back vacuum and freezing (sections 5 and 6).
Real run: the slot keeps WAL, then a cap releases it (measured output)

A stopped replica's slot grows pg_wal/ without limit; a cap releases it

Size of the primary's pg_wal/ after each step (after a checkpoint), colour by the slot's wal_status. measured

Synchronous replication: no lost commits, at a price

By default replication is asynchronous: the primary confirms a commit once its own WAL is flushed, and the replica gets it a moment later; if the primary dies in that moment, failover loses those commits. With synchronous_standby_names set, a commit waits for a named standby, and synchronous_commit picks how far: remote_write (written there), on (flushed there), remote_apply (replayed, so a read there sees it) (WAL settings). local and off skip the standby; off does not even wait for the primary's own disk, so a crash can lose the last fraction of a second of commits (it never corrupts the database).

With on throughput fell from 27,568 to 11,562 inserts per second, mostly the extra round trip per commit; across availability zones (about 1 ms apart) or regions (tens of ms) the cost grows with distance. The sharp edge: if the only synchronous standby goes away, every commit on the primary waits forever. In the run, the insert sat in wait_event SyncRep; cancelling it printed The transaction has already committed locally, but might not have been replicated to the standby, so cancelling does not undo the commit. The usual production setting is therefore synchronous_standby_names = 'ANY 1 (replica_a, replica_b)': wait for any one of two (quorum commit), so losing one does not stop writes. Patroni can also drop synchronous mode when no standby is healthy, trading a small data-loss window for availability.

Real run: the synchronous standby stops (measured output)

Waiting for a standby more than halves commit throughput, even on one machine

Single-row inserts per second, 8 clients, 10 s each, both servers on one laptop (loopback "network"). measured macOS fsync does not force the drive's cache, so every rate is higher than on a server with honest flushes; read the ratios.

Logical replication: copying rows, not files

Streaming replication copies the cluster byte for byte, so the replica runs the same major version and cannot be written to. Logical replication decodes the WAL into row changes and applies them on a subscriber, a normal writable database that may run a different major version and hold only some tables: a PUBLICATION on the source, a SUBSCRIPTION on the target, wal_level = logical. It is used for major upgrades with seconds of downtime (section 10), moving to another host or cloud, feeding tables to analytics, and change data capture into Kafka with Debezium, which reads a logical slot (Queues, streams and async work). Its limits (restrictions): schema changes (DDL), sequence values and large objects are not replicated, and every replicated table needs a primary key or replica identity for updates and deletes.

Without a fence both sides take writes; with a leader lock only one can

4. Failover: when the primary dies

Failover is making a replica the new primary and pointing the application at it. Postgres does one step, promotion: the replica stops replaying, starts a new timeline and accepts writes (pg_ctl promote, 0.12 s here). The hard parts are around it: deciding the primary is really dead and not just cut off from the monitor, making sure it can no longer accept writes, moving the connections, and bringing the old primary back. Get the first two wrong and you have split brain: two servers that both accept writes. Watch both ways on the same partition (the toggle swaps them):

  1. Normal. The primary takes every write and streams WAL to the replica.
  2. A partition. The monitor and the replica lose the primary. It is not dead: some clients still reach it and keep writing.
  3. Promote the replica by hand. pg_ctl promote: server promoted in 0.12 s, on a new timeline. Nobody stopped the old primary.
  4. Split brain. Both accept writes. In the run, row 2150968 is written to the OLD primary on one side and written to the NEW primary on the other.
  5. Repair: pg_rewind. The old primary is rewound to the point the histories diverged (0/B1000060), copying 211 MB of 908 MB, and rejoins as a replica. Its write is gone: a data loss for whoever made it.

The promotion, the two conflicting rows and the pg_rewind numbers are from the real run (the split brain was staged by promoting the replica while the old primary kept running); the leader-lock frames follow Patroni's documentation, not run here.

In the run, row id 2150968 held written to the OLD primary on one server and written to the NEW primary on the other; neither is right, and merging is manual, row by row. (GitHub's 2018 outage began this way; below.) Fencing prevents it: before promoting, make sure the old primary cannot accept writes, by stopping it, cutting its network or powering it off through the cloud API (the old name is STONITH, "shoot the other node in the head"). The old primary is then repaired with pg_rewind, which copies back only the blocks changed since the histories diverged (211 MB of 908 MB here) and discards the old side's writes: correct for the database, a data loss for whoever wrote them, which is why fencing comes first.

Real run: promotion, split brain, pg_rewind; and GitHub 2018 (measured output, case)

GitHub's 21 October 2018 outage began this way: a 43-second network partition triggered an automated cross-site failover, writes landed on both sides, and reconciling them kept the site degraded for 24 hours and 11 minutes (GitHub post-incident analysis; MySQL, same lesson).

pg_rewind needs wal_log_hints = on or data checksums, and the old primary's WAL back to the last common checkpoint; the first attempt for this page failed until wal_keep_size kept it.

Patroni and managed failover

Patroni (patroni/patroni) runs beside each Postgres server and keeps a leader lock with a time to live in a consensus store (etcd, Consul, ZooKeeper or Kubernetes). Only the holder may be primary: a primary that cannot renew the lock demotes itself, and a replica promotes only after acquiring it, so "who is primary" is answered once by the store, the problem Raft solves (Distributed systems fundamentals). A hardware or software watchdog can reset a primary that hangs. On Kubernetes, CloudNativePG plays the same role. Applications find the current primary through a DNS name, a load balancer, a pooler, or a multi-host connection string with target_session_attrs=read-write. Managed services run the equivalent: Amazon Aurora says a failover typically restores service in under 60 seconds and often under 30 (Aurora high availability). Two things stay yours: the application must reconnect and retry, because connections to the dead primary fail mid-transaction (Reliability engineering), and with asynchronous replication the last commits before the failure may be lost. Jepsen also found that RDS Multi-AZ clusters for PostgreSQL 13.15 to 17.4 could show replica reads that violate snapshot isolation (Long Fork), because of how stock replicas decide which transactions are visible (Jepsen, 2025-04-29): read from the primary when correctness matters.

Versions when read: Patroni v4.1.5 (2026-08-12), CloudNativePG v1.30.1 (2026-09-23).

5. Vacuum and autovacuum: the cleaning crew

Postgres never overwrites a row in place: an UPDATE writes a new version and marks the old one replaced, a DELETE only marks the row, and old versions stay while any running transaction might still see them (MVCC, on Transactions and concurrency). Once no transaction can see a version it is a dead tuple (tuple is Postgres's word for a row version). VACUUM removes dead tuples and their index entries and marks the space reusable; it also records which pages are all-visible (so index-only scans can skip the table) and freezes old rows (section 6). Autovacuum is the background launcher that runs VACUUM and ANALYZE on each table when enough has changed.

When autovacuum runs

A table is vacuumed when its dead tuples exceed autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor × rows, by default 50 + 20% of the table (vacuum settings). The launcher checks every autovacuum_naptime (1 minute) with up to autovacuum_max_workers (3) workers, each slowed by a cost limit (autovacuum_vacuum_cost_delay 2 ms per 200 cost units) so it does not swamp the disk. PostgreSQL 18 added autovacuum_vacuum_max_threshold (default 100 million), so a huge table no longer waits for a fifth of itself to die: at the default 0.2, a billion-row table would otherwise collect 200 million dead rows first. Predict that number for a billion rows at 0.01, then drag.

On a big table the default 20% is enormous: per-table scale factors exist for this

Dead tuples before autovacuum starts = 50 + scale factor × rows, capped at 100,000,000 in PostgreSQL 18. Updates per second to reach it in an hour = threshold / 3,600.

Watching it on a churned table

The test table is chat_state: one row per chat (100,000 rows) with an unread count and the time of the last message, updated whenever a chat gets a message, the hottest kind of table a chat product has. pgbench updates random rows at a steady 1,500 per second; the launcher checks every 5 s instead of every minute so a cycle fits on screen; everything else is default. Fig. 5 draws the table's pages through the same four phases, with the run's numbers:

  1. A table is 8 KB pages of row versions. chat_state's 100,000 rows fill 879 pages (autovacuum's own log says so). The visibility map keeps one bit per page, set while every row on it is visible to everyone; vacuum and index-only scans skip those pages.
  2. HOT updates mostly clean up after themselves. When an update changes no indexed column and the page has room, Postgres writes a heap-only tuple (HOT): the new version goes on the same page, no index is touched, and the next visitor to a full page prunes dead versions on the spot. In the run, 93% of the first 58,564 updates were HOT and dead tuples never passed 4,757, with no VACUUM at all.
  3. One index on the updated column: every update is a full one. An index on last_message_at (for "chats by recent activity") makes each update write its new version wherever there is room plus a new index entry, and leave a dead version behind: about 1,500 a second. Before indexing a hot table, compare n_tup_hot_upd with n_tup_upd; free space in each page (fillfactor = 90) makes HOT more likely.
  4. Autovacuum is a sawtooth. Dead tuples rise to the trigger (50 + 0.2 × 100,000 = 20,050) and autovacuum removes them and their index entries, marks the space reusable and sets the visibility bits again. New versions reuse the space, so the table grows a little, then holds: five runs in 80 s, a healthy steady state.
  5. One forgotten transaction stops all cleanup. A session that ran one SELECT inside a transaction and never committed keeps its snapshot, so no row version newer than it can be removed, in any table. Autovacuum keeps running and removes nothing; its log says tuples: 0 removed, 182379 remain, 82363 are dead but not yet removable with a removable cutoff that does not move, and the table grows to 1,552 pages.
  6. End the session; one VACUUM. pg_terminate_backend(pid) ends it; a manual VACUUM then removed 89,743 dead versions in a fraction of a second. 1,615 pages remain: the space is free inside the file, which keeps its size. Set idle_in_transaction_session_timeout (section 7). A replication slot with an old xmin, a replica with hot_standby_feedback = on running a long query, or an abandoned prepared transaction (section 6) pin the snapshot the same way.

Pages, row versions and visibility bits drawn one box for many; the page counts, dead-tuple counts and log lines are from the run (measured).

The same run, as measured

Every point of the chart is a real sample of pg_stat_user_tables, once a second, and the four shaded bands are the phases of Fig. 5: HOT (dead tuples stay in the low thousands), the index (the sawtooth, five autovacuum runs), the open transaction (nine more autovacuum runs remove nothing; dead tuples and size climb in a straight line to 86,930), and the manual VACUUM after the session ends.

Real run: the forgotten transaction, autovacuum's log, then a manual VACUUM (measured output)

HOT barely needs vacuum, autovacuum saws, one open transaction stops all cleanup

dead tuples (n_dead_tup)table size, MB (right axis)autovacuum ran

One sample a second of chat_state under 1,500 updates a second; the dots mark each autovacuum run. measured

VACUUM against VACUUM FULL

Plain VACUUM makes space reusable but almost never returns it to the operating system: the file keeps its size. VACUUM FULL rewrites the table into a new compact file and rebuilds its indexes, which does return space, under an ACCESS EXCLUSIVE lock for the whole rewrite: nothing can even read the table.

On this 200 MB table the lock lasted under two seconds (a reader with lock_timeout gave up while it ran); on a 500 GB table it would be hours of a table nobody can read. Online, you reclaim space with pg_repack or pg_squeeze, which build a copy in the background, replay the changes made meanwhile and take the exclusive lock only for a brief swap (both are extensions missing from the pgserver build, so not measured here). Often you need neither: if the table will grow back, reusable space is fine.

Real run: a reader tries the table during VACUUM FULL; and the tool versions (measured output, dated)

Latest when read: reorg/pg_repack tag ver_1.5.3; cybertec-postgresql/pg_squeeze REL1_9_4 (2026-07-29).

Tuning autovacuum: what teams actually change (reference configuration)
-- a big, hot table: vacuum after 1% has changed, not 20%, and let it work faster
ALTER TABLE messages SET (autovacuum_vacuum_scale_factor = 0.01, autovacuum_vacuum_threshold = 1000,
                          autovacuum_analyze_scale_factor = 0.02);
ALTER TABLE chat_state SET (fillfactor = 90);          -- room on each page for HOT updates

-- postgresql.conf: more and faster workers on a machine with fast disks
autovacuum_max_workers = 6               -- PostgreSQL 18: changeable without restart, up to autovacuum_worker_slots (16)
autovacuum_vacuum_cost_limit = 2000      -- default -1 uses vacuum_cost_limit (200), shared by all workers
maintenance_work_mem = '1GB'             -- memory for remembering dead tuples during one pass
log_autovacuum_min_duration = '10s'      -- log every slow autovacuum: your best diagnostic

-- the query to watch
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum, autovacuum_count
FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;

Values are illustrative starting points, not measured optima; parameters and defaults from the PostgreSQL 18 vacuum settings.

Never turn autovacuum off for a table to "save IO": it is also what prevents section 6.

VACUUM frees space inside the file; only a rewrite shrinks it

6. Transaction ID wraparound: the outage that stops all writes

Every transaction that writes gets a transaction ID (XID), a 32-bit counter, and every row version records the XID that created it. Visibility asks "was this row created by a transaction older than mine?", and with 32 bits that comparison is done modulo 232: each XID sees about 2.1 billion (231) IDs as the past and the rest as the future. A row whose creator fell more than 231 behind would suddenly look like it came from the future and vanish. So VACUUM freezes old rows, marking them older than every transaction, and each table remembers its oldest unfrozen XID (relfrozenxid; the database's minimum is datfrozenxid) (routine vacuuming). Fig. 6 draws the counter as the circle it is, and walks the run from a healthy age to the refusal and back:

  1. 232 IDs on a circle. Every writing transaction takes the next XID, and comparisons wrap: from the current XID, the 231 IDs behind it are the past and the 231 ahead are the future.
  2. Freezing keeps the past short. VACUUM freezes old rows as it goes, so only the arc from the oldest unfrozen XID (datfrozenxid) to now matters: its length is the age. A healthy database saws between 0 and 200 million.
  3. 200 million: aggressive autovacuum. Past autovacuum_freeze_max_age every table this old gets an anti-wraparound vacuum that scans every unfrozen page, even with autovacuum switched off. If the age keeps rising here, something is holding the oldest XID.
  4. Something holds the oldest XID. A forgotten prepared transaction (refund-42 in the run), an open transaction or a slot's xmin stops freezing at its XID, so the age grows with every transaction: this page's alerts fire at 500 million (warn) and 1 billion (page); at 1.6 billion (vacuum_failsafe_age) vacuum drops its cost limits and skips index cleanup. Still silent in the log: only your alert has fired.
  5. 40 million left: warnings. Every command logs WARNING: database "template0" must be vacuumed within 3000299 transactions (the run was started just short of the limit, so the first warning already shows about 3 million).
  6. 3 million left: writes refused. 308 more inserts succeeded, then ERROR: database is not accepting commands to avoid wraparound data loss, while reads still worked. The holder query found refund-42, a prepared transaction 2,144,483,647 XIDs old.
  7. The fix: remove the holder, then VACUUM. ROLLBACK PREPARED and a normal VACUUM (FREEZE) brought every database back to an age under 300 in 0.36 s; the oldest unfrozen XID jumps to now.

Thresholds from the PostgreSQL 18 documentation: aggressive freezing autovacuum at 200 million (autovacuum_freeze_max_age), even with autovacuum switched off; the failsafe at 1.6 billion (vacuum_failsafe_age) drops the cost limits and skips index cleanup; warnings at 40 million before the wraparound point; refusal of new XIDs at 3 million before it. The 500 million and 1 billion alert lines are this page's suggestion. The circle is to scale: 231 = 2,147,483,648 is half of it, so the last 40 million are under 2% of the half-turn, which is why the figure moves in close for steps 5 and 6.

Freezing can only advance up to the oldest transaction anything still needs, so the causes are those of section 5: a transaction left open, an abandoned prepared transaction (from two-phase commit; it survives restarts until someone commits or rolls it back by name), a replication slot holding an old xmin, or autovacuum too slow for a write-heavy database. Two billion transactions take weeks even on a busy server, so for this page a throwaway server's counter was moved forward with pg_resetwal -x, just short of the refusal point, after leaving behind a forgotten prepared transaction; from then on every line in steps 5 to 7 is real.

Stale advice in the error itself
PostgreSQL 16's refusal message still says Stop the postmaster and vacuum that database in single-user mode. The current documentation says single-user mode should be avoided whenever possible and a normal VACUUM works, which is what fixed it above on this tiny database (routine vacuuming, PostgreSQL 18). Remove what holds the XID back first; a VACUUM before that freezes nothing.
Real run: a wraparound emergency, from warning to fix (measured output)

It happens to real companies (Sentry 2015, Mandrill 2019, Notion before it sharded; below), and on a big database the fix can take many hours of vacuuming, all of it with writes refused.

Three wraparound outages (cases)

It happens. Sentry was down for most of a US working day on 20 July 2015 when Postgres stopped accepting writes to prevent wraparound (Sentry, 2015-07-23); Mailchimp's Mandrill was down from 4 to 5 February 2019 when one shard hit the limit (Mailchimp); Notion called wraparound "an existential threat to the product" in the post explaining why it sharded (Notion, 2021-10-06).

The alert that prevents it
Graph SELECT datname, age(datfrozenxid) FROM pg_database and the top tables by age(relfrozenxid). Warn when any database passes about 500 million (a quarter of the way) and page at about 1 billion; a healthy database saws between 0 and 200 million as anti-wraparound vacuums finish. Alert separately on prepared transactions older than a few minutes and on inactive replication slots.

7. Connections and pooling

Each connection is a whole operating-system process (section 1). What one backend costs, measured, is in the tiles beside this text.

A backend grows with use (cached catalog entries, memory kept after a big sort), so a thousand long-lived connections add up to gigabytes. But Andres Freund's 2020 analysis found the overhead below 2 MiB per connection with huge pages, and the real ceiling was CPU: every snapshot scanned the list of all connections, which PostgreSQL 14 made much cheaper (Analyzing the limits of connection scalability in Postgres, 2020-10-08). What remains is starting a process per new connection, and contention when many more processes are active than there are cores:

One backend: a few MB idle, more after use, and a connect costs milliseconds

One fresh, idle backend
MB
physical footprint (macOS vmmap)
After reading the catalogs
MB
one query on information_schema.columns
After one 64 MB sort
MB
kept by the process until it exits
Connect, SELECT 1, disconnect
ms
median of 300, direct, no TLS, same machine

measured PostgreSQL 16.2, psycopg . Shared memory is counted in every process that touches it, so per-process memory is hard to measure honestly; the footprint above excludes most of it.

Reconnecting for every query keeps 2% of the throughput; reconnecting to PgBouncer instead is 5.6 times faster

Trivial queries (SELECT 1) per second, 8 clients. "New connection each time" is pgbench -C: connect, run one query, disconnect, as an application without a pool or a serverless function does. measured How many pooled connections give the most throughput, and what reconnecting does to a real workload, is Query planning and performance section 8; sizing a pool with Little's law is Capacity planning and performance.

max_connections, and the arithmetic nobody did

max_connections defaults to 100, needs a restart to change, and keeps 3 for superusers (connection settings); in the run the application role got 97 connections and the next was refused with FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute. It runs out through pools: SQLAlchemy's default is 5 connections plus up to 10 overflow per process (SQLAlchemy pooling), so twenty pods can open 20 × 15 = 300, a deploy briefly runs old and new pods together (600), and workers and cron jobs add theirs. Raising max_connections to thousands is the wrong fix: most would sit idle, and the active ones fight over the same cores and locks. The PostgreSQL wiki's rule of thumb for the number of active connections that gives the best throughput is about (2 × CPU cores) + number of disks (wiki: Number Of Database Connections; a starting point to measure from, not a law).

Real run: a role opens connections until refused (measured output)

PgBouncer: many clients, few server connections

PgBouncer is a small single-process pooler that speaks the Postgres protocol, so applications connect to it as if it were the database. Its pool_mode decides when a server connection is lent: session (a client keeps one from connect to disconnect: everything works, it only saves the connect cost), transaction (one transaction at a time, then it goes back: hundreds of mostly idle clients share a few; the mode almost everyone runs) and statement (returned after every statement, so multi-statement transactions are refused; rare). Fig. 7 shows what that buys, with the run's numbers:

  1. Without a pooler: one backend per client. max_connections = 100 with 3 kept for superusers: the application role got 97 backends, and the next connection was refused with remaining connection slots are reserved.
  2. PgBouncer in front: 1,000 clients, 20 server connections. The clients connect to PgBouncer as if it were the database; with default_pool_size = 20, Postgres sees 20 backends.
  3. Transaction mode: lent for one transaction. A client gets a server connection when its transaction starts and gives it back at COMMIT; the next client in line takes it, so a few connections serve hundreds of mostly idle clients.
  4. More work than connections: a short queue. With 300 clients running a 50 ms transaction at once, SHOW POOLS printed cl_active 832, cl_waiting 168, sv_active 20. That queue is far cheaper than a thousand processes fighting over the cores.
Real run: 1,000 clients through PgBouncer (measured output)

A session SET rides the server connection to the next client

The two ways transaction pooling bites

In transaction mode one client's consecutive transactions may run on different server connections, and one server connection serves many clients, so anything that lives in the session breaks: SET, LISTEN, session advisory locks, WITH HOLD cursors, temporary tables kept across transactions, SQL-level PREPARE (PgBouncer feature table). Both of these happened on the first try. The first, step by step:

  1. A borrows server connection 1. Client A starts a transaction; PgBouncer lends it server connection 1. Both server connections have the default statement_timeout (0, off).
  2. A runs SET statement_timeout = '5s'. A session-level SET changes the server connection's session, not client A: PgBouncer passes it through.
  3. A's transaction ends; the connection goes back. Transaction mode returns connection 1 to the pool the moment the transaction ends, still carrying 5s.
  4. B gets connection 1, and A's setting. Client B never ran SET, but SHOW statement_timeout says 5s. Any query of B's longer than 5 s is now cancelled.

Pool of two server connections; which connection each client gets is drawn, the timeouts each client saw are from the run (measured: client B saw 5s in ten of ten SHOW statement_timeout).

No error reports the first: it is a correctness bug. Use SET LOCAL inside a transaction, or set defaults per role (ALTER ROLE app SET statement_timeout = '5s'). The second is a crash that appeared only after the fifth execution: psycopg 3 prepares a query on the server automatically once it has run five times (prepare_threshold), and asyncpg and many JDBC setups do the same; with max_prepared_statements = 0, 3 of 30 runs failed with DuplicatePreparedStatement: prepared statement "_pg3_0" already exists, with 200 none did. PgBouncer has tracked protocol-level prepared statements since 1.21.0 and, since 1.24.0, does so by default with max_prepared_statements = 200 (changelog); the run set 0 to reproduce what older configurations still do. Check the setting before blaming the driver.

Real run: session state leaks; prepared statements collide (measured output)
Keep the pooler patched
A pooler sits in front of every connection, so a crash there is an outage. PgBouncer 1.26.0 (2026-09-23) fixes CVE-2026-19888, an unauthenticated crash in the SCRAM login exchange present since 1.11.0 (changelog); the measurements here used 1.24.1, which is affected.
Other poolers (versions dated)

Supavisor (Supabase's pooler, v2.9.13), PgDog (pooler, load balancer and sharder, weekly releases, v0.1.60), managed proxies such as RDS Proxy. PgCat has had no release since 2024-11-11 (postgresml/pgcat).

Timeouts: the cheapest protection there is

All of these default to 0, off (client settings). Set them per role, so the migration and analytics roles can differ from the web application (values illustrative; pick them from your latency targets):

ALTER ROLE app SET statement_timeout = '5s';                    -- no web request needs a 5-minute query
ALTER ROLE app SET idle_in_transaction_session_timeout = '30s'; -- a forgotten transaction cannot block vacuum for long
ALTER ROLE app SET transaction_timeout = '60s';                 -- PostgreSQL 17+: the whole transaction
ALTER ROLE migrator SET lock_timeout = '3s';                    -- a migration gives up instead of queueing everyone (section 8)
Real run: what the application sees when a timeout fires (measured output)

8. Safe schema changes: the lock queue

Most ALTER TABLE forms need an ACCESS EXCLUSIVE lock, even when the change itself is metadata-only and takes a millisecond. The danger is not the change but the queue: locks are granted in order, so an ALTER waiting behind one long transaction makes every later query on that table wait behind the ALTER, even plain reads that would not conflict with the long transaction. Staged on users:

The first process, blocked by nobody, is idle inside a transaction that read users; the ALTER TABLE ... ADD COLUMN waits for its exclusive lock; the three SELECTs are blocked by the ALTER, not by the idle transaction. Ending either releases all of them. In production every migration therefore runs with a short lock_timeout and retries, so a blocked ALTER gives up in seconds instead of queueing the site:

SET lock_timeout = '3s';      -- give up instead of queueing every reader behind us
ALTER TABLE users ADD COLUMN locale text;
-- on "canceling statement due to lock timeout": wait, retry with backoff, alert after a few attempts

Slow forms get safe recipes: CREATE INDEX CONCURRENTLY, ADD CONSTRAINT ... NOT VALID then VALIDATE CONSTRAINT, a nullable column backfilled in batches. Which of 21 common changes takes which lock, rewrites the table or scans it, measured with the recipes and a lock-queue animation with and without lock_timeout, is the "ALTER TABLE, measured" tab of SQL and data modelling.

Real run: one idle transaction, one ALTER TABLE, and everyone else waiting (measured output)

Three reads wait on the ALTER, which waits on one idle transaction

From one real pg_stat_activity snapshot with pg_blocking_pids(pid) (process ids and waits as printed). measured

9. Monitoring: the numbers that warn you

Every failure in the table at the top, except a sudden hardware loss, is visible hours or days ahead in a handful of numbers. The general method (metrics, logs, traces, alerting on symptoms) is on Observability; for a database the four golden signals (latency, traffic, errors, saturation, from Google's SRE book) come from these views:

SignalFor PostgresWhere it comes from
LatencyQuery time, per normalised querypg_stat_statements (needs shared_preload_libraries: docs) and the application's own histograms; the slow-query workflow is on Query planning and performance
TrafficTransactions per second, rows read and writtenpg_stat_database (xact_commit, tup_inserted, ...), as rates
ErrorsRollbacks, deadlocks, failed connections, log errorspg_stat_database (xact_rollback, deadlocks), the server log
SaturationConnections, CPU, IO, disk, replication lag, retained WAL, XID age, dead tuplespg_stat_activity, pg_stat_replication, pg_replication_slots, pg_database, pg_stat_user_tables, the host

Three numbers in the dashboard output deserve a second look: cache_hit_pct (share of page reads served from shared buffers; normally above 99% on a busy production database, and a drop means the working set no longer fits in memory), temp_files (sorts and hashes spilling because work_mem was too small for them, section 1), and an index bigger than a quarter of its table (is it used? idx_scan says).

Real run: the dashboard queries after a short pgbench run (measured output)

Finding the query that is hurting you

pg_stat_activity ordered by query_start shows the oldest running statement first (in the run, a self-join of messages 4 s in). pg_cancel_backend(pid) cancels the current query and keeps the connection; pg_terminate_backend(pid) ends the whole session and rolls back its transaction. Prefer cancel. When everything on one table hangs, look for the lock queue of section 8 with pg_blocking_pids().

Real run: a runaway query, found and cancelled (measured output)

The alerts worth having

AlertQuery or metricWarnPage
Disk usedhost metric for the data volume80%90%
Retained WAL / inactive slotpg_replication_slots: active, retained bytesinactive 10 min or above 5 GBwal_status unreserved
WAL archiving failingpg_stat_archiver.failed_count risingany failurefailing 15 min
Newest backup too oldbackup tool's metricsolder than schedule2 x schedule
Replication lagpg_stat_replication.replay_lag30 s5 min
Transaction ID agemax(age(datfrozenxid))500 million1 billion
Connectionscount(*) in pg_stat_activity / max_connections70%90%
Long transactionsoldest xact_start among non-idle and idle-in-transaction sessions5 min30 min
Dead tuplesn_dead_tup / n_live_tup on big tables20%(investigate, rarely a page)
Errors and latencyrollback rate, deadlocks, p95 query latencyvs your baselinevs your SLO

Thresholds are this page's suggested starting points, not sourced standards; tune them to your database. The usual collector is postgres_exporter feeding Prometheus and Grafana; hosted options (pganalyze, Datadog, the clouds' own tools) read the same views.

10. Upgrades: minor releases and major versions

In 18.6, 18 is the major version and 6 the minor release. Minor releases only fix bugs and security issues and never change the on-disk format: install the new binaries and restart, after reading the release notes for occasional extra steps; they come roughly quarterly (18.6 and 17.11 on 2026-08-13: release notes). A major version comes once a year, may change the catalogs and storage format, so the data directory must be converted, and is supported for five years (versioning policy):

Five years each: PostgreSQL 14 ends on 2026-11-12

Support windows from the versioning policy page, read 2026-10-04; the vertical line is that day, about five weeks before 14's end. Managed services charge or force-upgrade after end of life (Amazon calls it RDS Extended Support), so "we will upgrade later" has a date: plan major upgrades a year ahead and rehearse them on a restored copy.

pg_upgrade: convert in place

pg_upgrade creates the new version's empty cluster, copies the schema with pg_dump, then moves the data files across unchanged, since the table format rarely changes. Its modes decide how the files move: copy (safe, slow for big databases), --link (hard links: seconds for any size, but the old cluster is unusable once the new one has started), --clone (copy-on-write file systems) and, since PostgreSQL 18, --swap (moves directories, often the fastest) (pg_upgrade docs). Always run --check first. Measured, 16.2 to 17.11, both servers stopped throughout:

On this 221 MB database both modes took about two seconds, almost all of it the fixed cost of dumping and restoring the schema; copy mode adds the time to copy every byte (about 17 minutes per terabyte at 1 GB/s, illustrative disk speed), link mode does not. Before PostgreSQL 18 planner statistics are not carried over, so until vacuumdb --analyze-in-stages finishes, queries can get bad plans; PostgreSQL 18's pg_upgrade keeps them (18 release notes). Downtime is the whole run plus restarts. Physical replicas cannot follow a major upgrade: they are rebuilt, or upgraded with the rsync procedure in the docs.

Real run: pg_upgrade --check, then a server with no statistics (measured output)

Logical replication: upgrade with seconds of downtime

For large databases, build a server on the new version, copy the schema, subscribe it to the old one with logical replication (section 3), let it catch up while the old one serves, then switch the application. Measured, 16 publishing to 17, with the classic trap at the end: logical replication copies rows, not sequence positions, so the new server's messages_id_seq was still at 1 (the old one at 1231288) and the first insert failed with duplicate key value violates unique constraint "messages_pkey". At cutover: stop writes, wait for the subscriber to catch up, copy every sequence's value (setval), then move traffic. Also plan for tables without a primary key, schema changes during the migration (not replicated) and large objects. PostgreSQL 17 added pg_createsubscriber, which turns a physical replica into a logical one so the initial copy is skipped, and keeps logical slots across pg_upgrade from 17 onwards (17 release notes). Amazon RDS Blue/Green Deployments wrap the same idea (RDS Blue/Green).

Real run: a 17 subscriber follows a 16 primary, then the cutover (measured output)

11. Security basics

The database gets the narrowest door, in four layers from outside in. Network: no public IP; only the application's subnet (and a bastion or VPN for humans) reaches port 5432. Who may connect: pg_hba.conf, where each line is type database user address method, read top to bottom, first match wins (pg_hba.conf docs); use hostssl lines and scram-sha-256 passwords, the default since PostgreSQL 14 (MD5 passwords are deprecated and PostgreSQL 18 warns when one is set: 18 release notes). Encryption in transit: ssl = on on the server and sslmode=verify-full on clients, so they also check the server's certificate (anything weaker can be intercepted). Least privilege: a role is a user or a group; each kind of client gets its own with only what it needs, the application does not own the tables, and nothing runs as a superuser. Least privilege also limits mistakes: a role without DELETE on messages cannot run section 2's 14:03 statement at all.

pg_hba.conf and roles for the chat product (reference configuration)
# pg_hba.conf: TLS from the app subnet, SCRAM passwords; nothing else gets in
hostssl  chat  app,migrator  10.20.0.0/16  scram-sha-256
hostssl  chat  +readonly     10.30.0.0/24  scram-sha-256
host     all   all           0.0.0.0/0     reject

-- roles: the migration role owns the schema, the app only reads and writes rows
CREATE ROLE migrator LOGIN;                         -- runs schema migrations, owns the tables
CREATE ROLE app LOGIN;                              -- the web service
CREATE ROLE readonly NOLOGIN;                       -- a group for analysts and dashboards
GRANT CONNECT ON DATABASE chat TO app, readonly;
GRANT USAGE ON SCHEMA public TO app, readonly;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
ALTER DEFAULT PRIVILEGES FOR ROLE migrator IN SCHEMA public
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app;   -- tables created later too
ALTER DEFAULT PRIVILEGES FOR ROLE migrator IN SCHEMA public GRANT SELECT ON TABLES TO readonly;

Subnets and role names are illustrative. Since PostgreSQL 15 ordinary roles can no longer create objects in the public schema by default (15 release notes).

Two more layers when the product needs them: row-level security, so the database itself filters rows by tenant and a bug in one query cannot leak another customer's chats (taught with the chat schema on SQL and data modelling; RLS docs), and auditing (the pgaudit extension, or the managed service's audit log) to record who read or changed what. Keep credentials in a secret manager, rotate them, and give humans individual named roles so the log says who did it.

12. Managed Postgres: what it takes off your plate

A managed service runs the server: provisioning, minor upgrades, automated backups and point-in-time restore, a standby with automatic failover, dashboards. It does not design your schema, fix slow queries, size your connection pools, tune autovacuum for your hottest table, choose when to do a major upgrade, or test that a restore gives you what you need: sections 5 to 10 stay your job. How to choose: on a cloud already, its stock managed Postgres (RDS, Cloud SQL, Azure Flexible Server) is the default; Aurora and AlloyDB buy faster failover, more readers and storage that grows by itself, at a higher price and with less portability; Neon and Supabase suit small, spiky or many-database workloads and fast-moving teams; running it yourself (Patroni or CloudNativePG, pgBackRest, PgBouncer, postgres_exporter) is cheapest in money and most expensive in on-call time. Safe to defer: none of the five rules at the top.

The services compared, with list prices (volatile: read 2026-10-04)

List prices read on 2026-10-04 (USD, us-east-1 or the provider's default region); the Database atlas tab of the root has each product's row with sources.

ServiceWhat it isFailover and backupsPrice example (list, 2026-10-04)
Amazon RDS for PostgreSQLStock Postgres on a managed VM with EBS storageMulti-AZ standby; backups kept 0 to 35 days; transaction logs to S3 every 5 minutes (docs)db.m7g.large (2 vCPU, 8 GiB): $0.168/h, Multi-AZ $0.337/h; gp3 storage $0.115/GB-month (AWS price list)
Amazon Aurora PostgreSQLPostgres engine on AWS's shared storage, kept in copies across three Availability ZonesUp to 15 readers; failover typically under 60 s, often under 30 (docs)Serverless v2 $0.12 per ACU-hour; storage $0.10/GB-month plus $0.20 per million I/Os, or I/O-Optimized $0.225/GB-month
Google Cloud SQLManaged stock Postgres on Google CloudRegional HA; Enterprise Plus: 99.99% SLA including maintenance, PITR logs up to 35 days (editions)Enterprise: $0.0413 per vCPU-hour, $0.007 per GiB-hour; HA doubles (pricing; region of the default table not stated: unconfirmed)
Google AlloyDBPostgres-compatible engine on Google's disaggregated storage, with a columnar cacheHA standby in a second zone; read pools$0.06608 per vCPU-hour, $0.0112 per GiB-hour (pricing; region unconfirmed)
Azure Database for PostgreSQLFlexible Server: managed stock PostgresZone-redundant HA; backups 7 days by default, configurable (overview)not collected
NeonServerless Postgres: storage separated from compute, scale to zero, instant branches; owned by Databricks (announced 2025-05-14)History window for restores: Free 6 hours, Launch up to 7 days, Scale up to 30 daysLaunch $0.106, Scale $0.222 per compute-unit hour (pricing)
SupabaseA Postgres database per project plus auth, storage and APIsDaily backups (Pro: 7 days); PITR as an add-on, about $100/month for 7 days (backups)Pro from $25/month including $10 compute credit; Micro compute $0.01344/h (compute)
Crunchy BridgeManaged stock Postgres from Crunchy Data, acquired by Snowflake (announced 2025-06-02) and now sold as Snowflake PostgresHA option; pgBackRest-based backupsHobby-0 $9/month, Standard-8 $140/month, storage $0.10/GB (pricing page, still live; whether new sign-ups are accepted: unconfirmed)

One always-on node with 2 vCPU and 8 GiB for a 730-hour month, compute only, from the unit prices above: RDS $0.168 x 730 (Multi-AZ $0.337 x 730); Cloud SQL (2 x $0.0413 + 8 x $0.007) x 730, HA doubles; AlloyDB (2 x $0.06608 + 8 x $0.0112) x 730. Storage, backups, I/O and network come on top. Derived on this page, not quoted.