Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 15 / Stage 4

How PostgreSQL works inside

Goal: Build the mental model performance work stands on — processes, 8 kB pages and out-of-line storage for oversized values, the write-ahead log, the memory areas, MVCC's debris and VACUUM's job, and the statistics the planner lives by. Time: ~2.5 hours

What you will learn

  • Process architecture: the postmaster, one backend per connection
  • Storage: heap files, 8 kB pages, tuples, out-of-line storage
  • The write-ahead log: durability and checkpoints
  • Memory: shared_buffers, work_mem, and the OS cache
  • MVCC on disk: dead tuples, and watching a table bloat
  • VACUUM and autovacuum — and transaction ID wraparound
  • ANALYZE and pg_stats: how the planner estimates

From here on, lessons build big tables with generate_series — fast to make, honest to measure. shopdb stays our small friend.

Topics in this part

Practice

SQL workbench — write and run queries here

Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.

These poke at the engine itself. All on shopdb except where a solution builds its own lab table (re-runnable).


Exercise 1: Meet your backend

What to do: One query: your backend's process id, the database you're in, and how many client backends the server is running right now.

💡 Hint: pg_backend_pid(), current_database(), and a count over pg_stat_activity filtered to backend_type = 'client backend'.


Show the solution to Exercise 1
-- Exercise 1: Meet your backend
SELECT pg_backend_pid() AS my_backend,
       current_database() AS db,
       (SELECT count(*) FROM pg_stat_activity
        WHERE backend_type = 'client backend') AS client_backends;

Exercise 2: Size audit

What to do: For orders: heap size, total index size, and the all-in total — each human-readable.

💡 Hint: pg_relation_size, pg_indexes_size, pg_total_relation_size, wrapped in pg_size_pretty.


Show the solution to Exercise 2
-- Exercise 2: Size audit (re-runnable)
-- Table, its largest index, and total (heap + indexes + out-of-line storage) for orders.
SELECT pg_size_pretty(pg_relation_size('orders'))       AS heap,
       pg_size_pretty(pg_indexes_size('orders'))        AS indexes,
       pg_size_pretty(pg_total_relation_size('orders')) AS total;

Exercise 3: The bloat experiment

What to do: Build a 50,000-row lab table; record its fresh size; update every row twice; show live/dead counts and the grown size; VACUUM; show dead = 0 — and explain in one sentence why the file didn't shrink.

Sample output (the ending):

 n_dead_tup | after_vacuum 
------------+--------------
          0 | 7568 kB
(1 row)

💡 Hint: pg_stat_force_next_flush() + a 0.2s sleep makes the stats readable immediately. The file keeps its size because plain VACUUM recycles space inside the table; only VACUUM FULL rewrites.


Show the solution to Exercise 3
-- Exercise 3: The bloat experiment (re-runnable)
DROP TABLE IF EXISTS bloat_lab;
CREATE TABLE bloat_lab AS
SELECT g AS id, 'row ' || g AS note FROM generate_series(1, 50000) g;
SELECT pg_size_pretty(pg_relation_size('bloat_lab')) AS fresh_size;
UPDATE bloat_lab SET note = note || ' v2';
UPDATE bloat_lab SET note = note || ' v3';
SELECT pg_stat_force_next_flush();
SELECT pg_sleep(0.2);
SELECT n_live_tup, n_dead_tup,
       pg_size_pretty(pg_relation_size('bloat_lab')) AS bloated_size
FROM pg_stat_user_tables WHERE relname = 'bloat_lab';
VACUUM bloat_lab;
SELECT pg_stat_force_next_flush();
SELECT pg_sleep(0.2);
SELECT n_dead_tup, pg_size_pretty(pg_relation_size('bloat_lab')) AS after_vacuum
FROM pg_stat_user_tables WHERE relname = 'bloat_lab';
-- The file stays big: plain VACUUM reclaims space for reuse, not for the OS.

Exercise 4: Watch the WAL earn a COMMIT

What to do: Read pg_current_wal_lsn(), insert a throwaway product, read it again — the position moved: your change exists as log records before anything else. Clean up after yourself.

💡 Hint: the LSN is a byte offset into the log stream; every INSERT advances it.


Show the solution to Exercise 4
-- Exercise 4: Watch the WAL earn a COMMIT
SELECT pg_current_wal_lsn() AS before_insert;
INSERT INTO products (name, category_id, price, stock)
VALUES ('WAL Demo Widget', 3, 9.99, 1);
SELECT pg_current_wal_lsn() AS after_insert;
-- The position advanced: the change exists as log records first.
DELETE FROM products WHERE name = 'WAL Demo Widget';

Exercise 5: Read the planner's mind

What to do: ANALYZE customers, then pull n_distinct and null_frac for city and email from pg_stats — and decode the negative numbers.

Sample output:

 attname | n_distinct | null_frac  
---------+------------+------------
 city    | -0.6666667 | 0.16666667
 email   |         -1 |          0
(2 rows)

💡 Hint: negative n_distinct is a fraction of rows (−1 = all unique) — the planner's way of saying "this scales with the table". null_frac 0.17 is Sara.

Show the solution to Exercise 5
-- Exercise 5: Read the planner's mind (re-runnable)
ANALYZE customers;
SELECT attname, n_distinct, null_frac
FROM pg_stats
WHERE tablename = 'customers' AND attname IN ('city', 'email')
ORDER BY attname;
-- Negative n_distinct is a FRACTION of rows (scales as the table grows):
-- email -1 = every row unique; city -0.67 = about 0.67 x rows distinct
-- (4 of 6 here). null_frac 0.17 = one customer in six has a NULL city.

Common mistakes

Mistake What happens Fix
Hundreds of raw connections Memory burn, scheduler thrash A pooler (Stage 5B); connections are processes
SELECT * dragging oversized out-of-line columns Needless reassembly I/O Name the columns you read
Disabling autovacuum ("it causes load") Bloat, stale stats, wraparound risk Tune it per-table; never off
VACUUM FULL as routine maintenance Exclusive lock, full rewrite Plain VACUUM + autovacuum; FULL for recovery only
Forgetting ANALYZE after bulk loads Planner estimates from a vanished world ANALYZE in the load script
Setting work_mem huge globally OOM under concurrency Modest default; raise per-session for known big sorts

Quick recap

  • One backend process per connection under the postmaster; pg_stat_activity lists them.
  • Tables are 8 kB pages of tuples; ctid is a row's address; oversized values spill sideways into out-of-line storage.
  • The write-ahead log is written first and data pages later; that single stream provides durability, crash replay, and replication.
  • shared_buffers caches pages; work_mem is per-operation (spills when exceeded).
  • Updates leave dead tuples behind, and dead tuples become bloat; VACUUM reclaims the space inside the file, autovacuum automates it, and freezing prevents wraparound.
  • The planner trusts pg_stats, not your data — keep ANALYZE fresh.

Checklist

Before Part 16, make sure you can:

  • Explain what (0,3) in a ctid means.
  • Trace a COMMIT's durability: what's flushed, what isn't yet.
  • Reproduce the bloat experiment and read n_dead_tup before/after VACUUM.
  • Say what plain VACUUM reclaims and what only VACUUM FULL returns.
  • Name the three memory settings and which one multiplies per operation.
  • State what ANALYZE maintains and when to run it by hand.

Read more: the official routine vacuuming chapter, WAL introduction, and storage layout docs.

Search the guide