DB·57
PostgreSQL in Depth
How PostgreSQL works and how to run it: the process architecture, databases, schemas and search_path, roles, privileges and row-level security, extensions and the type system, the planner, EXPLAIN and EXPLAIN ANALYZE, MVCC with VACUUM, ANALYZE and autovacuum (and transaction ID wraparound), the WAL, physical and logical replication, declarative partitioning, and what's new in PostgreSQL 17 and 18 (asynchronous I/O, skip scan, uuidv7, virtual generated columns, temporal constraints, OAuth authentication). Compared with MySQL/InnoDB, SQL Server and Oracle.
Start here: what PostgreSQL is doing underneath
A family of processes
PostgreSQL isn't one program but a family of processes sharing memory. Listing them on a running server:
$ ps -o pid,cmd -u postgres
1271 /usr/lib/postgresql/16/bin/postgres -D /tmp/pgdata -p 5433
1272 postgres: checkpointer
1273 postgres: background writer
1275 postgres: walwriter
1276 postgres: autovacuum launcher
1277 postgres: logical replication launcher
The postmaster (the first line) listens for connections and starts a new backend process for every client connection; the others are background workers that flush data to disk, write the log, and clean up. All of them share a block of memory, the shared buffer cache, where table and index pages are cached (SHOW shared_buffers → 128MB by default, typically raised to about a quarter of RAM). Because each connection is a whole process, connections are expensive (the lab measured about 4 ms to open one, and each holds memory), which is why applications use connection pools and why max_connections defaults to just 100.
Every update writes a new row version
Watch what an UPDATE actually does. ctid is a row version's physical address (page, slot), and xmin/xmax are the ids of the transactions that created and deleted it:
CREATE TABLE dish (id int PRIMARY KEY, name text, price_paise int);
INSERT INTO dish VALUES (1, 'Masala dosa', 9000), (2, 'Idli', 5000);
SELECT ctid, xmin, xmax, * FROM dish;
UPDATE dish SET price_paise = 9500 WHERE id = 1;
SELECT ctid, xmin, xmax, * FROM dish;
ctid | xmin | xmax | id | name | price_paise (before)
-------+-------+------+----+-------------+-------------
(0,1) | 18633 | 0 | 1 | Masala dosa | 9000
(0,2) | 18633 | 0 | 2 | Idli | 5000
ctid | xmin | xmax | id | name | price_paise (after)
-------+-------+------+----+-------------+-------------
(0,2) | 18633 | 0 | 2 | Idli | 5000
(0,3) | 18634 | 0 | 1 | Masala dosa | 9500
The Masala dosa moved from slot 1 to slot 3, and transaction 18634 created it. Looking at the raw page (with the pageinspect extension) shows the old version is still there:
lp | t_xmin | t_xmax | t_ctid lp | t_xmin | t_xmax | t_ctid
----+--------+--------+-------- ----+--------+--------+--------
1 | 18633 | 18634 | (0,3) 1 | | | ← after VACUUM: slot freed
2 | 18633 | 0 | (0,2) 2 | 18633 | 0 | (0,2)
3 | 18634 | 0 | (0,3) 3 | 18634 | 0 | (0,3)
PostgreSQL never overwrites a row in place. An update marks the old version as deleted by transaction 18634 (t_xmax) and writes a new version. This is MVCC, multi-version concurrency control: a transaction that started before 18634 committed keeps seeing the ₹90 version, so readers never block writers and writers never block readers (chapter 59). The price is cleanup: old versions nobody can see any more are dead tuples, and VACUUM (run automatically by autovacuum) frees their space for reuse. The lab shows what happens when it can't keep up.
The write-ahead log
SELECT pg_current_wal_lsn() AS before \gset
INSERT INTO dish SELECT g, 'dish ' || g, 1000 FROM generate_series(3, 10002) g;
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), :'before')) AS wal_written_for_10000_rows;
wal_written_for_10000_rows
----------------------------
1439 kB
Before any change reaches the table files, it's appended to the write-ahead log (WAL), and COMMIT returns only when the WAL is safely on disk. If the server crashes, it replays the WAL from the last checkpoint to restore every committed change: that's how durability works without writing every changed page to disk at commit time. The same WAL stream, shipped to other servers, is how replication works: the lab runs a replica and measures how far behind it is.
Plans and statistics
EXPLAIN SELECT * FROM dish WHERE id = 42;
Index Scan using dish_pkey on dish (cost=0.27..8.29 rows=1 width=40)
Index Cond: (id = 42)
EXPLAIN SELECT * FROM dish WHERE price_paise = 1000; ← before ANALYZE
Seq Scan on dish (cost=0.00..65.60 rows=1 width=40)
ANALYZE dish;
EXPLAIN ANALYZE SELECT * FROM dish WHERE price_paise = 1000; ← after ANALYZE
Seq Scan on dish (cost=0.00..189.03 rows=10000 width=17) (actual time=0.011..1.065 rows=10000 loops=1)
Filter: (price_paise = 1000)
Rows Removed by Filter: 2
EXPLAIN shows the plan the planner chose; EXPLAIN ANALYZE also runs it and shows what actually happened. The planner uses statistics about each column (row counts, common values, histograms) to estimate how many rows each step returns. Before ANALYZE, it guessed 1 row for a filter that matched 10,000; with a bigger table and a join, a guess that wrong produces a terrible plan. Autovacuum also runs ANALYZE automatically after enough changes; after bulk loads, run it yourself. Chapter 60 is about reading and fixing plans.
How deep to go in PostgreSQL
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain processes, shared buffers, MVCC, VACUUM, WAL and replication in a sentence each |
| L2 | Configure roles, schemas, extensions, autovacuum basics and read EXPLAIN output |
| L3 | Explain tuple visibility, HOT updates, freezing and wraparound, checkpoints, physical and logical replication, partitioning |
| L4 | Diagnose bloat, blocked vacuum, replication lag, connection exhaustion and bad estimates |
| L5 | Plan capacity, high availability, upgrades and partitioning for a production database |
| L6 | Operate a fleet of PostgreSQL clusters with automation, observability and upgrade policy |
Architecture
Processes and memory
PostgreSQL uses a process-per-connection architecture. The postmaster listens on port 5432 and forks a new backend process for each client connection. Background processes handle shared work:
Consequences:
- Connections are expensive: each is a process with its own memory (several MB, more with large
work_memsorts) and fork cost. Thousands of connections hurt performance through memory use, contention on the proc array, and context switching. Use connection pooling: app-side pools (HikariCP, Vol. 3 ch. 49) sized small, plus a server-side pooler (PgBouncer, PgCat, Odyssey, RDS Proxy, Supavisor) in transaction mode when many app instances connect. Transaction mode means session state (session-level prepared statements,SET, advisory locks,LISTEN) doesn't persist between transactions, though PgBouncer 1.21+ supports protocol-level prepared statements. - Memory settings:
shared_buffersis the database's page cache, typically about 25% of RAM. PostgreSQL also relies on the OS page cache (double buffering).work_memis memory per sort or hash operation, per backend, so one complex query can use several multiples of it. Set it conservatively and raise it per session for reports.maintenance_work_memis for VACUUM and index builds.effective_cache_sizeis a planner hint about the total cache available.- MySQL uses one thread per connection (or a thread pool in some editions), which makes connections cheaper than PostgreSQL's, though pooling is still recommended. SQL Server and Oracle have their own process and thread models and session memory. Oracle offers a shared server mode and DRCP pooling.
Databases, schemas and search_path
A PostgreSQL cluster (one server instance) contains databases. A connection is to one database, and cross-database queries need postgres_fdw or dblink. Each database contains schemas: namespaces for tables, views, functions and types.
CREATE SCHEMA billing AUTHORIZATION billing_owner;
CREATE TABLE billing.invoices (…);
SHOW search_path; -- "$user", public
SET search_path = billing, public; -- unqualified names resolve in this order
ALTER ROLE billing_app SET search_path = billing; -- per-role default
Uses of schemas: separating modules of one application (a modular monolith's orders, billing and catalog schemas with separate owners), multi-tenancy (schema per tenant: fine for tens to hundreds of tenants, painful for thousands), extensions in their own schema, and staging versus live tables for swaps.
Security note: before PostgreSQL 15, every user could create objects in the public schema. Combined with search_path, an attacker could shadow functions such as lower() with a malicious one (CVE-2018-1058). PostgreSQL 15 revoked CREATE on public from PUBLIC. Always schema-qualify in security-sensitive functions, and set search_path on SECURITY DEFINER functions.
MySQL has no schema level: "database" and "schema" are synonyms, one level below the server. SQL Server and Oracle have schemas (in Oracle, a schema is a user).
Roles, privileges and row-level security
PostgreSQL has a single concept, the role, that covers both users (LOGIN) and groups (roles granted to other roles):
-- Group roles (no login) carry privileges
CREATE ROLE app_read NOLOGIN;
CREATE ROLE app_write NOLOGIN;
GRANT USAGE ON SCHEMA shop TO app_read, app_write;
GRANT SELECT ON ALL TABLES IN SCHEMA shop TO app_read;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA shop TO app_write;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA shop TO app_write;
-- Future tables created by the owner get the same grants automatically:
ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA shop GRANT SELECT ON TABLES TO app_read;
ALTER DEFAULT PRIVILEGES FOR ROLE shop_owner IN SCHEMA shop GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_write;
-- Login roles (users) inherit from group roles
CREATE ROLE orders_service LOGIN PASSWORD '…' IN ROLE app_write;
CREATE ROLE analyst_ada LOGIN IN ROLE app_read;
-- Predefined roles help (PG 14+): pg_read_all_data, pg_write_all_data, pg_monitor, pg_maintain (17)
GRANT pg_monitor TO metrics_exporter;
Least privilege in practice:
- The migration role owns the schema (DDL).
- The application role can only read and write data (no DDL, no
TRUNCATE). - Analysts read replicas with read-only roles.
- Superuser is never used by applications. Managed services (RDS, Cloud SQL, Azure) don't give you real superuser anyway.
Row-level security (RLS) filters rows per role or session automatically, which makes it a strong tool for multi-tenant applications:
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY; -- apply to the table owner too
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id')::uuid) -- rows visible / updatable
WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid); -- rows insertable / updated-to
-- The application sets the tenant per transaction (SET LOCAL resets at commit: safe with poolers in transaction mode)
BEGIN;
SET LOCAL app.tenant_id = '0190f6c2-…';
SELECT * FROM orders WHERE status = 'PAID'; -- implicitly AND tenant_id = …
COMMIT;
RLS turns "every query must remember WHERE tenant_id = ?" (the cross-tenant data leak waiting to happen, Vol. 3 ch. 50's BOLA problem) into a database guarantee. Caveats: policy predicates must be indexable (put tenant_id first in indexes), roles with BYPASSRLS and superusers skip policies, and leaky functions (LEAKPROOF) and views need care. SQL Server has a similar feature (security predicates), and Oracle has Virtual Private Database. MySQL has no native RLS.
Authentication (pg_hba.conf decides which hosts, users and databases use which method):
scram-sha-256: the password default since PostgreSQL 14.md5is deprecated as of 18 and will be removed.- Certificate (mTLS client certificates).
- LDAP / GSSAPI (Kerberos) / RADIUS.
- OAuth 2.0 (new in 18): the
oauthmethod lets clients authenticate with tokens from an identity provider through a validator module. That enables SSO-style database access without static passwords. - Cloud IAM authentication (AWS RDS IAM, GCP Cloud SQL IAM, Azure Entra ID): short-lived tokens instead of passwords.
Always require TLS for remote connections (hostssl lines, sslmode=verify-full in clients).
Extensions
PostgreSQL's extension system adds types, functions, operators, index methods and even background workers, without forking the database. It's one of PostgreSQL's biggest strengths:
| Extension | Adds |
|---|---|
pg_stat_statements |
Per-query statistics (calls, total and mean time, rows, buffer hits). The first tool for finding slow queries (chapter 60) |
pgcrypto |
Hashing, encryption functions |
pg_trgm |
Trigram similarity, fast LIKE '%x%' and ILIKE with GIN/GiST indexes, fuzzy search |
btree_gist, btree_gin |
B-tree-like operators in GiST/GIN (used for exclusion constraints) |
citext |
Case-insensitive text |
hstore, ltree |
Key/value pairs, hierarchical paths |
| PostGIS | Geospatial types, indexes and thousands of functions: the reference GIS database |
| pgvector | Vector type + HNSW/IVFFlat indexes for embeddings and semantic search (chapter 63) |
| TimescaleDB | Time-series hypertables, compression, continuous aggregates |
| Citus | Distributed (sharded) PostgreSQL (chapter 61) |
pg_partman |
Partition maintenance automation |
postgres_fdw, file_fdw, others |
Foreign data wrappers: query other databases and files as tables |
pg_cron |
Scheduled jobs inside the database |
auto_explain, pg_hint_plan, pg_repack, pgaudit, hypopg |
Plan logging, hints, online table rebuilds, audit logging, hypothetical indexes |
CREATE EXTENSION IF NOT EXISTS pg_stat_statements; -- also needs shared_preload_libraries = 'pg_stat_statements'
SELECT * FROM pg_available_extensions ORDER BY name;
Managed services allow-list extensions. Check what your provider supports before designing around one.
The type system
PostgreSQL's types (chapter 55 covered choosing them) are extensible: you can define composite types, enums, domains, ranges and base types (in C). Highlights:
- Ranges and multiranges (
int4range,tstzrange,daterange, andtstzmultirangesince 14) with operators for overlap&&, containment@>and adjacency-|-, plus GiST indexing. They model validity periods, bookings and pricing windows correctly, including half-open bounds[start, end). - Network types (
inet,cidr,macaddr) with containment operators. jsonb, arrays,tsvector, geometric types,uuid,interval,money(avoid it),bytea,xml.- Large values are stored out of line with TOAST (The Oversized-Attribute Storage Technique): values over about 2 KB are compressed (pglz or lz4) and/or moved to a side table, so rows stay small. Reading a TOASTed column costs extra I/O, so avoid
SELECT *when wide columns aren't needed.
Queries and plans
The query planner
Every SQL statement goes through parse → analyse/rewrite (views, rules) → plan → execute. The planner (optimiser) enumerates candidate plans (scan methods per table, join orders, join algorithms, sort or hash strategies) and picks the cheapest by its cost model:
- Costs are abstract units built from
seq_page_cost(1.0),random_page_cost(4.0 by default; lower it to about 1.1–1.5 on SSDs),cpu_tuple_costand similar. - Costs depend on cardinality estimates (how many rows each step produces), which come from statistics gathered by
ANALYZE: per-column histograms, most-common values, null fraction, number of distinct values and correlation. - Bad estimates are the root of most bad plans. If the planner thinks a filter returns 10 rows when it returns 1 million, it picks a nested loop that runs forever.
- For many joins (more than
geqo_threshold, 12 tables by default), the genetic query optimiser searches heuristically instead of exhaustively. - Extended statistics (
CREATE STATISTICS) capture correlations between columns (dependencies, n-distinct, MCV lists), so estimates forWHERE city = 'Pune' AND state = 'MH'aren't multiplied as if the columns were independent.
PostgreSQL deliberately has no query hints in core (the pg_hint_plan extension adds them). The philosophy is to fix statistics, schema or the query, not to pin plans. Oracle and SQL Server support hints and plan pinning (SQL plan baselines, Query Store forced plans), and MySQL has optimiser hints.
EXPLAIN and EXPLAIN ANALYZE
EXPLAIN shows the chosen plan with estimates. EXPLAIN ANALYZE runs the query and adds actual times and row counts, so wrap writes in a transaction you roll back:
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, FORMAT TEXT) -- BUFFERS is included by default with ANALYZE in PG 18
SELECT c.email, count(*) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= now() - interval '7 days'
GROUP BY c.email
ORDER BY orders DESC
LIMIT 10;
Limit (cost=4892.31..4892.34 rows=10 width=40) (actual time=38.912..38.917 rows=10 loops=1)
Buffers: shared hit=2817 read=412
-> Sort (cost=4892.31..4904.81 rows=5000 width=40) (actual time=38.910..38.913 rows=10 loops=1)
Sort Key: (count(*)) DESC
Sort Method: top-N heapsort Memory: 26kB
-> HashAggregate (cost=4709.27..4759.27 rows=5000 width=40) (actual time=36.201..37.540 rows=4821 loops=1)
Group Key: c.email
-> Hash Join (cost=1540.00..4609.27 rows=20000 width=32) (actual time=9.811..29.004 rows=19422 loops=1)
Hash Cond: (o.customer_id = c.id)
-> Index Scan using orders_created_at_idx on orders o (cost=0.43..2810.43 rows=20000 width=8)
(actual time=0.031..12.880 rows=19422 loops=1)
Index Cond: (created_at >= (now() - '7 days'::interval))
-> Hash (cost=915.00..915.00 rows=50000 width=40) (actual time=9.640..9.641 rows=50000 loops=1)
Buckets: 65536 Batches: 1 Memory Usage: 4024kB
-> Seq Scan on customers c (cost=0.00..915.00 rows=50000 width=40) (actual …)
Planning Time: 0.412 ms
Execution Time: 39.102 ms
How to read it:
- It's a tree. Read from the most indented nodes (executed first, feeding their parents) outwards and up.
cost=startup..total(planner units, estimated) versusactual time=first..lastin ms per loop. Multiply byloopsfor the total.rowsestimated versus actual: big mismatches (10× or more) point to stale or insufficient statistics, correlated columns, or functions the planner can't see through. This is the first thing to check.Buffers: shared hit(from cache) /read(from disk or OS cache): the real I/O cost.- Watch for
Rows Removed by Filter(a scan read many rows to keep few: index candidate),Sort Method: external merge Disk(spilled:work_memtoo small or too many rows),Batches > 1in hashes (spilled), and nested loops with largeloopsover inner sequential scans.
Tools: explain.depesz.com, explain.dalibo.com (PEV2) and pgMustard visualise plans. auto_explain logs plans of slow queries automatically. Chapter 60 goes deep on plan nodes and optimisation.
Other engines: MySQL EXPLAIN ANALYZE (8.0.18+, tree format) and EXPLAIN FORMAT=JSON; SQL Server actual execution plans (SSMS, SET STATISTICS IO, TIME ON) and Query Store; Oracle EXPLAIN PLAN, DBMS_XPLAN.DISPLAY_CURSOR with ALLSTATS LAST, and SQL Monitor.
MVCC and maintenance
MVCC, VACUUM and ANALYZE
PostgreSQL implements MVCC (multi-version concurrency control, chapter 59) by keeping multiple versions of a row in the table itself:
- An
UPDATEdoesn't overwrite in place. It marks the old tuple dead (by setting itsxmax) and inserts a new version (with a newxmin). ADELETEjust setsxmax. - Each transaction sees the versions visible to its snapshot (based on
xmin/xmaxand the commit status in the commit log). Readers never block writers, and writers never block readers. - The cost is that dead tuples accumulate (bloat): table and index pages fill with versions nobody can see any more.
VACUUM reclaims them:
| Operation | Does | Locks |
|---|---|---|
VACUUM |
Marks dead tuples' space reusable (free space map), updates the visibility map (enables index-only scans), and freezes old tuples | Light lock: reads and writes continue |
VACUUM FULL |
Rewrites the table compactly, returning space to the OS | ACCESS EXCLUSIVE: blocks everything. Avoid on live tables; use pg_repack or pg_squeeze for online rebuilds |
ANALYZE |
Samples rows and updates planner statistics | Light |
VACUUM (ANALYZE) |
Both | Light |
Autovacuum runs both automatically: workers wake up and process tables whose dead-tuple count exceeds autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor × reltuples (50 + 20% by default). The defaults suit small tables poorly-to-fine and large tables badly: for a 500M-row table, 20% means waiting for 100M dead tuples. Tune per table:
ALTER TABLE orders SET (
autovacuum_vacuum_scale_factor = 0.01, -- vacuum after ~1% churn
autovacuum_analyze_scale_factor = 0.005,
autovacuum_vacuum_insert_scale_factor = 0.05 -- insert-only tables also need vacuum (visibility map, freezing; PG 13+)
);
-- Global: raise autovacuum_max_workers, autovacuum_vacuum_cost_limit (vacuum throttling) on modern hardware
What blocks VACUUM from cleaning up:
- Long-running transactions (or idle-in-transaction sessions): dead tuples newer than the oldest active snapshot can't be removed, because that transaction might still need them. One forgotten
BEGINin a psql session, or a stuck application connection, can bloat a whole database. Setidle_in_transaction_session_timeoutand monitorpg_stat_activity. - Replication slots that aren't consumed (they also hold WAL), and hot standby feedback from replicas running long queries.
- Prepared transactions left open (two-phase commit).
Transaction ID wraparound
PostgreSQL transaction IDs are 32-bit (about 4 billion, and comparisons are modular with a 2-billion horizon). Old tuples must be frozen (marked as visible to everyone) before their xmin falls too far behind. Otherwise, once the counter wraps, old rows would appear to be "in the future" and become invisible. To prevent data loss, PostgreSQL forces anti-wraparound autovacuums, and as a last resort stops accepting writes until a vacuum completes. That has caused well-known outages at high-write-rate companies.
-- Monitor: how close is each database (and table) to the freeze limit?
SELECT datname, age(datfrozenxid) AS xid_age,
round(100.0 * age(datfrozenxid) / 2000000000, 1) AS pct_to_wraparound
FROM pg_database ORDER BY xid_age DESC;
-- Alert well before ~50%; investigate long transactions, stuck slots, or vacuum falling behind.
PostgreSQL 13–18 made freezing more efficient (insert-triggered vacuums, eager freezing in 18). 64-bit XIDs remain a long-running discussion, and some forks have them.
How other engines handle versions: MySQL InnoDB and Oracle store old versions in an undo log (rollback segments). The table holds the newest version, and readers reconstruct older ones from undo. There's no table bloat from old versions, but long transactions grow the undo history (InnoDB's "history list length", purged by purge threads) and can make reads slow. Oracle has the famous ORA-01555 snapshot too old. SQL Server uses locking by default, and with snapshot isolation or RCSI it keeps versions in tempdb (or in-row with Accelerated Database Recovery). Each design moves the cost of versioning somewhere different.
Durability and replication
The write-ahead log
The WAL (write-ahead log) is the heart of durability and replication (chapter 58 covers the mechanics):
- A change is first recorded in the WAL (an append-only sequence of records in 16 MB segment files in
pg_wal/). - At commit, the WAL is flushed to disk (
fsync). That's what makes the commit durable. - The modified data pages stay in
shared_buffersand are written to data files later, by the background writer or checkpointer. - After a crash, recovery replays the WAL from the last checkpoint to bring the data files up to date.
Settings worth knowing: wal_level (replica by default; logical for logical decoding), synchronous_commit (off trades the last few hundred milliseconds of commits on a crash for latency, with no corruption, so it's reasonable for some workloads), full_page_writes (protects against torn pages), max_wal_size and checkpoint_timeout (checkpoint frequency versus recovery time), and wal_compression. Never turn off fsync in production: that risks corruption, not just data loss.
The WAL also powers point-in-time recovery (archived WAL replayed on top of a base backup to any moment, chapter 64), physical replication and logical decoding.
Physical (streaming) replication
Streaming replication ships WAL records from the primary to standbys, which replay them continuously. The result is a byte-identical copy of the whole cluster:
primary ──WAL stream──▶ standby 1 (hot standby: read-only queries)
──WAL stream──▶ standby 2 (in another zone)
- Asynchronous (the default): the primary commits without waiting for standbys. It's fast, but a failover can lose the last few transactions (non-zero RPO) and standbys lag (chapter 61).
- Synchronous (
synchronous_standby_names = 'ANY 1 (s1, s2)'): a commit waits until at least one standby confirms. Withsynchronous_commit = on, that means flushed to the standby's WAL; withremote_apply, applied and visible to reads there. It gives zero data loss at the cost of commit latency (a network round trip) and availability risk (writes stall if no synchronous standby is available). - Hot standby: standbys serve read-only queries. Conflicts between replay and long queries are resolved by cancelling queries (
max_standby_streaming_delay) or withhot_standby_feedback(which causes primary bloat). - Replication slots make the primary retain WAL until each consumer has received it. A dead consumer then fills the disk unless
max_slot_wal_keep_sizecaps it (and PostgreSQL 18 can invalidate idle slots after a timeout). - Failover: PostgreSQL itself doesn't decide when to promote a standby. Use Patroni (the de facto HA manager, with etcd/Consul/Kubernetes for leader election), managed services (RDS Multi-AZ, Aurora, Cloud SQL HA, Azure Flexible Server), CloudNativePG on Kubernetes, or pg_auto_failover. Fencing the old primary (preventing split brain) is the hard part (chapter 61).
Logical replication
Logical replication decodes the WAL into row-level changes (insert, update and delete per table) and applies them to subscribers through a publish/subscribe model:
-- On the source (wal_level = logical)
CREATE PUBLICATION orders_pub FOR TABLE orders, order_lines WHERE (status <> 'DRAFT'); -- row filters (PG 15+)
-- On the target
CREATE SUBSCRIPTION orders_sub
CONNECTION 'host=source dbname=shop user=replicator sslmode=verify-full'
PUBLICATION orders_pub;
| Physical (streaming) | Logical | |
|---|---|---|
| Granularity | Whole cluster, byte-for-byte | Selected tables (and columns/rows) |
| Target | Read-only standby of the same major version | A writable database, possibly a different major version or schema |
| Uses | HA, read replicas, DR | Zero-downtime major version upgrades, consolidating or splitting databases, replicating subsets, feeding CDC |
| Doesn't replicate | — | DDL (schema changes must be applied separately), sequences (until recent improvements), large objects |
Change data capture (CDC): tools like Debezium consume logical decoding (the pgoutput plugin) to stream changes into Kafka. That's the basis of the outbox pattern's CDC relay (Vol. 3 ch. 51) and of syncing search indexes and caches (chapters 53 and 63). PostgreSQL 17 added failover slots (logical replication slots synchronised to standbys, so CDC survives failover) and pg_createsubscriber.
MySQL comparison: replication is based on the binary log (row-based binlog, GTIDs for position tracking), which is logical by nature. Group Replication and InnoDB Cluster provide HA, and orchestrator/MySQL Router or managed services handle failover. SQL Server has Always On availability groups. Oracle has Data Guard (physical) and GoldenGate (logical).
Scaling a single table
Partitioning
Declarative partitioning (PostgreSQL 10+, much improved since) splits one logical table into partitions by a key:
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY,
tenant_id uuid NOT NULL,
created_at timestamptz NOT NULL,
payload jsonb NOT NULL,
PRIMARY KEY (id, created_at) -- unique constraints must include the partition key
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_10 PARTITION OF events FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
CREATE TABLE events_2026_11 PARTITION OF events FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE TABLE events_default PARTITION OF events DEFAULT; -- catches rows with no matching partition
CREATE INDEX ON events (tenant_id, created_at); -- created on every partition
-- Retention: drop a whole month instantly (no DELETE, no bloat, no vacuum)
ALTER TABLE events DETACH PARTITION events_2026_04 CONCURRENTLY;
DROP TABLE events_2026_04;
Strategies: RANGE (time: the most common), LIST (region, tenant tier), HASH (spread evenly by modulus), and sub-partitioning.
Benefits:
- Partition pruning: queries filtering on the key skip irrelevant partitions, at plan time and at execution time.
- Cheap retention:
DROP/DETACHa partition instead ofDELETEmillions of rows. - Smaller indexes per partition and per-partition maintenance (vacuum, reindex).
- Old partitions can live on cheaper storage (tablespaces) or be archived.
Costs and pitfalls:
- Queries without the partition key touch every partition.
- Primary and unique keys must include the partition key.
- Too many partitions (thousands) increase planning time and memory.
- Creating future partitions must be automated (
pg_partman,pg_cron, or app jobs). A missing partition means failed inserts, or rows landing in the default partition. - PostgreSQL 19 was in beta in 2026 with improved partition
MERGE/SPLITsupport.
Partitioning splits data within one server. Sharding spreads it across servers (chapter 61: Citus, application-level sharding, distributed SQL). MySQL supports partitioning too (with stricter rules: all unique keys must include the partition columns, and there are no foreign keys on partitioned tables). SQL Server and Oracle have mature partitioning (Oracle's is an extra-cost option).
What's new
Modern PostgreSQL: versions 17, 18 and 19
PostgreSQL ships one major version per year (usually September or October), each supported for 5 years. Major upgrades need pg_upgrade (fast with --link or 18's --swap; PostgreSQL 18 now preserves planner statistics across upgrades), dump/restore, or logical replication for near-zero downtime.
PostgreSQL 17 (September 2024): incremental backups (pg_basebackup --incremental + pg_combinebackup), a vacuum memory overhaul (much less memory, faster), JSON_TABLE and SQL/JSON constructors, MERGE … RETURNING, failover slots for logical replication, COPY … ON_ERROR ignore, faster B-tree IN (…) lookups, and the pg_maintain predefined role.
PostgreSQL 18 (September 25, 2025):
| Feature | What it means |
|---|---|
Asynchronous I/O (io_method = worker by default, or io_uring on Linux, or sync) |
PostgreSQL can issue many reads concurrently instead of one synchronous read at a time. Sequential scans, bitmap heap scans and vacuum benefit (up to 2–3× in I/O-bound cases, especially on cloud block storage with high latency). Tune effective_io_concurrency/io_workers |
| B-tree skip scan | A multicolumn index on (tenant_id, created_at) can now serve WHERE created_at > … without a condition on tenant_id, by skipping through the distinct leading values. It's useful when the leading column has few distinct values, and reduces the need for extra indexes |
uuidv7() |
Native time-ordered UUID generation (chapter 55) |
| Virtual generated columns (now the default kind) | Computed at read time, no storage (chapter 56) |
| Temporal constraints | PRIMARY KEY (room_id, during WITHOUT OVERLAPS), UNIQUE … WITHOUT OVERLAPS, and FOREIGN KEY (…, PERIOD valid_at) REFERENCES …: SQL:2011-style validity periods enforced natively over range types |
RETURNING OLD/NEW |
Before and after values from INSERT, UPDATE, DELETE and MERGE |
| OAuth authentication | The oauth auth method with validator modules. md5 deprecated |
Data checksums on by default in initdb |
Detects storage corruption |
EXPLAIN ANALYZE shows buffers by default, more index and memory detail |
Better diagnostics |
| Upgrades | Planner statistics preserved; pg_upgrade --swap, parallel checks |
| Others | Parallel GIN index builds, better OR-clause index use, PG_UNICODE_FAST collation and casefold(), wire protocol 3.2, logical replication conflict reporting |
-- PostgreSQL 18 temporal constraints: no overlapping prices per product, and FKs that respect validity periods
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE product_prices (
product_id bigint NOT NULL,
valid daterange NOT NULL,
price_cents bigint NOT NULL,
PRIMARY KEY (product_id, valid WITHOUT OVERLAPS)
);
CREATE TABLE order_lines_t (
product_id bigint NOT NULL,
sold_on daterange NOT NULL,
FOREIGN KEY (product_id, PERIOD sold_on) REFERENCES product_prices (product_id, PERIOD valid)
);
PostgreSQL 19 is at the release-candidate stage as this book is written (October 2026); general availability was moved to 19 November 2026 to allow more bug fixing. Its headline features are a built-in REPACK command (with a CONCURRENTLY option) that rewrites a bloated table without the long exclusive lock of VACUUM FULL or CLUSTER, parallel index vacuuming in autovacuum with a pg_stat_autovacuum_scores view showing how autovacuum prioritises tables, an IO option for EXPLAIN showing asynchronous I/O per plan node, ON CONFLICT DO SELECT, WAIT FOR LSN (read-your-writes on replicas), IGNORE NULLS for window functions such as lag and first_value, and new statistics views (pg_stat_lock, pg_stat_recovery). Several features announced during development (SQL/PGQ property graphs, partition MERGE/SPLIT, temporal UPDATE … FOR PORTION OF) were pulled before release. Check the final release notes before planning around any of them.
Operating PostgreSQL: a short checklist
- Observability:
pg_stat_statements;pg_stat_activity(long, idle-in-transaction and blocked sessions;wait_event);pg_stat_user_tables(seq scans, dead tuples, last autovacuum);pg_stat_io(16+); replication lag (pg_stat_replication); and an exporter (postgres_exporter) with dashboards. - Timeouts:
statement_timeout(per role or app),lock_timeout(especially for migrations),idle_in_transaction_session_timeout. - Safe migrations:
CREATE INDEX CONCURRENTLY,ADD CONSTRAINT … NOT VALID+VALIDATE, a shortlock_timeoutwith retries for DDL (a DDL waiting for a lock blocks everyone queued behind it), and avoiding table rewrites (changing a column type usually rewrites the table). - Backups and PITR tested regularly (chapter 64).
- Connection pooling, sane
work_mem, autovacuum tuning for big tables, andrandom_page_costfor SSDs. - Upgrade cadence: stay on a supported major version, and apply minor releases promptly (they're bug and security fixes and replace only binaries).
Lab: MVCC, vacuum, durability and replication, observed
PostgreSQL 16 on a 2-core machine, driven from Python and pgbench; experiment 5 adds a streaming replica on the same machine, created with pg_basebackup -R -X stream -c fast. Each experiment is a production problem in miniature.
Experiment 1: bloat
A 200,000-row table with autovacuum switched off for it, every row updated four times:
200,000 rows: 27 MB
after updating every row 4 times (no vacuum): 135 MB
after VACUUM: 135 MB (space reusable, not returned)
4 more full updates after VACUUM: 135 MB (reused the freed space)
after VACUUM FULL (rewrites the table, exclusive lock): 27 MB
Each full update wrote 200,000 new row versions and left 200,000 dead ones, so the table grew to five times its live size. Plain VACUUM didn't shrink the file; it marked the dead space reusable, and the next four updates fit into it with no growth. That's the steady state autovacuum aims for: a table a little larger than its live data, recycling space. VACUUM FULL (or pg_repack, or PostgreSQL 19's REPACK CONCURRENTLY) rewrites the table compactly but, in its plain form, takes an exclusive lock for the duration. Bloat that grows without bound means autovacuum isn't keeping up: tune it per table (autovacuum_vacuum_scale_factor, cost limits) rather than running VACUUM FULL on a schedule.
Experiment 2: a long transaction blocks cleanup
A connection opens a REPEATABLE READ transaction, reads the table, and stays open while another session updates every row:
VACUUM while a 'REPEATABLE READ' transaction is open: removed 0, dead but not yet removable 200000
after that transaction ends: removed 200000
The open snapshot might still need the old versions, so VACUUM wasn't allowed to remove any of them. In production the culprits are a forgotten transaction in a client tool, an application that opens a transaction and then calls a slow external service, an idle in transaction connection leaked by a bug, a long analytical query, or an abandoned replication slot: one of them can make every table in the database bloat for hours. Monitor pg_stat_activity for old xact_start and state = 'idle in transaction', and set idle_in_transaction_session_timeout and statement timeouts.
Experiment 3: HOT updates
30,000 updates of a qty column, with and without an index on it, and with the default fill factor (100) or 70:
fillfactor 100, qty (not indexed): HOT updates 93 of 30,000
fillfactor 100, qty (indexed) : HOT updates 0 of 30,000
fillfactor 70, qty (not indexed): HOT updates 30,000 of 30,000
fillfactor 70, qty (indexed) : HOT updates 0 of 30,000
A heap-only tuple (HOT) update writes the new version on the same page and skips every index, because the indexes still point at the old slot, which redirects to the new one. It needs two things: no indexed column changed, and free space on the page. With full pages (fill factor 100) almost no update could stay on its page; leaving 30% free made all of them HOT. Indexing qty made HOT impossible regardless, so every update also inserted a new entry into every index on the table. For tables with frequent updates, avoid indexing frequently-updated columns you don't query by, and consider a lower fill factor; watch n_tup_hot_upd in pg_stat_user_tables.
Experiment 4: commit durability and connection cost
pgbench's standard read-write transaction (scale 10), 4 clients for 15 seconds, and its read-only variant:
synchronous_commit=on : latency average 1.055 ms | tps 3,790
synchronous_commit=off: latency average 0.593 ms | tps 6,749
new connection per transaction (-C): average connection time 3.999 ms | tps 304
read-only, persistent connections: tps 41,303
read-only, new connection each: tps 436 (average connection time 4.490 ms)
Waiting for the WAL flush at each commit cost about 0.46 ms per transaction here (on a fast local disk; network storage can take several milliseconds). synchronous_commit=off returns before the flush: the risk is losing the last few hundred milliseconds of commits in a crash, but not corruption. It's a reasonable per-transaction choice for data you can recreate (analytics events, view counts), never for payments. Opening a new connection per transaction cut read-only throughput by 95×: connection setup (a process fork, authentication, catalog caches warming) dwarfed the queries. Use an application pool (HikariCP, chapter 49 of Volume 3) and, for many application instances, a server-side pooler like PgBouncer.
Experiment 5: an asynchronous replica
update on primary, read immediately from replica, 200 times: stale reads 199 | time until visible: median 0.53 ms, max 4.04 ms
writing to the replica: cannot execute UPDATE in a read-only transaction
1M-row insert (124 MB of WAL) took 3225 ms on the primary; replica caught up 1707 ms after the commit
The replica applies the primary's WAL stream continuously, and here was rarely more than a few milliseconds behind, yet 199 of 200 reads made immediately after a write saw the old value: "a few milliseconds" is longer than the gap between an application's write and its next read. A bulk insert produced 124 MB of WAL, and the replica finished applying it 1.7 seconds after the primary committed; on a busy system with a slower network or replica, lag of seconds to minutes is normal. Applications that read from replicas need read-your-writes handling: route a user's reads to the primary for a short time after they write, wait for the replica to reach the write's LSN (PostgreSQL 19's WAIT FOR LSN), or use synchronous replication (synchronous_commit = remote_apply) where the cost is acceptable. Replicas are read-only, as the error shows; chapter 61 covers failover.
Try it yourself
- Re-enable autovacuum on experiment 1's table with default settings and update it continuously for five minutes. What size does it settle at? Then set
autovacuum_vacuum_scale_factor = 0.01. - Leave a session
idle in transactionfor ten minutes while running pgbench in another, and watchn_dead_tupgrow inpg_stat_user_tables. - Use
pg_walinspectto list the WAL records generated by oneUPDATE, with and without an index on the updated column. - Promote the replica (
pg_ctl promote) while pgbench writes to the primary, and count how many committed transactions the promoted replica is missing.
Revision sheet: PostgreSQL in depth
Key ideas
- Architecture: postmaster, one backend process per connection, background processes (checkpointer, background writer, WAL writer, autovacuum, WAL sender/receiver), shared buffers plus the OS page cache, per-backend
work_mem. - Logical layout: cluster → databases → schemas (
search_path) → tables; roles with privileges and default privileges; row-level security policies; extensions. - Planner: statistics from
ANALYZE(pg_stats: null fraction, distinct values, most common values, histograms, correlation), extended statistics, cost parameters;EXPLAIN (ANALYZE, BUFFERS). - MVCC: tuple versions with
xmin/xmax, snapshots, dead tuples; HOT updates and fill factor; VACUUM (dead space, visibility map, freezing), autovacuum tuning; transaction ID wraparound and anti-wraparound vacuums. - WAL: write-ahead logging, checkpoints (
checkpoint_timeout,max_wal_size), full-page writes,synchronous_commitlevels, crash recovery. - Replication: physical streaming (async, sync,
remote_apply), replication slots, hot standby conflicts; logical replication (publications, subscriptions) for upgrades and selective sync. - Partitioning: declarative range/list/hash, partition pruning, detaching for retention.
- Versions: 17 (incremental backup, vacuum memory), 18 (async I/O, skip scan,
uuidv7(), temporal constraints, OAuth, checksums default), 19 (in release candidate, GA planned 19 November 2026:REPACK, parallel autovacuum index vacuuming,EXPLAIN (IO),WAIT FOR LSN).
Numbers to remember
- Lab: four full updates grew a table from 27 MB to 135 MB; an open snapshot left 200,000 dead tuples unremovable; fill factor 70 made 100% of non-indexed updates HOT;
synchronous_commit=offgave 1.8× TPS; a new connection per transaction cut read throughput 95×; an async replica returned stale data for 199 of 200 immediate reads. - Defaults:
shared_buffers128 MB,max_connections100, page 8 KB,autovacuum_vacuum_scale_factor0.2.
Pitfalls
- Long-running or idle-in-transaction sessions; abandoned replication slots (WAL fills the disk).
- Too many direct connections; no pooler.
- Default autovacuum settings on large, hot tables;
VACUUM FULLas routine maintenance. - Indexing frequently updated columns needlessly; ignoring HOT ratios.
- Reading from replicas without read-your-writes handling.
- Ignoring wraparound warnings; skipping
ANALYZEafter bulk loads.
Glossary
- Backend: the server process serving one connection.
- Tuple / row version: one physical version of a row.
- Dead tuple: a version no snapshot can see any more.
- HOT update: an update that stays on the same page and skips index maintenance.
- LSN: log sequence number, a position in the WAL.
- Replication slot: a server-side record that retains WAL until a consumer has received it.