Tables
A table is a stored relation e.g Users. Individual tables are stored across many files on your computer. This happens because a table could technically grow indefinitely but files can only be so large in any OS or file system. A Users tables might have the files file1, file2, file3.
Files
A file is the unit of storage on your OS. In the case of postgres, files contain different chunks from the database, different chunks of your table for example. Each table is split into 1GB segments so if your user table grows past 1gb it will be composed of separate files.
Pages
Postgres never fetches individual rows from the disk. It also never fetches full tables or full files at a time. These would be too large and the process inefficient. A page is the default unit of read and write operations in postgres. Postgres asks the OS for data one page at a time.
Each file is split into pages. Postgres divides every file into 8kb chunks. The boundary between one page and the other is implicit. e.g in file 1, the first 8192 bytes make up page1, the next 8192 bytes page2 and so on. A 1GB file contains 131,072 pages.
Page size is chosen to map with how your SSD works. Hardware pages are the lowest level we can do atomic writes to the storage device. Most modern SSDs guarantee atomic writes on 4kb hardware pages, so choosing an option like 8kb allows us to use disk IO efficiently. We can read and write from the disk efficently. Splitting our files into pages allows us to easily address that data. “Fetch me page 1” can be translated to go to the first file and ask the OS for the first 8kbs. The disk can do this in two operations only. We cant ask for 1 byte at a time from our SSD just like we cant address a single bit in when working with C. We deal with bytes. eg 1 byte(8 bits).
Think of a hardware page as the smallest addressable unit of storage and that roughly turns out to 4kb. Each file has page directory metadata mapping to where in the file a page is i.e offset.
Page Layout
Each page is typically laid out as represented below. This is called a slotted page layout.
This page organization allows us to support variable size data and have rows with variable width e.g varchar
as rows of the same type can occupy different widths.

The pages contain a page header, slot array and actual data appended from the bottom. We will go into more details on each of these right away.
Page Header
Each page has a page header section. The page header contains book keeping information e.g page checksum, DBMS version, compression information and pointers to free space. Your Database Management Systems (D.B.M.S) needs this information on every page to know how to deal with errors and know how to read the data.
Slot Array/Line Pointer Array
The slot array maps data tuples to their actual storage locations. When you see tuples think rows for now. In the diagram these are marked by lp1, lp2 .. lpn. The slot array addresses a row within a page. A line pointer is 4 bytes long and contains the offset of the tuple in the file, its size and flags pointing at its health. e.g dead, unused.
Tuples/Rows
Tuples represent the actual rows of data stored. Think your user details in the row.
Tuples are represented using a current tuple identidier ctid eg (0,1) which refers to page 0 line pointer 1.
That’s how we refer to that particular row.
1. Rows are packed into pages
Each page holds 3 rows here so the picture fits. A real 8 KB page holds dozens to hundreds.
2. Pages are grouped into 1 GB files
Inside the file with the marker, one cell is 2,048 pages.
The theoretical max size of a tuple is the whole size of a page - 8kb.
This is why postgres is not particularly suited for file storage.
Rows bigger than 8kb get TOASTed
moving them off to a separate TOAST table.
Postgres uses M.V.C.C which we will look at in a little while. MVCC allows readers and writers to operate concurrently without
blocking each other. When you execute UPDATE, Postgres does not modify the tuple in place, it writes a new version at the end.
The Line Pointer (LP) tracks each version separately.
The LP also tracks the health of a tuple denoting whether
it needs to be deleted e.g when we have a new version or when actually marked an older row for deletion.
You can select rows with their tuple versions as follows.
SELECT ctid, id, f_name FROM users;
ctid | id | f_name
-------+----+--------
(0,1) | 1 | Alice
(0,2) | 2 | Bob
(0,3) | 3 | Carol
(1,1) | 4 | Dave
(1,2) | 5 | Eve
We can find Alice by going to page 0 slot 1 - ctid(0,1)
B-trees and Indexes
Indexes are a data structure that helps speed up data retrieval.
There are several types of indexes e.g btree, geospatial, vector and hash indexes. A B-tree
is a data structure that allows you to query items on it in log n time.
B-trees are ordered such that we can traverse the tree cutting the work each time by a branching factor of n, which takes log n time to traverse.
Indexes, in Postgres, are stored in their own files just like tables. Compared to other files which are unordered and typically appended to as the database grows, indexes need ordering and reordering over time to be useful for search. After traversing the btree, we would end up finding a match containing a corresponding tuple telling us where the real data lives.
Since indexes are made up of their owns files they can grow large though usually at a fraction of the size of the indexed table. Indexes avoid full table scans. If a column is not indexed, the only way to find it is to fetch every page, one by one, through every file, an expensive operation compared to finding the data through the index.
While indexes help with searches they make writes a little slower as they need to be maintained. Maintenance could mean index re-ordering(tree rebalancing) or even writting to the index when you add a new column. This trade-off is acceptable though as the performance gains we gain in queries far exceeds the extra write effort needed to maintain the index.
Memory & Caching
Fetched pages are cached in memory inside of shared buffers. Shared_buffers is a memory pool accessible to all postgres processes. It’s designed to reduce disk IO by keeping frequently accessed data in memory.
Postgres always tries to fetch a page from its internal buffers before asking the OS for it. If the page is not in memory, it asks the OS for it. The OS checks its own cache, returning it from its own cache or fetching it from disk. Postgres then stores that page in its shared buffers. The next time you ask for data in a cached page it will return immediately, avoiding the expensive disk operation.
Where Postgres can find a page
shared_buffers
Postgres memory
~100 ns
OS page cache
kernel memory
~5 µs
Disk
Spinning disk
~8 ms
How big is each unit of time?
Stretched to human time: if 1 nanosecond lasted 1 second
| Real time | Stretched |
|---|---|
| 1 picosecond | 1 millisecond |
| 1 nanosecond | 1 second |
| shared_buffers, ~100 ns | 1 minute 40 seconds |
| 1 microsecond | 17 minutes |
| OS page cache, ~5 µs | 1 hour 23 minutes |
| 1 millisecond | 11.6 days |
| Disk, ~8 ms | 93 days, about 3 months |
| 1 second | 31.7 years |
Latencies are rough orders of magnitude. Real values vary with the hardware.
WAL
Write ahead log(WAL) is the core mechanism Postgres uses to guarantee data integrity, crash recovery and speed up writes.
Updates to data are done in memory. eg. UPDATE ... SET
Updated pages are marked as dirty(in memory) and the changes are written to a write ahead log (W.A.L).
Writing these changes to the WAL provides the persistence mechanism so that even if the server crashes we have the data written to durable storage.
A WAL is an append only. Append only makes it fast. Once data written on the WAL(one I.O operation), we communicate to the client that the data is saved. The client can go on to process other things.
Periodically, during checkpoints, dirty data in shared_buffers is written to disk. Once data is flashed to disk we can delete it from the WAL or it will grow infinitely.
1. Transaction modifies a row
2. Change is made in the page in shared_buffers (page marked DIRTY)
3. A WAL record describing the change is written to the WAL buffer (in memory)
4. On COMMIT: WAL buffer is flushed to disk (WAL file in pg_wal) ← durability point
5. Later (at checkpoint or eviction): the dirty page in shared_buffers
is flushed to the heap/index file on disk ← persistence point
Press Play to follow one UPDATE through Postgres.
MVCC
MVCC stands for multi version concurrency control.
A.C.I.D compliant databases promise transaction Isolation.
The Isolation database transaction property promises to provide certain guarantees to concurrent transactions that
ensures data integrity. We will go over these shortly.
Postgres provides full isolation guarantees using a MVCC architecture. But first, lets demonstrate the problem.
Say one transaction updates a field in a database but before it commits another concurrent transaction reads it. Imagine two concurrent transactions selecting user balance, debiting the amount and then committing.
CREATE TABLE accounts (id int PRIMARY KEY, balance int);
INSERT INTO accounts VALUES (1, 1000);
-- ============================================================================
-- THE PROBLEM: LOST UPDATE
-- ============================================================================
--
-- ⭐THE GOAL⭐: T1 debits 100, T2 debits 200. Correct final balance = 700.
-- ── Step 1: both transactions begin and read the balance ───────────────────
-- T1 -- T2
BEGIN; BEGIN;
SELECT balance FROM accounts SELECT balance FROM accounts
WHERE id = 1; WHERE id = 1
--------------------- both read 1000------------------------------------
-- ── Step 2: T1 debits 100 and commits ──────────────────────────────────────
-- T1
UPDATE accounts SET balance = balance - 100
WHERE id = 1;
COMMIT;
-- balance is now 900
-- ── Step 3: T2 debits 200 from its stale read of 1000 ──────────────────────
-- T2
UPDATE accounts SET balance = balance - 200
WHERE id = 1;
-- T2 computed 1000 − 200 = 800, unaware T1 already changed it to 900
COMMIT;
-- ── Result ─────────────────────────────────────────────────────────────────
-- Final balance = 800 ❌
-- Expected = 700
-- T1's −100 was overwritten by T2's write. That is the LOST UPDATE.
From the code above, we can see that transactions running concurrently can introduce unintended side effects. Ideally we want transactions to run without these negative side effects. To avoid developers having to handle concurrent transaction logic in code, databases provide us with isolation guarantees.
Isolation Levels
- Read Uncommitted - Allows you to read values uncommitted in a database. i.e read values from Tnx.1 in Tnx.2 that Tnx.1 could throw out. This allows
dirty readsand is not supported by Postgres. - Read Committed - Allows you to read values once they committed into a database. This is the default isolation level in Postgres. The implication here is if T.1 and T.2 run concurrently, any values committed might be available to the other transaction.
- Repeatable Reads - Ensures that once we read a column in a transaction, subsequent reads will get the same values even if other transactions committed new values.
- Serializable - Works same as Repeatable reads. Transactions are ordered as if they happened sequentially and not concurrently.
Full serializability is expensive, we want to have options selecting the intended isolation level depending on the work load. This is why different isolation levels exist. We do not need full serializability everywhere. It comes at a cost
This article covers isolation levels in greater detail. I could not recommend it enough. Isolation Levels
Versioned Columns
Earlier on, we talked about how postgres does not update data in place(in pages), instead it writes new tuples in new slot arrays. This is actually the mechanism postgres uses to implement transaction isolation (MVCC).
Transactions with Repeatable reads isolation level for example will only read from rows visible when they started.
The versioned rows are represented like this.
xmin │ xmax │ acctnum │ balance
────────┼────────┼─────────┼─────────
xmin -> transaction id of the transaction that created this version.
xmax -> transaction id of the transaction that deleted/superseded this version.
When different transactions are working, they take a snapshot (S). Read Committed takes the snapshot at the start of each statement enabling it to see newer data mid transaction. Repeatable reads and Serializable take a snapshot at the start of the transaction and work with that data through out. Having multiple versions of the same row enables them to take different snapshots and provide the different isolation guarantees.
xmin │ xmax │ acctnum │ balance
────────┼────────┼─────────┼─────────
125 │ 201 │ 789 │ 3 ← old version T.1
201 │ 0 │ 789 │ 500 ← new version T.2
Looking at the first failing example ie. T1 debits 100, T2 debits 200. Correct final balance = 700, this is how things change with transactions isolation under both read committed and repeatable reads/serializable isolation levels.
CREATE TABLE accounts (id int PRIMARY KEY, balance int);
INSERT INTO accounts VALUES (1, 1000); -- created by XID 0 (baseline)
-- ============================================================================
-- READ COMMITTED — atomic SQL update — with version columns
-- ============================================================================
--
-- ⭐THE GOAL⭐: T1 debits 100, T2 debits 200. Correct final balance = 700.
--
-- Version table starts as:
-- t_xmin │ t_xmax │ id │ balance
-- ───────┼────────┼────┼─────────
-- 0 │ 0 │ 1 │ 1000 ← live version, visible to everyone
-- ── Step 1: both begin (explicitly at READ COMMITTED) ──────────────────────
-- T1 -- T2
BEGIN ISOLATION LEVEL BEGIN ISOLATION LEVEL
READ COMMITTED; READ COMMITTED;
-- ── Step 2: T1 (XID 1) runs atomic UPDATE and commits ─────────────────────
-- T1
UPDATE accounts SET balance = balance - 100
WHERE id = 1;
-- T1 reads current balance = 1000 (from t_xmin=0),
-- computes 1000 − 100 = 900,
-- writes a NEW version with t_xmin = 1,
-- and stamps the old version's t_xmax = 1.
-- t_xmin │ t_xmax │ id │ balance
-- ───────┼────────┼────┼─────────
-- 0 │ 1 │ 1 │ 1000 ← superseded by T1
-- 1 │ 0 │ 1 │ 900 ← T1's new version
COMMIT;
-- ── Step 3: T2 (XID 2) runs atomic UPDATE ─────────────────────────────────
--
-- T2's UPDATE takes a FRESH snapshot at statement start (Read Committed).
-- It tries to update the row. But the row's live version (t_xmin=1) was
-- created by XID 1, which committed AFTER T2's transaction began.
--
-- What happens: Read Committed's conflict handling kicks in — T2
-- re-evaluates the UPDATE against the LATEST committed version.
-- It sees balance = 900 (from t_xmin=1), computes 900 − 200 = 700,
-- and writes a new version.
-- T2
UPDATE accounts SET balance = balance - 200
WHERE id = 1;
-- T2 sees latest committed version: t_xmin=1, balance=900
-- computes 900 − 200 = 700
-- writes a NEW version with t_xmin = 2,
-- stamps t_xmax = 2 on version 1.
COMMIT;
-- Final version table:
-- t_xmin │ t_xmax │ id │ balance
-- ───────┼────────┼────┼─────────
-- 0 │ 1 │ 1 │ 1000 ← superseded
-- 1 │ 2 │ 1 │ 900 ← superseded by T2
-- 2 │ 0 │ 1 │ 700 ← LIVE
-- ── Result ─────────────────────────────────────────────────────────────────
-- Final balance = 700 ✅
-- Expected = 700
CREATE TABLE accounts (id int PRIMARY KEY, balance int);
INSERT INTO accounts VALUES (1, 1000); -- created by XID 0 (baseline)
-- ============================================================================
-- THE FIX: REPEATABLE READ (abort + retry) — with version columns
-- ============================================================================
--
-- ⭐THE GOAL⭐: T1 debits 100, T2 debits 200. Correct final balance = 700.
--
-- Version table starts as:
-- t_xmin │ t_xmax │ id │ balance
-- ───────┼────────┼────┼─────────
-- 0 │ 0 │ 1 │ 1000 ← live version, visible to everyone
-- ── Step 1: both begin; both take ONE snapshot for the whole transaction ───
--
-- T1 gets XID 1, T2 gets XID 2. Both snapshots are taken now,
-- so both see only versions with t_xmin ≤ 0.
-- T1 -- T2
BEGIN ISOLATION LEVEL BEGIN ISOLATION LEVEL
REPEATABLE READ; REPEATABLE READ;
SELECT balance FROM accounts SELECT balance FROM accounts
WHERE id = 1; WHERE id = 1;
------------------- both see t_xmin=0 (1000)-------------------------------
-- ── Step 2: T1 (XID 1) debits 100 and commits ──────────────────────────────
--
-- T1's UPDATE does NOT overwrite version 0. It writes a NEW version with
-- t_xmin = 1, and stamps the old version's t_xmax = 1:
-- t_xmin │ t_xmax │ id │ balance
-- ───────┼────────┼────┼─────────
-- 0 │ 1 │ 1 │ 1000 ← old version, superseded by T1
-- 1 │ 0 │ 1 │ 900 ← T1's new version (committed)
-- T1
UPDATE accounts SET balance = 900
WHERE id = 1;
COMMIT;
-- ── Step 3: T2 (XID 2) tries to update the version it saw as 1000 ─────────
--
-- T2's snapshot was taken at Step 1, so it does NOT include XID 1.
-- T2 still believes the live version is t_xmin=0, balance=1000.
-- But look at that version's t_xmax: it is 1, and 1 has COMMITTED
-- (and is not in T2's snapshot). That means the version T2 wants to
-- update has ALREADY been superseded by a transaction T2 cannot see.
--
-- Postgres detects this on write:
--
-- ERROR: could not serialize access due to concurrent update
--
-- T2
UPDATE accounts SET balance = 800
WHERE id = 1;
-- t_xmax of the version T2 is updating = 1
-- 1 committed but is NOT in T2's snapshot (taken before 1)
-- → conflict → abort
ROLLBACK;
-- ── Step 4: T2 retries (new transaction XID 3, fresh snapshot → sees 1) ───
-- T2 (retry)
BEGIN ISOLATION LEVEL
REPEATABLE READ; -- new snapshot now includes XID 1
SELECT balance FROM accounts
WHERE id = 1; -- → 900
UPDATE accounts SET balance = 700
WHERE id = 1;
-- writes a NEW version with t_xmin = 3, stamps t_xmax = 3 on version 1
COMMIT;
-- Final version table:
-- t_xmin │ t_xmax │ id │ balance
-- ───────┼────────┼────┼─────────
-- 0 │ 1 │ 1 │ 1000 ← superseded
-- 1 │ 3 │ 1 │ 900 ← superseded by T2's retry
-- 3 │ 0 │ 1 │ 700 ← LIVE
-- ── Result ─────────────────────────────────────────────────────────────────
-- Final balance = 700 ✅
-- Expected = 700
Having multiple versions (MVCC) allows us to have our cake 🎂🍰 and eat it too. We can for the most part run transactions under lower isolation levels like read committed and when we want stricter guarantees we can switch to another serialization level that will either throw a serialization error or lock our rows.
Because postgres’s default isolation level is read committed the issue we saw at the start of the section is solved by default, without us needing to write any extra application code. Read committed also locks rows in certain conditions as shown below
CREATE TABLE accounts (id int PRIMARY KEY, balance int);
INSERT INTO accounts VALUES (1, 1000);
-- ⭐GOAL⭐: T1 debits 100, T2 debits 200. Correct final = 700.
-- T1 -- T2
BEGIN ISOLATION LEVEL BEGIN ISOLATION LEVEL
READ COMMITTED; READ COMMITTED;
SELECT balance FROM accounts SELECT balance FROM accounts
WHERE id = 1 FOR UPDATE; WHERE id = 1 FOR UPDATE;
-- ⏳ BLOCKS on T1's lock
UPDATE accounts SET balance = 900
WHERE id = 1;
COMMIT; 🔓
-- unblocks, re-reads 900
UPDATE accounts SET balance = 700
WHERE id = 1;
COMMIT;
-- Final balance = 700 ✅
You can show the different row versions and the tuple locations by running this query in your database
SELECT ctid, xmin, xmax, id, balance FROM accounts;
ctid │ xmin │ xmax │ id │ balance
───────┼──────┼──────┼────┼─────────
(0,1) │ 100 │ 105 │ 1 │ 1000 ← dead (UPDATE by txn 105)
(0,2) │ 105 │ 110 │ 1 │ 900 ← dead (UPDATE by txn 110)
(0,3) │ 110 │ 0 │ 1 │ 950 ← live
Over time we need to clear these older tuple versions and free up space. This is what the vacuum process does.
VACUUM
The vacuum process is responsible for clearing dead tuples and reclaiming used space. It should be noted that vacuuming does not automatically return the space to your OS. There are two types of vacuum, plain and full vacuum. In this example;
ctid │ xmin │ xmax │ id │ balance
───────┼──────┼──────┼────┼─────────
(0,1) │ 100 │ 105 │ 1 │ 1000 ← dead (UPDATE by txn 105)
(0,2) │ 105 │ 110 │ 1 │ 900 ← dead (UPDATE by txn 110)
(0,3) │ 110 │ 0 │ 1 │ 950 ← live
A plain vacuum simply finds the dead tuples ie (0,1) and (0,2) goes to the page 0 and marks line pointer 1 (lp1) and lp2 as unused, marking them as free space. Dead tuples in M.V.C.C will be any unused duplicates that live in the database. Vacuuming marks them free for deletion or reuse.
This does not return disk space to the OS. So even though you free up disk space, you won’t see an increase in HDD capacity. The space will be cleared internally though. A full vacuum actually rewrites the table into a new file freeing up disk space. This is much expensive and slower but does return disk space to the OS.
File on disk
8 KB
Free space in page
Tuples are drawn at 2 KB each so the page fits on screen. Real tuples are much smaller.
It’s important to vacuum regularly to avoid a maintenance issue in postgres called transaction id wrap around. Postgres’s txid was designed as a 32 bit integer meaning it overflows past 2^32-1 which is 4,294,967,295. After that it starts over at 3 (0,1,2 are reserved).
If auto-vacuuming is disabled or the database lags because of long running sessions/contention, unfrozen rows might be hidden because they might appear to come from the past. More on this here.
Postgres never actually lets it overflow, it stops accepting new transactions and writes fail with database is not accepting commands to avoid wraparound data loss. It stops early with a margin of 3 million transaction ids. The margin exists so admins can run vacuum by hand.
References
- Write Ahead Logs
- How Postgres stores rows
- Carnegie Mellon Database Storage
- File systems
- Carnegie Mellon Database Group
- Heap File Layout
- PostgreSQL pageinspect docs
- PostgreSQL TOAST storage docs
- The Internals of PostgreSQL
- Transaction isolation in Postgres
- Postgres transaction ID wraparound
- Transaction ID wraparound full recovery guide
- B-trees and database indexes
- Toasting in Postgres
- Ben’s Btree Visualizations
- Transaction Anomalies