users table in 2026CREATE TABLE users (
id bigint PRIMARY KEY,
profile jsonb );
-- row 1, version 2, after a year of features: 688 bytes
{"id": 1, "name": "Jane Smith-Rivera", "email": "jane@example.com",
"spouse": {"id": 2, "name": "Mike Rivera"},
"addresses": [{"type": "home", "line1": "14 Bryant Park Pl",
"city": "New York", "zip": "10018"},
{"type": "work", "line1": "350 Fifth Ave",
"city": "New York", "zip": "10118"}],
"preferences": {"theme": "dark", "language": "en-US",
"notifications": {"email": true, "sms": false, "push": true}},
"login_history": ["2026-11-01T08:12:00Z", "2026-11-03T18:40:11Z",
"2026-11-09T07:55:43Z", "2026-11-14T21:03:27Z",
"2026-11-17T06:48:09Z"],
"updated_at": "2026-11-18T18:30:00Z"}
profile || '{"theme": "light"}' rewrites all 688 bytes, not the 17 you changedlogin_history: 250 KB of dead versions per user per yearusers row never changes again-- before: one login rewrites the whole profile, 9,296 bytes by day 365
UPDATE users
SET profile = jsonb_set(profile, '{login_history}',
profile->'login_history' || to_jsonb(now()))
WHERE id = 1;
-- after: a table. INSERT one 40-byte row, UPDATE nothing
CREATE TABLE login_history (
user_id bigint NOT NULL REFERENCES users (id),
logged_in_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, logged_in_at)
);
INSERT INTO login_history (user_id) VALUES (1);
-- same size every time: replace last_login, keep no history in the document
UPDATE users
SET profile = jsonb_set(profile, '{last_login}', to_jsonb(now()))
WHERE id = 1;
cur.execute("SELECT * FROM orders WHERE id = %s FOR UPDATE", (oid,))
resp = requests.post("https://api.payments-provider.com/v1/charges", # HTTP to a third party
json={"card": card, "amount": amount})
cur.execute("UPDATE orders SET status = 'paid' WHERE id = %s", (oid,))
conn.commit()
* in psycopg2/3. JDBC, others differ here
INFO: finished vacuuming "app.public.orders": index scans: 0
tuples: 0 removed, 1483112 remain, 612004 are dead but not yet removable
removable cutoff: 982144, which was 61930 XIDs old when operation ended
"dead but not yet removable" with an old cutoff: someone holds the horizon.
| Holder | What it pins | Where to look |
|---|---|---|
| Report running 40 minutes * | snapshot (xmin) |
pg_stat_activity |
| Nightly batch in one transaction | xid and snapshot | pg_stat_activity |
pg_dump at noon |
snapshot | pg_stat_activity |
Physical slot with hot_standby_feedback |
xmin for every table |
pg_replication_slots |
| Logical slot nobody consumes | catalog_xmin; WAL is retained |
pg_replication_slots |
| Prepared transaction nobody finished | xmin, indefinitely |
pg_prepared_xacts |
* A read-only transaction holds one too.
cur.execute("SELECT * FROM orders WHERE id = %s FOR UPDATE", (oid,))
resp = requests.post("https://api.payments-provider.com/v1/charges", # HTTP to a third party
json={"card": card, "amount": amount}, timeout=30) # ? to 30 seconds, sometimes never
cur.execute("UPDATE orders SET status = 'paid' WHERE id = %s", (oid,))
conn.commit()
idle in transaction. At 300 commits a second, 9,000 can pile up* in psycopg2/3. JDBC, others differ here
-- backends holding a snapshot or an xid, oldest first
SELECT pid, datname, application_name, state,
age(backend_xmin) AS xmin_age,
age(backend_xid) AS xid_age,
now() - xact_start AS xact_time
FROM pg_stat_activity
WHERE backend_type = 'client backend'
AND (backend_xmin IS NOT NULL OR backend_xid IS NOT NULL)
ORDER BY greatest(age(backend_xmin), age(backend_xid)) DESC;
xmin_age is how many transactions committed since this one started.xact_time 10s * 500 xact/sec = 5,000 commitspg_replication_slots, pg_prepared_xacts, both in the demo fileFOR UPDATE plus the charge was never one transaction. Postgres cannot roll back an HTTP callUPDATE# borrow a connection. The pool was built with autocommit on
conn = pool.getconn()
# the charge runs with no transaction open
resp = requests.post("https://api.payments-provider.com/v1/charges",
headers={"Idempotency-Key": f"order-{oid}"},
data={"amount": amount, "currency": "usd",
"customer": cust, "confirm": "true"}, timeout=30)
# one UPDATE. The status guard replaces the row lock
cur.execute("UPDATE orders SET status = 'paid' "
"WHERE id = %s AND status = 'pending'", (oid,))
# the only transaction. SQL only, milliseconds
with conn.transaction():
cur.execute("INSERT INTO ledger ...")
cur.execute("UPDATE balances ...")
ALTER ROLE app_rw SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE app_rw SET transaction_timeout = '5min'; -- PG 17+: the whole transaction, idle or not
| alerting today | oldest idle-in-transaction age > 30 s; transactions open > 60 s | yes |
| xid age in transactions, the measure that matters; replication slots, prepared transactions | no | |
| verify | rerun the detection query; xmin_age falls back to the hundreds |
Replication lag and a WAL spike at 02:00
-- the nightly retention job
DELETE FROM events WHERE created_at < now() - interval '90 days';
events: 2,000,000,000 rows, 90 days retention, 6 indexes
| daily rows removed | ~22,000,000 | one day's worth |
| dead tuples in the heap | 22,000,000 | DELETE only marks them |
| WAL at delete time | 22,000,000 | also replayed on every replica |
| transaction | hours | holding an xid and a snapshot the whole time (Mistake #2) |
| vacuum | WAL traffic (heap + all indexes) |
-- which statement wrote last night's WAL spike?
SELECT queryid, calls, rows, wal_bytes, total_exec_time
FROM pg_stat_statements
ORDER BY wal_bytes DESC
LIMIT 5;
-- dead rows by table
SELECT relname, n_dead_tup, n_live_tup, last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 5;
wal_bytes over 1 GB for one statement with rows in the millionsn_dead_tup above a fifth of n_live_tup and last_autovacuum hours old (dead rows).-- events already exists. Build the partitioned table next to it; the key must include created_at
CREATE TABLE events_p (LIKE events INCLUDING DEFAULTS, PRIMARY KEY (id, created_at))
PARTITION BY RANGE (created_at);
CREATE TABLE events_p_2026_08 PARTITION OF events_p FOR VALUES FROM ('2026-08-01') TO ('2026-09-01');
-- one partition per month back to the retention edge, indexes on events_p; pg_partman keeps the calendar
INSERT INTO events_p SELECT * FROM events WHERE created_at >= '2026-08-01' AND created_at < '2026-09-01'; -- a month per batch
SET lock_timeout = '2s'; -- the swap is two renames
BEGIN; ALTER TABLE events RENAME TO events_old; ALTER TABLE events_p RENAME TO events; COMMIT;
-- from now on retention is a catalog change. PG 14+. not in a transaction block. waits for open transactions (Mistake #2)
ALTER TABLE events DETACH PARTITION events_p_2026_08 CONCURRENTLY;
DROP TABLE events_p_2026_08;
| rows removed | ~680,000,000, a month |
| dead tuples | 0 |
| WAL | catalog rows only |
| wall clock | milliseconds, once open transactions on events finish |
| alerting today | dead tuple ratio > 20% on large tables; replication lag | yes, hours later |
| the statement itself (WAL bytes per statement, rows deleted) | no | |
| verify | n_tup_del stays flat on the parent; the drop is a catalog change |
DELETE is one long-running transaction. Its xid pins the horizon for hoursDELETE empties stay allocated. Every INSERT and UPDATE walks a bigger indexMeasured on 1M rows. Extrapolated to 1B
| 1M rows, measured | 1B rows at 5,000 UPDATE/s | |
|---|---|---|
| heap + primary key on disk | 179 MB | 179 GB |
| seven int indexes on disk | 141 MB | 141 GB |
| page writes per UPDATE, primary key only | 2 | 10,000 per second |
| page writes per UPDATE, seven indexes | 9 | 45,000 per second |
| WAL per UPDATE, primary key only | 311 B | 134 GB per day |
| WAL per UPDATE, seven indexes | 855 B | 369 GB per day |
UPDATE takes 0.2 ms with 0 indexes or 7. Everything is in RAMUPDATE holds its connection through every one of those reads-- indexes with zero scans since the stats reset, largest first
SELECT s.relname, s.indexrelname, s.idx_scan, s.last_idx_scan, -- last_idx_scan: PG 16+
pg_relation_size(s.indexrelid) AS bytes
FROM pg_stat_user_indexes s
JOIN pg_index i USING (indexrelid)
WHERE s.idx_scan = 0
AND NOT i.indisunique
AND NOT i.indisprimary
ORDER BY pg_relation_size(s.indexrelid) DESC;
idx_scan = 0 with bytes over 100 MB: a write tax on every INSERT and non-HOT UPDATEstats_reset in pg_stat_database; a short window is not proofHOT: Only update the HEAP (Heap Only Tuples) if the new version fits on the same page and no indexed column change
UPDATE pgbench_accounts SET abalance = abalance + 1 WHERE aid = $1;
CREATE INDEX ON pgbench_accounts (abalance); -- second run only
no index on abalance |
one index on abalance |
|
|---|---|---|
| update | HOT update | every update changes abalance → no HOT |
| indexes | no index touched; old version pruned in place on the next visit | an index entry every time |
| dead tuples | stay flat, even with autovacuum off | every update leaves a dead tuple behind |
SELECT relname, n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd, -- n_tup_newpage_upd: PG 16+
n_dead_tup
FROM pg_stat_user_tables
WHERE n_tup_upd > 0
ORDER BY n_tup_upd DESC;
n_tup_hot_upd under half of n_tup_upd: an indexed column is updated, or the page is fullpg_get_indexdef() first, then DROP INDEX CONCURRENTLY| alerting today | unused index bytes (daily); invalid indexes (hourly) | yes |
| HOT ratio | no | |
| verify | hot_pct recovers on the next sample; the index is gone from pg_index |
Actually - it's efficiency
Thirty years of the same response, raise max_connections.
| Mistake | What it does to connections | The efficiency fix |
|---|---|---|
| connection storms | one per request, the CPU forks | Properly Sized pool |
| ignoring MVCC | every reader steps over the dead versions | a key that only grows gets its own table |
| long-running transactions | held for the whole wait | only SQL inside the transaction |
| bulk DELETE | one held for hours, every query slower | partition and DROP |
| unused indexes | every write holds longer, the pool grows | no index without a SELECT |
Make each transaction cheaper and the connection count follows
Scott Mead · scott@meads.us
Slides and the SQL from this talk will be posted: https://www.meetup.com/postgres-nyc/
Slides: Creative Commons Attribution License (CC BY 4.0). SQL and scripts: PostgreSQL License.
INFO: finished vacuuming "app.public.orders": index scans: 0
tuples: 0 removed, 1483112 remain, 612004 are dead but not yet removable
removable cutoff: 982144, which was 61930 XIDs old when operation ended
"dead but not yet removable" with an old cutoff: someone holds the horizon.
| Holder | What it pins | Where to look |
|---|---|---|
| Report running 40 minutes * | snapshot (xmin) |
pg_stat_activity |
| Nightly batch in one transaction | xid and snapshot | pg_stat_activity |
pg_dump at noon |
snapshot | pg_stat_activity |
Physical slot with hot_standby_feedback |
xmin for every table |
pg_replication_slots |
| Logical slot nobody consumes | catalog_xmin; WAL is retained |
pg_replication_slots |
| Prepared transaction nobody finished | xmin, indefinitely |
pg_prepared_xacts |
* A read-only transaction holds one too.
You see nothing, until one query holds a connection for hours.
statement_timeoutlock_timeoutidle_in_transaction_session_timeouttransaction_timeout (PG 17)idle_session_timeout (PG 14)All five default to 0: a connection can be held forever.
ALTER ROLE reporting SET statement_timeout = '15min';
SELECT rolname -- login roles with no statement_timeout override
FROM pg_roles r
WHERE rolcanlogin
AND NOT EXISTS (SELECT 1 FROM pg_db_role_setting s
WHERE s.setrole = r.oid AND s.setconfig::text LIKE '%statement_timeout%');
| alerting today | login roles with unlimited timeouts | no |
| verify | the query above returns no application roles |