Most of us use PostgreSQL as a box that takes SQL and returns rows. That works until something odd happens: a table keeps growing even though you delete rows, a query is fast on Monday and slow on Friday, or the server runs out of connections at 300 clients. Each of these makes sense once you know a few things about how Postgres is built inside.
This article follows one query through the system, then looks at how Postgres stores data, keeps it safe after a crash, and lets many transactions work at the same time.
One process per connection
PostgreSQL uses a process model. When the server starts, a main process called the postmaster listens on port 5432. When a client connects, the postmaster forks a new operating-system process, a backend, that serves only that connection until it closes.
Next to the backends run several background processes:
- the checkpointer, which regularly writes changed pages to disk;
- the background writer, which writes some dirty pages early so backends rarely have to;
- the WAL writer, which flushes the write-ahead log;
- the autovacuum launcher and its workers, which clean up old row versions;
- with replication, the WAL sender and WAL receiver.
The process model is simple and robust: a crash in one backend does not corrupt the memory of another. The cost is that each connection is a real process with its own memory. That is why thousands of direct connections are a bad idea and why tools like PgBouncer sit in front of busy Postgres servers.
The life of a query
Say a backend receives:
SELECT name FROM users WHERE email = 'amina@example.com'; It goes through four stages.
- Parser. The text is checked for syntax and turned into a parse tree.
- Analyzer and rewriter. Names are resolved against the system catalogs (does
usersexist, what type isemail), and rules such as views are expanded. - Planner. This is where the speed comes from. The planner considers different ways to get the rows: a sequential scan of the whole table, an index scan on
emailif an index exists, and for joins, nested loop, hash join or merge join. It estimates a cost for each plan using statistics about the table (row counts, common values, value distribution) gathered byANALYZE, and picks the cheapest. - Executor. The chosen plan is a tree of nodes. The executor pulls rows through that tree and sends them back to the client.
You can see the plan with EXPLAIN, and the plan plus real timings with EXPLAIN ANALYZE:
EXPLAIN ANALYZE SELECT name FROM users WHERE email = 'amina@example.com'; When a query suddenly gets slow, stale statistics are a common reason. The planner thinks a filter returns 10 rows when it returns 100,000, and picks a plan that only makes sense for 10. Running ANALYZE on the table often fixes it.
Pages, heap files and shared buffers
On disk, each table is stored as one or more files called the heap. The file is split into fixed-size pages (8 KB by default). Each page holds a small header, an array of pointers, and the row versions themselves, which Postgres calls tuples. Indexes are separate files made of pages too; the default index type is a B-tree.
Postgres never reads a single row from disk. It reads the whole page into shared buffers, a memory area shared by all backends. If another query needs the same page, it is already in memory. Pages that were changed in memory are "dirty" and get written back to the data files later, by the background writer or at a checkpoint. Postgres also relies on the operating system's own file cache, which is why shared buffers are usually set to a fraction of RAM, not most of it.
The write-ahead log (WAL)
If dirty pages are written back "later", what happens when the server loses power before that? The answer is the write-ahead log.
Before a change to a data page is considered safe, Postgres writes a record describing that change to the WAL, an append-only sequence of files in the pg_wal directory. When you run COMMIT, Postgres makes sure the WAL records for your transaction are flushed to disk (with the default synchronous_commit = on). The data pages themselves can stay dirty in memory.
Appending to one log is much cheaper than writing scattered pages all over the data files. And it is enough for durability: after a crash, Postgres starts from the last checkpoint and replays the WAL forward, redoing every change that was committed. A checkpoint is a moment where all dirty pages have been flushed, so recovery never has to look further back than that.
The same WAL is what makes streaming replication and point-in-time recovery work: a replica receives the WAL stream and replays it, and a backup plus archived WAL lets you restore to any moment.
MVCC: many versions of a row
Here is the part that explains the most surprises. Postgres uses multi-version concurrency control (MVCC). It does not update a row in place. An UPDATE writes a new version of the row and marks the old one as expired. A DELETE only marks the row as expired.
Every tuple carries two hidden fields:
-
xmin: the ID of the transaction that created this version; -
xmax: the ID of the transaction that deleted or replaced it (empty if it is still current).
Each statement or transaction works with a snapshot: the set of transactions that were committed when it started. A row version is visible if it was created by a transaction in the snapshot and not deleted by one. You can look at the hidden fields:
SELECT xmin, xmax, * FROM users WHERE id = 1; The benefit is large: readers never block writers and writers never block readers. A long report can read a consistent view of the data while other transactions update the same rows. Two transactions that update the same row still wait on each other, through row-level locks.
VACUUM: cleaning up dead tuples
MVCC has a price. Old row versions stay in the pages after nobody can see them anymore. These are dead tuples, and a table full of them is called bloated: it takes more disk, more memory in shared buffers, and longer scans.
VACUUM finds dead tuples that no running transaction can still see and marks their space as reusable. It also updates the visibility map, which helps index-only scans, and the free space map. Plain VACUUM does not normally shrink the file on disk; VACUUM FULL rewrites the table to its minimum size but takes a heavy lock while it does.
Autovacuum runs this for you based on how many rows changed. VACUUM also does one more job: freezing old transaction IDs. IDs are 32-bit and wrap around, so very old tuples must be marked as frozen. If vacuum can never run, Postgres will eventually refuse new writes to protect the data. This is why disabling autovacuum is almost always a mistake.
Common mistakes
- Long-running transactions. An open transaction, even an idle one, holds back the oldest snapshot. VACUUM cannot remove dead tuples newer than it, so tables bloat. Watch for
idle in transactionsessions inpg_stat_activity. - Too many connections. One process per connection means memory and context switching grow with clients. Use a connection pool.
- Ignoring statistics. After a big data load, run
ANALYZEso the planner has real numbers. - Turning off autovacuum because it "uses resources". Tune it instead.
- Treating
fsync = offas a speed setting. It removes the crash safety the WAL gives you.
In short
- Each connection is its own backend process, supported by background processes such as the checkpointer, WAL writer and autovacuum.
- A query is parsed, analyzed, planned with cost estimates based on statistics, and executed as a tree of nodes.
- Data lives in 8 KB pages, cached in shared buffers and written back later.
- The WAL is written first and flushed at commit, which gives durability, crash recovery and replication.
- MVCC keeps several versions of each row, so readers and writers do not block each other, and VACUUM cleans up the old versions.
Watch the animated version: https://youtu.be/i__7AX4q-AQ
Originally published at abdeldjalilchougui.biz.
