Sub topic 3
Transaction IDs
Earlier chapters showed that every row version carries xmin and xmax values. This chapter explains what those numbers are, when PostgreSQL hands them out, and why they behave the way they do. It assumes you can run psql with two sessions and that you have seen xmin, xmax and ctid on the accounts table. It also assumes you know what BEGIN, COMMIT and ROLLBACK do.
What a transaction ID is
A transaction ID (XID) is a 32-bit unsigned integer that PostgreSQL assigns to a transaction so it can mark row versions as "created by" or "deleted by" that transaction. The XID is the only link between a row version and the transaction that wrote it. Every visibility decision in later chapters comes down to comparing XIDs and asking what happened to the transaction behind each one.
XIDs are not timestamps and not commit order. They are a counter that increases by one each time a transaction needs an identity.
XIDs are assigned lazily
A transaction does not receive an XID when it starts. PostgreSQL assigns one the first time the transaction does something that must be recorded on disk, such as inserting, updating, deleting or locking a row. A read-only transaction never consumes an XID.
Until then, a transaction is identified by a virtual transaction ID (vXID), made of the backend's process slot number and a local counter, for example 5/102. Virtual IDs are never written to row versions and are not reused across restarts.
Run this in psql. The first statement recreates the table from earlier chapters if you need it.
CREATE TABLE IF NOT EXISTS accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100) ON CONFLICT DO NOTHING;
BEGIN;
SELECT pg_current_xact_id_if_assigned(); -- NULL: no XID yet
SELECT balance FROM accounts WHERE id = 1; -- a read does not assign one
SELECT pg_current_xact_id_if_assigned(); -- still NULL
SELECT locktype, virtualxid, transactionid
FROM pg_locks
WHERE pid = pg_backend_pid()
AND locktype IN ('virtualxid', 'transactionid');
-- one 'virtualxid' row, no 'transactionid' row
SELECT pg_current_xact_id(); -- forces assignment
SELECT locktype, virtualxid, transactionid
FROM pg_locks
WHERE pid = pg_backend_pid()
AND locktype IN ('virtualxid', 'transactionid');
-- now a 'transactionid' row appears too
COMMIT;Every transaction holds an exclusive lock on its own ID for its whole life. This is how another transaction waits for it to finish: it requests a share lock on that ID and blocks until the owner commits or aborts. The next chapters on write conflicts build on this.
Lazy assignment keeps the XID counter from being used up by read traffic. A busy reporting database can run millions of SELECT transactions without moving the counter.
XID order is not commit order
The XID is assigned at the first write, not at commit. A transaction with a lower XID can therefore commit after one with a higher XID.
Here, A began before B, but B has the lower XID because it wrote first. A has the higher XID but committed first. Because of this, you cannot decide visibility by asking "is this XID lower than mine?" PostgreSQL has to look up whether each XID committed, and it needs a snapshot to decide which commits count. Both are covered in later chapters.
XIDs are 32-bit and compared in a circle
A 32-bit counter holds about 4.3 billion values. PostgreSQL does not let it simply run out. It treats the XID space as a circle and compares two normal XIDs with modular arithmetic. For any XID, the 2^31 (about 2.1 billion) XIDs "before" it are in its past and the 2^31 XIDs "after" it are in its future.
This only works if no live row version carries an XID more than about 2 billion transactions old. If one did, it would suddenly appear to be in the future and the row would vanish. Vacuum prevents this by freezing old row versions, which marks them as visible to everyone regardless of their XID. The final chapters on wraparound cover this. For now, remember that the 32-bit width is the reason freezing exists.
PostgreSQL reserves a few values at the bottom of the range:
| XID | Name | Meaning |
|---|---|---|
| 0 | Invalid | "No transaction". An `xmax` of 0 means the row version has not been deleted or locked. |
| 1 | Bootstrap | Used while the cluster is being created by `initdb`. |
| 2 | Frozen | Reserved. Modern versions mark frozen rows with flag bits instead of storing 2 in `xmin`. |
| 3 and up | Normal | Ordinary transaction IDs, compared circularly. |
When the counter passes 2^32 − 1, it skips back to 3.
The 64-bit view: xid and xid8
Two types appear in SQL, and mixing them up is a common source of confusion.
xidis the 32-bit type. Thexminandxmaxsystem columns have this type.xid8is a 64-bit type that adds an epoch (a count of wraparounds) in the high 32 bits. It never wraps in practice.pg_current_xact_id()returns it.
You can cast xid8 to xid to compare it with xmin. The cast drops the epoch.
BEGIN;
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
SELECT pg_current_xact_id() AS xid8_value,
pg_current_xact_id()::xid AS xid_value,
xmin AS row_xmin
FROM accounts
WHERE id = 1;
-- xid_value and row_xmin are equal
COMMIT;Use xid8 when you need to store or compare IDs over a long period, such as in logical replication tooling. Use xid when you are inspecting tuples.
Measuring how old an XID is
The age() function returns how many transactions ago an XID was assigned, relative to the current counter. It is the standard way to see how close a row, table or database is to the 2-billion limit.
SELECT id, xmin, age(xmin) AS xid_age
FROM accounts;
SELECT datname, age(datfrozenxid) AS xid_age
FROM pg_database
ORDER BY xid_age DESC;A freshly written row has a small age. A row that has been frozen shows an age counted from the freeze point, and age(datfrozenxid) tells you how long it has been since the database was last cleaned up. The second query is the same one you will use later when diagnosing wraparound risk.
Subtransactions get their own XIDs
A savepoint starts a subtransaction. When a subtransaction first writes, it receives its own XID, separate from the top-level transaction's. This lets ROLLBACK TO abort the inner work while the outer transaction still commits.
BEGIN;
SELECT pg_current_xact_id(); -- top-level XID, for example 760
SAVEPOINT s1;
INSERT INTO accounts VALUES (2, 50);
SELECT xmin FROM accounts WHERE id = 2; -- a higher XID, for example 761
ROLLBACK TO s1; -- XID 761 is aborted
COMMIT; -- XID 760 commits
SELECT count(*) FROM accounts WHERE id = 2; -- 0The row inserted under XID 761 stays in the heap as a dead version, because its creator aborted. Visibility checks treat it as if it never existed.
Common mistakes
- Assuming a lower XID means an earlier commit. Order of XIDs follows first write only.
- Assuming a
SELECTconsumes XIDs. It does not, unless it locks rows withFOR UPDATEor similar. - Comparing
xidwith<or>. Thexidtype has equality but no ordering operators, because the circular comparison cannot be expressed as a normal sort. Useage()or cast toxid8within the same epoch. - Reading
xmax = 0as "never touched". It means no transaction has deleted or locked this version. A row lock also setsxmax. - Forgetting that a rolled-back transaction still consumed an XID. The counter never moves backward and gaps are normal.
Exercise
In a fresh session you run BEGIN; SELECT * FROM accounts; and then SELECT pgcurrentxactidif_assigned(); What does the second query return, and what changes if you then run UPDATE accounts SET balance = balance WHERE id = 1; and repeat the query?
Show answer
The first call returns NULL, because a read-only transaction has only a virtual transaction ID and no XID. After the UPDATE, the call returns a number. The UPDATE writes a new row version, so the transaction is assigned a real XID, and that XID is also the xmin of the new version.
Exercise
Session A starts a transaction, then session B starts a transaction. B updates a row first and A updates a different row second. Which session has the lower XID, and does that tell you which one committed first?
Show answer
Session B has the lower XID, because XIDs are assigned at the first write, not at BEGIN. The XID tells you nothing about commit order. Either session can commit first, which is why visibility must check the commit status of each XID.
Exercise
Why can PostgreSQL not leave row versions with very old XIDs untouched forever, and what mechanism prevents the resulting problem?
Show answer
XIDs are 32-bit and are compared circularly, so only about 2 billion XIDs count as "in the past". A row version whose xmin becomes older than that would appear to be in the future and would stop being visible. Vacuum freezes old row versions so they are treated as visible to everyone regardless of their XID.