Sub topic 1
Why PostgreSQL keeps multiple versions of a row
Prerequisites
This chapter assumes you can do the following:
- Write basic SQL: SELECT, INSERT, UPDATE and DELETE.
- Explain what a transaction is and use BEGIN, COMMIT and ROLLBACK.
- State the ACID properties at a high level, especially isolation.
- Run psql and open two sessions against the same database.
You don't need to know anything about PostgreSQL internals. This chapter gives the reasoning behind MVCC. Later chapters cover the mechanics.
The problem: many users, one row
A database serves many clients at once. Suppose one client is running a report that reads every row of an accounts table, and another client is transferring money between two of those accounts. The report should see a consistent picture. It must not show a transfer that is half done, with money taken from one account and not yet added to the other.
The classic solution is locking. A reader takes a shared lock, a writer takes an exclusive lock, and the two conflict. This gives correct results, but a long report blocks every writer, and a busy writer makes every reader wait. Throughput drops as concurrency rises, which is the opposite of what you want from a database.
The MVCC idea
PostgreSQL uses multiversion concurrency control (MVCC). The core idea fits in one sentence: an UPDATE or DELETE does not overwrite or erase the old row. It creates a new version of the row, and each query reads whichever version belongs to its view of the data.
This gives two guarantees you can rely on every day:
- Readers do not block writers.
- Writers do not block readers.
A report reads the versions that existed when it started. A concurrent transfer writes new versions next to them. The two never wait for each other, and the report still sees a consistent picture.
| Approach | Reader vs. writer | Writer vs. writer | Old data kept? |
|---|---|---|---|
| Lock-based concurrency | Block each other | Block each other | No, rows are overwritten in place |
| MVCC in PostgreSQL | Do not block | Block only on the same row | Yes, until nothing needs it |
Writers still conflict with other writers that touch the same row. Two transactions cannot both create the next version of one row. A later chapter covers that case.
See it with two sessions
Create a table and a row. Run this in any session.
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100);Now open two psql sessions, A and B, and run the steps in order.
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1; -- returns 100
-- Session B (runs immediately, does not wait for A)
UPDATE accounts SET balance = 90 WHERE id = 1;
-- Session A (still inside its transaction)
SELECT balance FROM accounts WHERE id = 1; -- still returns 100
COMMIT;
SELECT balance FROM accounts WHERE id = 1; -- now returns 90Three things happened here:
- Session B's UPDATE finished at once, even though Session A had read the same row and its transaction was still open. The reader did not block the writer.
- Session A's second SELECT returned the old value. Session B had already committed, but Session A kept reading the version that matched its own view of the data. The writer did not disturb the reader.
- After Session A committed, its next query got a fresh view and returned 90.
The next sections explain how this is possible.
How it works, in outline
PostgreSQL stores each table as a heap, a collection of fixed-size pages that hold rows. Each stored row is called a tuple, and each tuple is one row version. When you run an UPDATE, PostgreSQL does not edit the tuple in place. It does this instead:
- It marks the current tuple as deleted by your transaction.
- It writes a new tuple with the new column values, in the same heap.
For a short time after the UPDATE in the demo above, the heap holds two versions of the row with id = 1, one with balance 100 and one with 90. Each version carries a small amount of bookkeeping that records which transaction created it and which transaction, if any, removed it. When a query runs, PostgreSQL compares that bookkeeping against the query's snapshot, a record of which transactions had already committed when the query (or transaction) took its view. It then returns only the versions that snapshot is allowed to see.
You don't need the details yet. The next chapters cover row versions, transaction IDs, the system columns, and the exact visibility rules in turn. For now, keep one picture in mind: a logical row is really a chain of physical versions, and each query picks the right one.
What this buys you
- Consistent reads without read locks. A plain SELECT takes no row locks, so it never waits for a writer and never makes a writer wait.
- Long reads are safe. An analytical query or a
pg_dumpcan run for minutes against a changing database and see a stable picture. - Cheap rollback. If a transaction aborts, its new versions are simply never treated as visible. PostgreSQL does not need to undo work in the table, as it would after overwriting rows in place.
Some other databases get the same benefits by keeping old versions in a separate undo area and overwriting the row in place. PostgreSQL keeps old versions in the table itself. This choice explains most of the operational behavior you will meet later.
The cost: old versions pile up
Keeping old versions is not free. Every UPDATE leaves a version that, once no query can see it anymore, is garbage. These leftovers are called dead tuples. They take disk space, they make scans read extra pages, and they make indexes larger. Left alone, a table that is updated heavily can grow far larger than the data it holds. This growth is called bloat.
PostgreSQL cleans up with VACUUM, which runs automatically as autovacuum, and which marks the space of dead tuples as reusable. Vacuum can only remove a version when no current or future snapshot can see it, so a transaction left open for hours can stop cleanup across the whole database. Transaction IDs are also finite numbers, so old rows need periodic maintenance to stay valid. These are the later chapters on dead tuples, long-running transactions and wraparound.
You can see that a table has accumulated dead tuples with a query like this:
SELECT relname, n_live_tup, n_dead_tup
FROM pg_stat_user_tables
WHERE relname = 'accounts';The counts are estimates updated by the statistics system, so they can lag behind recent changes. Treat them as a guide and not as an exact count.
What to remember
- MVCC lets PostgreSQL serve readers and writers at the same time by keeping several versions of a row.
- An UPDATE or DELETE marks the old version and, for an update, adds a new one. It does not overwrite.
- Each query reads the versions that match its snapshot, so reads need no row locks.
- The price is dead tuples, which VACUUM must reclaim, and which long-running transactions can keep alive.
Exercise
In the two-session demo, Session A is in a REPEATABLE READ transaction and has already read the row. Session B updates the row and commits. Why does Session B's UPDATE not wait for Session A, and why does Session A's second SELECT still return 100?
Show answer
A plain SELECT takes no row lock, so there is nothing for Session B's UPDATE to wait on. B's UPDATE creates a new row version (balance 90) and marks the old one (balance 100) as deleted by B's transaction, but it leaves the old version in the heap. Session A's second SELECT uses the snapshot from its first query. That snapshot treats B's change as not yet committed, so A reads the old version and gets 100.
Exercise
A table that receives many UPDATEs keeps growing on disk even though the number of live rows stays constant. Using what this chapter covered, give the likely cause and name the mechanism that normally fixes it.
Show answer
Each UPDATE leaves the previous row version behind as a dead tuple, and the new version is written as an additional tuple. If dead tuples are not reclaimed fast enough, the table bloats. VACUUM, normally run automatically by autovacuum, marks the space of dead tuples as reusable once no snapshot can still see them.