PostgreSQL Operations Traps: Common Mistakes at Scale and Why Shutdown Takes Longer Than StartupThematic roundup · digest for November 26
Conceptual cinematic scene of a scheduled database shutdown with a timer and VACUUM indicator
Thematic roundup2 sections≈ 6 min

PostgreSQL Operations Traps: Common Mistakes at Scale and Why Shutdown Takes Longer Than Startup

On a laptop, PostgreSQL forgives almost anything: you run queries without a pool, wipe a table with a single DELETE, and everything finishes in milliseconds. Under real load, those same habits hit disk I/O and uptime: tables bloat, VACUUM stalls, and planned restarts drag on for minutes. Let's look at two major blind spots—common mistakes at scale and slow server shutdowns.

PostgreSQL Mistakes That Surface at Scale

Databricks engineer Scott Mead (22 years with PostgreSQL) compiled five systemic traps—numbered starting from zero—in his talk slides and SQL demo repo.

Mistake #0 is connection churn. Every new connection spawns a separate PostgreSQL process via fork(), allocating memory, authenticating, and warming a cold catalog cache. When a query takes 5 ms and connecting takes 2 ms (or 40 app servers hold 50 unpooled connections each), reconnect frequency crushes the database. Fix it with PgBouncer or a driver pool (psycopg 3, HikariCP, Go database/sql), and spot churn using the sessions counter in pg_stat_database (PG 14+) across two snapshots one minute apart.

Mistake #1 is ignoring MVCC. An UPDATE writes a new row version onto an 8192-byte page and marks the old one dead via xmax. Until VACUUM runs, readers step over dead tuples. If a freed 48-byte slot is smaller than a new 64-byte row, the Free Space Map can't reuse it, and the table bloats.

Mistake #2 is long idle in transaction sessions. The classic pattern: SELECT ... FOR UPDATE, a 2–30 second HTTP call to a payment API, then UPDATE and COMMIT. An open transaction holds row locks and pins the xmin horizon—the oldest active transaction boundary. Once pinned, VACUUM cannot clean dead rows newer than that boundary in any table across the database.

-- Stalled transactions holding back the xmin horizon
SELECT pid, usename, state,
  date_trunc('second', now() - xact_start) AS xact_age,
  date_trunc('second', now() - state_change) AS idle_for,
  greatest(age(backend_xid), age(backend_xmin)) AS horizon_age,
  left(query, 60) AS last_statement
FROM pg_stat_activity
WHERE state LIKE 'idle in transaction%'
ORDER BY xact_start;

-- Role-level guardrails (transaction_timeout added in PG 17)
ALTER ROLE app_rw SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE app_rw SET transaction_timeout = '5min';

Set these timeouts with ALTER ROLE rather than globally: migrations and reports can still finish, while your backend won't stall VACUUM. On timeout, the client gets SQLSTATE 25P03 and must reconnect.

Mistake #3 is an overnight bulk DELETE on a 2-billion-row table (say, rows older than 90 days). One transaction creates a dead tuple and a WAL record per row, floods replication, and forces VACUUM to scan every index—and still won't return pages to the OS. Partition the table by date instead and drop old data instantly with DROP TABLE.

Mistake #4 is unused, duplicate, and invalid indexes. An index on a frequently updated column disables HOT (Heap-Only Tuple) updates, which normally update a row on the same 8 KB page without touching indexes. Meanwhile, broken indexes left behind by a failed CREATE INDEX CONCURRENTLY are ignored by the planner, yet the database keeps updating them on every write.

-- Indexes with zero scans (excluding PK, UNIQUE, and constraints)
SELECT s.schemaname, s.relname AS tbl, s.indexrelname AS idx,
  pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
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
  AND NOT EXISTS (
    SELECT 1 FROM pg_constraint c WHERE c.conindid = s.indexrelid
  )
ORDER BY pg_relation_size(s.indexrelid) DESC;

-- Invalid indexes left behind by a failed CREATE INDEX CONCURRENTLY
SELECT indexrelid::regclass AS idx, indrelid::regclass AS tbl,
  pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_index
WHERE NOT indisvalid OR NOT indisready;

Both queries use standard system views and immediately show how much space you can reclaim.

Check Stats and Replicas Before Dropping

Before running DROP INDEX, check stats_reset in pg_stat_database and run the same check on every replica: each node tracks index scans locally.

Why PostgreSQL Shuts Down Slowly and How to Fix It

Stopping PostgreSQL often takes longer than starting it. Laurenz Albe of Cybertec, in his breakdown of slow shutdowns, alongside the PostgreSQL docs, points to pg_ctl stop modes and the final checkpoint.

Mode (-m)SignalServer BehaviorWhen to Use
smartSIGTERMBlocks new connections and waits forever for active onesAlmost never: one pooled client stalls restarts
fastSIGINTDrops sessions, rolls back transactions, shuts down cleanlyStandard default choice
immediateSIGQUITKills processes immediately without flushing buffersEmergencies only: forces crash recovery on start

immediate is a false friend for anyone coming from Oracle, where SHUTDOWN IMMEDIATE performs a clean stop. In PostgreSQL, it's pulling the power cord: the seconds you save turn into slow crash recovery on startup.

So why is even fast slow? Before shutting down cleanly, Postgres runs a shutdown checkpoint—flushing all dirty pages from shared_buffers to disk. The larger your shared_buffers and write rate (plus full-page writes), the longer that flush takes.

-- Log checkpoint duration and write volume
ALTER SYSTEM SET log_checkpoints = on;

-- Flush dirty buffers to disk before stopping
CHECKPOINT;

Enable log_checkpoints = on to see flush sizes in your logs, then run CHECKPOINT; manually right before your maintenance window. The server flushes dirty pages while still online, and you can stop it cleanly right after:

# Fast clean shutdown after a manual CHECKPOINT
pg_ctl stop -D "$PGDATA" -m fast

The final shutdown checkpoint only has a tiny tail from the last few seconds to write, so the server stops almost instantly. To keep buffers from piling up before restarts, tune regular checkpoints with checkpoint_timeout, max_wal_size, and checkpoint_completion_target so disk writes spread smoothly in the background.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 5