โ† Back to Home

๐Ÿ—„๏ธ How a Database Works Inside

Pages, tuples and MVCC in raw hex, B-tree lookups, the buffer pool, the write-ahead log and VACUUM in a real PostgreSQL 16, plus a 60-line LSM-tree you can run.

To most developers, a database is a box: SQL goes in, rows come out. That box is one of the most carefully engineered pieces of software you'll ever use. It has to make data survive power cuts, serve thousands of clients at once without corrupting anything, and find one row among a billion in under a millisecond.

This article opens the box. We'll use a real PostgreSQL 16 instance and look at the actual bytes on disk, the actual pages the query engine reads, and the actual cost of a commit. Then we'll build a tiny LSM-tree storage engine in Python, the design behind RocksDB, Cassandra and many others, and compare the two approaches.

Everything here is measured. The query plans, hex dumps and timings come from PostgreSQL 16.2 running on a laptop (WSL2, ext4 on an SSD). Your numbers will differ, but the ratios won't.

The Big Picture

Almost every relational database has the same five parts:

   SQL text
      โ”‚
      โ–ผ
 โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   parse โ†’ rewrite โ†’ plan: "use the email index, then fetch 1 heap page"
 โ”‚ Query engine โ”‚
 โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
        โ”‚ "give me page 4512 of table users"
        โ–ผ
 โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   RAM cache of 8 KB pages (shared_buffers = 128 MB here)
 โ”‚ Buffer pool  โ”‚   hit โ†’ microseconds          miss โ†’ read from the OS / disk
 โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
        โ”‚
 โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
 โ”‚ Data files   โ”‚   โ”‚ Write-ahead log (WAL) โ”‚   every change is logged here FIRST,
 โ”‚ heap + index โ”‚   โ”‚ append-only           โ”‚   and fsynced at COMMIT
 โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
        โ–ฒ
        โ”‚ background: checkpointer, background writer, autovacuum

The rest of this article goes through these parts one by one: pages, tuples, indexes, the buffer pool, the planner, the WAL, and the cleanup processes.

Everything Is a Page

A database never reads "a row" from disk. It reads a page (PostgreSQL calls it a block): a fixed-size chunk, 8 KB in PostgreSQL, 16 KB in MySQL's InnoDB, 4 KB in SQLite by default. Disks and operating systems work in blocks, so databases do too.

Let's create a tiny table and find its file:

create table accounts (id int primary key, owner text not null, balance int not null);
insert into accounts values (1,'alice',100),(2,'bob',50),(3,'carol',75);

select pg_relation_filepath('accounts') as heap_file,
       pg_relation_filepath('accounts_pkey') as index_file;
  heap_file   |  index_file
--------------+--------------
 base/5/16384 | base/5/16389

A table is just a file in the data directory (base/<database oid>/<table file node>). The primary key index is a separate file. Three rows take exactly one page:

$ ls -l pgdata/base/5/16384
-rw------- 1 postgres postgres 8192 Nov 30 20:24 pgdata/base/5/16384

Inside the page

Every row version has a physical address, its ctid: (page number, slot in the page). PostgreSQL also shows two hidden system columns, xmin (the transaction that created this row version) and xmax (the transaction that deleted or replaced it, 0 if none):

 ctid  | xmin | xmax | id | owner | balance
-------+------+------+----+-------+---------
 (0,1) |  731 |    0 |  1 | alice |     100
 (0,2) |  731 |    0 |  2 | bob   |      50
 (0,3) |  731 |    0 |  3 | carol |      75

All three rows were created by transaction 731 and live in page 0, slots 1โ€“3. Now let's update Alice's balance:

update accounts set balance = balance - 30 where id = 1;
select ctid, xmin, xmax, * from accounts;
 ctid  | xmin | xmax | id | owner | balance
-------+------+------+----+-------+---------
 (0,2) |  731 |    0 |  2 | bob   |      50
 (0,3) |  731 |    0 |  3 | carol |      75
 (0,4) |  732 |    0 |  1 | alice |      70

Alice moved from slot 1 to slot 4, and her xmin is now 732. PostgreSQL didn't change the row in place. It wrote a new version of it. The old one is still there. Here's the end of the raw page file after a checkpoint, with xxd:

$ xxd pgdata/base/5/16384 | tail -12
00001f60: dc02 0000 0000 0000 0000 0000 0000 0000  ................
00001f70: 0400 0380 0229 1800 0100 0000 0d61 6c69  .....).......ali
00001f80: 6365 0000 4600 0000 db02 0000 0000 0000  ce..F...........
00001f90: 0000 0000 0000 0000 0300 0300 0209 1800  ................
00001fa0: 0300 0000 0d63 6172 6f6c 0000 4b00 0000  .....carol..K...
00001fb0: db02 0000 0000 0000 0000 0000 0000 0000  ................
00001fc0: 0200 0300 0209 1800 0200 0000 0962 6f62  .............bob
00001fd0: 3200 0000 0000 0000 db02 0000 dc02 0000  2...............
00001fe0: 0000 0000 0000 0000 0400 0340 0205 1800  ...........@....
00001ff0: 0100 0000 0d61 6c69 6365 0000 6400 0000  .....alice..d...

Read it from the bottom up, because rows are filled from the end of the page backwards:

Offset Bytes Meaning
0x1ff0 โ€ฆaliceโ€ฆ then 6400 0000 The old Alice: balance 0x64 = 100
0x1fd8 db02 0000 dc02 0000 Its header: xmin 0x2db = 731, xmax 0x2dc = 732: "deleted by transaction 732"
0x1fc0 โ€ฆbob then 3200 0000 Bob, balance 0x32 = 50
0x1fa0 โ€ฆcarolโ€ฆ then 4b00 0000 Carol, balance 0x4b = 75
0x1f60โ€“0x1f80 dc02 0000 โ€ฆ alice โ€ฆ 4600 0000 The new Alice: xmin 732, balance 0x46 = 70

All integers are little-endian, so 6400 0000 is 0x00000064 = 100. The page layout looks like this:

   8 KB page
  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  โ”‚ page header (24 B): LSN of last change, free-space bounds โ”‚
  โ”‚ line pointers: [1]โ†’0x1fd8 [2]โ†’0x1fb0 [3]โ†’0x1f88 [4]โ†’0x1f60โ”‚  grows โ†’
  โ”‚                                                          โ”‚
  โ”‚                    free space                            โ”‚
  โ”‚                                                          โ”‚
  โ”‚  โ† grows   [new alice 70] [carol 75] [bob 50] [old alice 100]โ”‚
  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Why keep the old version? That's MVCC (multi-version concurrency control). A transaction that started before 732 committed must still see Alice's balance as 100, so the old version has to stay readable until no transaction needs it. Readers never block writers, and writers never block readers. The cost is that dead versions pile up and need cleaning: that's VACUUM, later in this article. Transactions and Isolation Levels explores what each transaction gets to see.

Indexes: B-Trees

Let's scale up to a million users and look for one email:

create table users (id int primary key, email text not null, country text not null, created_at timestamptz not null);
insert into users
  select g, 'user'||g||'@example.com', (array['NP','DE','US','IN','GB'])[1+g%5], now() - (g||' minutes')::interval
  from generate_series(1,1000000) g;
 heap  | pages | pkey
-------+-------+-------
 65 MB |  8334 | 21 MB

Without an index

explain (analyze, buffers) select * from users where email = 'user777777@example.com';

 Gather (actual rows=1 loops=1)
   Workers Planned: 2
   Buffers: shared hit=8334
   ->  Parallel Seq Scan on users (actual rows=0 loops=3)
         Filter: (email = 'user777777@example.com'::text)
         Rows Removed by Filter: 333333
 Execution Time: 25.380 ms

shared hit=8334: the query touched every one of the table's 8,334 pages, and three processes checked all million rows to find one. That's a sequential scan, and its cost grows linearly with the table.

With an index

create index users_email_idx on users(email);
 Index Scan using users_email_idx on users (actual rows=1 loops=1)
   Index Cond: (email = 'user777777@example.com'::text)
   Buffers: shared hit=4
 Execution Time: 0.013 ms

4 pages instead of 8,334. 0.013 ms instead of 25 ms, about 2,000 times faster. The 4 pages are: the B-tree root, one internal page, one leaf page, and the heap page that holds the row.

                         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  page 1: root           โ”‚ โ€ฆ user3 โ”‚ user5 โ”‚ user7 โ”‚ โ€ฆ   โ”‚
                         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                              โ”‚ "user777777" is between user7 and user8
                         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  page 2: internal       โ”‚ โ€ฆ user7770 โ”‚ user7775 โ”‚ user7780 โ€ฆ โ”‚
                         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  page 3: leaf           โ”‚ user777776 โ†’ (4512,3)          โ”‚
                         โ”‚ user777777 โ†’ (4520,17)   โ—€โ”€โ”€โ”€โ”€โ”€โ”‚โ”€โ”€ key โ†’ ctid
                         โ”‚ user777778 โ†’ (4520,18)          โ”‚
                         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                              โ”‚ follow the ctid
                         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  page 4: heap page 4520 โ”‚ โ€ฆ row 17: id=777777, email=โ€ฆ โ”‚
                         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  (illustrative keys and ctids; keys sort as text, so "user777777" falls between "user7" and "user8")

A B-tree is a balanced tree with a huge fan-out: each 8 KB page holds hundreds of keys, so each level multiplies the reach by hundreds. Three levels reach millions of rows; four levels reach billions. The depth barely grows with the data, which is why index lookups stay fast as tables grow. The Data Structures article covers why a B-tree beats a binary tree on disk.

Indexes aren't free

 email_idx
-----------
 39 MB

The email index is 39 MB, more than half the size of the 65 MB table. Every insert must now update the heap and both indexes. More indexes means faster reads and slower writes, and that trade-off is the core of database tuning.

The Planner: Choosing How to Run a Query

SQL says what you want, not how to get it. The planner estimates the cost of alternatives using table statistics (ANALYZE collects them) and picks the cheapest:

explain select * from users where id between 10 and 20;
 Index Scan using users_pkey on users
   Index Cond: ((id >= 10) AND (id <= 20))

explain select * from users where country = 'NP';
 Seq Scan on users
   Filter: (country = 'NP'::text)

Eleven rows out of a million: use the index. A fifth of the table matches country = 'NP': just read the whole table in order. An index lookup costs a random page read per row, so beyond a few percent of the table a sequential scan wins. Even with an index on country, the planner would ignore it here. That's not a bug.

Pro tip: always read plans with EXPLAIN (ANALYZE, BUFFERS). ANALYZE actually runs the query and shows real row counts next to estimates; a big mismatch means stale statistics. BUFFERS shows how many pages were touched, which is a far more stable measure than milliseconds.

The Buffer Pool: RAM in Front of the Disk

Look again at the first index lookup and the second:

first run:   Buffers: shared hit=1 read=3     Execution Time: 0.073 ms
second run:  Buffers: shared hit=4            Execution Time: 0.013 ms

hit means the page was already in PostgreSQL's buffer pool (shared_buffers, 128 MB here), and read means it had to ask the operating system. The second run found everything in memory and was 5ร— faster.

The buffer pool is a big array of 8 KB slots. A lookup table maps (file, page number) to a slot. When the pool is full, a clock-sweep algorithm evicts pages that haven't been used recently. Pages that have been changed are dirty and must be written back before their slot can be reused.

   query wants (users, page 4520)
        โ”‚
        โ–ผ
   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ shared_buffers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ”‚  hash table: (users,4520) โ†’ slot 913?        โ”‚โ”€โ”€โ”€โ”€ hit: return pointer (โ‰ˆ 100 ns)
   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
        โ”‚ miss
        โ–ผ
   evict a victim slot (write it first if dirty) โ†’ pread() 8 KB from the file
        โ”‚
        โ–ผ
   OS page cache hit (โ‰ˆ ยตs)   or   SSD read (โ‰ˆ 100 ยตs)   or   network disk (โ‰ˆ 1 ms)

There are two caches: PostgreSQL's own buffer pool, and the operating system's page cache underneath it. That's why PostgreSQL tuning guides suggest shared_buffers of about 25% of RAM, not 90%: the OS cache uses the rest. Other databases (InnoDB, Oracle) bypass the OS cache with O_DIRECT and manage almost all memory themselves.

The most important performance number for a database is the cache hit ratio. A working set that fits in RAM gives microsecond reads. One that doesn't makes every query wait on storage.

The Write-Ahead Log: How Commits Survive a Crash

Changing a page in the buffer pool is fast, but RAM disappears in a power cut. Writing the whole 8 KB page to its place on disk at every commit would be slow, and a crash halfway through writing a page would leave it torn.

Every serious database solves this the same way: write-ahead logging. Before a change is considered committed, a compact description of it is appended to a sequential log file and fsynced. The data pages themselves are written later, lazily, in the background.

  UPDATE accounts SET balance = 70 WHERE id = 1;  COMMIT;

  โ‘  change page 0 in the buffer pool (now dirty)        RAM
  โ‘ก append WAL record "page 0: new tuple (0,4) โ€ฆ"      WAL buffer (RAM)
  โ‘ข COMMIT โ†’ write the WAL to disk and fsync()         โ† the ONLY disk wait
  โ‘ฃ reply "COMMIT" to the client
  โ‹ฎ
  โ‘ค minutes later: checkpointer writes dirty page 0 to base/5/16384

  crash between โ‘ฃ and โ‘ค?  On restart, replay the WAL from the last
                          checkpoint: page 0 is rebuilt. Nothing lost.

Every WAL record has a position, the LSN (log sequence number). You can watch it move:

 lsn_before                        lsn_after
------------                      -----------
 0/14A85A8     โ”€โ”€ UPDATE 1 โ”€โ”€โ–ถ     0/14A86E0

0x14A86E0 โˆ’ 0x14A85A8 = 0x138 = 312 bytes of WAL for our one-row update. And the page header in the hex dump earlier starts with b886 4a01, LSN 0/14A86B8: each page remembers the last WAL record that touched it, so recovery knows which records still need replaying.

Why sequential logging wins

Appending to a log is a sequential write to one file. Updating pages in place means random writes all over many files. On spinning disks the difference was 100ร—. On SSDs it's smaller but still large, and a log also lets many commits share one fsync ("group commit").

The real cost of COMMIT

Because COMMIT waits for an fsync, how you group work into transactions matters enormously. 2,000 single-row inserts, three ways:

# 1. autocommit style: COMMIT after every insert
for i in range(N): cur.execute("insert into events (payload) values (%s)", ("x",)); c.commit()
# 2. one transaction
for i in range(N): cur.execute("insert into events (payload) values (%s)", ("x",))
c.commit()
# 3. COMMIT each, but don't wait for the fsync
cur.execute("set synchronous_commit = off")
2000 inserts, one COMMIT each                       5574.6 ms       359 rows/s
2000 inserts in ONE transaction                      169.3 ms    11,816 rows/s
2000 inserts, COMMIT each, synchronous_commit=off    416.0 ms     4,808 rows/s

33ร— faster just by grouping into one transaction. Each COMMIT costs one WAL fsync, about 2.8 ms on this disk. synchronous_commit = off keeps the per-commit structure but returns before the fsync, so a crash can lose the last fraction of a second of commits (the database stays consistent, it just forgets the most recent transactions). That's a reasonable trade for analytics events, and a terrible one for payments.

Full-page writes: the hidden WAL multiplier

Our one-row update wrote 312 bytes of WAL. But updating 100,000 rows wrote far more than 100,000 ร— 312 bytes:

update users set country = 'NP' where id <= 100000;
 wal_written_by_update
-----------------------
 75 MB

Two reasons. First, the first change to any page after a checkpoint logs the entire 8 KB page (full_page_writes = on), to protect against torn pages if the OS crashes mid-write. Second, each new row version needed new entries in both indexes. WAL volume drives replication traffic, backup size and disk wear, so this matters in production.

Checkpoints and VACUUM: The Cleanup Crew

Checkpoints

The WAL can't grow forever. Periodically (checkpoint_timeout = 5min, or after max_wal_size = 1GB of WAL), the checkpointer writes all dirty pages to the data files. Once that's done, WAL from before the checkpoint isn't needed for crash recovery and can be recycled. Longer intervals mean less write work and fewer full-page images, but a longer replay after a crash.

VACUUM

MVCC leaves dead row versions behind. After updating another 100,000 rows:

 n_live_tup | n_dead_tup | n_tup_upd | n_tup_hot_upd
------------+------------+-----------+---------------
    1000000 |     200000 |    200000 |             0

VACUUM finds versions that no running transaction can still see, and marks their space as reusable:

vacuum (verbose) users;
pages: 0 removed, 9167 remain, 1669 scanned (18.21% of total)
tuples: 100000 removed, 918174 remain, 0 are dead but not yet removable
index scan needed: 834 pages from table (9.10% of total) had 100000 dead item identifiers removed

Notice three things:

Autovacuum does this automatically in the background. When it can't keep up (because of long-running transactions that pin old versions, or tables that are updated very heavily), tables "bloat", queries slow down, and in the worst case PostgreSQL has to stop to protect itself from transaction ID wraparound. Monitoring n_dead_tup and the age of the oldest transaction is part of running PostgreSQL.

A Different Design: LSM-Trees

B-trees update pages in place (or, in PostgreSQL, near in place). A Log-Structured Merge-tree never updates anything on disk. It only appends new files and merges them later. It's the engine inside RocksDB, LevelDB, Cassandra, ScyllaDB, HBase, InfluxDB and CockroachDB's storage layer.

   write โ”€โ”€โ–ถ WAL (append + fsync) โ”€โ”€โ–ถ memtable (sorted, in RAM)
                                           โ”‚ full?
                                           โ–ผ flush
                                     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                           level 0   โ”‚ SSTable 3   โ”‚  newest   immutable, sorted files
                                     โ”‚ SSTable 2   โ”‚
                                     โ”‚ SSTable 1   โ”‚  oldest
                                     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                            โ”‚ background compaction merges them,
                                            โ–ผ drops overwritten values and tombstones
                           level 1   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                     โ”‚  one bigger sorted SSTable  โ”‚
                                     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
   read โ”€โ”€โ–ถ memtable โ†’ newest SSTable โ†’ โ€ฆ โ†’ oldest  (Bloom filters skip files that can't have the key)

A tiny LSM-tree you can run

This toy engine (about 60 lines) has every essential part: a WAL, a memtable, immutable sorted files, tombstones for deletes, and compaction.

import bisect, json, os

TOMBSTONE = None

class TinyLSM:
    """A toy LSM-tree: in-memory memtable, append-only log, immutable sorted files."""

    def __init__(self, path, memtable_limit=4):
        self.path, self.limit = path, memtable_limit
        os.makedirs(path, exist_ok=True)
        self.memtable = {}
        self.sstables = sorted(f for f in os.listdir(path) if f.endswith(".sst"))
        self.wal = open(os.path.join(path, "wal.log"), "a")

    def put(self, key, value):
        self.wal.write(json.dumps([key, value]) + "\n")    # 1. durable log first
        self.wal.flush(); os.fsync(self.wal.fileno())
        self.memtable[key] = value                          # 2. then memory
        if len(self.memtable) >= self.limit:
            self.flush()

    def delete(self, key):
        self.put(key, TOMBSTONE)                            # deletes are writes too

    def flush(self):
        name = f"{len(self.sstables):06d}.sst"
        with open(os.path.join(self.path, name), "w") as f:
            json.dump(sorted(self.memtable.items()), f)     # sorted, immutable file
        self.sstables.append(name)
        self.memtable.clear()
        self.wal.truncate(0)

    def get(self, key):
        if key in self.memtable:                            # newest data first
            return self.memtable[key]
        for name in reversed(self.sstables):                # then newest file โ†’ oldest
            rows = json.load(open(os.path.join(self.path, name)))
            keys = [k for k, _ in rows]
            i = bisect.bisect_left(keys, key)               # binary search: files are sorted
            if i < len(keys) and keys[i] == key:
                return rows[i][1]
        return None

    def compact(self):
        if self.memtable:
            self.flush()                                    # include the newest writes
        merged = {}
        for name in self.sstables:                          # oldest โ†’ newest, newer wins
            merged.update(dict(json.load(open(os.path.join(self.path, name)))))
            os.remove(os.path.join(self.path, name))
        self.sstables = []
        self.memtable = {k: v for k, v in merged.items() if v is not TOMBSTONE}
        self.flush()                                        # one file, no tombstones

db = TinyLSM("data")
for i, fruit in enumerate(["apple", "banana", "cherry", "date", "elder", "fig", "grape", "honeydew"]):
    db.put(fruit, i)
db.put("apple", 100)          # an update is just a newer write
db.delete("banana")
print("files:", db.sstables, "memtable:", db.memtable)
print("apple =", db.get("apple"), "| banana =", db.get("banana"), "| fig =", db.get("fig"))
for name in db.sstables:
    print(name, open(os.path.join("data", name)).read())
db.compact()
print("after compaction:", db.sstables, open("data/000000.sst").read())

Output:

files: ['000000.sst', '000001.sst'] memtable: {'apple': 100, 'banana': None}
apple = 100 | banana = None | fig = 5
000000.sst [["apple", 0], ["banana", 1], ["cherry", 2], ["date", 3]]
000001.sst [["elder", 4], ["fig", 5], ["grape", 6], ["honeydew", 7]]
after compaction: ['000000.sst'] [["apple", 100], ["cherry", 2], ["date", 3], ["elder", 4], ["fig", 5], ["grape", 6], ["honeydew", 7]]

Look at what happened:

Real engines add Bloom filters (to skip files without reading them), sparse indexes inside each file, levels with size ratios, and compaction running in background threads.

B-Tree vs LSM-Tree

B-tree (PostgreSQL, MySQL InnoDB, SQLite) LSM-tree (RocksDB, Cassandra, ScyllaDB)
Write pattern Random page updates (plus a sequential WAL) Purely sequential appends
Write throughput Good Excellent, especially on slow or networked disks
Point reads One tree descent: predictable May check several files (Bloom filters help)
Range scans Excellent: leaves are sorted and linked Good, but must merge across files
Space Free space inside pages, bloat without vacuum Old versions until compaction; compresses well
Background work VACUUM / page cleaning Compaction, which can cause latency spikes
Sweet spot Read-heavy and mixed OLTP, complex queries Write-heavy: logs, metrics, time series, feeds

There's a well-known way to frame the trade-off. You can optimise for at most two of read cost, write cost and space (the "RUM conjecture"). B-trees favour reads. LSM-trees favour writes and space. Every storage engine is a point on that triangle.

Life of an UPDATE, End to End

UPDATE accounts SET balance = 70 WHERE id = 1

  1. Parse and plan. The planner sees id = 1 on the primary key and picks an Index Scan on accounts_pkey.
  2. Descend the B-tree. Root page โ†’ leaf page, each fetched through the buffer pool. The leaf says id 1 lives at ctid (0,1).
  3. Fetch heap page 0. Check visibility: xmin 731 committed, xmax 0, so this version is live for us.
  4. Lock the row. Set xmax = 732 on the old version (a concurrent writer would now wait for us).
  5. Write the new version. Insert (1, alice, 70) with xmin 732 at (0,4), and add an index entry pointing to it.
  6. Log it. Append WAL records describing both page changes (312 bytes). Pages are now dirty in RAM only.
  7. COMMIT. Write a commit record, fsync the WAL, and mark transaction 732 committed in the commit log. Only now does the client get "COMMIT".
  8. Later: checkpoint. The checkpointer writes dirty page 0 to base/5/16384. WAL before this point can be recycled.
  9. Later still: VACUUM. Once no transaction can see balance 100, the old version at (0,1) is removed and its space reused.

Practice: Look Inside Your Own Database

-- where does a table live, and how big is it?
select pg_relation_filepath('users'), pg_size_pretty(pg_total_relation_size('users'));

-- physical location and MVCC headers of rows
select ctid, xmin, xmax, * from users limit 5;

-- pages touched by a query (the most honest performance metric)
explain (analyze, buffers) select * from users where email = 'someone@example.com';

-- WAL generated by a statement
select pg_current_wal_lsn() \gset
update users set country = 'GB' where id < 1000;
select pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), :'pg_current_wal_lsn'));

-- dead tuples and the last autovacuum
select relname, n_live_tup, n_dead_tup, last_autovacuum from pg_stat_user_tables order by n_dead_tup desc;

-- buffer cache hit ratio for the whole database
select round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) as hit_pct
from pg_stat_database where datname = current_database();

The one-sentence summary: a database is a page cache in front of data files, with a sequential log that makes commits durable, an index structure that turns lookups into a few page reads, and a background process that cleans up after itself. Everything else is optimisation.

Copied to clipboard!