This article started in December 15 2025, published in December 4 2026.

TL;DR

  • MVCC gives each transaction a consistent view of data without copying the whole database
  • It keeps multiple physical tuples (versions) of the same logical row and uses snapshots to decide visibility
  • Old tuples are cleaned up by vacuum once no one can see them

0. Prerequisites

This article assumes the reader is aware of isolation levels in a database.

References

1. Repeatable Read Example

There is a row containing a user’s balance in the table user_balance as below:

iduser_idbalance
110015000

Assume two transactions are working on the same row concurrently:

TimeTX 1TX 2
1BEGIN ISOLATION LEVEL REPEATABLE READ;BEGIN;
// read committed by default
2select balance from user_balance where user_id = 1001;
// see 5000 as user’s balance
3update user_balance set balance = balance + 1000 where user_id = 1001;
4COMMIT;
// user’s balance now is 6000
5select balance from user_balance where user_id = 1001;
// as expected, still see user’s balance 5000

From the above example, TX 1 is running on the repeatable read isolation level. At first, it sees the user’s balance of 5000. After TX 2 commits a new user’s balance, TX 1 still sees the user’s balance as 5000. No matter what other transactions do, TX 1 always sees the user’s balance as 5000 (unless it changes the user’s balance by itself). That is what snapshot means: helping transactions see a consistent view of data.

In Postgres, serializable behaves the same way; the transaction also sees a consistent snapshot.

How do they implement the consistent snapshot for each transaction? What is a snapshot? Do they make a copy of the entire database when the transaction begins so they can refer to the old values, or is there a better way? Let’s dive in.

2. Postgres Internal

2.1 Transaction ID (aka XID)

Postgres uses a 32-bit integer as xid. There is a global counter for xid; it is monotonically increasing; therefore, former transactions will have smaller xid than later transactions (Well, it’s actually more complex than that, but for the sake of this article, let’s just think about it that way)

Postgres assigns xid to a transaction lazily; it means if you BEGIN a transaction, Postgres won’t assign an xid to it until the first query that modifies data, such as INSERT, UPDATE, DELETE, MERGE, and SELECT ... FOR UPDATE/SHARE. That also means that if you BEGIN a transaction that only reads data, then it won’t get an xid. Because xid is only necessary for data-modifying queries, as it needs to record the xid of the transaction that does the action.

A single create, update, or delete - without BEGIN - also got an xid.

To know if the current transaction has been assigned an xid or not, use the function pg_current_xact_id_if_assigned().

The function pg_current_xact_id() is a bit different; it will force Postgres to assign an xid to the current transaction regardless of whether it needs it or not.

References

2.2 Inspecting the Heap Page

When creating a table, we define the columns; each row in that table will have all of those defined columns. But internally, each row has a few more columns used by the system itself.

ctid, xmin, and xmax are three of those hidden system columns that we need in this article.

Now let’s create the table user_balance.

Note: I use the tool psql in this post.

We can start a new Postgres container on Docker, open the terminal, and use psql -U postgres -d postgres to interact with the database.

The first postgres is the username; the second postgres is the database name.

1
2
3
4
5
CREATE TABLE user_balance (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL,
    balance NUMERIC(12, 2) NOT NULL
);

Begin a new transaction and insert a new row into the table. Notice that the ID of the transaction is 767.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
postgres=# begin;
BEGIN
postgres=*# SELECT pg_current_xact_id();
 pg_current_xact_id 
--------------------
                767
(1 row)

postgres=*# INSERT INTO user_balance (user_id, balance)
VALUES (1001, 5000);
INSERT 0 1
postgres=*# commit;
COMMIT

Now we can query the columns that we defined along with the system columns:

1
2
3
4
5
postgres=# select ctid, xmin, xmax, user_id, balance from user_balance where user_id = 1001;
 ctid  | xmin | xmax | user_id | balance 
-------+------+------+---------+---------
 (0,1) |  767 |    0 |    1001 | 5000.00
(1 row)
  • ctid aka current tuple ID; the physical location of the row is at offset 1 of the heap page 0
  • xmin is the ID of the transaction inserting the row version; 767 matches the transaction ID above.
  • xmax is the ID of the transaction that deleted the row version; the value of 0 means the row version isn’t deleted by any transaction yet; it’s the latest version of the row.

Now, let’s try to update the row.

1
2
3
4
5
6
7
postgres=# update user_balance set balance = balance + 1000 where user_id = 1001;
UPDATE 1
postgres=# select ctid, xmin, xmax, user_id, balance from user_balance where user_id = 1001;
 ctid  | xmin | xmax | user_id | balance 
-------+------+------+---------+---------
 (0,2) |  768 |    0 |    1001 | 6000.00
(1 row)
  • ctid current physical location of the row is now moved to offset 2 of the heap page 0. Notice that the previous version is in offset 1.
  • xmin is changed to 768, which is the ID of the transaction updating the row.

Important: The data rows we can retrieve with a select query like the one above are referred to as logical rows. A logical row is backed by tuples (physical rows). In other words, logical rows are what the data presents to you - what you see; tuples (physical rows) are what are stored and managed by the database in its storage.

Tuples are stored in a space called the heap; the heap is divided into pages, each 8 KB. We can use the pageinspect tool to see what is really stored in the heap page.

1
2
3
4
postgres=# CREATE EXTENSION IF NOT EXISTS pageinspect;
CREATE EXTENSION
postgres=# SELECT *
FROM heap_page_items(get_raw_page('user_balance', 0));

This query will show all data in the heap page 0 of the table user_balance

The SELECT will show a result with many columns like this:

1
2
3
4
5
 lp | lp_off | lp_flags | lp_len | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask2 | t_infomask | t_hoff | t_bits | t_oid |                    t_data                    
----+--------+----------+--------+--------+--------+----------+--------+-------------+------------+--------+--------+-------+----------------------------------------------
  1 |   8144 |        1 |     45 |    767 |    768 |        0 | (0,2)  |       16387 |       1282 |     24 |        |       | \x0100000000000000e9030000000000000b00818813
  2 |   8096 |        1 |     45 |    768 |      0 |        0 | (0,2)  |       32771 |      10498 |     24 |        |       | \x0100000000000000e9030000000000000b00817017
(2 rows)

There are many columns; now let’s focus on some important ones related to this post.

1
2
3
4
5
6
7
postgres=# SELECT lp, t_xmin, t_xmax, t_data
FROM heap_page_items(get_raw_page('user_balance', 0));
 lp | t_xmin | t_xmax |                    t_data                    
----+--------+--------+----------------------------------------------
  1 |    767 |    768 | \x0100000000000000e9030000000000000b00818813
  2 |    768 |      0 | \x0100000000000000e9030000000000000b00817017
(2 rows)

From the normal query, we see one (logical) row, but under the hood there are two (physical) tuples for that row.

  • lp is the line pointer, or the offset in the heap page. The first version (balance = 5000) is at offset 1; the second version (balance = 6000) is at offset 2.
  • t_data contains encoded data of the row version. The data of the row, like id, user_id, balance, is encoded and stored there.
  • t_xminand t_xmax are similar to xmin and xmax we saw above.
  • t_ctid is the pointer to the newer version of the row: lp 1 -> (0,2), the newest version points to itself. They form a chain from oldest to newest tuples.

Transaction with xid 767 created a logical row by inserting a tuple at offset 1 of heap page 0. Transaction with xid 768 updated the logical row created by 767 by updating the t_xmax of the tuple at offset 1 to 768 to mark the tuple as deleted, and inserting a new tuple for the new value at offset 2. In Postgres, there is no in-place update; an update is just a tuple deletion followed by a tuple insertion.

Logical row to physical tuple

  • Insert a logical row: insert a tuple with t_xmin set to the xid of the transaction that inserted it, and t_xmax is zero.
  • Delete a logical row: t_xmax of the tuple will be set to the xid of the transaction that deletes it.
  • Update a logical row: it is just a delete followed by an insert.

Why doesn’t Postgres do in-place update?

Doing in-place indeed helps save a lot of storage, but Postgres has reasons not to do so.

Keeping old versions as separate tuples helps readers not block the writer. For example, a transaction reads tuple 1 at the repeatable read isolation level; another transaction can update the row concurrently by inserting a tuple and marking the previous tuple as deleted; the reader continues to see a consistent value for the row. An in-place update needs to copy the old version elsewhere, like to an undo log in MySQL.

If the update is in place, after rollback, we need to revert all changes to their previous values. With the Postgres approach, we just leave our changes there and roll back instantly. Because we don’t edit the value, we create a new version of the values. All abandoned work will be cleaned up later.

References

2.3 pg_xact

This is where Postgres stores the status of an xid. We can use this query to get the status of an xid:

1
2
3
4
5
postgres=# SELECT pg_xact_status('768'::xid8);
 pg_xact_status 
----------------
 committed
(1 row)

The status can be: in progress, committed, aborted, or NULL if the xid is too old and its info gets truncated.

So when we see a tuple with xmin=xxx or xmax=yyy, don’t immediately conclude that the tuple was inserted or deleted; it depends on a few factors. One of those is that we need to check xmin and xmax statuses in pg_xact to see if it committed or rolled back.

2.4 Snapshot

Is a snapshot a copy of all data? nah, that’s too expensive. Instead, it’s defined by a few xid numbers. Since each logical row can have multiple physical tuples, Postgres uses these numbers to pick the right tuples to serve to the reader.

1
2
3
4
5
postgres=*# SELECT pg_current_snapshot();
 pg_current_snapshot 
---------------------
 778:782:778,779
(1 row)

The output is in the format: xmin:xmax:xip_list:

  • xmin: lowest active transaction ID at the snapshot taken time. If there are no active transactions, then xmin equals xmax. All changes committed by xid < xmin should be settled, either committed or rolled back.
  • xmax: the value is one past the highest completed xid; completed means either committed or rolled back. It defines the upper visibility bound. XIDs at or above this point are considered unsettled. Changes made by these xid should be ignored.
  • xip_list: list of active XIDs at the snapshot taken time. XIDs in the list are xmin <= xid < xmax. Changes made by these xid should also be ignored.

Let’s consider the snapshot 778:782:778,779. At the time the snapshot is created, the smallest xid of active transactions is 778; 782 is one past the highest completed xid. Between 778 and 782 [778,782), there are two active transactions: 778 and 779.

Snapshot 778:782:778,779

The way a snapshot is created:

  • Read committed: get a new snapshot at the start of any query in the transaction. Therefore, each query in the transaction may see a different snapshot.
  • Repeatable Read, Serializable: Get a snapshot at the start of the first query, and reuse that snapshot throughout the transaction. All queries in the same transaction see the same snapshot.

A confused case

Open a session with psql, then begin a transaction. Assume the current session is the only one connecting to the database instance.

1
2
3
4
5
6
7
postgres=# begin;
BEGIN
postgres=*# SELECT pg_current_snapshot();
 pg_current_snapshot 
---------------------
 777:777:
(1 row)

What does that snapshot 777:777: mean? As we already know, Postgres assigns an xid lazily when you do a data-modifying query (or you force it to get one xid). So the current transaction doesn’t have an xid yet. The xip_list is empty, indicating there is no active transaction at the time it is taken. xmax is 777, meaning the highest completed xid is 776; xmax = 776 + 1. For xmin, since the xip_list is empty, we can’t calculate the smallest active xid, right? In this case, xmin is xmax.

Even if you open many other concurrent sessions along with the above session and begin new transactions in each session, as long as those transactions haven’t been assigned an xid, the above session still sees that 777:777: snapshot.

2.5 MVCC rule

The general rule is that a tuple’s visibility is relative; it can be visible in some snapshots but invisible in others.

2.5.1 MVCC rules with xid

Now let’s put it together: each heap tuple has xmin and xmax columns storing xid. Each snapshot has xmin, xmax, and xip_list. Based on that information about the tuples and the snapshot, the database can decide which tuples are visible to the snapshot.

Note: In this section, xmin and xmax of a tuple are denoted as t.xmin and t.xmax. xmin, xmax, and xip_list of a snapshot are denoted as s.xmin, s.xmax, and s.xip_list.

In a snapshot POV, xid of a transaction can only be in two states:

  • Settled: in simple words, a settled xid means it has committed or rolled back before the snapshot is taken. In detail, it’s settled when xid < s.xmin. If s.xmin <= xid < s.xmax, then it’s settled when the xid is not in the s.xip_list.
  • Unsettled: The opposite of settled, unsettled xid are those that have begun but haven’t committed while the snapshot was taken, or begin after the snapshot was taken. In other words, it’s unsettled when xid is in the s.xip_list or xid >= s.xmax.

A settled xid also has two possible states: Committed, Rolled back

Postgres stores xid state in pg_xact; when an xid commits or rolls back, nothing in the heap page changes; it will just update the state in pg_xact.

When a reader encounters a tuple, if either xmin or xmax is settled according to the reader’s snapshot, the reader needs to check the xid state in pg_xact to know if that xid committed or rolled back. If the xid is unsettled, then there is no need to do the check, because the snapshot ignores that xid anyway.

But checking the pg_xact on every read would be ineffective. The first reader that does the checking will cache the result by setting the bits HEAP_XMIN_COMMITTED, HEAP_XMAX_COMMITTED, HEAP_XMIN_INVALID, HEAP_XMAX_INVALID in the t_infomask column of the tuple as a hint for later readers.

For those rolled-back tuples, the VACUUM process will lazily remove tuples inserted by rolled-back xids to free space. Those tuples have xmax set by rolled-back xids will be left there, because it’s harmless and will be overwritten by the xid that really deletes.

Aborted xid didWhat’s left in the heapEffect
InsertA new tuple is inserted with xmin set to the aborted xidThe inserted tuple is invisible to any snapshot
DeleteThe xmax of the deleted tuple is set to the aborted xidThe tuple is not considered deleted, and is visible to snapshots (still follows the MVCC rules)
UpdateCombine a Delete with an InsertThe deleted tuple is still visible, and the inserted tuple is invisible to any snapshot.

When specifying the visibility of a tuple from the POV of a snapshot, go through these two steps:

Step 1: If the xid in t.xmin

  • Unsettled -> invisible
  • Settled / Committed -> visible
  • Settled / Rolled back -> invisible

If visible, jump to step 2 to continue.

Step 2: If the xid in t.xmax

  • Empty -> hasn’t been deleted yet - visibility result from step 1
  • Unsettled -> visibility result from step 1
  • Settled / Committed -> invisible - regardless of visibility from step 1
  • Settled / Rolled back -> visibility result from step 1

Note: for settled xid, to know if it committed or rolled back, the reader will first check the hint bits on the column t_infomask; if no hint, it will check in the pg_xact and set the hints for later readers.

Exception:

A query can see changes made by earlier commands in its own transaction, even before it commits. But it doesn’t see the changes made by itself or by commands that run after it started.

This raises an interesting problem: because all changes in the same transaction share the same xid, how does Postgres know the order?

2.5.2 MVCC rules with cid

Within a transaction, each query is assigned a command ID, denoted as cid. cid starts at 0 when the transaction begins and increments each time the transaction executes a data-modification query. Each tuple has cmin for the cid of the insert command, and cmax for the cid of the delete command.

Each tuple has a t_field3 column and a bitmap column t_infomask with the bit HEAP_COMBOCID. t_field3 is meant to store information related to cmin and cmax.

So, to interpret t_field3, you need the bit HEAP_COMBOCID, xmin and xmax.

If the bit is off and xmax is empty, t_field3 is the cid of the query that inserted the tuple (cmin). If the bit is off and xmax is set, t_field3 is the cid of the query that deleted the tuple (cmax). This case occurs when the tuple is inserted and hasn’t been deleted, or inserted and deleted by different xids.

If the bit is on, the tuple is inserted and deleted by the same xid; t_field3 is the index of the (cmin, cmax) pair in memory. Since the pair of cmin and cmax is in memory, it can be discarded after the transaction finishes.

MVCC rules with cid within a transaction (currcid is the current cid in the transaction): Step 1: check cmin

  • cmin < currcid -> visible
  • cmin >= currcid -> invisible

If visible, jump to step 2 to continue.

Step 2: check cmax

  • cmax empty -> visible (not deleted yet)
  • cmax < currcid -> invisible
  • cmax >= currcid -> visible

Let’s take an example to demonstrate it:

1
2
3
4
BEGIN;                          -- xid 100
INSERT INTO t VALUES (1);       -- cid 0
UPDATE t SET v = v + 1;         -- cid 1
SELECT * FROM t;                -- cid 2
  • Line 1: begin a transaction
  • Line 2: insert a tuple with cmin = 0; the t_field3 now stores cmin. The heap looks like:
1
[value = 1 xmin=100  t_field3=cmin=0]
  • Line 3: update the tuple, scan through the pages in heap space; for each page, find matched records, delete the matched records, and insert new tuples into available space in the heap. The update might run into its own inserted tuple again: for example, the update currently scans the first page of the heap and inserts a tuple into the tail page; later, when it scans down to the tail, it will encounter its own inserted tuples. But this time cmin = currcid, so the tuples get ignored. After the update, the heap will now have two tuples:
1
2
[value = 1 xmin=100 xmax=100 t_infomask:HEAP_COMBOCID=true t_field3=index=0]
[value = 2 xmin=100 t_field3=cmin=1]

The array contains the cmin and cmax pair in memory; the index of the pair is zero:

1
[(cmin = 0 cmax = 1)]
  • Line 4: only see the second tuple because the first tuple got cmax < currcid.

Many cases can happen:

  • Other xid 1 insert and current xid 10 delete, t.xmax is current xid, t_field3 now stores cmax.
1
[value=123 xmin=1 xmax=10 t_field3=cmax=5]
  • Other xid 1 insert and current xid 10 update, just delete and insert new tuple.
1
2
[value=123 xmin=1 xmax=10 t_field3=cmax=5]
[value=124 xmin=10 t_field3=cmin=5]
  • Current xid 10 insert: t.xmin is the current xid. There are many inserted tuples with the same xid.
1
2
3
[value=123 xmin=10 t_field3=cmin=5]
[value=456 xmin=10 t_field3=cmin=6]
[value=789 xmin=10 t_field3=cmin=7]
  • Current xid 10 insert then delete; both t.xmax and t.xmin are the current xid.
1
[value=123 xmin=10 xmax=10 t_infomask:HEAP_COMBOCID=true t_field3=0]

Memory:

1
[(cmin=5 cmax=6)]
  • Current xid 10 insert then update; update is just a delete followed by an insert.
1
2
[value=123 xmin=10 xmax=10 t_infomask:HEAP_COMBOCID=true t_field3=index=0] 
[value=124 xmin=10 t_field3=cmin=6]

Memory:

1
[(cmin=5 cmax=6)]

2.5.3 MVCC rules with xid and cid

Step 1: check t.xmin

  • current xid -> visible if cmin < currcid, else invisible.
  • unsettled -> invisible
  • settled/committed -> visible
  • settled/rolled back -> invisible

If visible, jump to step 2 to continue checking.

Step 2: check t.xmax

  • empty -> visible
  • current xid -> invisible if cmax < currcid, else visible.
  • unsettled -> visible
  • settled/committed -> invisible
  • settled/rolled back -> visible

Note: for a settled xid, to know if it committed or rolled back, the reader will first check the hint bits on the column t_infomask; if no hint, it will check in the pg_xact and set the hints for later readers.

Important: In this article, I can only describe a rough idea of MVCC. It is in fact much more complicated than that. For example, it needs to handle subtransactions and row locks. For full details, please check out the code HeapTupleSatisfiesMVCC; it provides the MVCC rules in full.

References

2.6 Example

2.6.1 Repeatable Read vs Read Committed

For this example, I recreated the table from scratch; that’s why you see the jump in xid compared to section 2.2.

TimeTX 1TX 2TX 3TX 4
01BEGIN;
02SELECT pg_current_xact_id();
843
03SELECT pg_current_snapshot();
843:843:
04select balance from user_balance where user_id = 1001;
// 6000
05update user_balance set balance = balance + 1000 where user_id = 1001;
// 7000
06BEGIN ISOLATION LEVEL REPEATABLE READ;BEGIN;
07SELECT pg_current_snapshot();
843:843:
SELECT pg_current_snapshot();
843:843:
08select balance from user_balance where user_id = 1001
6000
select balance from user_balance where user_id = 1001
6000
09COMMIT;
10BEGIN;
11SELECT pg_current_xact_id();
844
12SELECT pg_current_snapshot();
844:844:
13select balance from user_balance where user_id = 1001
7000
14SELECT pg_current_snapshot();
843:843:
SELECT pg_current_snapshot();
844:844:
15select balance from user_balance where user_id = 1001
6000
select balance from user_balance where user_id = 1001
7000
16update user_balance set balance = balance + 1000 where user_id = 1001;
8000
17COMMIT;
18SELECT pg_current_snapshot();
843:843:
SELECT pg_current_snapshot();
845:845:
19select balance from user_balance where user_id = 1001
6000
select balance from user_balance where user_id = 1001
8000
20ROLLBACKCOMMIT

The heap dumps below were collected with this query:

1
2
SELECT lp, t_xmin, t_xmax, t_field3, t_ctid, t_infomask, t_data
FROM heap_page_items(get_raw_page('user_balance', 0));

Step 1: TX 1 BEGIN;

The BEGIN doesn’t change the heap page. Here is the heap dump after step 1; the table hasn’t been read by anyone before:

1
2
3
4
 lp | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask |                    t_data
----+--------+--------+----------+--------+------------+----------------------------------------------
  1 |    841 |    842 |        0 | (0,2)  |        258 | \x0100000000000000e9030000000000000b00818813
  2 |    842 |      0 |        0 | (0,2)  |      10242 | \x0100000000000000e9030000000000000b00817017

There are two tuples of the same logical row in the heap page. The tuple at offset 2 is the latest, with t_ctid pointing to itself; the tuple at offset 1 points to tuple 2.

Let’s also decode the t_infomask of each tuple. The hint bits in the table are listed in the bit order from left to right.

OffsetDecimalBinaryFlagsMeaning
12580000 0001 0000 0010XMIN_COMMITTED, HASVARWIDTHxmin is committed, HASVARWIDTH means the tuple has variable-width columns.
2102420010 1000 0000 0010UPDATED, XMAX_INVALID, HASVARWIDTHUPDATED means created by an UPDATE query, XMAX_INVALID means xmax is empty because t_xmax is 0

t_infomask

From those hints, tuple 1 doesn’t know if its xmax (842) is committed, and tuple 2 doesn’t know if its xmin (842) is committed.

Step 3: TX 1 SELECT pg_current_snapshot();

The current snapshot is 843:843:; xmin and xmax are 843. xids below 843 are settled; 843 and above are unsettled.

Step 4: TX 1 select balance from user_balance where user_id = 1001;

1
2
3
4
 lp | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask |                    t_data
----+--------+--------+----------+--------+------------+----------------------------------------------
  1 |    841 |    842 |        0 | (0,2)  |       1282 | \x0100000000000000e9030000000000000b00818813
  2 |    842 |      0 |        0 | (0,2)  |      10498 | \x0100000000000000e9030000000000000b00817017

Let’s check the heap after the select:

OffsetDecimalBinaryFlagsMeaning
112820000 0101 0000 0010XMAX_COMMITTED, XMIN_COMMITTED, HASVARWIDTHnow we know that xmax is committed
2104980010 1001 0000 0010UPDATED, XMAX_INVALID, XMIN_COMMITTED, HASVARWIDTHnow we know that xmin is committed

When the reader reads tuples 1 and 2, according to its snapshot, xid 842 is settled, but it doesn’t know if the xid is committed or rolled back. The reader found no hint bits in the tuples. So it must check the status of xid 842 in pg_xact and then cache the result in the hint bits. 842 is committed before our exercise, but the hint bits are lazily set by a reader. It’s fascinating to know that a read in Postgres can result in writes.

Since xid 842 is settled and committed, tuple 1 is invisible, and tuple 2 is visible.

Step 5: TX 1 update user_balance set balance = balance + 1000 where user_id = 1001;, not committed

1
2
3
4
5
 lp | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask |                    t_data
----+--------+--------+----------+--------+------------+----------------------------------------------
  ...
  2 |    842 |    843 |        0 | (0,3)  |       8450 | \x0100000000000000e9030000000000000b00817017
  3 |    843 |      0 |        0 | (0,3)  |      10242 | \x0100000000000000e9030000000000000b0081581b

The heap page now has a new tuple. Also notice that the t_infomask has changed in tuples 2 and 3; let’s decode it:

OffsetDecimalBinaryFlagsMeaning
284500010 0001 0000 0010UPDATED, XMAX_INVALID, XMIN_COMMITTED, HASVARWIDTHxmax is not empty and unknown status - check pg_xact
3102420010 1000 0000 0010UPDATED, XMAX_INVALID, HASVARWIDTHxmin unknown status - check pg_xact, xmax is empty

xid 843 marks tuple at offset 2 as deleted and inserts a new tuple at offset 3. Offset 3 is now the newest version of the logical row; t_ctid of tuple 2 now points to offset 3.

Also, in tuple 2, we observed that after a new insert in step 1, the tuple will have the bit XMAX_INVALID indicating that the xmax is empty. When the tuple is marked as deleted, the XMAX_INVALID bit is cleared, indicating that xmax is not empty and its status is unknown. Later, depending on the status of the xmax transaction, if it is rolled back, XMAX_INVALID will be enabled again; if it is committed, XMAX_COMMITTED will be enabled instead.

Step 7: TX 2 and 3 SELECT pg_current_snapshot();

Both TX 2 and 3 at step 5 have the snapshot 843:843:. At the time the snapshot was taken, the highest completed xid was 842 (smaller than the xid of TX 1); therefore, xmax = 842 + 1 = 843. xmin is the smallest active xid, which is also 843. xip_list is empty because there is no active xid that is smaller than xmax 843. This snapshot means all xid below 843 are settled, and all xid at and above 843 are unsettled.

Step 8: TX 2 and 3 select balance from user_balance where user_id = 1001;

The heap page still looks the same as in step 5.

According to the snapshot 843:843: POV, xid 843 is unsettled; therefore, its deletion of tuple 2 and insertion of tuple 3 are not effective. The tuple 2 inserted by xid 842 (settled) remains visible; the tuple 3 inserted by xid 843 is invisible to the snapshot.

Step 9: TX 1 COMMIT;

After TX 1 committed, the heap remains the same as step 5. It’s only that the status of TX 1 in pg_xact is now committed.

Step 12: TX 4 SELECT pg_current_snapshot();

TX 4 at this moment saw the snapshot 844:844:; the interpretation is similar to step 3.

Step 13: TX 4 select balance from user_balance where user_id = 1001

1
2
3
4
5
 lp | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask |                    t_data
----+--------+--------+----------+--------+------------+----------------------------------------------
  ...
  2 |    842 |    843 |        0 | (0,3)  |       9474 | \x0100000000000000e9030000000000000b00817017
  3 |    843 |      0 |        0 | (0,3)  |      10498 | \x0100000000000000e9030000000000000b0081581b

Tuples 2 and 3 have updated the t_infomask; let’s decode it:

OffsetDecimalBinaryFlagsMeaning
294740010 0101 0000 0010UPDATED, XMAX_COMMITTED, XMIN_COMMITTED, HASVARWIDTHxmax now committed
3104980010 1001 0000 0010UPDATED, XMAX_INVALID, XMIN_COMMITTED, HASVARWIDTHxmin now committed

According to the snapshot 844:844:, xid 843 is settled. In the previous heap dump at step 5, the reader doesn’t yet see hint bits for xmax in tuple 2 and for xmin in tuple 3. So the reader checks the status of 843 in pg_xact and updates the hint bits.

Also, according to the snapshot, tuple 3 is visible; the deletion on tuple 2 is effective; therefore, tuple 2 becomes invisible.

Step 14: TX 2 and 3 SELECT pg_current_snapshot();

Tx 2 and Tx 3 now see different snapshots; Tx 2 saw 843:843: and Tx 3 saw 844:844:. Tx 2 is at the repeatable-read isolation level; it always sees the same snapshot throughout its lifetime. Tx 3 is in read committed; each query will take a new snapshot. For Tx 3, the highest completed xid is 843; therefore, xmax is 844. xmin is simply the smallest xid, which is also 844. There is one active xid, 844 by TX4, but it does not satisfy the condition xid < xmax to qualify for xip_list.

Step 15: TX 2 and 3 select balance from user_balance where user_id = 1001;

Same heap dump as step 13. According to the snapshot of each transaction, Tx 2 still sees tuple 2; Tx 3 now sees tuple 3.

Step 16: TX 4 update user_balance set balance = balance + 1000 where user_id = 1001;

1
2
3
4
5
6
 lp | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask |                    t_data
----+--------+--------+----------+--------+------------+----------------------------------------------
  ...
  ...
  3 |    843 |    844 |        0 | (0,4)  |       8450 | \x0100000000000000e9030000000000000b0081581b
  4 |    844 |      0 |        0 | (0,4)  |      10242 | \x0100000000000000e9030000000000000b0081401f

Tuple 3 has updated the t_infomask; tuple 4 is new. Let’s decode it:

OffsetDecimalBinaryFlagsMeaning
384500010 0001 0000 0010UPDATED, XMAX_INVALID, XMIN_COMMITTED, HASVARWIDTHxmax is not empty and unknown status - check pg_xact
4102420010 1000 0000 0010UPDATED, XMAX_INVALID, HASVARWIDTHxmin unknown status - check pg_xact

The tuple at offset 3 cleared the XMAX_INVALID bit, indicating that xmax is not empty and its status is unknown; the next reader needs to check in pg_xact. This behavior has happened previously in step 5.

Tx 4 with xid 844 inserted a new tuple at offset 4 and marked the tuple at offset 3 as deleted, but its status in pg_xact is still in progress.

Step 17: TX 4 COMMIT;

Status of Tx 4 (xid 844) in pg_xact is committed; the heap remains the same as in step 16.

Step 18: TX 2 and 3 SELECT pg_current_snapshot();

Tx 2 running on repeatable read still sees the same 843:843: snapshot. Tx 3 already sees a new snapshot after Tx 4 commits: 845:845:. Since they have different snapshots, they will see different data. Tx 2 sees the same data throughout its lifetime. Tx 3 always sees the latest committed data.

Step 19: TX 2 and 3 select balance from user_balance where user_id = 1001

Assume that we execute the select on TX 2 before TX 3. Even though xid 844 was committed earlier, the select on TX 2 keeps the heap unchanged, whereas the same query on TX 3 updates the hint bits. Because TX 2 is on snapshot 843:843:, and xid 844 is unsettled to it, it never checks pg_xact.

1
2
3
4
5
6
 lp | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask |                    t_data
----+--------+--------+----------+--------+------------+----------------------------------------------
  ...
  2 |    842 |    843 |        0 | (0,3)  |       9474 | \x0100000000000000e9030000000000000b00817017
  3 |    843 |    844 |        0 | (0,4)  |       9474 | \x0100000000000000e9030000000000000b0081581b
  4 |    844 |      0 |        0 | (0,4)  |      10498 | \x0100000000000000e9030000000000000b0081401f

Again, the t_infomask 9474 on tuple 3 tells us that xmax 844 is committed, and 10498 on tuple 4 tells us that xmin 844 is committed.

OffsetDecimalBinaryFlagsMeaning
394740010 0101 0000 0010UPDATED, XMAX_COMMITTED, XMIN_COMMITTED, HASVARWIDTHxmax is committed
4104980010 1001 0000 0010UPDATED, XMAX_INVALID, XMIN_COMMITTED, HASVARWIDTHxmin is committed

TX 2 with snapshot 843:843: still sees tuple 2; TX 3 with snapshot 845:845: sees the latest tuple at offset 4.

Step 20: TX 2 rolls back and TX 3 commits

Tx 2 and Tx 3 perform read-only queries, so they don’t acquire an xid or modify the heap page.

2.6.2 The xip_list

xip_list shows an active xid list that satisfies the condition xid < xmax, with xmax from the snapshot. Notice that TX 2 and 3 in the example below don’t have the BEGIN and COMMIT; they are just single queries with no explicit transaction. Imagine that each of those independent queries will be wrapped in an implicit transaction, each with its own snapshot. The INSERT in TX 2 still got an xid.

TimeTX 1TX 2TX 3
01BEGIN;
02update user_balance set balance = balance + 1000 where user_id = 1001;
xid 845
03insert into user_balance(user_id, balance) values(1002, 5000);
xid 846, committed
04SELECT pg_current_snapshot();
845:847:845
05SELECT ctid, xmin, xmax, user_id, balance FROM user_balance;
(0,4) 1001: 8000, xmax = 845
(0,6) 1002: 5000

Step 1: TX 1 BEGIN.

The heap dump looks similar to the last dump on 2.6.1

Step 2: TX 1 update user_balance set balance = balance + 1000 where user_id = 1001;

1
2
3
4
5
6
7
 lp | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask |                    t_data
----+--------+--------+----------+--------+------------+----------------------------------------------
  ...
  ...
  ...
  4 |    844 |    845 |        0 | (0,5)  |       8450 | \x0100000000000000e9030000000000000b0081401f
  5 |    845 |      0 |        0 | (0,5)  |      10242 | \x0100000000000000e9030000000000000b00812823
OffsetDecimalBinaryFlagsMeaning
484500010 0001 0000 0010UPDATED, XMAX_INVALID, XMIN_COMMITTED, HASVARWIDTHxmax is not empty and unknown status - check pg_xact
5102420010 1000 0000 0010UPDATED, XMAX_INVALID, HASVARWIDTHxmin unknown status - check pg_xact

The xid 845 marked tuple 4 as deleted and inserted a new tuple at offset 5. xid 845 is still in progress.

Step 3: TX 2 insert into user_balance(user_id, balance) values(1002, 5000);

1
2
3
4
5
6
7
8
 lp | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask |                    t_data
----+--------+--------+----------+--------+------------+----------------------------------------------
  ...
  ...
  ...
  4 |    844 |    845 |        0 | (0,5)  |       8450 | \x0100000000000000e9030000000000000b0081401f
  5 |    845 |      0 |        0 | (0,5)  |      10242 | \x0100000000000000e9030000000000000b00812823
  6 |    846 |      0 |        0 | (0,6)  |       2050 | \x0200000000000000ea030000000000000b00818813
OffsetDecimalBinaryFlagsMeaning
620500000 1000 0000 0010XMAX_INVALID, HASVARWIDTHxmin status is unknown, xmax is empty

The Tx 2 (xid 846) inserts a new tuple at offset 6 for a new logical row; therefore, xmin is its xid. Tx 2 status in pg_xact is committed. The current logical row has only one tuple, so the tuple is the latest and t_ctid points to itself. So, in the table, there are currently two logical rows, with the latest tuples at offsets 5 and 6.

Also notice the hint bits of tuple 6; they don’t tell whether xmin is committed or rolled back. The next reader will need to check the status of xid 846 and set the hint bit accordingly.

Step 4: TX 3 SELECT pg_current_snapshot();

The snapshot is 845:847:845. So the highest completed xid at that time is 846, so xmax is 846 + 1. There is only one active xid at the snapshot time, which is 845; therefore, xmin is 845, and 845 is also included in xip_list because it’s smaller than xmax.

For this snapshot, all xids smaller than xid 845 are settled. All xids that are equal to or larger than xmax 847 are unsettled. xid 845 is unsettled because it’s in the xip_list; xid 846 is settled.

Step 5: TX 3 SELECT ctid, xmin, xmax, user_id, balance FROM user_balance;

1
2
3
4
5
6
7
8
 lp | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask |                    t_data
----+--------+--------+----------+--------+------------+----------------------------------------------
  ...
  ...
  ...
  4 |    844 |    845 |        0 | (0,5)  |       8450 | \x0100000000000000e9030000000000000b0081401f
  5 |    845 |      0 |        0 | (0,5)  |      10242 | \x0100000000000000e9030000000000000b00812823
  6 |    846 |      0 |        0 | (0,6)  |       2306 | \x0200000000000000ea030000000000000b00818813

Only tuple 6 has hint bit updates:

OffsetDecimalBinaryFlagsMeaning
623060000 1001 0000 0010XMAX_INVALID, XMIN_COMMITTED, HASVARWIDTHxmin 846 is commited, xmax is empty

Tuples 4 and 5 have no updates in t_infomask because xid 845 is unsettled in the current snapshot.

Since xid 845 is unsettled, its deletion on tuple 4 and insertion on tuple 5 are not effective. Tuple 4 is still visible, and tuple 5 is invisible to the current snapshot. Tuple 6 is visible to the current snapshot because 846 is settled and committed.

2.6.3 ROLLBACK

Continue from step 2.6.2

TimeTX 1TX 4
01ROLLBACK;
02SELECT pg_current_snapshot();
847:847:
03SELECT ctid, xmin, xmax, user_id, balance FROM user_balance;
(0,4) 1001: 8000, xmax = 845
(0,6) 1002: 5000

Step 1: TX 1 ROLLBACK;

The heap dump is the same as in the last dump in 2.6.2. Only the status of xid 845 becomes rolled back in pg_xact. The next reader will update the hint bits for those tuples affected by xid 845.

Step 2: TX 4 SELECT pg_current_snapshot();

The snapshot 847:847: means all xids smaller than 847 are settled; 847 and above are unsettled.

Step 3: TX 4 SELECT ctid, xmin, xmax, user_id, balance FROM user_balance;

1
2
3
4
5
6
7
8
 lp | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask |                    t_data
----+--------+--------+----------+--------+------------+----------------------------------------------
  1 |    841 |    842 |        0 | (0,2)  |       1282 | \x0100000000000000e9030000000000000b00818813
  2 |    842 |    843 |        0 | (0,3)  |       9474 | \x0100000000000000e9030000000000000b00817017
  3 |    843 |    844 |        0 | (0,4)  |       9474 | \x0100000000000000e9030000000000000b0081581b
  4 |    844 |    845 |        0 | (0,5)  |      10498 | \x0100000000000000e9030000000000000b0081401f
  5 |    845 |      0 |        0 | (0,5)  |      10754 | \x0100000000000000e9030000000000000b00812823
  6 |    846 |      0 |        0 | (0,6)  |       2306 | \x0200000000000000ea030000000000000b00818813

Notice that the t_infomask of offsets 4 and 5 has changed after the select:

OffsetDecimalBinaryFlagsMeaning
4104980010 1001 0000 0010UPDATED, XMAX_INVALID, XMIN_COMMITTED, HASVARWIDTHThe xmax is 845 (> 0), so XMAX_INVALID means xid aborted, so the xmax become ineffective
5107540010 1010 0000 0010UPDATED, XMAX_INVALID, XMIN_INVALID, HASVARWIDTHXMIN_INVALID is on, so the xmin becomes ineffective and this tuple is visible to no one. It will be cleaned up later by VACUUM.

The current table has two logical rows. Tuples 4 and 6 are data for the two logical rows, respectively. So why does the first logical row see tuple 4 instead of the latest tuple 5, even though tuple 4 is marked deleted by xid 845? It’s because the status of xid 845 has been rolled back in pg_xact; therefore, its deletion of tuple 4 and insertion of tuple 5 are ineffective.

3. VACUUM

In Postgres, a logical row can have many tuples, each for a version, from oldest to newest; the t_ctid of each tuple points to the newer tuple. As a result, the more updates a logical row has, the more tuples it contains; eventually, the heap space required for a single logical row grows very large.

Also observed that we don’t need to keep those tuples forever when no other snapshot references them, especially those tuples that got xmax. If we can be sure no current or future snapshot needs it, we can remove it, freeing space for other tuples.

There are two types of target tuples to clean up:

  • deleted tuples that are no longer needed. Two conditions: first, tuples with xmax committed; if rolled back, the delete doesn’t count. secondly, the xmax is below the cutoff xid (explained below).
  • tuples inserted by rolled back transactions

In Postgres, tuples that can be cleaned up by vacuum are called dead tuples.

One more thing to know is how indexes in Postgres point to tuples in the heap. So we know that a logical row can have multiple tuples; then which tuple does the index point to? There are two types of updates in Postgres: normal updates and heap-only tuple updates.

  • Normal update: Postgres adds a new index entry to point to the new tuple; lookups are directly from the index.
  • HOT update: only applicable when the new version fits on the same heap page as the previous version, and no indexed column changed. The index keeps pointing to the first tuple in the chain; when we do a lookup, we go from the index to the first one, and we can traverse all tuples of the logical row by following the t_ctid pointer.

Read more about HOT updates at https://www.postgresql.org/docs/current/storage-hot.html.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
postgres=# vacuum (verbose) user_balance;
INFO:  vacuuming "postgres.public.user_balance"
INFO:  finished vacuuming "postgres.public.user_balance": index scans: 0
pages: 0 removed, 1 remain, 1 scanned (100.00% of total)
tuples: 4 removed, 2 remain, 0 are dead but not yet removable
removable cutoff: 847, which was 0 XIDs old when operation ended
new relfrozenxid: 844, which is 4 XIDs ahead of previous value
index scan not needed: 0 pages from table (0.00% of total) had 0 dead item identifiers removed
avg read rate: 31.281 MB/s, avg write rate: 31.281 MB/s
buffer usage: 40 hits, 4 misses, 4 dirtied
WAL usage: 3 records, 1 full page images, 8508 bytes
system usage: CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s

postgres=# SELECT lp, lp_off, lp_flags, lp_len, t_xmin, t_xmax, t_ctid, t_infomask, t_infomask2, t_data
FROM heap_page_items(get_raw_page('user_balance', 0));
 lp | lp_off | lp_flags | lp_len | t_xmin | t_xmax | t_ctid | t_infomask | t_infomask2 |                    t_data
----+--------+----------+--------+--------+--------+--------+------------+-------------+----------------------------------------------
  1 |      4 |        2 |      0 |        |        |        |            |             |
  2 |      0 |        0 |      0 |        |        |        |            |             |
  3 |      0 |        0 |      0 |        |        |        |            |             |
  4 |   8144 |        1 |     45 |    844 |    845 | (0,5)  |      10498 |       49155 | \x0100000000000000e9030000000000000b0081401f
  5 |      0 |        0 |      0 |        |        |        |            |             |
  6 |   8096 |        1 |     45 |    846 |      0 | (0,6)  |       2306 |           3 | \x0200000000000000ea030000000000000b00818813
(6 rows)

postgres=# select ctid, xmin, xmax, user_id, balance from user_balance;
 ctid  | xmin | xmax | user_id | balance
-------+------+------+---------+---------
 (0,4) |  844 |  845 |    1001 | 8000.00
 (0,6) |  846 |    0 |    1002 | 5000.00
(2 rows)

From the above output, there is removable cutoff: 847, meaning that all tuples with committed xmax below 847 or aborted xmin will be removed. Because no current or future snapshots need those. In the scope of this article, the cutoff can be calculated as: removable cutoff = min(xmin of every active snapshot, xid of every in-progress transaction)

If there are no active snapshots or in-progress xids, the cutoff is the next assigned xid.

Note that in reality, the cutoff also accounts for the replication slots’ xmin, hot_standby_feedback from replicas, and prepared transactions. And the cutoff is applied to all tables in the database.

After vacuum, the tuple data at offsets 1, 2, 3, and 5 are freed. Slots 2, 3, and 5 become unused (lp_flags = 0), and slot 1 becomes a redirect (lp_flags = 2, lp_off = 4). tuple at offset 5 is left by the rolled-back xid 845. tuple at offset 4 is kept because its xmax 845 is rolled back. The tuple at offset 6 is kept because it’s visible to future snapshots.

The first logical row only got one tuple at offset 4 and a redirect at offset 1.

Why doesn’t the vacuum remove offset 1 completely? Because these are HOT updates, the index entry still points to offset 1; the vacuum avoids editing the index by keeping the offset 1 slot and redirecting the reader to offset 4.

Notice that the tuple 4 xmax is still 845, which is rolled back. This is harmless because the hint bit XMAX_INVALID is on, indicating that the xmax is rolled back.

Besides cleaning dead tuples, vacuum also does other tasks. In Postgres, you don’t need to run vacuum manually like this; it runs automatically.

Read more about vacuum at https://www.postgresql.org/docs/current/sql-vacuum.html.

4. Table bloat

In Postgres, table bloat is the situation in which the number of dead tuples accumulates too much. Let’s say a heap page can contain 100 tuples, but 80 of them are old and dead. That means Postgres needs to fetch more heap pages to retrieve enough data, resulting in more I/O, which is very expensive. The heap pages will then be cached in the buffer pool, but the buffer pool now mainly contains old and unused tuples.

Some issues lead to table bloat, such as tuples generated by UPDATE too fast, faster than the cleanup speed of autovacuum, or a long-running transaction blocking vacuum from cleaning up dead tuples.

UPDATE-intensive workload

The dead tuples need to be cleaned up by the vacuum; for workloads that do UPDATE too intensively, the vacuum can’t keep up. We can tune the vacuum to work more aggressively on tables that accumulate dead tuples very quickly.

An UPDATE-intensive workload leads to side effects, such as indexes becoming update-intensive, which makes the symptom even worse. We can use HOT updates to mitigate the impact of UPDATE-intensive workloads, but it only works when updating non-indexed columns, and the fillfactor setting facilitates that.

Long-running transaction

Assume a tx running in repeatable read has snapshot 100:110:100,101,102; that means all xids below 100 are settled; xids from 103 to 109 are also settled; xids 100, 101, 102, and all xids from 110 onward are unsettled. Depending on the committed/rolled back of those settled xid, all tuples that are visible to this snapshot must be kept in the heap until it finishes.

Deleting (xmax) xidSettled for this snapshot?Can the snapshot still see the tupleRemovable
< 100SettledNo, the deletes are countedYes
100, 101, 102UnsettledYes, the deletes are ignoredNo
103 - 109SettledNo, the deletes are countedYes in theory, but in practice Postgres uses a single cutoff (100)
>= 110UnsettledYes, the deletes are ignoredNo

So we know that Postgres only removes those dead tuples below the cutoff. And the cutoff is the minimum of active snapshots’ xmin and in-progress xids. When a snapshot like this stays active for too long, the cutoff can’t move forward; there are no more tuples below the cutoff for the vacuum to clean. And this affects the database globally; even if a long-running transaction touches only one table, dead tuples across all tables in the database will have their cleanup delayed as well.

This is the worst for repeatable read because the transaction has only one snapshot throughout its life cycle. As long as the transaction hasn’t finished, the snapshot is still active.

For read-committed, each statement gets a new snapshot, so for read-only, it only holds back the cutoff while a statement is running. But if the transaction modifies data, the cutoff will be held until the transaction commits.