Sub topic 1
How MVCC keeps old row versions
PostgreSQL does not overwrite a row when you change it. It writes a new version of the row and leaves the old one in place for a while. This chapter explains why it works that way and how to see it. The next chapters build on this to explain dead tuples and table bloat.
Prerequisites
This chapter assumes you have the following:
- Basic SQL:
SELECT,INSERT,UPDATE,DELETE, andCREATE TABLE. - Access to
psqlor another PostgreSQL client, and a scratch database where you can create tables. - A general idea of transactions (
BEGIN,COMMIT,ROLLBACK) and what an isolation level is. - A rough idea of what an index is.
The pageinspect example near the end needs a superuser, or a role that has been granted access to that extension's functions. Everything else runs as a normal user.
The problem MVCC solves
A database has to let many sessions read and write at once. A simple design uses locks: a writer blocks readers, and readers block writers. That is correct but slow under load.
PostgreSQL uses multiversion concurrency control (MVCC) instead. With MVCC, the database keeps several versions of a row at the same time. Each transaction sees the versions that were valid at a particular moment. The main result is that readers never block writers, and writers never block readers. Two writers still conflict if they change the same row.
The price is that old versions have to be stored somewhere and cleaned up later. That cleanup is the subject of the rest of this tutorial.
Where row versions live
A PostgreSQL table is stored as a heap: a file divided into 8 kB pages. Each page holds a number of row versions. The storage unit is a tuple, which is one physical version of one logical row. A logical row that has been updated three times can have several tuples in the heap.
Every tuple has a header with system columns. You can select them by name even though they are hidden from SELECT *. These four matter here:
| Column | Meaning |
|---|---|
| `xmin` | ID of the transaction that created this tuple. |
| `xmax` | ID of the transaction that deleted or replaced this tuple, or `0` if none has. |
| `ctid` | Physical location of the tuple as `(page number, item number)`. |
| `cmin`, `cmax` | Command counters, used for visibility inside a single transaction. |
A transaction ID (xid) is a 32-bit number assigned to a transaction when it first writes data. Newer transactions get higher numbers, so the IDs also give an ordering.
Watching an UPDATE create a new version
Run this in a scratch database. The transaction IDs you see will differ from the ones in the comments.
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts VALUES (1, 100);
SELECT ctid, xmin, xmax, * FROM accounts;
-- ctid | xmin | xmax | id | balance
-- (0,1) | 801 | 0 | 1 | 100The row lives at page 0, item 1. It was created by transaction 801, and xmax is 0 because nothing has deleted it.
Now update it:
UPDATE accounts SET balance = 150 WHERE id = 1;
SELECT ctid, xmin, xmax, * FROM accounts;
-- ctid | xmin | xmax | id | balance
-- (0,2) | 802 | 0 | 1 | 150The query returns one row, but its ctid has moved from (0,1) to (0,2), and xmin is now the updating transaction. The UPDATE did not change the tuple at (0,1). It did two things:
- It wrote a new tuple at
(0,2)with the new value andxmin = 802. - It set
xmax = 802on the old tuple at(0,1), marking it as replaced.
Your plain SELECT only returns the new tuple, because the old one is no longer visible to new queries. It is still on the page, though. The pageinspect extension lets you look at both:
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT lp, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('accounts', 0));
-- lp | t_xmin | t_xmax | t_ctid
-- 1 | 801 | 802 | (0,2)
-- 2 | 802 | 0 | (0,2)Item 1 is the old version. Its t_xmax is 802, and its t_ctid points forward to (0,2). This forms a chain from older to newer versions of the same logical row. Item 2 is the current version, and its t_ctid points to itself.
What each statement does to the heap
| Statement | Effect on the heap |
|---|---|
| `INSERT` | Writes a new tuple with `xmin` set to your xid. |
| `DELETE` | Sets `xmax` on the existing tuple. Nothing is removed. |
| `UPDATE` | Sets `xmax` on the old tuple and writes a new tuple. It is a delete plus an insert. |
| `SELECT` | Writes nothing to the tuple, apart from hint bits (see below). |
The key point is that DELETE does not free any space. It only marks the tuple, and the physical removal happens later.
Snapshots decide which version you see
A tuple is not simply "there" or "gone". Whether you see it depends on your snapshot. A snapshot is a record of which transactions had committed at a given moment. It is made up of the oldest still-running xid, the next xid to be assigned, and the list of transactions in progress between them.
For each tuple, PostgreSQL asks two questions:
- Did the transaction in
xmincommit before my snapshot was taken? If not, the tuple does not exist yet from my point of view. - Is
xmaxset, and did that transaction commit before my snapshot? If so, the tuple was already deleted from my point of view.
A tuple is visible when the first answer is yes and the second is no. When to take the snapshot depends on the isolation level:
- At
READ COMMITTED(the default), a new snapshot is taken for each statement. - At
REPEATABLE READandSERIALIZABLE, one snapshot is taken at the first statement of the transaction and kept until it ends.
This sequence shows two sessions at REPEATABLE READ:
You can reproduce this yourself. In session A:
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1; -- 150In session B:
UPDATE accounts SET balance = 200 WHERE id = 1;Back in session A:
SELECT balance FROM accounts WHERE id = 1; -- still 150
COMMIT;
SELECT balance FROM accounts WHERE id = 1; -- 200While session A is open, PostgreSQL has to keep the old tuple (balance 150), because A can still ask for it. This is the direct link between MVCC and bloat: the longer a snapshot lives, the longer old versions must be kept.
Rollbacks and aborted transactions
PostgreSQL does not undo anything when a transaction rolls back. The tuples the transaction wrote stay on the page. Instead, the transaction's status is recorded as aborted in the commit log (pg_xact). Any reader that finds a tuple whose xmin belongs to an aborted transaction treats it as if it never existed.
This makes ROLLBACK very fast. It also means a rolled-back INSERT or UPDATE still takes up space until cleanup removes it. Heavy rollback workloads create the same kind of garbage as heavy update workloads.
Hint bits
Checking the commit log for every tuple on every read would be expensive. To avoid it, the first reader that looks up a tuple's xmin or xmax status stores the result in the tuple header as hint bits. Later readers read the hint bit instead of the commit log.
This has a side effect that surprises people. A SELECT can dirty pages by setting hint bits, so it can cause writes. That is normal, and it is not a sign of a problem.
Row locks also use xmax
xmax has a second use. When you run SELECT ... FOR UPDATE or FOR SHARE, PostgreSQL records the lock in the tuple's xmax, together with flag bits showing it is a lock and not a delete. You can see this:
BEGIN;
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;
SELECT ctid, xmin, xmax FROM accounts WHERE id = 1;
-- xmax is now your transaction's ID, but the row is not deleted
ROLLBACK;So a nonzero xmax does not always mean the tuple is deleted. It can mean a lock is held, or that a transaction wrote an xmax and then rolled back. The visibility rules take all of this into account.
Edge cases to keep in mind
- Indexes point at tuples. Each index entry stores a
ctid. A new tuple version normally needs new index entries, which is why updates also make indexes grow. The chapter on preventing bloat covers the exception, called HOT updates. - An update that changes nothing still writes a new tuple.
UPDATE accounts SET balance = balance WHERE id = 1creates a new version. If you can, add aWHEREclause to skip rows that would not change. ctidis not a stable identifier. It changes on every update and when the table is rewritten. Use a primary key to identify rows.- Transaction IDs are finite. Because they are 32 bits, they eventually wrap around, and old tuples must be marked ("frozen") before that happens. A later chapter covers this.
- MVCC applies to rows, not to DDL. Commands such as
ALTER TABLEtake heavier locks and behave differently.
What comes next
You now have the model that the rest of the tutorial uses. Every UPDATE and DELETE leaves an old tuple behind. The tuple stays as long as some snapshot might still need it. Once no snapshot can see it, it has no purpose, but it still takes up space. The next chapter names such tuples and shows what happens when they pile up.
Exercise
You run UPDATE accounts SET balance = balance + 1 WHERE id = 1; and then SELECT ctid, xmin, xmax FROM accounts WHERE id = 1;. Compared with before the update, what changes in the result, and where does the previous version of the row go?
Show answer
The ctid changes to a new location (for example from (0,2) to (0,3)), and xmin becomes the ID of the updating transaction. xmax is 0 on the new tuple. The previous version is not removed or overwritten. It stays on the page with its xmax set to the updating transaction's ID, and its t_ctid points to the new tuple. It is invisible to new snapshots but remains until cleanup removes it.
Exercise
Session A runs BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM accounts; and leaves the transaction open. Session B then deletes every row and commits. What does session A see if it runs the count again, and why can PostgreSQL not remove the deleted tuples yet?
Show answer
Session A still sees the original count, because its snapshot was taken at its first statement and REPEATABLE READ keeps it for the whole transaction. The deleted tuples have xmax set by a committed transaction, but session A's snapshot treats that transaction as not yet committed. A can still need those versions, so they must stay on the page until A ends.