Home›Learn›PostgreSQL 1: why PostgreSQL
Course · Inside one serverLesson 5 of 330 read

PostgreSQL

Where does PostgreSQL keep my data, and why does a deleted row not shrink the file?

Chapter 1 · Why PostgreSQL

Why I reach for PostgreSQL

When a team asks me which database to start with, my answer is usually PostgreSQL, and I want to show you why before we open it up.

It is honest about your data.

Transactions, constraints and foreign keys are not extras. If the database says a row is committed, it survives a crash.

It does a lot in one place.

Relational tables, JSON documents, full-text search, geospatial with PostGIS, vectors with pgvector. Many apps never need a second database.

You can see everything.

Every table is a file, every change goes through one log, and the statistics views tell you what the engine is doing right now. That is what makes it debuggable at 3 a.m.

Where I would not use it alone.

Millions of writes a second spread across regions, or a cache that has to answer in microseconds. Later chapters show where Redis and Cassandra fit.

This track tells PostgreSQL as one story, the way I would walk a new engineer through it: what it is, how it stores your data, what happens on every write, how it stays up, how I run it, and what to do when it breaks. Start here, then follow the chapters in order.

This page is about one directory. I show you where PostgreSQL keeps every table, every index, and every log record. After it you will be able to point at a file for any table, read the WAL position, check replica lag, and tell whether dead row versions are piling up.

PostgreSQL: in one line

A relational database. Rows in tables. One data directory. Correctness first.

Good at: Money, orders, bookings. Anything with joins, constraints, and questions nobody has thought of yet. One log does both jobs. The WAL handles crash recovery and replication.

Runs as: one postmaster + a backend process per connection

Printable one-page cheat sheet for PostgreSQL →

One lookup, four pages: root, internal, leaf, heap

Root pageusers_pkey, in shared_buffers
→
Internal page42 sits between 25 and 87
→
Leaf page42 → page 7, slot 3
→
Heap pagebase/16384/16397, the row

Play with this walk: the B+ tree widget runs the same lookup step by step, with splits, deletes, and range scans.

Try it live: a real Postgres, in your browser

No install, no account. This panel runs a real PostgreSQL in your browser. It starts with the same users table as the Home walkthrough, ids 10, 25, and 87. Run the insert, then the select, then the EXPLAIN, and watch the same numbers come out of a real plan.

Live Postgres is not started yet. Press the button below.

Nothing run yet.

See the plan as a tree: which step is the villain

Run the EXPLAIN in the live panel above, then press Visualize last plan. The tree shows every step with its share of the time, the slowest step in red, and the one thing to fix first. Or paste any EXPLAIN (ANALYZE, BUFFERS) output below.

Notion: VACUUM stalled, and the database nearly stopped writing

By mid-2020, Notion ran on a single Postgres monolith. VACUUM began to stall consistently, so dead tuples stopped being reclaimed and disk space stopped coming back. Behind that sat transaction ID wraparound: Postgres stops all writes rather than overwrite old data, so the stall was not a slowdown, it was the product stopping.

The fix was application-level sharding. Notion split the monolith into 480 logical shards across 32 physical databases, routing by workspace ID so one workspace's data stays together. Writes went to both old and new databases through an audit log, the backfill took 3 days, dark reads checked the copy, and the cutover took 5 minutes of scheduled downtime.

VACUUM stalls: dead tuples pile up, and wraparound stops writes

VACUUM stallsdead tuples stop being reclaimed
→
Transaction ID wraparoundPostgres stops all writes
→
Shard by workspace ID480 logical shards, 32 databases
→
Fixaudit-log double-write, 5-minute cutover

Let's talk about the design. The options were a bigger machine, a packaged sharding system, or their own routing. A bigger machine was out: upkeep degraded before the hardware limit did. Citus and Vitess were on the table, but the clustering logic was opaque and Notion wanted control over the distribution. Their own routing won, and the price was real: cross-shard joins got expensive, transactions stayed inside one host, and 32 databases meant more maintenance. I would take the same trade at that scale, and I would copy one detail first: they prepared a reverse audit log so they could replay sharded writes back to the monolith if the cutover failed. They never needed it.

Full story with the numbers on the Stories page. Source: Herding elephants: Lessons learned from sharding Postgres at Notion, Notion Blog, October 6, 2021. The other real version of this story: Uber hit the same write amplification at scale. How to host Postgres on-prem, on EC2, in Kubernetes, or managed is on the Cloud page.

Before you leave, check this

One command. It tells you whether cleanup is keeping up.

SELECT relname, n_dead_tup FROM pg_stat_user_tables;

If n_dead_tup keeps climbing on a hot table, VACUUM is not keeping up.

Follow it

Follow one read

Where does one SELECT by primary key go, page by page? Step through it, then move the last page to disk and step again.

How many pages does PostgreSQL read to find one row by its id, in a table of a million rows?

Four: three index pages (root, branch, leaf) and the table page that holds the row. A million rows only needs a three-level index, which is why a lookup by key stays fast as the table grows.

Your turn

A table takes 5,000 updates a second on the same 10,000 rows. The row count never changes, but the table file keeps growing. What is happening, and what do you check first?

Write your answer down first. Then open mine.

Show my answer

What is happening: every UPDATE in PostgreSQL writes a new version of the row. The old version stays in the file as a dead row until vacuum removes it. If vacuum cannot keep up, or is not allowed to remove the dead rows, the file grows.

What I check first: whether something is holding back the cleanup. A transaction that has been open for hours, a session sitting idle in transaction, or a replication slot nobody reads all stop vacuum from removing rows that someone might still need. pg_stat_activity (oldest xact_start and backend_xmin) and pg_replication_slots show them. Then n_dead_tup and last_autovacuum in pg_stat_user_tables.

What I would change: end the long transaction first. Then make autovacuum visit this table more often with a lower autovacuum_vacuum_scale_factor on the table, and lower its fillfactor so updates that do not touch an indexed column can stay on the same page. Notebook 1 shows one open transaction taking a table from 5.8 MB to 29 MB.

Next · chapter 2How it stores your dataProcesses, memory, files and logs
Connected

Where this shows up

The same mechanism, old row versions, vacuum and long transactions, indexes and plans, replication and failover, elsewhere on the site: in real incidents, in measurements, and in designs.

Check yourself · 4 questions

Check yourself

Pick an answer. You will see whether it is right, and why.

1. You DELETE half the rows of a 10 GB table. What happens to the file size right away?

2. With synchronous_commit = on, when does COMMIT return?

3. What stops VACUUM from removing dead rows?

4. Where do a table's data files live?

One database decision a weekA short email each week: one real decision, the trade-off, and the command to check it. Unsubscribe in one click.

Part 1 of 4 · Learn · 56 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.

Start 1: the basicsStart 2: ten conceptsStart 3: how a query travelsStart 4: napkin mathThe courseShort videosPostgreSQL 1: why PostgreSQLPostgreSQL 2: how it stores your dataPostgreSQL 3: what happens on every writePostgreSQL 4: high availability with PatroniPostgreSQL 5: running it as a DBREPostgreSQL 6: when it breaksPostgreSQL on Kubernetes: CloudNativePGMySQL 1: why MySQLMySQL 2: how it stores your dataMySQL 3: what happens on every writeMySQL 4: high availability with InnoDB ClusterMySQL 5: running it as a DBREMySQL 6: when it breaksMySQL failover with OrchestratorMySQL on Kubernetes: the Percona operatorsMongoDB 1: why MongoDBMongoDB 2: how it stores your dataMongoDB 3: what happens on every writeMongoDB 4: high availability with replica setsMongoDB 5: running it as a DBREMongoDB 6: when it breaksMongoDB on Kubernetes: the Percona operatorB-tree and LSM treeRedis 1: why RedisRedis 2: how it stores your dataRedis 3: high availabilityRedis 4: running it as a DBRERedis 5: when it breaksCassandra 1: why CassandraCassandra 2: how it stores your dataCassandra 3: high availabilityCassandra 4: running it as a DBRECassandra 5: when it breaksVector databases 1: why vector searchVector databases 2: how it stores your dataVector databases 3: high availabilityVector databases 4: running it as a DBREVector databases 5: when it breaksDatabase familiesEngines side by sideQueries that look fine and are notLost updates and write skewMany servers 1: keep a copy runningMany servers 2: who is the leaderMany servers 3: CAP as settingsMany servers 4: unique IDsMany servers 5: split the dataMany servers 6: across servicesMany servers 7: a thousand databasesStaff path, zero to architect