Sub topic 2
Pages: the 8 KB unit of storage and I/O
This chapter assumes you can run basic SQL in psql and know what a transaction is. It also assumes you know a file is a sequence of bytes on disk. The previous chapter showed that a table lives in files on disk. Here we look at how PostgreSQL divides those files into fixed-size units called pages, and why that unit shapes performance.
What a page is
A page, also called a block, is a fixed-size chunk of a table or index file. PostgreSQL reads and writes relation files one page at a time. The default size is 8192 bytes (8 KB). Every file for a table, index, or other relation is a whole number of pages, so the file size is always a multiple of the page size.
You never ask PostgreSQL for "byte 5000 of the file". It asks for "block 0" or "block 41", loads that whole page, and then works inside it. Pages are numbered from 0, in file order. The first page of a table is block 0.
Check the page size on your server:
SHOW block_size;The result is normally 8192.
Why a fixed unit
A fixed page size gives PostgreSQL four things:
- Simple addressing. Block number N starts at byte offset N × 8192 in the file. No lookup structure is needed to find it.
- Efficient I/O. Disks and operating systems move data in blocks anyway. Reading 8 KB costs little more than reading a few bytes, so it makes sense to fetch a useful batch at once.
- A natural caching unit. The shared buffer cache holds pages. A page that holds many rows can serve many queries after one read.
- A natural unit for crash safety. WAL records, checksums, and recovery logic all work in terms of pages.
The trade-off is that a query that needs one 50-byte row still reads an 8 KB page. A query that touches many scattered rows can read many pages and use only a few bytes from each.
Page size is fixed at build time
The 8 KB size is chosen when PostgreSQL is compiled. The --with-blocksize configure option accepts values from 1 to 32 KB, as a power of 2. Nearly every installation uses the default, and managed services use it too. You cannot change the block size of an existing cluster. A cluster built with a different block size cannot read the data files of one built with another.
Several different "page sizes"
Several layers use similarly named units. They do not have to match:
| Layer | Typical size | Who decides |
|---|---|---|
| PostgreSQL page (block) | 8 KB | Compile-time setting |
| Operating system page | 4 KB | CPU and kernel |
| Disk sector | 512 bytes or 4 KB | Storage hardware |
| WAL block | 8 KB | Compile-time setting |
One PostgreSQL page usually spans two OS pages. This matters for crash safety, as the next sections show.
From file to page count
A relation file's size divided by the block size gives its number of pages. You can compute this with SQL:
CREATE TABLE page_demo (id int, payload text);
INSERT INTO page_demo
SELECT g, repeat('x', 100)
FROM generate_series(1, 10000) AS g;
SELECT pg_relation_size('page_demo') AS bytes,
pg_relation_size('page_demo') / current_setting('block_size')::int AS pages;pg_relation_size returns the size of the main fork in bytes. Dividing by block_size gives the page count.
The catalog pg_class also stores a page count in relpages. It is only an estimate, refreshed by VACUUM, ANALYZE, and some index operations. It can lag behind the real size.
ANALYZE page_demo;
SELECT relpages, reltuples
FROM pg_class
WHERE oid = 'page_demo'::regclass;For decisions about real size, use pg_relation_size. The planner uses relpages to estimate scan costs.
How many rows fit in a page
You can see the page boundaries through the ctid system column. Its first number is the block number. Cast it through point to extract that number and count rows per block:
SELECT (ctid::text::point)[0]::bigint AS block,
count(*) AS rows
FROM page_demo
GROUP BY block
ORDER BY block
LIMIT 5;For this table, each row takes about 140 bytes. That figure includes a 24-byte tuple header, the int, the 100-character text value, alignment padding, and a 4-byte line pointer. The page header takes 24 bytes of the 8192, leaving 8168. That fits about 58 rows per page, so 10,000 rows need roughly 173 pages. Your numbers should be close to these. Later chapters explain each of those costs.
Because a page has a fixed size, a table with narrow rows packs many rows per page and a table with wide rows packs few. Rows per page directly controls how many pages a scan must read.
A row must fit in one page
A normal heap tuple cannot span two pages. This is why very large values need special handling. When a row grows beyond roughly 2 KB, PostgreSQL tries to compress its large columns or move them out of line into a separate table. That mechanism is TOAST, covered in later chapters. For now, the point is that the page size is the reason TOAST exists.
The read path
When a query needs a row, PostgreSQL does not go straight to disk. It asks the buffer manager for a specific block of a specific relation. The buffer manager looks in shared_buffers, the memory area where PostgreSQL caches pages.
A buffer hit is cheap. A miss means a read call to the operating system. That read may be served from the OS file cache, which is still much faster than physical disk, or from the storage device.
Modified pages stay in shared buffers as dirty pages. The background writer and checkpointer later write them back to the file. Changes reach durable storage first through the WAL, so a crash does not lose committed work.
Seeing page I/O in a plan
EXPLAIN with the BUFFERS option reports how many pages a query touched:
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*) FROM page_demo;In the scan node you will see a line like Buffers: shared hit=173. Right after you create the table, pages are usually still in shared buffers, so you see hit. Pages loaded from outside shared buffers appear as read. For a sequential scan, the total is close to the table's page count, because the scan visits every page.
Compare an index lookup of one row:
CREATE INDEX page_demo_id_idx ON page_demo (id);
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM page_demo WHERE id = 4242;This touches only a few pages. These are the index pages along the path from the root to the entry, plus one table page that holds the row. Index pages are also 8 KB blocks in their own files.
Torn pages and full-page writes
Because an 8 KB PostgreSQL page usually spans two 4 KB OS pages, and the hardware may not write 8 KB atomically, a crash during a write can leave half of a page new and half old. This is called a torn page. A torn page cannot be repaired by replaying small WAL records, because those records assume the page started in a consistent state.
PostgreSQL handles this with full_page_writes, which is on by default. The first time a page is modified after a checkpoint, the WAL records a complete copy of that page. During recovery, PostgreSQL restores that copy and then applies later changes on top of it. The cost is extra WAL volume right after each checkpoint, which is one reason frequent checkpoints can hurt write-heavy workloads.
Page checksums
Each page header has a field for a checksum. When data checksums are enabled, PostgreSQL computes a checksum each time it writes a page out. It verifies the checksum each time it reads the page back from outside shared buffers. A mismatch raises an error and indicates that the storage layer changed the page contents.
Check whether your cluster uses them:
SHOW data_checksums;Checksums are chosen when the cluster is created with initdb --data-checksums. They can be switched on or off later for an offline cluster with the pg_checksums tool. They add a small CPU cost. Without them, silent corruption can go unnoticed until a query returns wrong data.
Edge cases to know
- Empty tables. A table with no rows has a file of 0 bytes, which is 0 pages. The first insert allocates block 0.
- Page count never shrinks on its own. Deleting rows leaves pages in place. Only
VACUUMcan truncate empty pages from the end of the file, andVACUUM FULLrewrites the whole table. Later chapters cover both. - Partly filled pages. A page need not be full. Free space inside a page is reserved for later inserts and updates. The
fillfactorstorage parameter lets you leave space on purpose. - Large relations. A table over 1 GB is split into several segment files, but each file is still a series of 8 KB pages, and block numbers continue across segments.
- Index and table pages share the cache. They compete for the same
shared_buffers. A big scan can push other useful pages out.
Key points
- PostgreSQL stores each relation as a sequence of fixed-size pages, 8 KB by default, numbered from 0.
- All table and index I/O happens in whole pages, through the shared buffer cache.
- File size divided by
block_sizegives the page count.ctidshows which block a row is in. - A normal row must fit in one page, which is why TOAST exists.
- Full-page writes protect against torn pages. Checksums detect corrupted pages.
Exercise
A table's main fork is 81,920 bytes on a server with the default block size. How many pages does the table have, and what block number does the last page have? Which SQL expression would compute the page count?
Show answer
The table has 81920 / 8192 = 10 pages. Blocks are numbered from 0, so the last page is block 9. The expression is pgrelationsize('tablename') / currentsetting('block_size')::int.
Exercise
You run EXPLAIN (ANALYZE, BUFFERS) on a sequential scan of a table with 500 pages and see "Buffers: shared hit=120 read=380". What does this tell you about where the pages came from? Why does a second run often show a different split?
Show answer
The scan touched 500 pages in total. 120 were already in sharedbuffers (hits), and 380 were loaded from outside shared buffers, from the OS cache or from disk. After the first run, the loaded pages are in sharedbuffers, so a second run shows more hits and fewer reads, as long as they were not evicted in the meantime.