Chapter 19 — PostgreSQL Deep Dive: Planner, Indexes, MVCC Ops, Production Tuning
Part IV · Data & Storage | Prerequisites: Ch 18 | Builds: Pulsely indexed from EXPLAIN, pooled, with a zero-downtime migration plan
Earlier you built a model of the machine: pages, the buffer pool, the WAL, the B-tree, MVCC tuple versions. That work was about what a storage engine is. This one is about operating one specific engine, in production, at the scale where the black box stops being kind. Pulsely has crossed that threshold. The observations table — every vital sign, lab value, and device reading the remote-monitoring fleet streams in — is forty million rows, the claims table is the thing revenue-cycle reconciles against every night, the chart-timeline endpoint is the thing clinicians feel on every patient open, and every one of those is now close enough to a cliff that "it works on my laptop" tells you almost nothing. The skills this chapter builds are the ones that separate someone who uses Postgres from someone who can be trusted to run it: reading what the planner actually decided and why, choosing indexes from evidence instead of folklore, keeping MVCC's corpses from eating your disk and your transaction-ID budget, rationing connections so the database doesn't drown in its own clients, and changing a column's type on a live forty-million-row table without taking the chart down.
This is a hands-on chapter. Almost every claim in it is something you can type into psql and watch happen, and you should. The deepest single habit it teaches is small and unglamorous: stop guessing, run EXPLAIN. Everything else is downstream of being able to read what Postgres tells you about its own reasoning.
1. The problem: the black box starts biting
Five pages, in the rough order Pulsely hit them.
It's 2 a.m. and the chart-timeline endpoint's p99 just went from 40 ms to nine seconds. Nothing deployed. No code changed. What changed is that a newly onboarded remote-monitoring cohort roughly tripled the number of rows matching a typical timeline query, the row counts crossed a threshold the planner cares about, and — because the table's statistics were stale — the planner mis-estimated how many rows the query would touch and flipped from an index scan to a sequential scan of the whole table. The query is identical. The plan is not. You cannot debug this by reading your code, because your code is innocent; the decision that broke you was made inside Postgres, from numbers you've never looked at.
Second page, slower burn. The claims table reports 2 GB on disk, but a careful count says it holds maybe 300 MB of live rows. The other 1.7 GB is bloat: dead tuples from years of UPDATEs as each claim churned through its lifecycle — submitted, accepted, adjudicated, paid or denied, appealed — that MVCC left behind and nothing reclaimed. Every query that scans claims is now reading six times the pages it needs, dragging six times the data through the buffer pool, evicting six times as much of everyone else's hot working set. The table isn't big. It's fat.
Third, an own-goal. Someone saw a slow query, "added an index," and shipped it. Writes to that table got three times slower, disk usage jumped, and the original query is exactly as slow as before — because the index column order violated a rule nobody had explained to them, so the planner can't use it for that query, while every INSERT and UPDATE still dutifully maintains it. An index you can't use is pure tax.
Fourth, an outage. The app opens a fresh database connection per request. Under a spike — 400 concurrent requests — it tries to open 400 connections. Postgres hits max_connections and starts refusing with FATAL: sorry, too many clients already. The box has eight cores. It is being asked to juggle 400 server processes, most of them doing nothing but waiting, and the contention from that makes even the connections that got in slower. A four-core-shaped workload drowned in connection count, not in real work.
Fifth, a self-inflicted freeze. A "quick" schema fix — ALTER TABLE observations ALTER COLUMN value TYPE numeric to move device readings off a legacy text column — took an ACCESS EXCLUSIVE lock on the table and proceeded to rewrite all forty million rows. For the eleven minutes that took, every read and every write to observations queued behind it, which meant every clinician's chart hung waiting on vitals. The migration "succeeded." It also took charting down at lunchtime.
🧭 Mental model. Pull these five apart and they're not five problems — they're four subsystems each biting once, plus DDL safety. The planner chose wrong (page 1, page 3). The storage/MVCC layer accumulated corpses (page 2). The connection layer was rationed by no one (page 4). And a schema change took a lock it didn't need to (page 5). The whole chapter is: learn to see, reason about, and tame each of these four, plus how to change schema without freezing the table.
The throughline is simple and a little uncomfortable. At Pulsely's old scale, Postgres genuinely was a black box that "just stored rows," and treating it as one cost you nothing. At this scale, every layer has mechanics, and each of those mechanics has a failure mode that only appears under load. You don't get to keep the black box. The good news is the box has excellent instruments, and most of this chapter is learning to read them.
2. The mental model: four subsystems and one rule
Hold four cooperating subsystems in your head. Each is something you can reason about separately, and almost every Postgres incident is one of them misbehaving.
- The planner decides how to fetch the rows your query asks for: which indexes, which join algorithm, in which order. It is a cost-minimizing optimizer working from estimates of how many rows each step will produce. It is usually right and occasionally, spectacularly, wrong.
- The executor + storage/MVCC layer is the rows themselves on disk — heap pages, index pages, and the tuple versions MVCC leaves lying around. This is where your data physically lives and where bloat physically accumulates.
- The connection/process layer is the fact that each Postgres connection is a separate operating-system process — a forked backend with its own memory and a slot in shared state. Connections are not cheap handles; they are heavyweight, and you must ration them.
- The catalog/statistics layer is the planner's beliefs about your data: how many distinct values a column has, what the common values are, how rows are distributed. The planner is only as good as these beliefs, and beliefs go stale.
🔑 The pages-not-rows invariant. A query's cost is the number of pages it must read, not the number of rows it returns. Everything in this chapter — every index, every
VACUUM, BRIN, covering indexes, partitioning — is ultimately one lever: touch fewer pages. When you don't know why something is slow, ask "how many pages is this touching, and why that many?" before you ask anything else.
Three more pictures, one per remaining subsystem.
An index is a sorted, redundant copy. Picture it exactly as you already have: a separate B-tree holding some columns' values in sorted order, each leaf entry pointing (via a TID, a tuple identifier — page number plus slot) back to the full row in the heap. It costs you write throughput and disk, and it buys you the ability to navigate to matching rows instead of scanning for them. That's the entire trade. An index is never free and never magic; it is a copy you maintain on every write in exchange for read locality.
MVCC means rows are appended and marked dead, never edited in place. An UPDATE does not overwrite a row; it writes a new tuple version and marks the old one dead. A DELETE just marks dead. Reads see a snapshot — a consistent view as of some point in time — not necessarily the latest truth. The consequence that will run through §5 and §6: every UPDATE and DELETE leaves a corpse, and someone has to bury the corpses. That someone is VACUUM.
A connection is a forked process, so you ration them through a pool. Because a connection is an OS process with real memory and a real scheduling cost, you do not hand them out one-per-request. You keep a small, fixed set of them and lend them out — a pool (a fixed, shared set of reusable DB connections the whole server borrows from) — so that 400 concurrent requests share, say, 20 connections rather than demanding 400.
That's the whole map. Planner, storage/MVCC, connections, stats. Keep it next to you; the rest of the chapter fills in each box.
3. Theory & invariants
A model tells you how to picture Postgres. Invariants tell you what stays true while you operate it. These are the load-bearing rules.
Plan nodes and the cost model
The planner builds a tree of plan nodes, executed bottom-up, each node producing rows for its parent. You only need a working vocabulary:
- Sequential scan — read every page of the table, filter as you go. The right choice when you need most of the table; a disaster when you need a handful of rows from a huge one.
- Index scan — walk a B-tree to find matching entries, then fetch each matching heap row by its TID (a "heap fetch"). Great for high selectivity (few matching rows); expensive per row, so bad if "few" turns out to be "most."
- Index-only scan — the same B-tree walk, but the query needs only columns the index already holds, so it never touches the heap at all. The fastest read shape Postgres has.
- Bitmap heap scan — when an index matches more rows than is worth fetching one-at-a-time, Postgres builds a bitmap of which pages hold matches, then reads those pages in physical order. It can also combine several indexes (bitmap-OR / bitmap-AND). The middle gear between index scan and seq scan.
For joins, three algorithms, each with a regime where it wins:
- Nested loop — for each row on the left, probe the right (usually via an index). Wins when the left side is tiny.
- Hash join — build a hash table of one side, stream the other through it. Wins for large, unsorted, roughly-equal inputs joined on equality.
- Merge join — sort both sides on the join key, then zip them together. Wins when both inputs are already sorted (e.g., by index order).
The planner assigns each plan a cost — an abstract number, not milliseconds — by weighing estimated work: seq_page_cost (default 1.0) per sequential page, random_page_cost (default 4.0) per random page, and cpu_tuple_cost / cpu_index_tuple_cost / cpu_operator_cost per row and per operation. It multiplies these weights by estimated row counts at each node and propagates the total up the tree, then picks the cheapest tree.
🔑 The estimate invariant. Every planner decision is only as good as its row estimates. A plan that's catastrophically slow is almost always a plan built on a wrong estimate — the planner thought a step would produce 12 rows, it produced 400,000, and a nested loop that would've been perfect for 12 became a self-join from hell. Your single most valuable diagnostic skill is comparing estimated rows to actual rows per node. Hold that thought; §4 makes it concrete.
Statistics: the planner's beliefs
The estimates come from per-column statistics that ANALYZE collects and stores in the catalog: n_distinct (how many distinct values), a most-common-values (MCV) list with their frequencies, a histogram of the rest of the distribution, and correlation (how well physical row order matches sorted order, which drives whether an index scan reads pages sequentially or randomly).
The deepest single failure mode lives here: the planner assumes columns are independent and multiplies their selectivities. If WHERE payer_id = 'AETNA' matches 2% of claims and WHERE cpt_code = '99213' (a standard office visit) matches 5%, the planner estimates the combination at 2% × 5% = 0.1%. But if that payer's claims are overwhelmingly office visits, the real number might be 4%. That 40× under-estimate is exactly how a query that should bitmap-scan ends up nested-looping millions of rows. Correlated columns — and clinical data is full of them, because a payer, a clinic, a diagnosis, and a procedure code all travel together — are the root cause of most real-world misestimates.
Index access invariants
You've already met the B-tree. Postgres has more index types, and each exists for one access shape:
- B-tree — the default. Equality, range (
<,>,BETWEEN), and sorted output (it can satisfy anORDER BYfor free, because the index is already sorted). This is your workhorse; reach for it unless you have a specific reason not to. - GIN (Generalized Inverted Index) — for "many keys per row." A JSONB document, an array, a
tsvector(full-text) — GIN inverts it: key → list of rows containing that key. This is the inverted index you've already met, built in. - GiST (Generalized Search Tree) — for overlap and nearest-neighbor. It indexes relationships (contains, overlaps, is-near) rather than equality: range types, geometry, "which readings fall in this window." Its most load-bearing use at Pulsely is the no-double-booking exclusion constraint — a GiST index over each provider's appointment time-range (
tstzrange) that lets Postgres reject, at write time, any new slot whose range overlaps an existing booking for the same provider. The database itself enforces "one provider, one patient, one time," so two front-desk staff racing for the same 9:00 slot can't both win. - BRIN (Block Range Index) — stores only the min/max value per block range (e.g., per 128 pages). Tiny — kilobytes where a B-tree would be gigabytes — but only useful when the data is physically clustered by the indexed column, like the append-only
observationsfirehose wherecreated_atrises monotonically with physical position.
🔑 The ESR rule (equality, sort, range). For a composite B-tree index, order the columns: equality-matched columns first, then the column you
ORDER BY, then range/inequality columns last. Why this exact order and not query order: a B-tree can only seek to a contiguous prefix of equality matches, and once it hits a range or inequality, everything after that column in the index is no longer in usable sorted order. So forWHERE patient_id = ? AND status = ? ORDER BY created_at DESC, the index is(patient_id, status, created_at)— seek to the(patient_id, status)equality prefix, then readcreated_atentries already in order, no sort step needed. Putcreated_atfirst, or put a range column before the equality columns, and the index becomes useless for this query. This single rule explains most "I added an index and it's ignored" mysteries.
A covering index (or index-only scan) is the payoff of the pages-not-rows invariant: if every column a query references is in the index — either as a key column or via INCLUDE (...) (which stores columns in the leaf without affecting sort order) — Postgres can answer entirely from the index and never touch the heap. One caveat that bites people in §6: this only works if the page is marked all-visible in the visibility map, which VACUUM maintains; on a freshly-written, un-vacuumed table, "index-only" scans still sneak back to the heap to check visibility.
MVCC invariants, restated for ops
Recall that every tuple carries xmin (the transaction that created it) and xmax (the transaction that deleted/superseded it, or 0 if live). In plain terms, a row is visible to you when two things hold:
- the transaction that created it (
xmin) had already committed when your snapshot was taken, and - the row hasn't been deleted yet as far as your snapshot can see (
xmaxis empty, or belongs to a transaction that hadn't committed at snapshot time).
If you've used React, it's like a component rendering from a frozen props snapshot: later writes to the store already exist, but this render doesn't see them — it only sees the values as of the moment it was handed. An UPDATE is insert a new version + set the old version's xmax. Read Committed takes a new snapshot per statement; Repeatable Read takes one snapshot at transaction start.
Two operational consequences this chapter owns:
Dead tuples accumulate and must be reclaimed. The old versions from UPDATE/DELETE are dead tuples — invisible to every current and future snapshot, but still occupying space until VACUUM marks their space reusable. Unreclaimed dead tuples are bloat (page 2 of §1).
🔑 The wraparound invariant. Transaction IDs (XIDs) are 32-bit, so they wrap around after ~4 billion. Think of XIDs as a 12-hour clock face rather than a straight line: Postgres tells past from future by a rule like "more than 6 hours behind me counts as the past." That works until a still-live row's creating transaction falls billions of XIDs behind — it wraps past the halfway mark and starts looking like the future, at which point that row would abruptly become invisible and vanish. To prevent this, old, still-live rows must be frozen — stamped "ancient: older than every possible snapshot, visible to all," which removes them from the clock entirely so wrapping can't misjudge them — before that ~2-billion horizon catches them. Freezing is
VACUUM's other, non-negotiable job — not cleanup, correctness. A database that stops vacuuming long enough will refuse all writes to protect itself from wraparound. This is the one item on the list that can lose you data or halt the database, so it gets its own alert in §5.
Pooling theory
A Postgres backend doing real work is bounded by hardware: it needs a CPU core to compute and disk bandwidth to read pages. Beyond a point set roughly by (cores × 2) + effective spindles — where effective spindles means roughly how many independent disks can read at once; on a single cloud SSD volume treat this as ~1, so an 8-core box lands near (8 × 2) + 1 ≈ 17 — more concurrent active connections don't add throughput. They add context-switching, lock contention, and cache thrash, and throughput goes down. So the useful number of simultaneously-active connections is small (often single or low double digits), even though you have hundreds of clients.
📎 Borrowed on credit: Little's Law and the general pool-sizing math. The formal relationship between pool size, request latency, and throughput — concurrency = arrival rate × service time, and how to derive a queue's behavior from it — is general queueing theory, and it belongs to performance engineering in Chapter 30. I'm borrowing only the conclusion here: a small pool of busy connections serves more total throughput than a large pool of mostly-waiting ones, because the bottleneck is cores and disk, not connection count. What this chapter owns is the Postgres-specific reality — connections are processes, the magic starting number is
(cores × 2) + spindles, and you enforce it with an external pooler. The general "why" is Chapter 30's to derive.
The mechanism that makes a small server-side pool serve a large client population is transaction-mode pooling: a pooler (PgBouncer) holds a small set of real Postgres connections and multiplexes many client connections onto them, handing a server connection to a client only for the duration of one transaction and returning it at COMMIT. We build it in §4 and §5.
4. Under the hood: reading what Postgres actually does
This is the longest beat because it's the one you'll use daily. We'll read plans, read the storage layer's vital signs, and wire up the connection layer — all on Pulsely.
Reading EXPLAIN
EXPLAIN <query> shows the plan the planner would choose, with estimates, without running the query. EXPLAIN ANALYZE <query> actually runs the query and shows estimates next to reality.
🛑 What we deliberately did not warn you about loudly enough yet.
EXPLAIN ANALYZEexecutes the statement. For aSELECTthat's harmless. For anUPDATE,DELETE, orINSERT, it really does mutate your data. Wrap mutating statements in a transaction you roll back:BEGIN; EXPLAIN ANALYZE UPDATE ...; ROLLBACK;. Forget this once and you'll learn it forever.
Here's the chart-timeline query and its plan. Read plans bottom-up and inside-out: the most indented node runs first and feeds its parent.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, provider_id, note_text, created_at
FROM chart_events
WHERE patient_id = 42 AND confidentiality = 'normal'
ORDER BY created_at DESC
LIMIT 50;
Before any index, you might see:
Limit (cost=84512.20..84512.33 rows=50 width=72) (actual time=903.1..903.2 rows=50 loops=1)
-> Sort (cost=84512.20..84933.51 rows=168524 width=72) (actual time=903.0..903.1 rows=50 loops=1)
Sort Key: created_at DESC
Sort Method: top-N heapsort Memory: 41kB
-> Seq Scan on chart_events (cost=0.00..78901.00 rows=168524 width=72)
(actual time=0.3..812.4 rows=171002 loops=1)
Filter: ((patient_id = 42) AND (confidentiality = 'normal'::text))
Rows Removed by Filter: 3920118
Buffers: shared read=41000
Planning Time: 0.2 ms
Execution Time: 903.5 ms
Every number here earns its keep. cost=startup..total is the planner's abstract estimate — startup cost (before the first row) versus total. rows= is the estimated row count; width= the estimated bytes per row. In EXPLAIN ANALYZE you also get actual time=startup..total (in real milliseconds), rows (actual), and loops (how many times this node ran — multiply per-loop numbers by loops for the true total). Rows Removed by Filter: 3920118 is the smoking gun: Postgres read four million rows to keep 171,002, then sorted them, to return 50. And Buffers: shared read=41000 — that's 41,000 disk page reads (read = from disk; shared hit = already cached). This plan is pounding disk.
🔑 The estimated-vs-actual habit. The single most useful thing you can do with a plan: at each node, compare
rows=(estimate) toactual ... rows=. A gap of 100× or more is a statistics/correlation problem, not an index problem — adding an index won't help if the planner can't believe the right estimate. A close match with a bad plan is an indexing problem. This one comparison tells you which of §3's failure modes you're in.
Now add the index ESR demands and re-run:
CREATE INDEX idx_chart_patient_conf_created
ON chart_events (patient_id, confidentiality, created_at DESC);
Limit (cost=0.56..38.10 rows=50 width=72) (actual time=0.04..0.41 rows=50 loops=1)
-> Index Scan using idx_chart_patient_conf_created on chart_events
(cost=0.56..126540.20 rows=168524 width=72) (actual time=0.03..0.38 rows=50 loops=1)
Index Cond: ((patient_id = 42) AND (confidentiality = 'normal'::text))
Buffers: shared hit=54
Planning Time: 0.3 ms
Execution Time: 0.47 ms
No Sort node — the index already returns rows in created_at DESC order (that's the ESR sort column paying off). No Rows Removed by Filter. Buffers: shared hit=54, all cache, all the way down. 903 ms → 0.47 ms. That's the diagram you'll draw in the exercises: a B-tree seek to the (patient_id, confidentiality) equality prefix, then an ordered walk of created_at, cut off at LIMIT 50.
B-tree: (patient_id, confidentiality, created_at DESC)
┌────────────────────────── ────────────────────────────┐
│ seek ──▶ patient_id=42 ─▶ confidentiality='normal' │ ← equality prefix (E)
│ └─▶ created_at: [newest ......] │ ← ordered scan (S), take 50
└──────────────────────────────────────────────────────┘
(a range column, if present, would go LAST — past it, order is lost)
Bitmap heap scans and recheck
When an index matches more than a handful but fewer than most rows, you'll see a bitmap heap scan. Here it's over observations, filtering the firehose down to one clinical category:
Bitmap Heap Scan on observations (actual rows=18204 loops=1)
Recheck Cond: (category = 'vital-signs')
Heap Blocks: exact=6051
-> Bitmap Index Scan on idx_observations_category (actual rows=18204 loops=1)
Index Cond: (category = 'vital-signs')
Postgres scanned the index to build a bitmap of which heap pages contain matches, then read those pages in physical order (sequential disk access beats 18,204 random fetches). Recheck Cond is listed because the bitmap can go lossy under memory pressure. The bitmap is built in work_mem — the per-operation RAM budget Postgres gives each sort or bitmap. In plain terms: when the bitmap gets too big to remember every matching row within that budget, it downgrades to remembering only which pages had matches — so Postgres must re-check the WHERE on every row of those pages to filter out the non-matches. (On an exact, non-lossy bitmap the recheck does no work — the line still appears in the plan.) The real power: Postgres can build several bitmaps from several indexes and combine them (BitmapAnd / BitmapOr) before touching the heap once.
Index mechanics that bite
- B-tree page splits &
fillfactor. Inserting into a full leaf page splits it in two, which costs I/O and fragments the index. For tables with heavy updates, a lowerfillfactor(e.g., 90) leaves slack so updates can stay on-page (HOT updates — see below). - GIN's pending list. GIN indexes (JSONB, full-text) buffer new entries in a pending list and merge them in batches (
fastupdate=on). This makes writes fast but means a just-inserted row may not be reflected in the index immediately, and a large pending list slows reads until merged. Tunegin_pending_list_limitorVACUUMto flush it (§6). - Partial index.
CREATE INDEX ... WHERE status = 'open'indexes only the matching rows. The index is smaller (faster, less write tax), but the planner uses it only when it can prove your query's predicate implies the index's —WHERE status = 'open' AND ...qualifies; a query without that predicate does not. (The classic Pulsely use: an index over only the open clinical orders, since that's the working set the worklist actually queries.) - Expression index.
CREATE INDEX ON patients (lower(email))indexes the result of the expression. The planner uses it only when the query contains the exact expression —WHERE lower(email) = $1hits it;WHERE email = $1does not. This is the fix for the classic "function on the column kills the index" pitfall.
The Node/TS path and the SELECT * trap
Running EXPLAIN from your app — via pg, or Prisma/TypeORM raw queries — is the same SQL:
const { rows } = await pool.query(
'EXPLAIN (ANALYZE, BUFFERS) SELECT id, note_text FROM chart_events WHERE patient_id = $1',
[42]
);
console.log(rows.map(r => r['QUERY PLAN']).join('\n'));
Note $1: parameterized, always — concatenating values into SQL is the injection hole you closed earlier, and it doesn't reopen because the query is going through EXPLAIN.
🏭 ORMs love
SELECT *. It feels harmless and it quietly destroys index-only scans: the moment your query references a column not in the index, Postgres must visit the heap, and your beautiful covering index degrades to an ordinary index scan plus a heap fetch per row. Select the columns you need. This is also whySELECT *ships more bytes over the wire — and with PHI, every column you didn't need is minimum-necessary surface you shouldn't have pulled — and it breaks silently when someone adds a column. Several costs, one bad habit.
There's a second ORM/pooler interaction we'll need in §5: the pg driver and many ORMs use named prepared statements for plan caching, and those are session state — they don't survive PgBouncer's transaction-mode connection juggling. Hold that; it's a real production gotcha with a real fix.
MVCC ops: reading the corpses
The storage layer's vital signs live in pg_stat_user_tables:
SELECT relname, n_live_tup, n_dead_tup,
last_autovacuum, last_vacuum
FROM pg_stat_user_tables
WHERE relname = 'claims';
n_dead_tup climbing far above some fraction of n_live_tup is your bloat early-warning. VACUUM does three things: marks dead tuples' space reusable (so future inserts fill it — note: VACUUM does not return disk to the OS, it recycles space within the table), updates the visibility map (which re-enables index-only scans), and freezes old XIDs (the wraparound defense from §3). VACUUM FULL is a different, heavier beast: it rewrites the entire table into a fresh file, does return disk to the OS, and takes an ACCESS EXCLUSIVE lock for the duration — which is why it's almost never what you want on a live table.
Autovacuum does this automatically. It triggers on a table when dead tuples exceed autovacuum_vacuum_scale_factor × n_live_tup + autovacuum_vacuum_threshold (default scale 0.2 = 20% of the table, plus 50 rows). For a big hot table like claims, waiting for 20% to go dead is far too much bloat; you'll tune this per-table in §5.
🔑 The long-transaction invariant. A dead tuple can only be reclaimed once it's invisible to every snapshot that could still read it. A single long-running or
idle in transactionconnection holds an old snapshot open, which means its snapshot might still need those "dead" tuples — soVACUUMcannot reclaim them anywhere in the database while that transaction lives. One forgottenBEGINin an app that neverCOMMITs can therefore cause unbounded bloat across every table. This is the "idle in transaction" killer, and it's the most common cause of mysterious, cluster-wide bloat.
MVCC tuple lifecycle (one logical row):
INSERT ──▶ [v1: xmin=100, xmax=0 (live)]
UPDATE ──▶ [v1: xmin=100, xmax=200 (dead)] [v2: xmin=200, xmax=0 (live)]
│ │
snapshot<200 still sees v1 ◀── long txn pins this │
│ │
VACUUM ──▶ reclaims v1's space ◀─ ONLY once no snapshot needs it
Wiring the connection layer: PgBouncer
PgBouncer sits between your app and Postgres. Its pool_mode is the whole game:
- session — a client holds a server connection for its entire session. Full Postgres feature set; almost no multiplexing benefit.
- transaction — a client gets a server connection only for one transaction, returned at
COMMIT/ROLLBACK. Massive multiplexing; the right default for web apps. Restriction: no cross-transaction session state — named prepared statements,SETthat should persist, session advisory locks — because the next transaction may land on a different server connection. - statement — returns the connection after every statement; even stricter, rarely used.
A minimal pgbouncer.ini:
[databases]
pulsely = host=10.0.0.5 port=5432 dbname=pulsely
[pgbouncer]
pool_mode = transaction
default_pool_size = 20 ; server conns per (db,user) — sized to the box
max_client_conn = 5000 ; client conns we'll accept — cheap, set high
reserve_pool_size = 5 ; emergency headroom
server_idle_timeout = 600
N app pods ──┐
pod1 (pool 20)│
pod2 (pool 20)├──▶ PgBouncer ──▶ 20 real Postgres backends ──▶ Postgres (8 cores)
... │ (transaction (default_pool_size)
pod12 (pool 20)│ mode)
└──▶ 240 *client* conns multiplexed onto 20 *server* conns
🏭 The named-prepared-statement gotcha is real and it's how teams get burned right after adopting PgBouncer: errors like
prepared statement "S_1" does not existappear under load, because transaction mode handed the next statement a different server connection that never saw thePREPARE. The fix is driver-side: tellpgnot to use protocol-level prepared statements across the pool, or disable statement caching in your ORM, or — for the rare path that genuinely needs session state — route it through a small session-mode pool instead. Decide this deliberately; don't discover it at 2 a.m.
Partitioning, JSONB, and full-text — built in
Partitioning splits one logical table into physical child tables by a key (range / list / hash). Its payoffs: dropping a whole month of readings is an instant DROP of a partition instead of a giant DELETE, and the planner can prune — skip partitions a query can't match — but only if the query filters on the partition key. The observations firehose is the natural candidate: partition it by time.
CREATE TABLE observations (id bigint, created_at timestamptz, ...)
PARTITION BY RANGE (created_at);
CREATE TABLE observations_2026_06 PARTITION OF observations
FOR VALUES FROM ('2026-06-01') TO ('2026-07-01');
JSONB stores JSON in a parsed binary form you can index and query: -> (get JSON), ->> (get text), @> (contains). A GIN index with jsonb_path_ops makes containment queries fast. JSONB is right for genuinely sparse or variable attributes — a device's raw payload envelope, say, where every vendor's model reports different fields; it's a schema smell when used to dodge modeling columns you query and constrain consistently — you lose type safety, FK integrity, and precise indexing, none of which you want to give up on the patient identifiers, LOINC/ICD-10 codes, or claim amounts you filter on every day. (The full per-aggregate "relational vs document" call is Chapter 16's; here it's just an index type.)
Full-text search lives in tsvector (a document reduced to normalized lexemes) and tsquery, with a GIN index for speed. At Pulsely the document is a clinical note — a clinician searching their own patients' charts for a phrase:
ALTER TABLE clinical_notes
ADD COLUMN search_doc tsvector
GENERATED ALWAYS AS (to_tsvector('english', chief_complaint || ' ' || note_text)) STORED;
CREATE INDEX idx_notes_search ON clinical_notes USING GIN (search_doc);
SELECT id, chief_complaint, ts_rank(search_doc, q) AS rank
FROM clinical_notes, plainto_tsquery('english', 'productive cough fever') q
WHERE search_doc @@ q
ORDER BY rank DESC LIMIT 20;
This gives you stemming, ranking, and a real inverted index without running another system.
📎 Borrowed on credit: real search infrastructure. Postgres full-text search is excellent until search becomes a product surface. Typo tolerance, synonyms, faceting, relevance tuning, multi-language analyzers at scale — and, critically here, access-scoped clinical search that only ever returns records the querying clinician is permitted to see — that's a dedicated search engine's job, and it's Chapter 22's to teach. Here I'm giving you the in-database option and its ceiling, not the engine that replaces it. Likewise, JSONB-as-a-document-store earns its full treatment against MongoDB in Chapter 20; this chapter owns it only as a Postgres index/storage feature.
5. In production: the diagnostic loop and the dials
Knowing the mechanics is half the job. The other half is a loop you run and dials you set deliberately.
The diagnostic loop. When something's slow, don't guess — follow the chain:
- Find the real culprit in
pg_stat_statements, ordered by total time, not call count. The query that's individually fast but runs 10,000×/s can hurt more than the one slow report nobody runs. (pg_stat_statementsis an extension; turn it on — it's the single most valuable observability tool Postgres ships.) EXPLAIN (ANALYZE, BUFFERS)it against production-representative data. Plans on a 5,000-row dev table are fiction.- Find the dominant node — the one eating the time and the buffers. Check estimated-vs-actual rows there.
- Fix the right thing: an index (if the estimate's right and the plan's wrong) or the stats (if the estimate's wrong).
- Re-measure. Always. The fix that "should" work sometimes makes a different node dominant.
Stats tuning the tutorials skip. After a bulk load — importing a payer's remittance file, backfilling a new device cohort — run ANALYZE before you trust any plan; fresh rows have no statistics. For a skewed column, raise its default_statistics_target (more histogram buckets, finer estimates). And for the correlated-columns problem from §3, use extended statistics:
CREATE STATISTICS stx_payer_cpt (dependencies, ndistinct)
ON payer_id, cpt_code FROM claims;
ANALYZE claims;
This teaches the planner that payer_id and cpt_code are not independent, fixing the multiply-the-selectivities misestimate at its root.
Index hygiene. Indexes rot. Find the dead weight:
SELECT indexrelname, idx_scan
FROM pg_stat_user_indexes
WHERE idx_scan = 0 AND relname = 'observations'; -- never used → drop candidates
Drop unused indexes (each one taxes every write), de-duplicate redundant ones (a (a, b) index makes a separate (a) index largely pointless), and rebuild bloated ones. And the rule that prevents the §1 freeze:
🔑
CREATE INDEX CONCURRENTLY, always, in production. A plainCREATE INDEXtakes a lock that blocks writes for the whole build.CONCURRENTLYbuilds the index in the background without blocking writes. The costs: it can't run inside a transaction, it scans the table twice (slower), and if it fails it can leave anINVALIDindex you mustDROPand retry. Worth every bit of that to not freeze the table.
Autovacuum tuning per table. The 20% default is wrong for hot tables. For claims, which churns through statuses constantly, make autovacuum aggressive:
ALTER TABLE claims SET (
autovacuum_vacuum_scale_factor = 0.02, -- vacuum at 2% dead, not 20%
autovacuum_vacuum_cost_limit = 2000 -- let it work faster
);
Monitor last_autovacuum and the dead-tuple ratio. And — the non-negotiable alert — watch transaction-ID age and alarm well before wraparound:
SELECT datname, age(datfrozenxid) AS xid_age
FROM pg_database ORDER BY xid_age DESC;
-- alert at ~200M (wraparound danger ~2B); investigate why autovacuum is behind
Pool sizing as a first-class decision. Start from the formula — connections ≈ (cores × 2) + effective_spindles — so an 8-core SSD box (effective spindles ≈ 1) lands around 16–20 server connections. Set PgBouncer's default_pool_size to that. Set max_client_conn high (it's cheap; client connections are light in the pooler). Keep each app instance's own pool small, and remember they sum: twelve pods × a 20-connection app pool = 240 connections demanding service, which is exactly the §1 outage if PgBouncer isn't multiplexing them down. The whole point of the external pooler is to bound that total.
Operationally: transaction mode for the web path, named prepared statements disabled in the driver (or routed to a session-mode pool), separate pools per database/user, and watch SHOW POOLS / SHOW STATS for saturation.
Zero-downtime migrations: expand-contract. This is the SQL/DDL-safety discipline this chapter owns. The §1 freeze happened because someone did a destructive change in one step. The safe shape is expand → migrate reads → contract, where every step is independently deployable and reversible:
- EXPAND. Add the new structure non-destructively: a new nullable column, or a new table. Adding a nullable column is a metadata-only change in modern Postgres — instant, no rewrite.
- Dual-write + backfill. Deploy code that writes both old and new. Backfill existing rows in batches (e.g., 10,000 at a time, committing between batches) so you never lock millions of rows in one transaction.
- MIGRATE READS. Once new is fully populated and verified, deploy code that reads from new.
- CONTRACT. Only after reads have moved and you're confident, drop the old column/table.
EXPAND ───▶ dual-write + batched backfill ───▶ switch reads ───▶ CONTRACT
(add new, (both written, old rows (read new) (drop old)
nullable) filled in batches)
safe rollback ◀── safe rollback ◀── safe rollback ◀── (point of no return here)
🔑 Safe-DDL rules. Know which
ALTERs takeACCESS EXCLUSIVEand rewrite the table — changing a column's type, or (on older Postgres) adding aNOT NULLcolumn with a volatile default — versus which are metadata-only (adding a nullable column; validating aNOT NULLby first adding aCHECK (col IS NOT NULL) NOT VALIDthenVALIDATE CONSTRAINT, which scans without an exclusive lock). And always wrap DDL in tightlock_timeoutandstatement_timeout: a migration that can't get its lock immediately should fail fast, not silently queue behind a long-running query while every other query queues behind it. That queueing is how one blockedALTERtakes down a whole app even though theALTERitself never ran.
📎 Borrowed on credit: the deploy choreography. Expand-contract has a deployment half — coordinating which app version is live during which migration step, feature-flagging the read switch, rolling back a bad deploy without orphaning a half-done backfill. That deploy/CI side is Chapter 38's. This chapter owns the SQL/DDL half: which statement is safe, how to batch, which locks each step takes. The two halves meet at the migration, but the deploy machinery is Ch 38's to build.
This is the Pulsely increment in full: real EXPLAIN plans drive a justified index set (one composite via ESR for the chart timeline, one GIN for clinical-note search, one partial for open orders, one GiST exclusion constraint that makes double-booking a slot physically impossible); PgBouncer in transaction mode with a sized pool sits in front of the DB; and observations.value gets retyped from legacy text to numeric via expand-contract with batched backfill, never a single destructive ALTER.
6. Common pitfalls
Each as signature → fix.
Function-wrapped column kills the index. Signature: a seq scan on a huge table despite an index on the column, because the predicate is WHERE date(created_at) = '2026-06-19' or has an implicit type cast (WHERE mrn = 42 with mrn a text column). The function/cast means the indexed raw column never appears. Fix: rewrite the predicate to be sargable (created_at >= '2026-06-19' AND created_at < '2026-06-20'), or build an expression index matching the exact expression.
Composite index "ignored." Signature: you have an index but the plan won't use it for a query you're sure it covers. Fix: check column order against ESR — a range or low-selectivity column placed before the equality columns makes the index unusable for that query. Reorder equality-first.
Wildly wrong row estimates. Signature: estimated rows and actual rows differ 100×+, and the plan is bad because of it. Fix: it's almost always correlated columns assumed independent — CREATE STATISTICS, raise default_statistics_target on the skewed columns, re-ANALYZE.
Index-only scan secretly hits the heap. Signature: you built a covering index but EXPLAIN shows Heap Fetches: <large>. Fix: the visibility map is stale after recent writes; VACUUM the table to mark pages all-visible so index-only scans can skip the heap.
Table grows forever, queries slow. Signature: n_dead_tup huge, disk climbing, even though row count is stable. Fix: find the long-lived / idle in transaction connection pinning the snapshot (a reporting query, a leaked BEGIN), kill it, set idle_in_transaction_session_timeout, and fix the app's transaction leak. Vacuum can't reclaim while that snapshot lives.
FATAL: too many clients already. Signature: outage under load, the database refusing connections while doing little real work. Fix: per-request connections; put PgBouncer in transaction mode in front and shrink the app-side pool. Raising max_connections is treating the symptom and making the contention worse.
Prepared-statement errors after adding PgBouncer. Signature: prepared statement "S_1" does not exist appears once you're in transaction mode. Fix: disable named/protocol-level prepared statements in the driver, or route the path that needs them to a session-mode pool.
Migration hung the whole app. Signature: a DDL statement waited on ACCESS EXCLUSIVE behind one long query, and every subsequent query queued behind the waiting DDL. Fix: lock_timeout + statement_timeout around DDL so it fails fast and retries; run CONCURRENTLY where applicable; do it off-peak.
GIN search index lags new rows. Signature: just-signed clinical notes don't appear in full-text results for a while. Fix: the GIN pending list hasn't merged; tune gin_pending_list_limit or VACUUM to flush it (or disable fastupdate if read-freshness matters more than write speed).
XID age climbing, autovacuum "too busy." Signature: age(datfrozenxid) marching toward hundreds of millions while autovacuum never catches up. Fix: this is a wraparound emergency in the making — run an aggressive manual vacuum, raise autovacuum cost limits, and find why autovacuum is being starved (often a long transaction, or cost limits set too conservatively).
7. Tradeoffs
Each is a dial, with the conditions under which you'd move it.
More indexes ↔ write throughput & bloat. Every index is re-maintained on every write and must itself be vacuumed. Reads get faster; writes get slower and the disk grows. Move toward fewer when an index's idx_scan is near zero, or when write latency dominates your workload (the observations firehose is write-heavy — index it sparingly). Move toward more only with a plan showing the index is actually used.
Normalized columns + joins ↔ a JSONB blob. JSONB buys schema flexibility for genuinely variable data — heterogeneous device payloads, a form's freeform extras; it costs you constraints, type safety, FK integrity, and precise indexing. Reverse toward real columns the moment an attribute is queried, filtered, or constrained consistently — a LOINC code, a claim amount, a patient identifier — at that point it deserves to be a typed, indexed column, not a path expression.
Postgres full-text search ↔ a dedicated search engine. FTS keeps search transactional and in one system — no extra moving part, no sync lag, and access scoping stays inside the same row-level rules as everything else. It caps out on relevance tuning, typo tolerance, synonyms, and scale. Reverse to a dedicated engine (Chapter 22) when clinical/patient search becomes a product surface rather than a convenience filter.
Transaction-mode pooling ↔ session-mode pooling. Transaction mode maximizes connection reuse (the whole point) but forbids cross-transaction session state — named prepared statements, session advisory locks, persistent SET. Session mode keeps the full feature set but multiplexes far fewer clients. Default transaction; carve out a small session pool for the rare path that genuinely needs session state.
External pooler (PgBouncer) ↔ in-app pool only. An in-app pool (HikariCP on the JVM, pg-pool in Node) is simpler — one fewer process to run. But it bounds connections per instance, and N instances sum into one Postgres with no global limit (the §1 outage). The external pooler is another hop to operate and monitor, but it's the only thing that bounds total connections across all your instances. At more than a couple of app instances, you want it.
🚫 A framing this book rejects. "HikariCP / our app pool already handles connection pooling, so we don't need PgBouncer." This conflates two different jobs. An in-process pool limits one process's connections; it has no idea the other eleven pods exist. Postgres sees the sum, and the sum is what exhausts
max_connections. In-app pooling and an external pooler are not competitors — the in-app pool reuses connections within a process; the external pooler bounds the total across processes. You frequently want both.
Partitioning ↔ a single table. Partitioning makes drop-by-time instant and lets the planner prune — if queries filter on the partition key. It also adds planning overhead, complicates unique constraints and FKs (they must include the partition key), and hurts queries that omit the key (they scan every partition). Don't partition under ~tens of millions of rows; the complexity isn't paid back. The observations firehose, at forty million and append-only by time, is exactly where it is paid back.
BRIN ↔ B-tree. BRIN is tiny and nearly free to maintain, but only wins when data is physically clustered by the indexed column — an append-only time series where created_at rises with physical position. The instant data is randomly ordered, BRIN is useless and you want a B-tree. Pick BRIN deliberately for the clustered case, never as a default.
8. Security & scale notes
The threat surface includes your own diagnostics. pg_stat_statements and EXPLAIN output can leak query shapes and literal values — and in this domain a leaked literal is an MRN or a diagnosis, so restrict who can read them. And JSONB does not exempt you from injection: @> / -> over untrusted input still needs parameterized queries. SQL injection doesn't disappear because the column type changed.
A missing index is a DoS amplifier. This is the security framing of the pages-not-rows invariant. An unindexed filter on a hot endpoint lets a cheap attacker request force a full-table scan, saturating disk I/O for every user. One missing index turns a trivial request into a denial-of-service lever. "Which endpoints can a stranger make do a seq scan?" is a security question, not just a performance one.
Connection exhaustion is a self-inflicted availability incident. The pooler is a security/availability control, not merely a performance tweak. Cap max_client_conn so a client-side connection leak — a bug in your app — can't take the cluster down by itself, and with it every clinician's access to the chart.
Plans shift with data volume and cache state, so a query that's fine in staging can regress in production as the table grows or the cache cools. Guard with pg_stat_statements regression alerting, not a one-time pre-launch check. The planner's job is to adapt; your job is to notice when it adapts badly.
VACUUM competes with foreground traffic for I/O. Tune its cost limits too low and cleanup starves — bloat and, eventually, wraparound. Too high and it steals I/O from the app — latency spikes on the chart. Both are scale failures; the right setting is per-table and watched.
Long-running analytics pin dead tuples cluster-wide. A revenue-cycle report that holds a snapshot open for minutes prevents VACUUM from reclaiming dead tuples everywhere, exactly like the §6 idle-transaction pitfall. Isolate reporting on a read replica.
📎 Borrowed on credit: replicas and distribution. "Run reporting on a replica," "fail over when the primary dies," "scale reads across followers" — replication and the distributed-systems reasoning behind it are Chapters 23–24's. I'm naming the operational reflex here (move heavy snapshots off the primary) without building the replication machinery, which is genuinely a separate, larger topic.
9. Interview lens & exercises
Interview questions
"This query is slow — walk me through diagnosing it."
Junior answer: "I'd add an index." (Jumps to a fix before a diagnosis.)
Senior answer: "Start from pg_stat_statements ordered by total time to confirm it's worth fixing, then EXPLAIN (ANALYZE, BUFFERS) on production-shaped data. Read the plan bottom-up, find the node eating the time and buffers, and compare estimated rows to actual rows there. If they're close and the plan's bad, it's an index problem. If they're off by 100×, it's stats — correlated columns, stale ANALYZE — and an index won't save me." Names the loop, not a reflex.
"Order the columns in a composite index for WHERE patient_id = ? AND status = ? ORDER BY created_at."
Junior: "(patient_id, status, created_at)" — possibly right, but offered as query order with no reason.
Senior: "(patient_id, status, created_at) by the ESR rule — equality columns first so the B-tree can seek to a contiguous prefix, then the ORDER BY column so the index returns rows already sorted and we skip the sort node entirely. A range column, if there were one, goes last, because past a range the index order is no longer usable." Same answer, with the seek-then-scan mechanic.
"Why doesn't deleting rows shrink the table, and what cleans it up?"
Junior: "Postgres should auto-clean it."
Senior: "MVCC marks tuples dead rather than removing them; the space is reclaimed by VACUUM, which marks it reusable (not returned to the OS — that's VACUUM FULL, which rewrites and locks). The classic trap is a long-running or idle-in-transaction connection holding a snapshot, which blocks reclamation cluster-wide. And VACUUM has a second job — freezing XIDs to prevent 32-bit transaction-ID wraparound, which can halt the database if neglected."
"Twelve app pods, each a 20-connection pool, on a four-core Postgres — what's wrong?"
Junior: "Raise max_connections."
Senior: "240 backends against a box whose useful concurrency is roughly (cores × 2) + spindles, so ~8–12 active. Raising max_connections makes the contention worse. Put PgBouncer in transaction mode to multiplex 240 client connections onto ~16 server connections, shrink the app pools, and size default_pool_size from the core formula. The fix is bounding total connections, not allowing more."
"Change a column's type on a 200-million-row table with zero downtime."
Junior: "ALTER TABLE ... ALTER COLUMN TYPE." (Takes ACCESS EXCLUSIVE, rewrites the table, freezes the chart.)
Senior: "Expand-contract. Add a new nullable column (metadata-only, instant). Deploy dual-write. Backfill existing rows in committed batches so I never lock millions at once. Verify, then switch reads to the new column. Only then drop the old one. Every step is independently deployable and reversible up to the contract, and I wrap the DDL in lock_timeout/statement_timeout so a blocked step fails fast instead of queueing every query behind it."
Exercises & the Pulsely increment
-
Index from EXPLAIN (ADR #1). Pull the top five Pulsely queries from
pg_stat_statementsby total time. For each, runEXPLAIN (ANALYZE, BUFFERS)and record the dominant node and the estimated-vs-actual gap. Then add a justified index set: one composite via ESR (the chart-timeline query), one GIN (clinical-note full-text search), one partial (WHERE status = 'open'on clinical orders). For each index, record the before/after plan and the write-amplification cost in ADR #1. -
Pool and prove it (ADR #2). Deploy PgBouncer in transaction mode. Configure the
pgdriver to avoid named prepared statements. Sizedefault_pool_sizefrom(cores × 2) + spindles. Load-test to reproducetoo many clientswithout the pooler, then show it gone with it. Capture the sizing math and the failure mode it prevents in ADR #2. -
Expand-contract for real. Retype
observations.valuefrom legacy text tonumericwith zero downtime: addvalue_numeric(nullable), dual-write, backfill in 10,000-row committed batches, switch reads, then contract. Do it on a copy first; prove each step rolls back cleanly before the contract. -
Induce and fix a misestimate. Build a two-column table where the columns are strongly correlated (model
payer_idandcpt_code, where a payer's claims skew to a few procedures). Show the planner's bad estimate (multiplying independent selectivities), addCREATE STATISTICS, re-ANALYZE, and show the corrected estimate and the better plan it produces. This is the single most instructive thing you can do to internalize §3's independence assumption.
Key takeaways
- Postgres is four subsystems you reason about separately: planner (how to fetch), storage/MVCC (the rows and their corpses), connection layer (processes you must ration), statistics (the planner's beliefs). Most incidents are exactly one of them misbehaving.
- A query's cost is pages touched, not rows returned. Every index, VACUUM, and tuning knob is one lever: touch fewer pages.
- Read the plan, don't guess.
EXPLAIN (ANALYZE, BUFFERS), bottom-up, and the killer habit: compare estimated rows to actual rows per node. A big gap is stats; a close gap with a bad plan is indexing. - ESR orders composite indexes: equality, then sort, then range. It explains most "my index is ignored" mysteries.
- MVCC leaves dead tuples that
VACUUMmust reclaim, and a single long/idle transaction blocks reclamation cluster-wide.VACUUMalso freezes XIDs to prevent 32-bit wraparound — a correctness job that can halt the database, not just hygiene. - Connections are processes. Ration them: PgBouncer in transaction mode multiplexes many clients onto a small server pool sized near
(cores × 2) + spindles. An in-app pool bounds one process; only an external pooler bounds the total. - Change schema with expand-contract, never a single destructive
ALTER. Add nullable, dual-write, batched backfill, switch reads, drop old — each step deployable and reversible, wrapped inlock_timeoutso a blocked migration fails fast instead of freezing every query behind it. - A missing index isn't just slow — it's a DoS amplifier, and the pooler is an availability control. Performance and security are the same conversation here.
← Previous: Ch 18 — How Databases Store Bytes · Up: Part IV overview · Master TOC · Next: Ch 20 — NoSQL Thinking & MongoDB →