Sub topic 2
Row versions in the heap
This chapter assumes you know basic SQL and transactions, and that you can run psql in two sessions. It covers where PostgreSQL stores row versions and how it links them. The chapters that follow cover how transaction IDs and snapshots decide which version a query sees.
The heap is an unordered pile of pages
PostgreSQL stores a table in a file called the heap. The heap is split into fixed-size pages of 8 kB by default. A page is the unit PostgreSQL reads from and writes to disk. A page holds many rows, and the table is a sequence of pages numbered from 0.
The heap has no sorting. A new row goes into whichever page has free space. A primary key does not control row placement. It is an index, stored separately, that points into the heap.
Each stored row is a row version, also called a tuple. A tuple holds:
- A fixed header of about 23 bytes. It includes the creating and deleting transaction IDs (
xminandxmax), a pointer to a newer version (t_ctid), and flag bits. - The column values.
One logical row can exist as several tuples at the same time. This is the basis of MVCC in PostgreSQL. An UPDATE does not overwrite the old tuple. It writes a new one.
Inside a page
A page has three regions:
| Region | Location | Contents |
|---|---|---|
| Page header | Start of the page | Bookkeeping, such as where free space begins and ends |
| Line pointer array | After the header, growing toward the end | One small entry per tuple, giving its offset and length in the page |
| Tuples | Filled from the end of the page backward | The row versions themselves |
Free space sits between the line pointers and the tuples. Both sides grow toward each other until the page is full.
Line pointers add a layer of indirection. Other structures refer to a tuple by a line pointer number, not by a byte offset. PostgreSQL can therefore move tuples within a page, for example to defragment it, without changing any reference to them.
ctid: the address of a version
A tuple's physical address is its ctid, a pair (page, item). (0,1) means page 0, line pointer 1. Indexes store these addresses. When an index lookup finds a match, it gets a ctid and fetches that tuple from the heap.
Two things about ctid matter in practice:
- It identifies a version, not a logical row. When a row is updated, the new version gets a new
ctid. - It is not stable.
VACUUM FULLand similar operations rewrite the table and change it. Never store actidas a permanent row identifier.
Each tuple also has a header field t_ctid. It normally holds the tuple's own address. After an update, the old version's t_ctid is changed to point to the new version. This builds a chain from oldest to newest, and the newest version points to itself.
Watching versions appear
The pageinspect extension lets you read a raw heap page. By default only a superuser can install and use it. Create a small table and update the same row three times. Each statement runs in its own transaction.
DROP TABLE IF EXISTS accounts;
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100);
UPDATE accounts SET balance = 90 WHERE id = 1;
UPDATE accounts SET balance = 80 WHERE id = 1;
UPDATE accounts SET balance = 70 WHERE id = 1;
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT lp, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('accounts', 0));A normal SELECT returns one row with balance = 70. The page holds four tuples. The transaction IDs in your output will differ, but the pattern looks like this:
lp | t_xmin | t_xmax | t_ctid
----+--------+--------+--------
1 | 801 | 802 | (0,2)
2 | 802 | 803 | (0,3)
3 | 803 | 804 | (0,4)
4 | 804 | 0 | (0,4)Reading the output:
lpis the line pointer number, so(0,lp)is the tuple'sctid.- Each
t_xminis the transaction that created that version. The first version was created by theINSERT, and each later one by anUPDATE. t_xmaxon versions 1 to 3 is the transaction that replaced them. This is the same number as the next version'st_xmin.- Version 4 has
t_xmax = 0, so nothing has replaced or deleted it. Itst_ctidpoints to itself.
The next two chapters explain xmin and xmax in full. For now, treat them as "created by" and "ended by".
Seeing it without pageinspect
You can see the same effect through ordinary SQL. The system columns ctid and xmin are hidden but can be selected by name:
SELECT ctid, xmin, balance FROM accounts;This shows only the visible version, so you see (0,4) and the latest xmin. Run it before and after an UPDATE and you will see ctid change.
Why the old version stays
Keeping old tuples can look wasteful. It is the point of the design. Suppose session A starts a long report while session B updates a row. A's query still needs the version that existed when it began. If B overwrote it in place, A would have to wait or see inconsistent data. Because B writes a new tuple, A reads the old tuple and B writes without waiting.
The old tuple must stay until no running transaction could need it. After that it is a dead tuple, and VACUUM reclaims its space. A later chapter covers this.
What the heap does not do
A few behaviors surprise people who expect in-place updates.
- Updating a row grows the table, at least until vacuum catches up. An
UPDATEof a single column still writes a whole new tuple, including all unchanged columns. - A
DELETEdoes not shrink the file. It only setsxmaxon the existing tuple. - A rolled-back
UPDATEstill leaves its new tuple in the page. It is invisible because its creating transaction aborted, but it takes space until vacuum removes it. - Large values over about 2 kB are compressed or moved to a separate TOAST table, which has its own versions. The heap tuple holds a small reference. An update that doesn't touch the large column can reuse the existing TOASTed value.
You can measure table size in pages:
SELECT pg_relation_size('accounts') / current_setting('block_size')::int AS pages;A freshly created one-row table reports 1. Run a loop of thousands of updates against it without letting vacuum run, and you will see the page count climb.
Common mistakes
- Treating
ctidas a key. It changes on every update, so it is only safe inside one transaction, for example in aDELETE ... WHERE ctid = ...cleanup of duplicates. - Expecting
heap_page_itemsto show only live data. It shows every line pointer, including dead ones. - Reading a small page count as proof of no bloat. On a tiny table, pruning and vacuum can remove old versions quickly. Page pruning is a cheap, local cleanup that PostgreSQL may do when it touches a page, so your own experiment can show fewer old tuples than the example above. Run it on a fresh table and look straight after the updates.
Summary of the model
- A table is a heap of 8 kB pages. Each page has a header, line pointers, free space and tuples.
- A tuple is one version of a row. One logical row can have several tuples.
ctidis(page, item), the address of one version.UPDATEwrites a new tuple and links the old one to it throught_ctid.- Old tuples stay until vacuum removes them.
Exercise
You run UPDATE accounts SET balance = balance + 1 WHERE id = 1; five times in separate autocommit statements on a fresh one-row table, with no vacuum in between. How many tuples does heap_page_items(get_raw_page('accounts', 0)) list, how many are visible to a plain SELECT, and what is the t_xmax of the newest tuple?
Show answer
Six tuples are listed: the original from the INSERT plus five from the updates. A plain SELECT sees one, the newest. The newest tuple has t_xmax = 0 because no transaction has replaced or deleted it, and its t_ctid points to itself. (If pruning has already run on the page, you may see fewer.)
Exercise
Why is it unsafe to use ctid as a permanent identifier for a row?
Show answer
ctid is the physical address of one row version. Every UPDATE creates a new version with a new ctid, and operations such as VACUUM FULL rewrite the table and move tuples. A stored ctid would soon point to a dead or different tuple. Use a primary key instead.