Database Internals: Pages, Heap, Tuples & I/O
"Every table and index is stored as an array of pages of a fixed size (usually 8 kB, although a different page size can be selected when compiling the server)." — PostgreSQL documentation, 66.6 Database Page Layout
Summary: how a row really sits on disk and in memory: pages, the heap, tuple headers, ctid, TOAST, the free space and visibility maps, and why the database always moves whole pages.
Focus: PostgreSQL's heap as the main example, MySQL InnoDB's clustered index and SQLite's b-tree file as the contrasts, and the I/O arithmetic that follows from each.
Learning goal: after this page you can open a page with pageinspect, predict whether an UPDATE will be HOT, explain why an index lookup costs two reads, and size and de-bloat a table on purpose.
This page is the foundation the rest of the database section stands on. It covers the storage layer completely: the page (block) as the unit of I/O, the PostgreSQL page header and line pointers, the tuple header (t_xmin, t_xmax, t_ctid, t_infomask), heap files and their 1 GB segments and forks, the free space map, the visibility map, fillfactor, heap-only tuple (HOT) updates, TOAST, row- vs column-oriented layout, sequential vs random I/O, the buffer pool and the OS page cache, the two-step index → heap lookup, index-only scans, clustered (InnoDB) vs heap (PostgreSQL) organisation, SQLite's b-tree pages, bloat vs fragmentation, and the tools to see all of it (pageinspect, pg_freespacemap, pg_relation_size). It deliberately stops at three borders: what xmin/xmax mean for snapshots, dead tuples and VACUUM policy is in MVCC, VACUUM & Bloat; index types and index design are in Indexing and the tree shapes in B-Tree vs B+Tree; B-tree vs LSM-tree engines and write amplification are in Storage Engines. Analytical column stores get their own page in OLTP vs OLAP & Columnar Storage.
Page map
| If you are looking for | Go to |
|---|---|
| The whole storage layer on one screen | Everything in one minute |
| Why databases use pages at all | Why pages, heaps and I/O units exist |
| Where the ideas come from (System R, Hellerstein et al.) | Where it comes from |
Page header, line pointers, pd_lower/pd_upper | The page |
t_xmin, t_xmax, t_ctid, t_infomask, null bitmap | The tuple header |
What ctid is and why you must not store it | ctid |
Files, 1 GB segments, _fsm, _vm forks | Heap files, segments and forks |
| Free space map and visibility map | FSM, VM |
fillfactor and HOT updates | fillfactor, HOT |
| Big values: TOAST, strategies, 2 KB threshold | TOAST |
| Row store vs column store at the page level | Row vs column layout |
| Sequential vs random I/O, read-ahead, read amplification | I/O |
shared_buffers, InnoDB buffer pool, OS page cache, double caching | Buffer pool and page cache |
| IO1 + IO2, bitmap heap scan, index-only scan | Index → heap lookup |
| InnoDB clustered index vs PostgreSQL heap | Clustered vs heap |
| SQLite pages, cells and overflow pages | SQLite |
| Bloat vs fragmentation | Bloat vs fragmentation |
| Every product side by side | What each database really does |
| Knobs, functions, error messages | Mechanics |
| Bloat, no HOT, wide rows, slow index scans, UUID keys, memory sizing | Solving the classic problems |
| Which setting for which table | Choosing |
| From monolith to distributed data | In architecture |
Reproduce everything with pageinspect | Lab |
Everything in one minute
The objects. Every row is unpacked below.
| Thing | In plain words | Tiny example | Where it matters |
|---|---|---|---|
| Page / block | Fixed-size box the database reads and writes as one unit | PostgreSQL 8 KB, InnoDB 16 KB, SQLite 4 KB default | Every I/O, every cache slot |
| Page header | First bytes of a page: LSN, checksum, where free space starts and ends | pd_lower = 36, pd_upper = 8096 | Crash recovery, free-space math |
| Line pointer (item id) | Small slot array that says where each tuple sits inside the page | lp 3 → offset 8096, length 30 | Lets tuples move inside a page without breaking pointers |
| Tuple | One stored row version, with a header | 23-byte header + null bitmap + columns | MVCC, row overhead |
ctid | Physical address of a tuple: (block, line pointer) | (7,3) | What PostgreSQL indexes point to |
| Heap | Table file where rows go wherever there is room, unordered | base/16384/24576 | PostgreSQL tables, SQL Server heaps |
| Clustered index | Table stored inside the primary-key B+tree | InnoDB, SQL Server clustered tables, SQLite rowid tables | PK lookups are one walk; secondaries carry the PK |
| Free space map (FSM) | Per-table map of how much room each page has | pg_freespace('t') | Where INSERT/UPDATE put new tuples |
| Visibility map (VM) | Two bits per page: all-visible, all-frozen | Index-only scan skips all-visible pages | VACUUM speed, index-only scans |
fillfactor | How full INSERT may pack a page | WITH (fillfactor = 80) | Room for HOT updates |
| HOT update | New row version on the same page, no new index entries | Update balance, not an indexed column | Write cost, index bloat |
| TOAST | Big values compressed and/or moved to a side table | 50 KB JSON → 18-byte pointer in the row | Wide rows, SELECT * cost |
The I/O facts.
| Fact | Number to remember | Consequence |
|---|---|---|
| Smallest read | One page, never one row | Reading one 40-byte row costs 8 KB (PostgreSQL) or 16 KB (InnoDB) |
| Index lookup by secondary key | IO1 (index) + IO2 (heap or clustered index) | Two trees or a tree and a heap; a covering index removes IO2 |
| Sequential vs random | Sequential bandwidth 10–100× random on disks (Hellerstein et al.) | Planners prefer sequential scans for large fractions of a table |
| Memory layers | Database buffer pool + OS page cache | Same page can be cached twice (double caching) |
| Segment size | PostgreSQL splits relations into 1 GB files | 24576, 24576.1, 24576.2 … |
| TOAST trigger | Row wider than about 2 KB (TOAST_TUPLE_THRESHOLD) | Big columns leave the main heap |
The three things to do.
| Situation | Do this |
|---|---|
| Table updated constantly, many indexes | Lower fillfactor (70–90) and keep frequently updated columns out of indexes so updates stay HOT |
| Table grows while row count does not | Measure with pg_relation_size + n_dead_tup; fix autovacuum first, rewrite (REPACK, pg_repack, VACUUM FULL) only if needed |
| Hot query reads a few columns through an index | Make the index covering (INCLUDE) and keep the table vacuumed so the visibility map allows index-only scans |
Why pages, heaps and I/O units exist
Storage hardware does not hand out single bytes. A disk reads sectors, an SSD reads flash pages, the operating system caches 4 KB memory pages, and every request has a fixed cost before the first byte arrives. So databases group rows into fixed-size pages and always move whole pages between disk and memory. Everything on this page follows from that choice: how many rows fit, why an update can be cheap or expensive, why an index lookup costs two reads, why a table can be large on disk while holding few rows.
| Small pages (SQLite 4 KB, InnoDB 4 KB option) | Large pages (InnoDB 16 KB default, 32/64 KB options) |
|---|---|
| Less wasted transfer for a single-row read | Fewer pages, shallower trees, better sequential scans |
| Less contention when many sessions write rows on one page | More rows share a latch, more contention on hot pages |
| More pages to track in the buffer pool | Larger rows fit before overflow/TOAST |
| Closer to SSD and OS page size | More unchanged bytes rewritten per modified page |
The analogy we reuse on this page: a warehouse of numbered boxes. The warehouse (the table file) is a row of identical boxes (pages). Each box has a label on the lid (page header) and, inside the lid, a small index card listing "item 1 is in the back-left corner, item 2 next to it…" (line pointers). The items (tuples) carry a sticker saying who put them there and who took them out (xmin/xmax). A forklift (I/O) can only carry a whole box, never a single item. A catalogue at the front (an index) says "Bob's item is in box 7, slot 3" (ctid). If you move an item to another box, the catalogue must be corrected; if you only swap it within the same box and leave a note in slot 3, it need not (HOT). Oversized items go to a separate storeroom and only a claim ticket stays in the box (TOAST).
Three common misunderstandings, up front
- "Reading one row reads one row." The database reads at least the whole page that holds it, and through a secondary index at least one more page. Row size matters far less than how many pages a query touches.
- "An UPDATE changes the row in place." In PostgreSQL every
UPDATEwrites a new tuple and marks the old one dead; the row'sctidchanges. InnoDB updates the clustered record in place and keeps the old version in the undo log. Both cost more than "change one field". - "A smaller table on disk only comes from deleting rows." Deleted and updated rows leave dead space that plain
VACUUMmakes reusable but does not return to the OS (except empty pages at the end). Size on disk and row count are different measures.
Where it comes from
The page-based storage manager is as old as relational systems: IBM System R and Ingres already stored relations as pages managed by a buffer pool. The best single description of the whole stack is Hellerstein, Stonebraker and Hamilton's Architecture of a Database System (Foundations and Trends in Databases, 2007). Their description of the buffer pool is still exact for PostgreSQL and InnoDB:
"The buffer pool is organized as an array of frames, where each frame is a region of memory the size of a database disk block." — Hellerstein, Stonebraker & Hamilton, Architecture of a Database System, 2007
They also explain why databases care so much about physical placement:
"Sequential bandwidth to and from disk is between 10 and 100 times faster than random access, and this ratio is increasing." — Hellerstein, Stonebraker & Hamilton, Architecture of a Database System, 2007
SSDs shrank that gap but did not remove it: random reads still cost more requests, more latency per byte and defeat read-ahead. PostgreSQL's heap with separate indexes descends from the Postgres research system of the 1980s; MySQL's InnoDB follows the "table is the primary-key B+tree" design; SQLite's file format (documented byte by byte on sqlite.org) stores every table and index as a b-tree in one file. The terms on this page come from those three manuals; when a product uses another word (SQL Server "RID", Oracle "ROWID", SQLite "cell"), the product is named.
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, the precise definition, a sequence or worked example, real scenarios, how each product does it, and the fix or the way to use it in SQL, Go and Laravel.
Page (block) Must-know
In plain words: a page is the fixed-size box that holds rows. The database never reads or writes less than one page.
Common misunderstanding: "Page size is a tuning knob I can change per table." In PostgreSQL the block size (BLCKSZ, block_size) is fixed when the server is compiled; the docs add "there is no support for having more than one page size in an installation". In InnoDB innodb_page_size is fixed when the instance is initialized. Only SQLite lets you pick a page size per database file (before it is created or with VACUUM).
Definition: PostgreSQL pages have five parts:
"24 bytes long. Contains general information about the page, including free space pointers." — PostgreSQL documentation, Table 66.2 Overall Page Layout, row
PageHeaderData
After the 24-byte header comes the array of line pointers (ItemIdData, 4 bytes each, an "(offset,length) pair"), then free space, then the items (tuples) stored "backwards from the end of unallocated space", and finally the special space (empty for tables, used by index access methods; B-tree pages keep left/right sibling links there). The header fields are pd_lsn (LSN of the last WAL record that changed the page), pd_checksum, pd_flags, pd_lower (start of free space), pd_upper (end of free space), pd_special, pd_pagesize_version and pd_prune_xid (oldest un-pruned xmax, a hint for page pruning).
Worked example: how many rows fit? A table (a int, b int): tuple header 23 bytes padded to 24 (MAXALIGN = 8), data 8 bytes, total 32; plus a 4-byte line pointer = 36 bytes per row. Usable space is 8192 − 24 = 8168, so about 226 rows per page. A table of 1,000,000 such rows needs about 4,425 pages ≈ 35 MB, although the "raw data" is only 8 MB. Row overhead dominates narrow tables.
page 0 after three INSERTs (PostgreSQL, 8192-byte block)
1 0 .. 23 PageHeaderData pd_lower = 36, pd_upper = 8096, pd_special = 8192
2 24 .. 35 lp 1, lp 2, lp 3 4 bytes each (offset, length, flags)
3 36 .. 8095 free space 8060 bytes
4 8096 .. 8127 tuple 3 written last, lowest address
5 8128 .. 8159 tuple 2
6 8160 .. 8191 tuple 1 written first, at the end of the pageReal scenarios: a SELECT of one 50-byte row costs one 8 KB read (or two with an index); a "small" lookup table of 5,000 rows fits in about 25 pages and is always in cache; a 2-billion-row event table is 16 TB of pages before indexes; setting innodb_page_size=4k on an OLTP MySQL server with tiny rows reduced write volume per change (the MySQL manual says smaller pages "might be more efficient for OLTP workloads involving many small writes").
| Product | Page size | Configurable? |
|---|---|---|
| PostgreSQL | 8 KB (block_size) | Only at compile time (--with-blocksize); one size per cluster |
| MySQL InnoDB | 16 KB (innodb_page_size) | 4, 8, 16, 32, 64 KB, only when the instance is initialized |
| SQLite | 4096 bytes default | Power of two 512–65536 per database file (PRAGMA page_size) |
| SQL Server | 8 KB pages, 64 KB extents (8 pages) | Fixed |
| Oracle | DB_BLOCK_SIZE, commonly 8 KB | Chosen at database creation; other sizes per tablespace |
| MongoDB (WiredTiger) | Variable-size B-tree pages, compressed on disk | Per-collection config strings, rarely changed |
Fix / how to use it: you do not change the page size; you design for it. Keep rows narrow, order fixed-width columns from widest to narrowest to avoid alignment padding ("column tetris"), and estimate table size from rows-per-page, not from raw data.
-- PostgreSQL: block size, pages and rows per page of a table
SHOW block_size; -- 8192
SELECT relpages, reltuples,
reltuples / NULLIF(relpages, 0) AS rows_per_page
FROM pg_class WHERE relname = 'accounts';
SELECT pg_relation_size('accounts') / current_setting('block_size')::int AS pages;The tuple header: t_xmin, t_xmax, t_ctid, t_infomask Must-know
In plain words: every stored row version in PostgreSQL starts with a 23-byte label that says which transaction created it, which one deleted or locked it, where its newer version is, and a set of status bits.
Common misunderstanding: "The row is just my columns." Each tuple carries at least 23 bytes of header (24 after alignment) plus a 4-byte line pointer. For a row of three integers the overhead is larger than the data.
Definition: HeapTupleHeaderData:
| Field | Size | Meaning |
|---|---|---|
t_xmin | 4 B | "insert XID stamp": transaction that created this version |
t_xmax | 4 B | "delete XID stamp": transaction that deleted, updated or locked it (0 if none) |
t_cid / t_xvac | 4 B | Command id inside the transaction (overlays t_xvac) |
t_ctid | 6 B | "current TID of this or newer row version" |
t_infomask2 | 2 B | Number of attributes plus flags (HEAP_HOT_UPDATED, HEAP_ONLY_TUPLE, HEAP_KEYS_UPDATED) |
t_infomask | 2 B | Flags: HEAP_HASNULL, HEAP_HASVARWIDTH, hint bits HEAP_XMIN_COMMITTED, HEAP_XMAX_INVALID, frozen, lock bits |
t_hoff | 1 B | Offset to user data (multiple of MAXALIGN) |
After the header comes an optional null bitmap (only when HEAP_HASNULL is set; one bit per column, so NULLs cost a bit, not a value), padding, and the column data. Hint bits in t_infomask cache the result of looking up a transaction's commit status, which is why the first SELECT after a bulk load can write pages. How the database uses xmin/xmax to decide visibility is the subject of MVCC, VACUUM & Bloat.
T1 (xid 741) tuple on page 0
1 INSERT INTO accounts VALUES (1,'ann',100); lp1: xmin=741 xmax=0 ctid=(0,1) infomask=XMAX_INVALID
2 COMMIT;
3 SELECT * FROM accounts; -- sets hint bit HEAP_XMIN_COMMITTED (page dirtied by a read)
T2 (xid 742)
4 UPDATE accounts SET balance=90 WHERE id=1; lp1: xmax=742 ctid=(0,2) HEAP_HOT_UPDATED
lp2: xmin=742 xmax=0 ctid=(0,2) HEAP_ONLY_TUPLE
5 COMMIT; -- lp1 is now dead for new snapshots; pruning will reclaim itReal scenarios: a "read-only" reporting query after a big COPY generates heavy writes (hint bits + WAL with checksums enabled); a table of (bigint, boolean, bigint) wastes 7 bytes of padding per row compared with (bigint, bigint, boolean); tables with 30 nullable columns that are mostly NULL stay compact thanks to the null bitmap.
| Product | Per-row header | Version information lives |
|---|---|---|
| PostgreSQL | 23 B header + 4 B line pointer | In the tuple (xmin/xmax), old versions in the heap |
| MySQL InnoDB | Record header (5 B in COMPACT/DYNAMIC) + hidden DB_TRX_ID (6 B), DB_ROLL_PTR (7 B), DB_ROW_ID (6 B, only without a PK) | Latest version in the clustered index, older ones in undo logs |
| SQLite | Cell header: payload size varint + rowid varint + record header | No versions in the table; rollback journal or WAL holds old pages |
| SQL Server | Row header ~4 B + null bitmap; 14 B versioning tag when row versioning is on | Version store (tempdb or ADR in the user database) |
| Oracle | Row header ~3 B; lock byte points to the block's ITL slots | Undo segments |
Fix / how to use it: read the header when debugging, never in application logic.
-- PostgreSQL: system columns are on every heap table
SELECT ctid, xmin, xmax, * FROM accounts WHERE id = 1;
-- Decode flags with pageinspect (superuser)
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT lp, t_xmin, t_xmax, t_ctid, raw_flags
FROM heap_page_items(get_raw_page('accounts', 0)),
LATERAL heap_tuple_infomask_flags(t_infomask, t_infomask2);ctid: the physical address Must-know
In plain words: ctid is "box 7, slot 3": the page number and line-pointer number of one row version.
Common misunderstanding: "ctid is PostgreSQL's hidden row id, I can use it as a key." The manual is explicit:
"a row's ctid will change if it is updated, or moved by a table-rewriting operation such as VACUUM FULL, CLUSTER, or REPACK. Therefore ctid should not be used as a row identifier. A primary key should be used to identify logical rows." — PostgreSQL documentation, 5.6 System Columns
Definition: a tid (ItemPointerData, 6 bytes: 4-byte block number + 2-byte line pointer number). Because a line pointer "is never moved until it is freed", tuples can be shuffled inside the page to compact space without changing their ctid. Every PostgreSQL index entry stores a ctid; the old version's t_ctid points to the new version, forming an update chain.
Session A ctid of row id=1
1 INSERT ... (1,'ann',100); (0,1)
2 UPDATE accounts SET balance=90 WHERE id=1; (0,2) same page: HOT if no indexed column changed
3 UPDATE accounts SET owner='bo' WHERE id=1; (0,3) owner is indexed: not HOT, new index entry
4 -- page 0 full; next update lands elsewhere
5 UPDATE accounts SET balance=80 WHERE id=1; (12,5) moved to block 12 via the FSM
6 VACUUM FULL accounts; (0,1) table rewritten, all ctids renumberedReal scenarios: a hand-written dedup query DELETE FROM t a USING t b WHERE a.ctid < b.ctid AND a.email = b.email (a legitimate one-off use); an ETL job that saved ctids to resume later and silently skipped rows after a VACUUM FULL; a support engineer comparing ctid before and after an update to confirm HOT is working.
| Product | Physical row address | Stable? |
|---|---|---|
| PostgreSQL | ctid (block, item) | No: changes on every UPDATE and rewrite |
| MySQL InnoDB | No physical address exposed; rows are found by primary key | The PK is the address |
| SQLite | rowid (64-bit key of the table b-tree) | Yes unless the table is rebuilt without an INTEGER PRIMARY KEY alias (VACUUM may renumber) |
| SQL Server | RID (file:page:slot) for heaps; clustering key otherwise | RID changes when a row is forwarded or the heap rebuilt |
| Oracle | ROWID | Changes on row movement (partition key update, SHRINK, MOVE) |
Fix / how to use it: use the primary key in applications; use ctid only to inspect physical behaviour. The Go and Laravel helpers below read ctid and xmin and report whether an update stayed on its page.
// Shows where a row physically lives in PostgreSQL: ctid (block, line
// pointer) and xmin (inserting transaction). It updates a non-indexed
// column and prints whether the new version stayed on the same page (a
// candidate HOT update) or moved. Debugging only: never store a ctid as an
// identifier, it changes on every UPDATE, VACUUM FULL, CLUSTER or REPACK.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
// RowLocation is the physical address of one row version.
type RowLocation struct {
CTID string // e.g. "(0,3)"
Block int64
Item int
XMin string // transaction id as text; xid has no Go type
}
func parseCTID(s string) (block int64, item int, err error) {
parts := strings.Split(strings.Trim(s, "()"), ",")
if len(parts) != 2 {
return 0, 0, fmt.Errorf("unexpected ctid %q", s)
}
if block, err = strconv.ParseInt(parts[0], 10, 64); err != nil {
return 0, 0, err
}
item, err = strconv.Atoi(parts[1])
return block, item, err
}
func locate(ctx context.Context, q interface {
QueryRowContext(context.Context, string, ...any) *sql.Row
}, id int64) (RowLocation, error) {
var loc RowLocation
// ctid and xmin are system columns: they exist on every heap table but
// only appear when named. Cast to text because database/sql has no tid/xid.
err := q.QueryRowContext(ctx,
`SELECT ctid::text, xmin::text FROM accounts WHERE id = $1`, id,
).Scan(&loc.CTID, &loc.XMin)
if err != nil {
return loc, err
}
loc.Block, loc.Item, err = parseCTID(loc.CTID)
return loc, err
}
func main() {
dsn := os.Getenv("DATABASE_URL") // postgres://postgres:pg@localhost:5432/postgres
if dsn == "" {
log.Println("DATABASE_URL not set; nothing to do")
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
db, err := sql.Open("pgx", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
for _, stmt := range []string{
`CREATE TABLE IF NOT EXISTS accounts (
id bigint PRIMARY KEY,
owner text NOT NULL,
balance bigint NOT NULL
) WITH (fillfactor = 80)`,
`INSERT INTO accounts VALUES (1, 'ann', 100) ON CONFLICT (id) DO NOTHING`,
} {
if _, err := db.ExecContext(ctx, stmt); err != nil {
log.Fatal(err)
}
}
before, err := locate(ctx, db, 1)
if err != nil {
log.Fatal(err)
}
// balance is not indexed: if the page has room this is a HOT update.
if _, err := db.ExecContext(ctx,
`UPDATE accounts SET balance = balance - 10 WHERE id = 1`); err != nil {
log.Fatal(err)
}
after, err := locate(ctx, db, 1)
if err != nil {
log.Fatal(err)
}
fmt.Printf("before: ctid=%s xmin=%s\n", before.CTID, before.XMin)
fmt.Printf("after: ctid=%s xmin=%s\n", after.CTID, after.XMin)
switch {
case before.CTID == after.CTID:
fmt.Println("impossible: every UPDATE writes a new row version")
case before.Block == after.Block:
fmt.Println("same block: new version fitted on the page (HOT candidate)")
default:
fmt.Println("moved to another block: every index got a new entry")
}
var hot, total int64
// Counters are flushed asynchronously; they may lag by a moment.
err = db.QueryRowContext(ctx, `
SELECT n_tup_hot_upd, n_tup_upd
FROM pg_stat_user_tables WHERE relname = 'accounts'`).Scan(&hot, &total)
if err != nil {
log.Fatal(err)
}
fmt.Printf("updates: %d total, %d HOT\n", total, hot)
}<?php
// app/Support/RowLocation.php — PostgreSQL only. Reads the physical address
// (ctid) and inserting transaction (xmin) of a row, for debugging HOT updates
// and bloat. Never persist a ctid or use it in a WHERE clause from the app:
// it changes on every UPDATE and on VACUUM FULL / CLUSTER / REPACK.
namespace App\Support;
use Illuminate\Support\Facades\DB;
final class RowLocation
{
/**
* @return array{ctid: string, block: int, item: int, xmin: string}|null
*/
public static function of(string $table, int $id): ?array
{
// ctid and xmin are system columns; cast to text because PDO has no
// tid/xid type. The table name is an identifier, so quote it with the
// grammar instead of binding it.
$quoted = DB::getQueryGrammar()->wrapTable($table);
$row = DB::selectOne(
"select ctid::text as ctid, xmin::text as xmin from {$quoted} where id = ?",
[$id],
);
if ($row === null) {
return null;
}
[$block, $item] = array_map('intval', explode(',', trim($row->ctid, '()')));
return ['ctid' => $row->ctid, 'block' => $block, 'item' => $item, 'xmin' => $row->xmin];
}
/**
* Update a non-indexed column and report whether the new version stayed
* on the same heap page (HOT candidate) or moved (every index updated).
*/
public static function demoHotUpdate(int $accountId): string
{
$before = self::of('accounts', $accountId);
DB::update('update accounts set balance = balance - 10 where id = ?', [$accountId]);
$after = self::of('accounts', $accountId);
if ($before === null || $after === null) {
return 'row not found';
}
return $before['block'] === $after['block']
? "same page: {$before['ctid']} -> {$after['ctid']} (HOT candidate)"
: "moved: {$before['ctid']} -> {$after['ctid']} (indexes got new entries)";
}
}Heap files, segments and forks Important
In plain words: a PostgreSQL table is a set of plain files named after a number; rows go wherever there is space, in no particular order. That unordered file is the heap.
Common misunderstanding: "Rows are stored in primary-key order" or "in insertion order". In a PostgreSQL heap neither is guaranteed: new rows go to any page the free space map offers, and SELECT without ORDER BY returns them in physical order, which changes after updates and vacuum. CLUSTER orders a table once; it does not keep it ordered.
Definition: "Each table and index is stored in a separate file", named after pg_class.relfilenode under PGDATA/base/<database oid>/. Each relation has forks: the main fork, the free space map (_fsm), the visibility map (_vm, tables only) and, for unlogged relations, the init fork (_init). Large relations are split:
"When a table or index exceeds 1 GB, it is divided into gigabyte-sized segments. The first segment's file name is the same as the filenode; subsequent segments are named filenode.1, filenode.2, etc." — PostgreSQL documentation, 66.1 Database File Layout
SELECT pg_relation_filepath('accounts'); -- base/16384/24576
$PGDATA/base/16384/24576 main fork, first 1 GB (blocks 0 .. 131071)
$PGDATA/base/16384/24576.1 main fork, next 1 GB (blocks 131072 .. 262143)
$PGDATA/base/16384/24576_fsm free space map
$PGDATA/base/16384/24576_vm visibility map
$PGDATA/base/16384/24579 TOAST table (pg_class.reltoastrelid) + its indexReal scenarios: TRUNCATE, VACUUM FULL, CLUSTER, REINDEX assign a new filenode (the OID stays), which is why backups and pg_relation_filepath must be re-checked after them; a disk-full incident where one table had hundreds of 1 GB segment files; tablespaces placing hot tables on faster disks via symlinks in pg_tblspc.
| Product | Files per table | Organisation |
|---|---|---|
| PostgreSQL | Main fork + _fsm + _vm (+ TOAST table, + one file set per index), 1 GB segments | Heap + separate indexes |
| MySQL InnoDB | One .ibd per table with innodb_file_per_table=ON (default); system tablespace ibdata1 otherwise | Clustered index + secondary indexes in the same tablespace, pages grouped into 1 MB extents (16 KB pages) |
| SQLite | Whole database in one file (+ -wal/-journal) | Every table and index is a b-tree inside that file |
| SQL Server | Data files (.mdf/.ndf) shared by many tables | Heap or clustered index per table |
| Oracle | Datafiles in tablespaces, segments made of extents | Heap-organised by default, index-organised (IOT) optional |
Fix / how to use it: never touch these files directly; use pg_relation_filepath(), pg_relation_size() and backups. Treat "no ORDER BY" as "random order".
Free space map (FSM) Important
In plain words: a small side file that remembers roughly how much free room each page has, so INSERT does not have to search the table for space.
Common misunderstanding: "After DELETE, the next INSERT immediately reuses that space." The space becomes reusable only after VACUUM (or page pruning) removes the dead tuples and the FSM is updated; until then new rows go to other pages or the end of the file.
Definition:
"Each heap and index relation, except for hash indexes, has a Free Space Map (FSM) to keep track of available space in the relation." — PostgreSQL documentation, 66.3 Free Space Map
It is a tree of FSM pages; leaves hold one byte per heap page. The values are "rounded to precision of 1/256th of BLCKSZ (32 bytes with default BLCKSZ)" and "not kept fully up-to-date" (pg_freespacemap docs). For indexes it only tracks entirely empty pages.
1 INSERT needs 120 bytes
2 look up FSM tree -> page 19 has ~3648 bytes free
3 pin page 19 in shared buffers, check real free space (pd_upper - pd_lower)
4 enough -> write tuple, add line pointer, update pd_lower / pd_upper
5 not enough (FSM was stale) -> correct FSM entry, ask again
6 no page with room -> extend the relation by a new block at the endReal scenarios: an append-only log table grows only at the end (FSM almost unused); a queue table with DELETE after processing fills old pages again only after vacuum; a table whose FSM was lost after a crash simply extends until vacuum rebuilds it.
| Product | Free-space tracking |
|---|---|
| PostgreSQL | _fsm fork, updated by VACUUM and when inserts find stale values |
| MySQL InnoDB | Free space managed per page and per extent/segment in the tablespace (file space header, extent descriptors); information_schema.TABLES.DATA_FREE reports unused allocated space |
| SQLite | Freelist of whole free pages (trunk and leaf pages); free space inside pages via freeblocks |
| SQL Server | PFS (Page Free Space) pages, GAM/SGAM for extents |
Fix / how to use it:
CREATE EXTENSION IF NOT EXISTS pg_freespacemap;
SELECT blkno, avail FROM pg_freespace('accounts') ORDER BY blkno LIMIT 10;
SELECT count(*) FILTER (WHERE avail > 4096) AS half_empty_pages,
count(*) AS pages
FROM pg_freespace('accounts');Visibility map (VM) Must-know
In plain words: two bits per heap page: "everything on this page is visible to everyone" and "everything on this page is frozen". It lets VACUUM skip pages and lets index-only scans skip the heap.
Common misunderstanding: "An index-only scan never touches the table." It touches the heap for every row whose page is not marked all-visible. On a table updated constantly, an "Index Only Scan" in EXPLAIN can still do thousands of heap fetches.
Definition:
"The visibility map stores two bits per heap page. The first bit, if set, indicates that the page is all-visible, or in other words that the page does not contain any tuples that need to be vacuumed." — PostgreSQL documentation, 66.4 Visibility Map
The bits are conservative: "Visibility map bits are only set by vacuum, but are cleared by any data-modifying operations on a page." Indexes do not have a VM.
VACUUM writer index-only scan
1 page 7 all tuples old -> set all-visible bit
2 index entry -> (7,3); VM bit set -> return from index
3 UPDATE row on page 7 -> VM bit cleared
4 index entry -> (7,3); VM bit clear -> read heap page 7 (heap fetch)
5 next VACUUM sets the bit againReal scenarios: EXPLAIN (ANALYZE) showing Heap Fetches: 48211 on an index-only scan right after a bulk update; a COUNT(*) that becomes fast after VACUUM; anti-wraparound vacuum finishing quickly on an insert-only archive because most pages are all-frozen.
| Product | Equivalent |
|---|---|
| PostgreSQL | _vm fork, two bits per page; inspect with pg_visibility |
| MySQL InnoDB | Not needed for covering reads: secondary-index pages carry a PAGE_MAX_TRX_ID; if it is older than the read view, the index record is used directly, otherwise InnoDB visits the clustered index |
| SQL Server, Oracle | No VM; covering index reads use the index's own versioning/undo |
| SQLite | Not needed (no row versions in the b-tree) |
Fix / how to use it: keep autovacuum up with the write rate on tables that serve index-only scans; check Heap Fetches; see MVCC, VACUUM & Bloat for autovacuum tuning.
EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM accounts WHERE id BETWEEN 1 AND 1000;
-- Index Only Scan using accounts_pkey ... Heap Fetches: 0 (after VACUUM)
CREATE EXTENSION IF NOT EXISTS pg_visibility;
SELECT all_visible, all_frozen, count(*) FROM pg_visibility_map('accounts') GROUP BY 1, 2;fillfactor Important
In plain words: how full INSERT may pack each page. The rest is kept free so updates of rows on that page can put their new version next to the old one.
Common misunderstanding: "Lower fillfactor makes every table faster." It makes the table bigger (more pages to scan and cache) and helps only tables whose rows are updated. For insert-only tables 100 is right.
Definition:
"The fillfactor for a table is a percentage between 10 and 100. 100 (complete packing) is the default. When a smaller fillfactor is specified, INSERT operations pack table pages only to the indicated percentage; the remaining space on each page is reserved for updating rows on that page." — PostgreSQL documentation, CREATE TABLE, storage parameters
Changing it with ALTER TABLE … SET (fillfactor = 80) affects only pages filled afterwards; rewrite the table to apply it everywhere. B-tree indexes have their own fillfactor (default 90). InnoDB has a server-wide innodb_fill_factor that only applies to sorted index builds; its normal insert path leaves 1/16 of each page free.
page with fillfactor 100 page with fillfactor 80
1 INSERTs fill 8168 bytes INSERTs stop at ~6530 bytes
2 UPDATE row 5: no room on page UPDATE row 5: new version fits on same page
3 new version -> other page via FSM HOT update: no index changes
4 every index gets a new entry old version pruned later, space reusedReal scenarios: a sessions table where last_seen_at is updated every request; an accounts.balance table; a job queue whose status changes three times per job; a counters table. All benefit from fillfactor 70–90. An events table that is only appended to does not.
| Product | Knob | Default |
|---|---|---|
| PostgreSQL table | fillfactor storage parameter | 100 |
| PostgreSQL B-tree index | fillfactor index storage parameter | 90 |
| MySQL InnoDB | Automatic 1/16 free on insert; innodb_fill_factor for sorted index builds; MERGE_THRESHOLD (50%) for page merges | — / 100 / 50 |
| SQL Server | FILLFACTOR on indexes (rebuild time only) | 0 (= 100) |
| Oracle | PCTFREE per table | 10 |
Fix / how to use it:
CREATE TABLE sessions (
id uuid PRIMARY KEY,
user_id bigint NOT NULL,
last_seen_at timestamptz NOT NULL
) WITH (fillfactor = 80);
ALTER TABLE accounts SET (fillfactor = 85); -- new pages only
-- apply to existing pages with a rewrite (locks the table; see Solutions for online options)
VACUUM FULL accounts;// Laravel migration: fillfactor is PostgreSQL-specific, so use a statement
Schema::create('sessions', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignId('user_id');
$table->timestampTz('last_seen_at');
});
DB::statement('ALTER TABLE sessions SET (fillfactor = 80)');Heap-only tuples (HOT) Must-know
In plain words: if an update does not touch any indexed column and the new version fits on the same page, PostgreSQL writes it on that page and does not add entries to any index.
Common misunderstanding: "With HOT, the ctid stays the same." It does not: the new version gets a new line pointer on the same page, so ctid goes from (0,1) to (0,2). What stays is the index entry, which keeps pointing at (0,1); PostgreSQL follows the chain from there.
Definition: from the manual, HOT is possible when:
"The update does not modify any columns referenced by the table's indexes, not including summarizing indexes. The only summarizing index method in the core PostgreSQL distribution is BRIN." "There is sufficient free space on the page containing the old row for the updated row." — PostgreSQL documentation, 66.7 Heap-Only Tuples (HOT)
Then no new index entries are needed, and intermediate versions can be removed during normal page access (page pruning), with the original line pointer turned into a redirect to the newest live version.
update heap page 0 index on id
1 INSERT id=1 lp1 = v1 id=1 -> (0,1)
2 UPDATE balance (HOT) lp1 = v1 (HOT_UPDATED) -> lp2 v2 id=1 -> (0,1) unchanged
3 UPDATE balance (HOT) lp2 -> lp3 v3 unchanged
4 any reader touches page, prune lp1 = REDIRECT -> lp3, lp2 unused, v1 v2 removed
5 UPDATE owner (indexed column) new version v4 anywhere new entries in EVERY indexReal scenarios: adding an index on updated_at "for a dashboard" turned every UPDATE non-HOT and doubled write I/O on a busy orders table; a last_login_at column updated on every login stays cheap because it is not indexed; a table with fillfactor 100 shows n_tup_hot_upd near zero until fillfactor is lowered.
| Product | Equivalent behaviour |
|---|---|
| PostgreSQL | HOT + page pruning; monitor n_tup_hot_upd and n_tup_newpage_upd in pg_stat_user_tables |
| MySQL InnoDB | Updates are in place in the clustered index; secondary indexes change only if their columns change (secondaries point at the PK, not a physical address), so "HOT" is the default |
| SQL Server | In-place update when the row still fits; otherwise a heap row becomes a forwarded record, a clustered row causes a page split |
| Oracle | In-place update; row migration when the row grows beyond PCTFREE space |
Fix / how to use it: keep updated columns out of indexes, give update-heavy tables room (fillfactor), and measure:
SELECT relname, n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd,
round(100.0 * n_tup_hot_upd / NULLIF(n_tup_upd, 0), 1) AS hot_pct
FROM pg_stat_user_tables ORDER BY n_tup_upd DESC LIMIT 20;TOAST Must-know
In plain words: when a row is too wide, PostgreSQL compresses big values and, if still too big, cuts them into chunks stored in a hidden side table, leaving an 18-byte pointer in the row.
Common misunderstanding: "A tuple can span pages, so a 1 MB JSON column is stored in the row." PostgreSQL "does not allow tuples to span multiple pages"; big values must go out of line. The opposite misunderstanding also exists: "SELECT * on a table with big JSON is as cheap as SELECT id." It is not: every selected TOASTed value is fetched and decompressed.
Definition:
"The TOAST management code is triggered only when a row value to be stored in a table is wider than TOAST_TUPLE_THRESHOLD bytes (normally 2 kB). The TOAST code will compress and/or move field values out-of-line until the row value is shorter than TOAST_TUPLE_TARGET bytes (also normally 2 kB, adjustable) or no more gains can be had." — PostgreSQL documentation, 66.2 TOAST
Out-of-line values are cut into chunks of at most TOAST_MAX_CHUNK_SIZE ("about 2000 bytes", so four chunk rows fit a page) stored in pg_toast.pg_toast_<oid> with columns chunk_id, chunk_seq, chunk_data. Only variable-length (varlena) types can be TOASTed; the logical limit per value is 1 GB. Compression is pglz or lz4 (default_toast_compression, or per column COMPRESSION). The four strategies:
| Strategy | Compress? | Move out of line? | Default for |
|---|---|---|---|
PLAIN | No | No | Fixed-length types (int, timestamp) |
EXTENDED | Yes, first | Yes, if still too big | Most varlena types (text, jsonb, bytea) |
EXTERNAL | No | Yes | Nothing by default; good for substr() on large text/bytea |
MAIN | Yes | Only as a last resort | numeric |
INSERT INTO docs(body) VALUES (<6 KB of JSON>)
1 row width 6100 > TOAST_TUPLE_THRESHOLD (about 2 KB with 8 KB pages)
2 EXTENDED: try pglz/lz4 compression of body -> 2600 bytes, still > target
3 move compressed body out of line: chunk_id 91822, chunk_seq 0 (1996 B), 1 (604 B)
4 row stores an 18-byte TOAST pointer; heap row now ~60 bytes
5 UPDATE docs SET title = ... -> body unchanged, no TOAST work ("values of unchanged fields are normally preserved as-is")Real scenarios: an events.payload jsonb table whose main heap is 2 GB but whose TOAST table is 60 GB; SELECT * from an API endpoint that only needed three columns spending most of its time detoasting; substr(log_text, 1, 200) getting faster after SET STORAGE EXTERNAL; switching default_toast_compression = lz4 to cut CPU on JSON writes.
| Product | Large values |
|---|---|
| PostgreSQL | TOAST: compress, then out-of-line chunks in pg_toast_<oid>, 18-byte pointer |
MySQL InnoDB DYNAMIC (default) | Long VARCHAR/BLOB/TEXT stored "fully off-page, with the clustered index record containing only a 20-byte pointer to the overflow page" |
MySQL InnoDB COMPACT/REDUNDANT | First 768 bytes in the record, rest on overflow pages |
| SQLite | Payload beyond the in-page threshold goes to a linked list of overflow pages |
| SQL Server | ROW_OVERFLOW_DATA and LOB_DATA allocation units |
| MongoDB | Whole document (max 16 MB BSON) in the WiredTiger B-tree, block-compressed |
Fix / how to use it:
SELECT pg_column_size(payload) AS stored_bytes, octet_length(payload::text) AS raw_bytes,
pg_column_compression(payload) AS method
FROM events WHERE id = 42;
ALTER TABLE logs ALTER COLUMN body SET STORAGE EXTERNAL; -- fast substr, no compression
ALTER TABLE events ALTER COLUMN payload SET COMPRESSION lz4; -- new values only
ALTER TABLE events SET (toast_tuple_target = 4080); -- keep more inline (new rows only)
SELECT reltoastrelid::regclass, pg_size_pretty(pg_relation_size(reltoastrelid))
FROM pg_class WHERE relname = 'events';In Go and Laravel the fix is mostly "select only the columns you need": SELECT id, status FROM events never detoasts payload; in Eloquent use ->select(['id', 'status']) instead of the default *.
Row-oriented vs column-oriented layout Important
In plain words: a row store puts all columns of a row next to each other in a page; a column store puts all values of one column next to each other. Same table, different boxes.
Common misunderstanding: "Column stores are just faster." They are faster for scans and aggregates over a few columns, and slower for fetching or updating whole single rows, which must be stitched from many column files.
Definition: N-ary storage (NSM) = row store (PostgreSQL heap, InnoDB, SQLite, SQL Server rowstore, Oracle default). Decomposition storage (DSM) = column store (ClickHouse, Amazon Redshift, Vertica, DuckDB, Apache Parquet files, SQL Server columnstore indexes). PAX is the hybrid: row groups, column-wise inside each group (Parquet row groups, ORC stripes).
query row store (8 KB pages) column store
1 SELECT * WHERE id = 3 1 index walk + 1 heap page 1 block per column (4) + stitch
2 SELECT SUM(amount) over 100 M rows every page, all columns only amount blocks, compressed 5-10x
3 UPDATE status WHERE id = 3 1 new tuple rewrite/append in a column segment + delete maskReal scenarios: an OLTP orders database (PostgreSQL) feeding a nightly analytics warehouse (ClickHouse, Redshift or BigQuery) through CDC; a "reporting replica" that is still a row store and so still reads every column; PostgreSQL extensions (cstore_fdw, Citus columnar, TimescaleDB compression) adding columnar storage inside PostgreSQL.
| Workload | Row store | Column store |
|---|---|---|
| Point lookup / single-row write | Excellent | Poor |
| Scan of a few columns over many rows | Reads all columns (read amplification) | Excellent |
| Compression | Moderate (per page/TOAST) | High (similar values together, run-length, dictionary) |
| Typical products | PostgreSQL, MySQL InnoDB, SQLite, SQL Server, Oracle | ClickHouse, Redshift, Vertica, DuckDB, Parquet |
Fix / how to use it: keep OLTP in a row store, ship data to a column store for analytics; details in OLTP vs OLAP & Columnar Storage.
I/O unit, sequential vs random I/O, read amplification Must-know
In plain words: the database pays per page read, and reading pages one after another is much cheaper than jumping around. Read amplification is "how many bytes I read to get the bytes I wanted".
Common misunderstanding: "On SSDs random I/O is free." SSDs narrow the gap, but random reads still mean one request per page, no OS read-ahead, and more CPU per byte; PostgreSQL's default random_page_cost = 4.0 vs seq_page_cost = 1.0 still describes many systems (lower it to 1.1–2 for fast SSDs, measured).
Definition: the I/O unit of the database is its page; the OS reads in 4 KB memory pages with read-ahead for sequential files; devices have their own units (512 B/4 KB sectors, 4–16 KB flash pages). Sequential I/O reads adjacent blocks (seq scan, B-tree leaf chains, bitmap heap scans in block order). Random I/O jumps (index scans over uncorrelated heaps). Read amplification = pages read × page size ÷ bytes needed.
SELECT * FROM orders WHERE customer_id = 7 (50 matching rows, 10 M-row table)
1 index on customer_id: 3 index pages (root, internal, leaf) IO1
2 50 ctids spread across 50 different heap pages IO2 x 50 random
3 total 53 pages x 8 KB = 424 KB read for ~5 KB of rows read amplification ~85x
4 same 50 rows physically clustered (CLUSTER or sequential PK) IO2 x 2-3 pagesReal scenarios: a report that is fast on staging (data in cache) and slow in production (cold disk, random I/O); a bitmap heap scan beating an index scan because it visits heap pages in block order; pg_stats.correlation near 1 for a time-ordered created_at (cheap range scans) and near 0 for customer_id.
| Product | Read-ahead / prefetch |
|---|---|
| PostgreSQL | Relies on OS read-ahead for seq scans; effective_io_concurrency for bitmap heap scans; asynchronous I/O (io_method) in newer releases |
| MySQL InnoDB | Linear read-ahead (innodb_read_ahead_threshold), optional random read-ahead |
| SQLite | OS read-ahead; PRAGMA mmap_size for memory-mapped reads |
| SQL Server | Read-ahead built into scans |
Fix / how to use it: make queries touch fewer pages: covering indexes, physical correlation (sequential keys, CLUSTER, partitioning by time), narrow rows, SELECT only needed columns. Measure with EXPLAIN (ANALYZE, BUFFERS): shared hit = pages from the buffer pool, read = pages from the OS (page cache or disk).
Buffer pool, OS page cache and double caching Must-know
In plain words: the database keeps recently used pages in its own memory (buffer pool). The operating system also keeps recently read file pages in its memory (page cache). Unless the database bypasses the OS, a page can sit in both.
Common misunderstanding: "Give the database 90% of RAM." For InnoDB with O_DIRECT that is close to right (the manual: "up to 80% of physical memory is often assigned to the buffer pool"). For PostgreSQL, which reads through the OS page cache, the docs start at 25% and say more than 40% is unlikely to help because "PostgreSQL also relies on the operating system cache".
Definition: Hellerstein et al. describe the problem directly:
"Given that the DBMS has to do its own buffering carefully for correctness, any additional buffering by the OS is redundant." — Hellerstein, Stonebraker & Hamilton, Architecture of a Database System, 2007
They name two costs: wasted memory and "an additional copying step: on reads, data is first copied from the disk to the OS buffer, and then copied again to the DBMS buffer pool". A buffer pool is an array of page-sized frames, a hash table from page id to frame, pin counts (a pinned page cannot be evicted), a dirty flag, and a replacement policy (PostgreSQL clock-sweep with usage counts; InnoDB LRU with a young/old midpoint).
read block 7 of accounts (PostgreSQL)
1 hash lookup in shared_buffers -> miss
2 pick a victim frame (clock sweep); if dirty, write it out first
3 pread() 8 KB -> OS page cache: hit (memory copy) or miss (device I/O + read-ahead)
4 copy into the frame, pin it, read tuples, unpin
5 later UPDATE marks the frame dirty; checkpointer/bgwriter writes it back (WAL first)Real scenarios: a 64 GB PostgreSQL server with shared_buffers = 16GB where most reads are "read" in EXPLAIN but still fast (OS cache hits); an InnoDB server with a 4 GB buffer pool on 64 GB RAM thrashing because O_DIRECT means the OS cache does not help; a container memory limit counting the page cache and OOM-killing PostgreSQL.
| Product | Database cache | OS page cache used? | Key knobs |
|---|---|---|---|
| PostgreSQL | shared_buffers (default 128 MB; start at 25% of RAM) | Yes, by design (buffered I/O) | shared_buffers, effective_cache_size (planner hint only) |
| MySQL InnoDB | Buffer pool (default 128 MB; often 50–80% of RAM on dedicated servers) | No with innodb_flush_method=O_DIRECT (Unix default when supported) | innodb_buffer_pool_size, innodb_buffer_pool_instances |
| SQLite | Page cache per connection (PRAGMA cache_size) | Yes, or mmap | cache_size, mmap_size |
| SQL Server | Buffer pool (max server memory) | No (unbuffered I/O) | max server memory |
| Oracle | Buffer cache in the SGA | Usually no (direct I/O/ASM) | DB_CACHE_SIZE, SGA_TARGET |
| MongoDB WiredTiger | Internal cache (default 50% of (RAM − 1 GB)) | Yes, for compressed file pages | storage.wiredTiger.engineConfig.cacheSizeGB |
| Redis | Everything lives in memory; no pages, no buffer pool | Only for RDB/AOF files | maxmemory |
Fix / how to use it:
SHOW shared_buffers;
CREATE EXTENSION IF NOT EXISTS pg_buffercache;
SELECT c.relname, count(*) AS buffers, pg_size_pretty(count(*) * 8192) AS cached
FROM pg_buffercache b JOIN pg_class c ON b.relfilenode = pg_relation_filenode(c.oid)
WHERE b.reldatabase = (SELECT oid FROM pg_database WHERE datname = current_database())
GROUP BY c.relname ORDER BY buffers DESC LIMIT 10;
-- MySQL
SELECT @@innodb_buffer_pool_size, @@innodb_flush_method;
SHOW ENGINE INNODB STATUS; -- BUFFER POOL AND MEMORY section: hit rate, young/not youngIndex → heap: the two-step lookup (IO1, IO2) Must-know
In plain words: an index does not contain the row; it contains the key and a pointer. First you read the index (IO1) to get the pointer, then the table page (IO2) to get the row.
Common misunderstanding: "An index scan is always cheaper than a full table scan." Each matching row may cost a random heap read; past a few percent of the table, a sequential scan reading every page once is cheaper, and the planner switches.
Definition:
"All indexes in PostgreSQL are secondary indexes, meaning that each index is stored separately from the table's main data area (which is called the table's heap in PostgreSQL terminology). This means that in an ordinary index scan, each row retrieval requires fetching data from both the index and the heap." — PostgreSQL documentation, 11.9 Index-Only Scans and Covering Indexes
SELECT name FROM employees WHERE email = 'bob@x.io' (PostgreSQL)
1 IO1 read B-tree root page (usually cached)
2 IO1 read internal page (usually cached)
3 IO1 read leaf page: 'bob@x.io' -> ctid (7,3)
4 IO2 read heap block 7, line pointer 3
5 check xmin/xmax against the snapshot (visibility lives only in the heap)
6 follow HOT chain if lp 3 is a redirect; return the rowThree variants change IO2: a bitmap heap scan collects many ctids, sorts them by block and reads each heap page once in order; an index-only scan skips IO2 when the visibility map says the page is all-visible; a covering index (INCLUDE) makes index-only scans possible for more queries.
Real scenarios: a lookup by email doing 4 buffer reads per call (3 index + 1 heap); an "Index Scan" on status = 'pending' that turns into a bitmap scan when 10% of rows match; SELECT id, email FROM users WHERE email = ? becoming an index-only scan after CREATE INDEX ... (email) INCLUDE (id).
| Product | Secondary index stores | Second step |
|---|---|---|
| PostgreSQL | Key + ctid | Heap page read, unless index-only scan + VM bit |
| MySQL InnoDB | Key + primary-key columns | Walk of the clustered index by PK ("covering" if all needed columns are in the secondary) |
| SQLite (rowid table) | Key + rowid | Walk of the table b-tree by rowid |
| SQL Server | Key + RID (heap) or clustering key (clustered table) | RID lookup or key lookup |
| Oracle | Key + ROWID | Table access by index ROWID |
| MongoDB WiredTiger | Key + RecordId | Fetch document (FETCH stage) unless covered (PROJECTION_COVERED) |
Fix / how to use it:
CREATE INDEX users_email_incl ON users (email) INCLUDE (id, name);
EXPLAIN (ANALYZE, BUFFERS) SELECT id, name FROM users WHERE email = 'bob@x.io';
-- Index Only Scan using users_email_incl ... Heap Fetches: 0 Buffers: shared hit=4Clustered (InnoDB) vs heap (PostgreSQL) organisation Must-know
In plain words: in InnoDB the table is the primary-key B+tree: rows live in its leaf pages, in PK order. In PostgreSQL the table is a heap and the primary key is just another index pointing into it.
Common misunderstanding: "PostgreSQL's CLUSTER makes it like InnoDB." CLUSTER reorders the heap once by an index; new rows and updates are not kept in that order and the PK index is still separate.
Definition: from the MySQL 8.4 manual:
"Accessing a row through the clustered index is fast because the index search leads directly to the page that contains the row data." "In InnoDB, each record in a secondary index contains the primary key columns for the row, as well as the columns specified for the secondary index." — MySQL 8.4 Reference Manual, 17.6.2.1 Clustered and Secondary Indexes
Without a PRIMARY KEY, InnoDB uses the first UNIQUE NOT NULL index, else a hidden GEN_CLUST_INDEX on a 6-byte row id. Because secondaries carry the PK, "if the primary key is long, the secondary indexes use more space". When inserts are sequential, InnoDB pages end "about 15/16 full"; random inserts leave them "from 1/2 to 15/16 full" (page splits).
PK lookup: SELECT * FROM users WHERE id = 42
1 InnoDB: walk clustered index -> leaf holds the row 1 tree walk
2 PostgreSQL: walk users_pkey -> ctid -> heap page index + heap
secondary lookup: WHERE email = 'bob@x.io'
3 InnoDB: walk email index -> PK 42 -> walk clustered index 2 tree walks
4 PostgreSQL: walk email index -> ctid -> heap page index + heap
update of a non-indexed column
5 InnoDB: in place in the clustered leaf, old version to undo secondaries untouched
6 PostgreSQL: new tuple; HOT if room on the page, else new entry in every indexReal scenarios: a MySQL table with a CHAR(36) UUID primary key and six secondary indexes, each carrying 36 extra bytes per entry, plus page splits from random inserts; switching to BIGINT AUTO_INCREMENT or a time-ordered UUIDv7 shrinks indexes and the buffer pool working set; in PostgreSQL the same UUID costs only in the PK index itself because other indexes store a 6-byte ctid.
| Aspect | PostgreSQL heap | MySQL InnoDB clustered | SQLite | SQL Server |
|---|---|---|---|---|
| Row location | Any heap page | Leaf of PK B+tree, PK order | Leaf of table b-tree, rowid order (WITHOUT ROWID: PK order) | Heap (RID) or clustered index |
| PK lookup | Index + heap | One tree walk | One tree walk on rowid | Heap: index + RID lookup; clustered: one walk |
| Secondary index payload | ctid (6 B) | Full PK | rowid | RID or clustering key |
| Range scan by PK | Random heap pages unless correlated | Sequential leaf pages | Sequential leaf pages | Clustered: sequential |
| Cost of random PK (UUIDv4) | PK index bloat only | Page splits, fragmentation, larger secondaries | Page splits in WITHOUT ROWID | Page splits |
| Non-key update | New tuple (HOT if possible) | In place + undo | In place in page (journal/WAL protects) | In place / forwarded record |
Fix / how to use it: in InnoDB always define a short, increasing primary key; in PostgreSQL choose PKs for the domain and rely on correlation tricks (time-ordered keys, partitioning, CLUSTER on cold tables) for range scans. Deeper tree mechanics: B-Tree vs B+Tree and MySQL Storage Engines.
SQLite: b-tree pages, cells and overflow pages Good to know
In plain words: a SQLite database is one file cut into equal pages; every table and index is a b-tree inside that file, and rows are "cells" inside b-tree pages.
Common misunderstanding: "SQLite has no storage engine, it just writes rows to a file." It has a full page-based b-tree format with free lists, overflow pages and a journal or WAL, documented byte by byte.
Definition:
"The main database file consists of one or more pages. The size of a page is a power of two between 512 and 65536 inclusive. All pages within the same database are the same size." — SQLite, Database File Format
A b-tree page has "the 100-byte database file header (found on page 1 only)", "the 8 or 12 byte b-tree page header", "the cell pointer array", "unallocated space", "the cell content area" and "the reserved region": the same header / slot array / free space / items-from-the-end shape as PostgreSQL. Table b-trees (B+trees keyed by rowid) store rows in leaves; index b-trees store keys. When a cell's payload exceeds a threshold, "only the first few bytes of the payload are stored on the b-tree page and the balance is stored in a linked list of content overflow pages". A WITHOUT ROWID table is stored as an index b-tree keyed by the primary key (a clustered table).
SQLite page 5 (table b-tree leaf, 4096 bytes)
1 8-byte page header: type 0x0d, first freeblock, cell count = 3, cell content start = 3900
2 cell pointer array: 3900, 3960, 4030
3 unallocated space
4 cells: [payload size][rowid][record header][columns] ... (last cell may point to overflow page 91)| SQLite term | PostgreSQL term | InnoDB term |
|---|---|---|
| Page | Page / block | Page |
| Cell pointer array | Line pointers (ItemIdData) | Page directory slots |
| Cell | Tuple / index tuple | Record |
| Overflow page | TOAST chunk | Off-page / overflow page |
| rowid | ctid (but stable) | DB_ROW_ID (hidden PK) |
| Freelist | Free space map | Free extents / segments |
Fix / how to use it: PRAGMA page_size, PRAGMA page_count, PRAGMA freelist_count, and VACUUM to compact. Full coverage in SQLite in Depth.
Bloat vs fragmentation Important
In plain words: bloat is space inside the table taken by dead or empty slots, so the table is bigger than its live data. Fragmentation is data being out of order or spread across half-empty pages, so reading it takes more, and more random, I/O.
Common misunderstanding: "Bloat and fragmentation are the same and VACUUM fixes both." Plain VACUUM makes dead space reusable (fixing future growth) but does not shrink the file or reorder rows. Rewrites (VACUUM FULL, CLUSTER, REPACK, pg_repack, InnoDB OPTIMIZE TABLE) fix both, at the cost of a rewrite and, for the built-in ones, an exclusive lock.
Definition: bloat ≈ (relation size − estimated live data) ÷ relation size; it comes from MVCC dead tuples not yet vacuumed or vacuumed but not reused, and from deletes. Fragmentation in B+tree tables (InnoDB, SQL Server) comes from page splits on random inserts; in PostgreSQL heaps it shows as low correlation and half-empty pages. File-system fragmentation is a third, rarely relevant meaning.
day action pages live rows note
1 0 load 1 M rows (fillfactor 100) 4425 1 M
2 1 UPDATE all rows once (no room, not HOT) 8850 1 M old versions dead
3 1 autovacuum 8850 1 M dead space reusable, file same size
4 2 UPDATE all rows again 8850 1 M reuses freed space: no growth
5 3 VACUUM FULL / REPACK / pg_repack 4425 1 M rewritten, compact, ctids renumberedReal scenarios: a queue table of 2,000 live rows that is 40 GB because a long-running transaction blocked vacuum for a week; an InnoDB table with random UUID keys whose pages average 60% full; a nightly DELETE of old rows that never shrinks the file (partition by time and DROP partitions instead).
| Product | Reclaim inside file | Shrink / reorder (rewrite) |
|---|---|---|
| PostgreSQL | VACUUM / autovacuum (truncates only empty pages at the end) | VACUUM FULL, CLUSTER, REPACK (newer releases), pg_repack extension (online) |
| MySQL InnoDB | Purge of undo + page merges (MERGE_THRESHOLD) | OPTIMIZE TABLE (= ALTER TABLE ... FORCE, online DDL) |
| SQLite | Freelist reuse | VACUUM, PRAGMA auto_vacuum = INCREMENTAL |
| SQL Server | Ghost cleanup | ALTER INDEX ... REBUILD / REORGANIZE |
| Oracle | Space reuse below PCTFREE | ALTER TABLE ... SHRINK SPACE, MOVE |
Fix / how to use it: measure first (the Go and Laravel size reports below), fix vacuum, then rewrite only what stays bloated. The vacuum side belongs to MVCC, VACUUM & Bloat.
// Prints a size report for the largest tables in a PostgreSQL database:
// heap (main fork), TOAST + FSM + VM, indexes, total, the HOT-update ratio
// and the dead-tuple share. Read-only; safe to run against production with a
// role that can read pg_stat_user_tables.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"text/tabwriter"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
const report = `
SELECT c.oid::regclass::text AS table_name,
pg_relation_size(c.oid) AS heap_bytes,
pg_table_size(c.oid) - pg_relation_size(c.oid) AS toast_fsm_vm_bytes,
pg_indexes_size(c.oid) AS index_bytes,
pg_total_relation_size(c.oid) AS total_bytes,
pg_relation_size(c.oid) / current_setting('block_size')::bigint AS pages,
coalesce(s.n_live_tup, 0) AS live_tuples,
coalesce(s.n_dead_tup, 0) AS dead_tuples,
coalesce(s.n_tup_upd, 0) AS updates,
coalesce(s.n_tup_hot_upd, 0) AS hot_updates
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid
WHERE c.relkind IN ('r', 'm')
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT $1`
// TableSize is one row of the report.
type TableSize struct {
Name string
Heap, ToastFsmVM, Index, Total int64
Pages int64
Live, Dead, Updates, HOT int64
}
func pct(part, whole int64) string {
if whole == 0 {
return "-"
}
return fmt.Sprintf("%.0f%%", 100*float64(part)/float64(whole))
}
func human(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
}
func main() {
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
log.Println("DATABASE_URL not set; nothing to do")
return
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
db, err := sql.Open("pgx", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.QueryContext(ctx, report, 20)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
w := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0)
fmt.Fprintln(w, "table\theap\ttoast+fsm+vm\tindexes\ttotal\tpages\tdead\tHOT")
for rows.Next() {
var t TableSize
if err := rows.Scan(&t.Name, &t.Heap, &t.ToastFsmVM, &t.Index, &t.Total,
&t.Pages, &t.Live, &t.Dead, &t.Updates, &t.HOT); err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\n",
t.Name, human(t.Heap), human(t.ToastFsmVM), human(t.Index), human(t.Total),
t.Pages, pct(t.Dead, t.Live+t.Dead), pct(t.HOT, t.Updates))
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
w.Flush()
}<?php
// app/Console/Commands/TableSizeReport.php — `php artisan db:table-sizes`
// PostgreSQL: heap vs TOAST/FSM/VM vs indexes, dead-tuple share and HOT ratio.
// MySQL: data_length / index_length / data_free from information_schema.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Number;
final class TableSizeReport extends Command
{
protected $signature = 'db:table-sizes {--limit=20}';
protected $description = 'Show physical size, bloat hints and HOT ratio per table';
public function handle(): int
{
$limit = (int) $this->option('limit');
$rows = DB::connection()->getDriverName() === 'pgsql'
? $this->postgres($limit)
: $this->mysql($limit);
$this->table(
['table', 'heap/data', 'toast+fsm+vm', 'indexes', 'total', 'dead / free', 'HOT'],
$rows,
);
return self::SUCCESS;
}
/** @return list<array<int, string>> */
private function postgres(int $limit): array
{
$result = DB::select(<<<'SQL'
select c.oid::regclass::text as name,
pg_relation_size(c.oid) as heap,
pg_table_size(c.oid) - pg_relation_size(c.oid) as toast_fsm_vm,
pg_indexes_size(c.oid) as indexes,
pg_total_relation_size(c.oid) as total,
coalesce(s.n_live_tup, 0) as live,
coalesce(s.n_dead_tup, 0) as dead,
coalesce(s.n_tup_upd, 0) as upd,
coalesce(s.n_tup_hot_upd, 0) as hot
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
left join pg_stat_user_tables s on s.relid = c.oid
where c.relkind in ('r', 'm')
and n.nspname not in ('pg_catalog', 'information_schema')
order by pg_total_relation_size(c.oid) desc
limit ?
SQL, [$limit]);
return array_map(fn ($r) => [
$r->name,
Number::fileSize($r->heap),
Number::fileSize($r->toast_fsm_vm),
Number::fileSize($r->indexes),
Number::fileSize($r->total),
$this->percent($r->dead, $r->live + $r->dead),
$this->percent($r->hot, $r->upd),
], $result);
}
/** @return list<array<int, string>> */
private function mysql(int $limit): array
{
// InnoDB: the table IS the clustered index, so data_length includes
// the rows; data_free is allocated-but-unused space in the tablespace.
$result = DB::select(<<<'SQL'
select table_name as name, data_length as data, index_length as indexes,
data_free as free
from information_schema.tables
where table_schema = database() and engine = 'InnoDB'
order by data_length + index_length desc
limit ?
SQL, [$limit]);
return array_map(fn ($r) => [
$r->name,
Number::fileSize($r->data),
'-',
Number::fileSize($r->indexes),
Number::fileSize($r->data + $r->indexes),
Number::fileSize($r->free),
'-',
], $result);
}
private function percent(int|float $part, int|float $whole): string
{
return $whole > 0 ? round(100 * $part / $whole).'%' : '-';
}
}What each database really does
| Product | Page | Table organisation | Row address in indexes | Big values | Cache |
|---|---|---|---|---|---|
| PostgreSQL | 8 KB | Heap + separate B-tree/GIN/GiST/BRIN indexes | ctid | TOAST (2 KB threshold, pglz/lz4) | shared_buffers + OS page cache |
| MySQL InnoDB | 16 KB | Clustered PK B+tree | Primary key | Off-page with 20-byte pointer (DYNAMIC) | Buffer pool, O_DIRECT |
| SQLite | 4 KB default | B+tree per table (rowid) or per WITHOUT ROWID table | rowid | Overflow page chains | Page cache per connection |
| SQL Server | 8 KB, 64 KB extents | Heap or clustered index; columnstore option | RID or clustering key | Row-overflow / LOB pages | Buffer pool |
| Oracle | DB_BLOCK_SIZE (often 8 KB) | Heap by default, IOT option | ROWID | LOB segments (SecureFiles) | Buffer cache (SGA) |
| MongoDB (WiredTiger) | Variable B-tree pages, compressed | Documents keyed by RecordId (clustered collections optional) | RecordId | Documents ≤ 16 MB, block compression | WiredTiger cache + OS cache |
| CockroachDB | Pebble (LSM) SSTable blocks | Rows are KV pairs keyed by PK (clustered by PK) | Primary key | Large values in KV, no TOAST | Pebble block cache |
| Redis | No pages: in-memory structures | Keys in a hash table | n/a | Up to 512 MB per string | All data in RAM |
Mechanics
Knobs and functions you will actually use Must-know
| Knob / function | Product | What it does |
|---|---|---|
block_size (read-only) | PostgreSQL | Page size, 8192 by default |
shared_buffers | PostgreSQL | Buffer pool size; restart required |
effective_cache_size | PostgreSQL | Planner's guess of shared_buffers + OS cache; allocates nothing |
random_page_cost, seq_page_cost | PostgreSQL | Planner cost of random vs sequential page reads (4.0 / 1.0) |
effective_io_concurrency | PostgreSQL | Prefetch depth for bitmap heap scans |
fillfactor | PostgreSQL table/index | Packing percentage (tables 100, B-tree 90) |
toast_tuple_target | PostgreSQL table | Target row length for TOAST (default 2040 with 8 KB pages) |
default_toast_compression | PostgreSQL | pglz (default) or lz4 |
ALTER TABLE … SET STORAGE | PostgreSQL | PLAIN, EXTENDED, EXTERNAL, MAIN |
pg_relation_size(rel, fork) | PostgreSQL | Size of one fork (main, fsm, vm, init) |
pg_table_size, pg_indexes_size, pg_total_relation_size | PostgreSQL | Table incl. TOAST/FSM/VM; all indexes; both together |
pg_column_size, pg_column_compression | PostgreSQL | Stored bytes of a value; compression method |
pg_relation_filepath | PostgreSQL | File path relative to PGDATA |
pageinspect: get_raw_page, page_header, heap_page_items, heap_tuple_infomask_flags, bt_page_items | PostgreSQL | Read raw pages (superuser) |
pg_freespacemap: pg_freespace | PostgreSQL | FSM values per page |
pg_visibility: pg_visibility_map | PostgreSQL | VM bits per page |
pg_buffercache | PostgreSQL | What is in shared_buffers now |
innodb_page_size | MySQL | 4–64 KB, set at initialization |
innodb_buffer_pool_size | MySQL | Buffer pool (default 128 MB) |
innodb_flush_method | MySQL | O_DIRECT avoids double caching |
innodb_file_per_table | MySQL | One .ibd per table (default ON) |
innodb_fill_factor, MERGE_THRESHOLD | MySQL | Sorted-build packing; page merge threshold |
ROW_FORMAT | MySQL | DYNAMIC (default), COMPACT, REDUNDANT, COMPRESSED |
PRAGMA page_size, cache_size, mmap_size | SQLite | Page size; page cache; memory-mapped I/O |
Torn pages, checksums and why pages are written carefully Important
A database page (8 or 16 KB) is larger than what most devices write atomically (often 4 KB). If power fails mid-write, the page on disk is half old, half new: a torn page. PostgreSQL protects against it with full_page_writes (the first change to a page after a checkpoint logs the whole page image in WAL) and detects corruption with data checksums (pd_checksum; on by default for new clusters since PostgreSQL 18, check with SHOW data_checksums). InnoDB uses the doublewrite buffer: pages are first written to a doublewrite area, then to their place. The pd_lsn in every page header is what lets crash recovery know whether a WAL record was already applied. The full story is in Durability, WAL & Crash Recovery.
Error messages you will meet Good to know
| Message | Product | Meaning |
|---|---|---|
ERROR: row is too big: size …, maximum size 8160 | PostgreSQL (SQLSTATE 54000) | Even after TOAST the row does not fit a page (too many fixed-width or PLAIN columns) |
ERROR: index row size … exceeds btree version 4 maximum 2704 for index "…" | PostgreSQL (54000) | A B-tree entry must fit in about a third of a page; index a hash or prefix instead |
ERROR: tables can have at most 1600 columns | PostgreSQL (54011) | Hard limit of the tuple format |
ERROR 1118 (42000): Row size too large (> 8126) | MySQL InnoDB, 16 KB page | Too many inline columns; use DYNAMIC and TEXT/BLOB |
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535 | MySQL | Server-level 64 KB row definition limit |
invalid page in block … of relation … | PostgreSQL (XX001) | Page header or checksum failed validation: storage corruption |
string or blob too big | SQLite | Value exceeds SQLITE_MAX_LENGTH (default 1,000,000,000 bytes) |
Solving the classic problems
The table keeps growing but the row count does not (bloat)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Fix vacuum | Find long transactions (pg_stat_activity.xact_start), tune autovacuum per table | Stops new bloat | Does not shrink existing files |
| Online rewrite | pg_repack extension (or REPACK where available) | Compacts without a long exclusive lock | Needs 2× space during the run |
| Offline rewrite | VACUUM FULL / CLUSTER | Built in, simplest | ACCESS EXCLUSIVE lock for the whole run |
| Partition by time | DROP/DETACH old partitions instead of DELETE | No dead tuples at all | Schema change; see Partitioning |
| MySQL | OPTIMIZE TABLE t | Online for InnoDB | Rebuild I/O, replication lag |
SELECT relname, n_live_tup, n_dead_tup,
pg_size_pretty(pg_relation_size(relid)) AS heap,
last_autovacuum
FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;
ALTER TABLE queue_jobs SET (autovacuum_vacuum_scale_factor = 0.01);The Go sizes program and the Laravel db:table-sizes command above print heap, TOAST/FSM/VM, index and total size with the dead-tuple share, so bloat shows up in one table.
Updates are slow on a table with many indexes (no HOT)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Lower fillfactor | ALTER TABLE t SET (fillfactor = 80) + rewrite | Room for HOT on the same page | Table 20–25% larger |
| Keep hot columns unindexed | Drop or move indexes on updated_at, counters, status timestamps | Updates stay HOT | Queries on those columns need another path (BRIN, partial index) |
| Split hot columns | Move counters to a narrow side table | Small, fast-updating rows | Extra join |
| Use BRIN for time columns | BRIN is summarizing, does not block HOT | Cheap index on updated_at | Only useful when correlated with physical order |
ALTER TABLE orders SET (fillfactor = 85);
DROP INDEX IF EXISTS orders_updated_at_idx;
CREATE INDEX orders_updated_at_brin ON orders USING brin (updated_at);
SELECT n_tup_upd, n_tup_hot_upd FROM pg_stat_user_tables WHERE relname = 'orders';// Go: watch the HOT ratio after a deploy (same query as the sizes report)
var upd, hot int64
err := db.QueryRowContext(ctx,
`SELECT n_tup_upd, n_tup_hot_upd FROM pg_stat_user_tables WHERE relname = $1`,
"orders").Scan(&upd, &hot)// Laravel migration: fillfactor + BRIN, both PostgreSQL-only statements
DB::statement('ALTER TABLE orders SET (fillfactor = 85)');
DB::statement('CREATE INDEX orders_updated_at_brin ON orders USING brin (updated_at)');Wide rows and big JSON make everything slow (TOAST)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Select only needed columns | No SELECT *; Eloquent select([...]) | Big values never detoasted | Discipline in code |
| Move big values to a side table | documents(id, ...) + document_bodies(document_id, body) | Main heap small and cache-friendly | Join when needed |
lz4 compression | ALTER COLUMN ... SET COMPRESSION lz4 | Faster compress/decompress than pglz | New values only |
SET STORAGE EXTERNAL | For substr on large text/bytea | Partial fetch of chunks | No compression, more space |
| Object storage | Store files in S3-compatible storage, keep a key | Database stays small | Two systems to keep consistent |
// Eloquent: avoid loading the TOASTed payload in a list endpoint
$events = Event::query()
->select(['id', 'type', 'created_at']) // payload not selected, never detoasted
->latest()
->limit(50)
->get();Index scans are slow on cold data (random I/O)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Covering index | CREATE INDEX ... INCLUDE (...) + vacuumed table | Index-only scan, no IO2 | Bigger index; useless if VM bits are clear |
| Physical correlation | Time-ordered keys, time partitioning, CLUSTER on cold tables | Range scans read few pages | CLUSTER is one-off and locks |
| Bitmap heap scan | Let the planner choose it (statistics up to date) | Heap read in block order | Lossy for huge result sets |
| Tune cost model | random_page_cost = 1.1–2 on SSD, effective_cache_size to real cache | Better plan choices | Wrong values cause worse plans |
CREATE INDEX orders_customer_incl ON orders (customer_id) INCLUDE (status, total);
VACUUM (ANALYZE) orders;
SELECT attname, correlation FROM pg_stats WHERE tablename = 'orders';Random UUID primary keys in InnoDB
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Auto-increment PK | BIGINT UNSIGNED AUTO_INCREMENT | Sequential inserts, pages ~15/16 full, 8-byte PK in secondaries | IDs are guessable; see ID Generation |
Time-ordered UUID (v7) stored as BINARY(16) | Generate in the app | Mostly sequential, global uniqueness | 16 bytes in every secondary |
UUID_TO_BIN(uuid, 1) for v1 UUIDs | Swap time parts | Sequential-ish for v1 | Only for v1 UUIDs |
// Laravel 13: the HasUuids trait generates UUIDv7 (time-ordered) by default
Schema::create('orders', function (Blueprint $table) {
$table->id(); // BIGINT clustered PK in InnoDB
$table->uuid('public_id')->unique(); // external identifier
$table->timestamps();
});Sizing memory without double caching
| Engine | Starting point | Why |
|---|---|---|
| PostgreSQL | shared_buffers = 25% RAM, effective_cache_size = 50–75% RAM | Buffered I/O: the OS cache is the second tier |
| MySQL InnoDB | innodb_buffer_pool_size = 50–80% RAM, innodb_flush_method = O_DIRECT | Bypasses the OS cache, so the buffer pool is the only cache |
| SQLite | PRAGMA cache_size = -65536 (64 MB) per connection, or mmap_size | Small embedded footprint |
| Containers | Memory limit > buffer pool + per-connection memory + page cache headroom | Page cache counts toward cgroup memory |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Insert-only log/event table | fillfactor 100, BRIN on time, partition by time | DROP partitions for retention | No updates, so no need for free space |
| Update-heavy OLTP table (balances, sessions) | fillfactor 70–90, few indexes, none on updated columns | Monitor n_tup_hot_upd | Keeps updates HOT |
| Table with large JSON/text | Default EXTENDED, lz4, select only needed columns | Side table for bodies | Main heap stays small |
| Hot read query on a few columns | Covering index with INCLUDE | Aggressive autovacuum on that table | Index-only scan needs VM bits |
| MySQL InnoDB table | Short, increasing PK | UUIDv7 in a secondary unique column if needed | Clustered order, small secondaries |
| Analytics over billions of rows | Column store (ClickHouse, Redshift, DuckDB, Parquet) | CDC from the OLTP row store | Read only the needed columns, compressed |
| Need a stable row identifier | Primary key | Never ctid/ROWID | Physical addresses move |
| Table bloated after an incident | Fix vacuum blockers, then pg_repack | VACUUM FULL only in a maintenance window | Rewrite is the only way to shrink |
| Embedded/edge database | SQLite, default 4 KB pages, WAL mode | VACUUM occasionally | One file, page-based b-trees |
In architecture: from a single process to a distributed system
Storage internals look like a single-server topic, but they decide how much a design costs at every scale: how big a table becomes, how much RAM a working set needs, what a replica has to copy, and why analytics moves to another system.
Monolith: one process, one database
How it shows up: one PostgreSQL or MySQL serves the whole app; every endpoint's cost is "pages touched". The internals on this page decide whether the working set fits in shared_buffers + OS cache.
Simplest correct usage: short increasing primary keys, narrow hot tables, SELECT only needed columns (TOAST), fillfactor on the two or three tables updated per request (sessions, carts, counters), and a weekly glance at the size report.
Example (simple): a Laravel shop where carts.updated_at is written on every click. Setting fillfactor = 80 on carts and not indexing updated_at keeps those writes HOT; the table stays the same size for months.
Example (complex): the same monolith grows an audit_logs table with a jsonb diff per change. It reaches 300 GB, mostly TOAST, and its pages push the hot orders pages out of cache. The fix is architectural: partition audit_logs by month, select only metadata in admin lists, and move old partitions to cheaper storage.
Modular monolith and multiple databases
How it shows up: modules own schemas in one database, so they share one buffer pool, one WAL stream and one autovacuum worker pool. A module with a churn-heavy table (a job queue) can evict the pages another module needs: a storage-level noisy neighbour.
Example: Billing and Notifications in one PostgreSQL. Notifications inserts and deletes 5 million rows a day in outbox_notifications; autovacuum spends its time there and Billing's invoice table builds up dead tuples. Rules: give churn tables their own autovacuum settings and fillfactor, keep them narrow (payload in TOAST or elsewhere), and when one module's I/O dominates, give it its own database. That is the moment module boundaries pay off.
Microservices: each service its own storage
What survives: each service's database has its own pages, cache and bloat profile, so the right settings can differ per service. What does not: a shared cache or a shared physical design; one service cannot rely on another's indexes or table order.
Order service (PostgreSQL) relay Search service (Elasticsearch)
1 INSERT orders (heap, fillfactor 90) + INSERT outbox (same transaction)
2 SELECT ... FROM outbox ORDER BY id LIMIT 500 FOR UPDATE SKIP LOCKED
3 publish, then DELETE FROM outbox WHERE id <= ...
-- outbox: insert + delete churn -> dead tuples; vacuum it aggressively, keep it narrow
4 index document (its own segments, own merges)Countermeasures: treat high-churn service tables (outbox, inbox, job queues, idempotency keys) as storage hot spots: small rows, payload size limits, per-table autovacuum, periodic pg_repack, or time partitions dropped daily. Each service publishes facts, not physical identifiers: never put a ctid or InnoDB internal row id in a message. See Transactional Outbox.
Distributed data: replicas, caches and distributed SQL
Physical replicas copy pages. PostgreSQL streaming replication and InnoDB-based physical replicas replay changes to the same pages, so the replica has the same bloat, the same ctids and the same TOAST tables; a VACUUM FULL on the primary is a full rewrite on every replica too. Logical replication and MySQL binlog replication ship rows, so the replica has its own physical layout and its own bloat. Details: Replication & Failover.
Caches change the I/O math. A Redis or application cache in front of the database removes IO1 and IO2 for hot keys entirely; the database then sees mostly cold, random reads, which is exactly where page layout and correlation matter most.
Distributed SQL changes the storage model. CockroachDB, TiDB and YugabyteDB store rows as key-value pairs in LSM engines keyed by primary key (clustered by PK, no heap, no ctid, no fillfactor); secondary indexes are separate key ranges pointing to the PK, like InnoDB. Their "pages" are SSTable blocks, and compaction replaces vacuum. See Storage Engines and Distributed SQL.
Analytics moves to column stores. At scale the row store keeps OLTP and a CDC pipeline feeds a column store; the row-vs-column picture above is the reason.
Scaling path: 1×, 10×, 100×
| Load | What changes | Storage consequence |
|---|---|---|
| 1× (one server, working set fits in RAM) | Defaults, sensible keys, no SELECT * on wide tables | Almost every read is a cache hit; internals rarely visible |
| 10× (working set larger than RAM, hot update tables) | Buffer pool sizing, fillfactor/HOT, covering indexes, autovacuum per table, read replicas | Random I/O and bloat become the bottleneck; page-level tuning pays off |
| 100× (billions of rows, many services) | Partitioning by time, sharding, column store for analytics, object storage for blobs | Tables are managed as partitions; retention by DROP; Billion-Row Tables |
At every step the question is the same: how many pages does this query or write touch, and are they already in memory?
Lab
PostgreSQL 17 or later in Docker; pageinspect, pg_freespacemap and pg_visibility ship with the server. Exact transaction ids and some byte counts will differ on your machine; the shapes will not.
Setup.
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
docker exec -it pg psql -U postgresCREATE EXTENSION IF NOT EXISTS pageinspect;
CREATE EXTENSION IF NOT EXISTS pg_freespacemap;
CREATE EXTENSION IF NOT EXISTS pg_visibility;Experiment 1: look inside a page.
CREATE TABLE tiny (id int, name text);
INSERT INTO tiny VALUES (1, 'a'), (2, 'b'), (3, 'c');
SELECT lower, upper, special, pagesize FROM page_header(get_raw_page('tiny', 0));
-- lower | upper | special | pagesize
-- 36 | 8096 | 8192 | 8192 24-byte header + 3 x 4-byte line pointers = 36
SELECT lp, lp_off, lp_len, t_xmin, t_xmax, t_ctid, t_infomask
FROM heap_page_items(get_raw_page('tiny', 0));
-- lp | lp_off | lp_len | t_xmin | t_xmax | t_ctid | t_infomask
-- 1 | 8160 | 30 | 750 | 0 | (0,1) | 2050 tuples grow down from the end
-- 2 | 8128 | 30 | 750 | 0 | (0,2) | 2050 30 = 24 header + 4 int + 2 short text
-- 3 | 8096 | 30 | 750 | 0 | (0,3) | 2050 2050 = HEAP_XMAX_INVALID | HEAP_HASVARWIDTH
SELECT count(*) FROM tiny; -- a read sets hint bits
SELECT lp, t_infomask, raw_flags
FROM heap_page_items(get_raw_page('tiny', 0)),
LATERAL heap_tuple_infomask_flags(t_infomask, t_infomask2);
-- 1 | 2306 | {HEAP_HASVARWIDTH,HEAP_XMIN_COMMITTED,HEAP_XMAX_INVALID} the SELECT dirtied the pageExperiment 2: ctid changes on every UPDATE; HOT keeps the index entry. Two terminals show that the row moves while the index does not.
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int) WITH (fillfactor = 80);
CREATE INDEX accounts_owner_idx ON accounts (owner);
INSERT INTO accounts SELECT g, 'u' || g, 100 FROM generate_series(1, 3) g;
SELECT ctid, xmin, * FROM accounts WHERE id = 1; -- (0,1) Terminal A Terminal B
1 UPDATE accounts SET balance = 90 WHERE id = 1;
2 SELECT ctid FROM accounts WHERE id = 1; -- (0,4)
3 SELECT itemoffset, ctid FROM bt_page_items('accounts_pkey', 1);
-- key 1 still -> (0,1): HOT, no new pkey entry
4 UPDATE accounts SET owner = 'ann' WHERE id = 1; -- owner is indexed: not HOT
5 SELECT ctid FROM accounts WHERE id = 1; -- (0,5)
6 SELECT ctid FROM bt_page_items('accounts_pkey', 1);
-- now two entries for key 1: (0,1) and (0,5)
7 SELECT n_tup_upd, n_tup_hot_upd FROM pg_stat_user_tables
WHERE relname = 'accounts'; -- 2 | 1 (stats may lag a moment)SELECT lp, lp_flags, t_ctid, t_infomask2 FROM heap_page_items(get_raw_page('accounts', 0));
-- lp 1: t_ctid (0,4), HEAP_HOT_UPDATED set in t_infomask2
-- lp 4: HEAP_ONLY_TUPLE set, t_ctid (0,5) (it was then updated non-HOT)
-- a pure HOT chain on another row (before any VACUUM, so no line pointer is reused yet)
UPDATE accounts SET balance = 80 WHERE id = 2; -- (0,2) -> (0,6), HOT
UPDATE accounts SET balance = 70 WHERE id = 2; -- (0,6) -> (0,7), HOT
VACUUM accounts;
SELECT lp, lp_flags, lp_off, t_ctid FROM heap_page_items(get_raw_page('accounts', 0));
-- lp 1, lp 4: lp_flags 0 (LP_UNUSED): dead chain removed, its index entries pointing to (0,1) vacuumed
-- lp 2: lp_flags 2 (LP_REDIRECT), lp_off 7: the pkey still says (0,2) and is redirected to lp 7
-- lp 5, lp 7: lp_flags 1 (LP_NORMAL): the live rows id=1 and id=2
-- lp 6: lp_flags 0 (LP_UNUSED); the next INSERT on this page may reuse lp 1, 4 or 6Experiment 3: the TOAST threshold.
CREATE TABLE docs (id int, body text);
ALTER TABLE docs ALTER COLUMN body SET STORAGE EXTERNAL; -- no compression: deterministic sizes
INSERT INTO docs VALUES
(1, repeat('x', 1000)), -- row ~1 KB: below the ~2 KB threshold, stays inline
(2, repeat('x', 3000)); -- row ~3 KB: moved out of line
SELECT id, pg_column_size(body) AS stored, octet_length(body) AS raw FROM docs;
-- 1 | 1004 | 1000
-- 2 | 3000 | 3000 size of the out-of-line value
SELECT reltoastrelid::regclass AS toast FROM pg_class WHERE relname = 'docs';
-- pg_toast.pg_toast_24601 (use your number below)
SELECT chunk_id, chunk_seq, length(chunk_data) FROM pg_toast.pg_toast_24601;
-- chunk_id | chunk_seq | length
-- 24607 | 0 | 1996
-- 24607 | 1 | 1004
ALTER TABLE docs ALTER COLUMN body SET STORAGE EXTENDED;
INSERT INTO docs VALUES (3, repeat('x', 3000));
SELECT id, pg_column_size(body), pg_column_compression(body) FROM docs WHERE id = 3;
-- 3 | ~45 | pglz highly compressible: compressed inline, no TOAST rowsExperiment 4: fillfactor and HOT under repeated updates.
CREATE TABLE ff100 (id int PRIMARY KEY, n int);
CREATE TABLE ff70 (id int PRIMARY KEY, n int) WITH (fillfactor = 70);
INSERT INTO ff100 SELECT g, 0 FROM generate_series(1, 100000) g;
INSERT INTO ff70 SELECT g, 0 FROM generate_series(1, 100000) g;
SELECT pg_relation_size('ff100') AS ff100, pg_relation_size('ff70') AS ff70;
-- ~3.5 MB vs ~5 MB: fillfactor 70 costs space up front
-- three rounds touching 10% of rows each
UPDATE ff100 SET n = n + 1 WHERE id % 10 = 0; UPDATE ff70 SET n = n + 1 WHERE id % 10 = 0;
UPDATE ff100 SET n = n + 1 WHERE id % 10 = 0; UPDATE ff70 SET n = n + 1 WHERE id % 10 = 0;
UPDATE ff100 SET n = n + 1 WHERE id % 10 = 0; UPDATE ff70 SET n = n + 1 WHERE id % 10 = 0;
SELECT relname, n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd,
pg_size_pretty(pg_relation_size(relid)) AS heap,
pg_size_pretty(pg_indexes_size(relid)) AS idx
FROM pg_stat_user_tables WHERE relname IN ('ff100', 'ff70');
-- ff100: low HOT share on the first round (pages full), new pages appended, pkey index grows
-- ff70 : HOT share close to 100%, heap and index sizes unchangedExperiment 5: sizes and forks.
SELECT pg_relation_filepath('ff70');
SELECT pg_size_pretty(pg_relation_size('ff70', 'main')) AS main,
pg_size_pretty(pg_relation_size('ff70', 'fsm')) AS fsm,
pg_size_pretty(pg_relation_size('ff70', 'vm')) AS vm,
pg_size_pretty(pg_table_size('ff70')) AS table_total,
pg_size_pretty(pg_indexes_size('ff70')) AS indexes,
pg_size_pretty(pg_total_relation_size('ff70')) AS everything;
SELECT * FROM pg_freespace('ff70') LIMIT 5; -- free bytes per page (32-byte precision)
VACUUM ff70;
SELECT all_visible, count(*) FROM pg_visibility_map('ff70') GROUP BY 1; -- t | <pages>
EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM ff70 WHERE id < 1000;
-- Index Only Scan ... Heap Fetches: 0Common misconceptions
| Belief | Reality |
|---|---|
| "The database reads only the row I asked for." | It reads whole pages: 8 KB in PostgreSQL, 16 KB in InnoDB, plus index pages. |
"ctid is a stable hidden row id." | It changes on every UPDATE and on VACUUM FULL, CLUSTER, REPACK; use the primary key. |
"A HOT update keeps the same ctid." | The new version gets a new line pointer on the same page; the index entry stays unchanged. |
"DELETE makes the table smaller." | It creates dead tuples; VACUUM makes space reusable; only a rewrite shrinks the file. |
| "Lower fillfactor is always faster." | It wastes space on tables that are not updated and makes scans read more pages. |
| "Index-only scans never read the table." | They read the heap for every page not marked all-visible in the visibility map. |
| "An index scan always beats a sequential scan." | Past a few percent of rows, random IO2 reads cost more than one sequential pass. |
| "PostgreSQL stores rows in primary-key order." | The heap is unordered; CLUSTER orders it once and the order decays. |
| "InnoDB secondary indexes point to the row's location." | They store the primary key and do a second B+tree walk. |
| "Big JSON in a column is free if I don't filter on it." | SELECT * detoasts it; only not selecting it is free. |
| "Give the database all the RAM." | PostgreSQL relies on the OS page cache too; InnoDB with O_DIRECT does not. Size accordingly. |
| "Page size can be tuned per table." | Fixed per PostgreSQL build and per InnoDB instance; only SQLite chooses per file. |
| "Column stores are better databases." | They are better for scans of few columns and worse for single-row reads and writes. |
| "Bloat and fragmentation are the same thing." | Bloat is wasted space; fragmentation is bad order or half-empty pages; fixes overlap but differ. |
Cheat sheet
| Topic | What to remember |
|---|---|
| Page sizes | PostgreSQL 8 KB, InnoDB 16 KB, SQLite 4 KB default, SQL Server 8 KB |
| PostgreSQL page | 24 B header, 4 B line pointers growing forward, tuples growing backward, special space for indexes |
| Tuple overhead | 23 B header (24 aligned) + 4 B line pointer; null bitmap only if NULLs |
ctid | (block, line pointer); changes on update and rewrite; debugging only |
| Files | base/<db oid>/<relfilenode>, 1 GB segments .1 .2, forks _fsm _vm _init |
| FSM | One byte per page, 32-byte precision, updated by VACUUM |
| VM | Two bits per page: all-visible, all-frozen; set by VACUUM, cleared by writes |
| HOT | No indexed column changed + room on page → no new index entries |
| fillfactor | Tables 100, B-tree indexes 90; 70–90 for update-heavy tables |
| TOAST | ~2 KB threshold, chunks ~2000 B, strategies PLAIN/EXTENDED/EXTERNAL/MAIN, 18-byte pointer |
| Index lookup | IO1 index + IO2 heap (PostgreSQL) or clustered index (InnoDB); covering index removes IO2 |
| InnoDB | Table = PK B+tree; secondaries carry the PK; keep PK short and increasing |
| Caches | PostgreSQL shared_buffers 25% + OS cache; InnoDB buffer pool up to 80% with O_DIRECT |
| Size functions | pg_relation_size (one fork), pg_table_size (+TOAST/FSM/VM), pg_indexes_size, pg_total_relation_size |
| Bloat fix | Fix vacuum → pg_repack / REPACK → VACUUM FULL in a window; MySQL OPTIMIZE TABLE |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does reading a single 40-byte row in PostgreSQL cost at least 8 KB of I/O? Must-know
Answer
Answer: The page is the smallest unit the storage manager reads; the row lives in an 8 KB block, and through a secondary index you also read at least one index leaf page.
2 — What do pd_lower and pd_upper tell you? Good to know
Answer
Answer: The start and end of free space on the page. Line pointers are allocated at pd_lower and grow forward; tuples are written below pd_upper and grow backward. Free space = pd_upper − pd_lower.
3 — A row has ctid (0,1). After UPDATE of a non-indexed column with room on the page, what is its ctid, and what does the primary-key index point to? Important
Answer
Answer: A new line pointer on the same page, e.g. (0,2); the index entry still points to (0,1), which links (and later redirects) to the new version. That is a HOT update.
4 — Name the two conditions for a HOT update. Important
Answer
Answer: No column referenced by a (non-summarizing) index changes, and the page holding the old version has enough free space for the new one.
5 — Why might an "Index Only Scan" still read the heap? Must-know
Answer
Answer: Visibility lives only in heap tuples. If the page's all-visible bit in the visibility map is not set, the heap tuple must be checked (shown as Heap Fetches).
6 — When does PostgreSQL TOAST a value, and what are the four strategies? Important
Answer
Answer: When the row is wider than TOAST_TUPLE_THRESHOLD (about 2 KB). PLAIN (neither), EXTENDED (compress then move out, default), EXTERNAL (move out, no compression), MAIN (compress, move out only as last resort).
7 — Why does a long UUID primary key hurt InnoDB more than PostgreSQL? Important
Answer
Answer: InnoDB secondaries store the full PK and the table is ordered by PK, so random UUIDs cause page splits and bloat every secondary index. PostgreSQL secondaries store a 6-byte ctid, and the heap is unordered.
8 — What is double caching, and how do PostgreSQL and InnoDB treat it? Must-know
Answer
Answer: The same page cached in the database buffer pool and the OS page cache. PostgreSQL accepts it and relies on the OS cache (moderate shared_buffers); InnoDB avoids it with O_DIRECT and a large buffer pool.
9 — Which functions give the heap only, the table with TOAST/FSM/VM, all indexes, and everything? Good to know
Answer
Answer: pg_relation_size, pg_table_size, pg_indexes_size, pg_total_relation_size.
10 — A queue table has 2,000 live rows but is 40 GB. Is that bloat or fragmentation, and what are the steps? Important
Answer
Answer: Bloat. Find what blocked vacuum (long transactions, replication slots), let vacuum catch up, then rewrite online with pg_repack/REPACK or VACUUM FULL in a window; consider partitioning or smaller rows.
11 — What does a SQLite "cell pointer array" correspond to in PostgreSQL? Good to know
Answer
Answer: The line pointer (ItemIdData) array: slots after the page header pointing at cells/tuples stored from the end of the page.
Glossary
| Term | Meaning |
|---|---|
| Page / block | Fixed-size unit of storage and I/O (PostgreSQL 8 KB, InnoDB 16 KB) |
BLCKSZ / block_size | PostgreSQL's compile-time page size |
Page header (PageHeaderData) | First 24 bytes of a PostgreSQL page: LSN, checksum, flags, free-space offsets |
pd_lsn | LSN of the last WAL record that changed the page |
pd_checksum | Page checksum when data checksums are enabled |
pd_lower / pd_upper | Offsets to the start and end of free space |
pd_special | Offset to the special space used by index access methods |
pd_prune_xid | Oldest un-pruned xmax on the page; hint for pruning |
Line pointer / item identifier (ItemIdData) | 4-byte slot (offset, length, flags) pointing to a tuple in the page |
LP_REDIRECT / LP_DEAD / LP_UNUSED | Line-pointer states after HOT pruning and vacuum |
| Tuple | One stored row version in PostgreSQL |
HeapTupleHeaderData | 23-byte tuple header |
t_xmin / t_xmax | Inserting and deleting/locking transaction ids |
t_cid | Command id within the transaction |
t_ctid | Pointer to this or the newer version of the row |
t_infomask / t_infomask2 | Flag bits: nulls, var-width, hint bits, HOT flags, attribute count |
t_hoff | Offset to user data inside the tuple |
| Hint bits | t_infomask bits caching commit status; set by the first reader |
| Null bitmap | One bit per column marking NULLs; present only if any NULL |
MAXALIGN / alignment padding | 8-byte alignment that adds padding between columns and after the header |
ctid / TID / ItemPointer | (block, line pointer) physical address of a tuple |
| Update chain | Old versions linked to new ones through t_ctid |
| Heap / heap file | Unordered table storage in PostgreSQL |
| Relfilenode | Number that names a relation's files |
| Fork | Separate file of a relation: main, _fsm, _vm, _init |
| Segment | 1 GB piece of a relation file (.1, .2, …) |
| Tablespace | Directory location for relations (pg_tblspc symlinks) |
| Free space map (FSM) | Per-relation tree storing approximate free space per page |
| Visibility map (VM) | Two bits per heap page: all-visible, all-frozen |
| All-visible / all-frozen | VM states that let index-only scans and vacuum skip pages |
fillfactor | Percentage of a page INSERT may fill |
| HOT (heap-only tuple) | Update kept on the same page without new index entries |
| Page pruning | Removing dead HOT versions during normal page access |
n_tup_hot_upd / n_tup_newpage_upd | pg_stat_user_tables counters for HOT updates and updates that moved to a new page |
| TOAST | The Oversized-Attribute Storage Technique: compression and out-of-line chunks |
TOAST_TUPLE_THRESHOLD / toast_tuple_target | Row width (~2 KB) that triggers TOAST; target width after it |
TOAST chunk (chunk_id, chunk_seq, chunk_data) | Rows of the TOAST table holding pieces of a value |
| PLAIN / EXTENDED / EXTERNAL / MAIN | TOAST strategies per column |
| varlena | PostgreSQL's variable-length value format with a length header |
| pglz / lz4 | TOAST compression methods |
| Row-oriented (NSM) | Storage with whole rows together in pages |
| Column-oriented (DSM) | Storage with each column's values together |
| PAX | Hybrid: row groups stored column-wise (Parquet, ORC) |
| I/O unit | The smallest amount the database reads or writes: one page |
| Sequential I/O / random I/O | Reading adjacent blocks vs jumping between blocks |
| Read-ahead | OS or engine prefetch of the next blocks during sequential reads |
| Read amplification | Bytes read divided by bytes needed |
| Write amplification | Bytes written to storage divided by bytes logically changed |
Buffer pool / shared_buffers | Database-managed cache of pages in frames |
| Frame / pin / dirty page | Buffer slot; a pinned page cannot be evicted; a dirty page differs from disk |
| Clock sweep / LRU | Buffer replacement policies (PostgreSQL / InnoDB) |
| OS page cache | Kernel cache of file pages |
| Double caching (double buffering) | Same page cached by both the database and the OS |
O_DIRECT | File flag that bypasses the OS page cache (InnoDB innodb_flush_method) |
effective_cache_size | PostgreSQL planner hint for total cache |
| IO1 / IO2 | Index read, then heap (or clustered-index) read |
| Bitmap heap scan | Collect ctids, sort by block, read heap pages once in order |
| Index-only scan | Answer from the index, skipping the heap for all-visible pages |
| Heap Fetches | EXPLAIN counter of heap visits during an index-only scan |
Covering index / INCLUDE | Index carrying extra payload columns for index-only scans |
| Correlation | pg_stats measure of how well physical order follows a column |
| Clustered index | Table stored in the primary-key B+tree (InnoDB, SQL Server clustered, SQLite) |
GEN_CLUST_INDEX / DB_ROW_ID | InnoDB's hidden clustered index and 6-byte row id when no PK exists |
DB_TRX_ID / DB_ROLL_PTR | InnoDB hidden columns: last modifying transaction, pointer to undo |
| Secondary index | Any non-clustered index; in InnoDB it carries the PK |
| Bookmark / key lookup | Second step from a secondary index to the row |
| Page split / page merge | B+tree page division on insert; joining under-filled pages (MERGE_THRESHOLD) |
innodb_page_size / innodb_fill_factor | InnoDB page size; sorted-build fill percentage |
ROW_FORMAT=DYNAMIC | InnoDB default row format: long values fully off-page with a 20-byte pointer |
| Overflow page | Page holding the rest of a value that did not fit (InnoDB, SQLite) |
| Extent | Group of contiguous pages (InnoDB 1 MB, SQL Server 64 KB) |
.ibd / innodb_file_per_table | InnoDB per-table tablespace file and the setting that creates it |
| SQLite cell / cell pointer array | Row or key record in a b-tree page / its slot array |
rowid / WITHOUT ROWID | SQLite's 64-bit table key / tables clustered by PK |
| Freelist | SQLite list of unused pages |
| RID / ROWID / RecordId | Physical row address in SQL Server heaps / Oracle / MongoDB WiredTiger |
| Forwarded record | SQL Server heap row moved to another page with a pointer left behind |
| Bloat | Space in a relation not holding live data |
| Fragmentation | Data out of logical order or in half-empty pages |
VACUUM FULL / CLUSTER / REPACK / pg_repack | PostgreSQL rewrites that compact (and optionally reorder) a table |
OPTIMIZE TABLE | MySQL rebuild of an InnoDB table |
| Torn page | Partially written page after a crash |
full_page_writes / doublewrite buffer | PostgreSQL and InnoDB protections against torn pages |
| Data checksums | Per-page checksum to detect corruption |
pageinspect | Extension to read raw pages: get_raw_page, page_header, heap_page_items, heap_tuple_infomask_flags, bt_page_items |
pg_freespacemap / pg_freespace | Extension and function to read the FSM |
pg_visibility | Extension to read the VM |
pg_buffercache | Extension showing pages currently in shared_buffers |
pg_relation_size / pg_table_size / pg_indexes_size / pg_total_relation_size | Size of one fork / table with TOAST, FSM, VM / indexes / everything |
pg_column_size / pg_relation_filepath | Stored size of a value / path of a relation's first segment |
References
- PostgreSQL documentation, Chapter 66 Database Physical Storage: 66.1 Database File Layout, 66.2 TOAST, 66.3 Free Space Map, 66.4 Visibility Map, 66.6 Database Page Layout, 66.7 Heap-Only Tuples
- PostgreSQL documentation: CREATE TABLE (storage parameters: fillfactor, toast_tuple_target), ALTER TABLE, System Columns, Index-Only Scans and Covering Indexes, Database Object Management Functions, Resource Consumption (shared_buffers)
- PostgreSQL modules: pageinspect, pg_freespacemap, pg_buffercache
- MySQL 8.4 Reference Manual: InnoDB On-Disk Structures, Clustered and Secondary Indexes, The Physical Structure of an InnoDB Index, InnoDB Row Formats, Buffer Pool, File Space Management, InnoDB Multi-Versioning, InnoDB Startup Options and System Variables
- SQLite: Database File Format
- Hellerstein, Stonebraker & Hamilton, "Architecture of a Database System", Foundations and Trends in Databases 1(2), 2007. PDF
- Laravel 13: Database: Getting Started, Migrations, Artisan Console, Helpers (Number::fileSize)
- Go:
database/sql, pgx v5 stdlib