Performance Engineering

Article · 7:00

The five index types and when each wins, reading EXPLAIN ANALYZE honestly, statistics, and the vacuum and bloat that cause slow decay.

Measure first. Every instinct about why a query is slow is worth less than one EXPLAIN ANALYZE. The commonest outcome of actually looking is that the problem was not where the team assumed.

EXPLAIN shows the plan; EXPLAIN ANALYZE runs the query and shows the plan with real numbers. The single most useful habit is comparing the planner's estimated rows with the actual rows on each node. When they diverge by an order of magnitude, the planner is choosing badly because it has been told something false - stale statistics, a correlation it cannot see, a function it cannot estimate through. Fixing the estimate is usually better than forcing the plan.

Add (ANALYZE, BUFFERS) always. shared hit is a page found in cache; read is a page fetched from disk. A query reading far more buffers than it returns rows is doing work you have not noticed.

The index types, and what each is for.

B-tree is the default and serves equality, ranges and ordering. For a composite index, column order is the design: an index on (a, b) serves WHERE a = ? and WHERE a = ? AND b = ?, but not WHERE b = ?. Put the equality columns first and the range column last.

GIN indexes values that contain multiple items - JSONB containment, array membership, full-text search. Large, slower to update, and the only reasonable way to query inside a document column.

GiST handles geometric and range data, and is what makes the exclusion constraint from Module 1 possible.

BRIN is tiny and stores a summary per block range. It is excellent on a column that is physically correlated with its order - an append-only timestamp - and useless otherwise. For a large append-only table it can be a thousand times smaller than the B-tree while serving the same range query.

Partial and expression indexes are the two most under-used features in PostgreSQL. WHERE status = 'pending' on an index means only pending rows are stored, so an index over 0.1% of a huge table is both tiny and sharply selective. An expression index on lower(email) is what makes a case-insensitive lookup use an index at all.

Vacuum. Dead tuples are reclaimed by VACUUM, run automatically by autovacuum. On a heavily updated table the default settings are frequently too lax, autovacuum falls behind, the table bloats, and queries slow down gradually over weeks - which is why this presents as "the database is getting slower" rather than as an incident. pg_stat_user_tables tells you the dead tuple count and when autovacuum last ran. Tune autovacuum_vacuum_scale_factor per table for the hot ones.

Laboratory exercise 4 - a measured improvement.

Load representative data - at least a million rows, with a realistic distribution rather than uniform random, because uniform data makes every index look good. Establish a baseline: pick five queries from your capstone, run each under load, and record p50, p95 and p99 latency, throughput, and the buffer counts.

Then apply the techniques above, one at a time, re-measuring after each. Include at least one case where adding an index made things worse or made no difference, and explain why.

Deliverable: a benchmark report with the baseline, each change, and the measured effect on all three percentiles; the EXPLAIN (ANALYZE, BUFFERS) output before and after for each query; and your explanation of the change that did not help. A report showing only improvements suggests you stopped measuring when you got the answer you wanted.

-- ------------------------------------------------------------------
-- Read the estimate against the actual. That gap is the diagnosis.
-- ------------------------------------------------------------------
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT e.account_id, sum(e.amount_minor)
FROM ledger.entry e
WHERE e.created_at >= now() - interval '30 days'
GROUP BY e.account_id;

--  HashAggregate  (cost=.. rows=200 width=16)
--                 (actual time=847.2..849.1 rows=94,812 loops=1)
--    Buffers: shared hit=1,204 read=98,447
--    ->  Seq Scan on entry e  (cost=.. rows=5,012 width=16)
--                             (actual time=0.1..612.4 rows=1,204,882 loops=1)
--          Filter: (created_at >= ...)
--          Rows Removed by Filter: 8,795,118
--
-- Three things are wrong here and all are visible:
--   estimate 5,012 against actual 1,204,882  -> stale statistics
--   Seq Scan with 8.8M rows discarded        -> no usable index
--   read=98,447                              -> going to disk, hard
--
-- Fix the estimate FIRST. A planner given the truth often picks the
-- right plan with no other change:
ANALYZE ledger.entry;

-- ------------------------------------------------------------------
-- The five index types, each on the query it is for.
-- ------------------------------------------------------------------

-- B-tree. Column order IS the design: this serves WHERE account_id = ?
-- and WHERE account_id = ? AND created_at > ?, but NOT created_at alone.
CREATE INDEX CONCURRENTLY entry_account_time
    ON ledger.entry (account_id, created_at DESC);
--        ^^^^^^^^^^ CONCURRENTLY: no ACCESS EXCLUSIVE lock, so writes
--        continue. Slower, and it can leave an INVALID index if it
--        fails - check pg_index.indisvalid afterwards. Always use it
--        in production.

-- BRIN: a summary per block range. Tiny, and only works when the
-- column is physically correlated with insertion order - which an
-- append-only timestamp is.
CREATE INDEX entry_time_brin ON ledger.entry
    USING brin (created_at) WITH (pages_per_range = 64);
-- On 10M append-only rows: B-tree ~210 MB, BRIN ~200 KB. Both serve
-- the range scan. Check it is earning its place:
SELECT correlation FROM pg_stats
 WHERE tablename = 'entry' AND attname = 'created_at';
-- Near 1.0 or -1.0: BRIN works. Near 0: it will read the whole table.

-- GIN: for columns that CONTAIN things.
CREATE INDEX account_tags_gin ON ledger.account USING gin (tags);
CREATE INDEX account_meta_gin ON ledger.account USING gin (metadata jsonb_path_ops);
SELECT * FROM ledger.account WHERE tags @> ARRAY['vip'];
SELECT * FROM ledger.account WHERE metadata @> '{"tier": "gold"}';

-- Partial: index only the rows you query. An index over 0.1% of a
-- huge table is both tiny and extremely selective.
CREATE INDEX transfer_pending ON ledger.transfer (created_at)
    WHERE reference LIKE 'pending-%';

-- Expression: without this, lower(holder) cannot use an index at all.
CREATE INDEX account_holder_lower ON ledger.account (lower(holder));
SELECT * FROM ledger.account WHERE lower(holder) = 'holder 42';

-- Covering: INCLUDE adds payload columns so the heap is never visited.
CREATE INDEX entry_covering ON ledger.entry (account_id, created_at)
    INCLUDE (amount_minor);
-- Look for "Index Only Scan" and "Heap Fetches: 0" in the plan.

-- ------------------------------------------------------------------
-- Finding what to fix, and what is dead weight.
-- ------------------------------------------------------------------
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

SELECT round(total_exec_time::numeric, 1) AS total_ms,
       calls,
       round(mean_exec_time::numeric, 2) AS mean_ms,
       round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 1) AS pct,
       left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC LIMIT 10;
-- Order by TOTAL, not mean. A 5 ms query run two million times costs
-- more than a 9-second report run once a night.

-- Indexes nobody uses: they cost write throughput and disk for nothing.
SELECT relname, indexrelname, idx_scan,
       pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0 AND indexrelname NOT LIKE '%_pkey'
ORDER BY pg_relation_size(indexrelid) DESC;

-- Bloat and autovacuum, the slow decay:
SELECT relname, n_live_tup, n_dead_tup,
       round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
       last_autovacuum, autovacuum_count
FROM pg_stat_user_tables WHERE n_dead_tup > 1000
ORDER BY n_dead_tup DESC;

-- Make autovacuum work harder on a hot table. The default 20% scale
-- factor means a 100M-row table waits for 20M dead rows.
ALTER TABLE ledger.entry SET (autovacuum_vacuum_scale_factor = 0.02);

Discussion

No questions on this topic yet. Sign in to ask the first one.