I’ve been watching the CMU database group classes for quite a while, but I’ve never actually engaged on it, do the exercises, read the papers, etc., so I decided to start a series to learn more about database systems. This time will be different, I commit to myself, (and you guys), to go over the classes and chapters actually creating something. I’m just a salaryman, so I might not be able to do it as often as I’d like, but this will probably be a 1-year series.
The resources we’re going to use:
Andy Pavlo is the GOAT of databases, and he is a teacher at the CMU Database Group. They keep it all free on the web, lectures, slides, notes, projects. When I found that out, my mind was blown. Such good content for zero dollars is still crazy to me.
The most important material is the Database System Concepts book, so be sure to read it if you want to explore the topics more deeply. Also, please check the comment section if you have any suggestions, or if I made a mistake.
by Isaac Asimov
In this post we’ll answer three questions: how a database stores a row inside a page, how that page gets to disk and back, and how the buffer pool keeps the hot pages in memory. Then we’ll build it all in Zig.
This post is related to the #04: Memory Management class.
Chapter 13.2-13.5 (Whenever you see a chapter without a book reference, assume it’s from the Database System Concepts book)
The repo is here: db-internals.
It’s a fixed-size block of bytes; usually 4 KB, though 8 KB or 16 KB are typical, and the database always reads and writes entire pages, never individual rows, since a disk seek is vastly slower than accessing memory. There’s also a technical limitation, a disk is always read in chunks, never individual bytes.
L1 cache is 1ns, main memory access is 100ns, SSD random read: 16,000ns, a single hard spinning disk seek: 2,000,000ns. This webpage is a good way of visualizing that.
The naive layout is a byte blob: rows concatenated, one after another.
If that worked, life would be simple, but it doesn’t. Rows vary in length, so we can’t determine where row x begins, we’d have to scan the file each time we need a row. We need at least a header, a method to more easily locate the slots on the page, and a way to track how much space remains on the page at any moment.
The fix is an indirection layer: a small directory of slots at the front of the page, and the row data at the back growing from the opposite direction.
The header is 8 bytes:
Each slot is 4 bytes:
They grow toward each other, and the free space is whatever is left in the middle: upper - lower.
Because a slot is a stable identifier. A row’s identity is (page_id, slot_id), not its byte offset.
When you delete row 0, you mark its slot as deleted (length = 0) and leave the bytes where they are. O(1), and every other row keeps its identity.
When you eventually reclaim the space, you compact the page: copy the live rows toward the end, update the slots that point to them. The rows move. The slot numbers don’t. The slot directory itself never shrinks; a deleted slot remains as a tombstone so that all higher slot numbers stay at their original indexes, we don’t want to keep allocating and then freeing heap, it’s an expensive operation.
The page size I’m going to use is 8192 bytes. There are several papers about page layout, and page size versus disk I/O trade-offs, if you are interested, I recommend this paper by Graefe.
Let’s write ”hello” and then ”world” into an empty page and look at the actual bytes. PAGE_SIZE is 8192; u16 fields are little-endian.
After ”hello”:
After ”world”
Offset Bytes Meaning
0x0000 02 00 slot_count = 2
0x0002 10 00 lower = 16
0x0004 F6 1F upper = 8182
0x0008 FB 1F 05 00 slot 0: offset 8187, length 5
0x000C F6 1F 05 00 slot 1: offset 8182, length 5
0x1FF6 77 6F 72 6C 64 “world”
0x1FFB 68 65 6C 6C 6F “hello”Read FB 1F as little-endian: 0x1FFB = 8187. Slot 0 says “row 0 is 5 bytes starting at 8187”. Slot 1 says “row 1 is 5 bytes starting at 8182”.
Note that ”world” sits at a lower address than ”hello”, even though it’s the newer row. Rows are allocated from the end of the page downward, remember the slotted page layout, so the second insert lands just below the first. Slot order and physical order don’t have to match.
One more detail. When we insert a row we need room for the row and for its slot:
The 4 bytes are the directory entry. The header isn’t part of needed because it sits below lower, it’s already accounted for.
Postgres doesn’t have to do this at all, as it uses MVCC and never updates rows in place, it’s a bit more complicated, so we won’t go into all the details here. Probably another article will cover this. Postgres is the database system I know the most, so you’ll see me refer to it occasionally.
The easy case is a shrink or same-size replacement, we just overwrite the bytes in place and update the slot’s length field and be done with it.
The tricky case is when the new record doesn't fit in the slot. If we move it, the slot index has to stay the same. The solution is a forwarding pointer: leave a sentinel in the original slot (length = 0xFFFF) and store the new slot index in the offset field. read checks for the sentinel and follows one level of indirection. update follows it too before updating, so you never get a chain of forwards.
The original (page_id, slot_id) stays valid from the caller’s perspective. We only allow forwarding once tough, otherwise it'd be a mess to maintain.
The whole page format is one struct with a pointer to the bytes:
Note that SlottedPage is just an interpretation of the raw bytes. SlottedPage is a view over a buffer someone else owns. That’s the separation we want: the page format knows nothing about memory management, and the buffer manager knows nothing about slots.
The pool is a fixed array of frames. A frame is one page-sized buffer plus the bookkeeping needed to manage it, I also added a read/write latch for concurrency control. We’ll go through the replacement policy next, while watching the CMU class, I implemented the Clock replacement policy, which is awesome, great cache locality, extremely simple and fast.
A page table maps page ids to frame pointers, so “is this page already in memory?” is a hash lookup O(1):
Hash maps aren't quite O(1), if you haven't looked at the language implementations for their hash maps, you should.
The key field is pin_count. When a caller is using a page, it must not be evicted from under them. So:
fetch either finds the page already resident (bumps the pin count), or picks a free frame, evicts something if needed, and reads the page from disk.
If every frame is pinned, fetch returns error.BufferFull. It’s the backpressure mechanism that stops one transaction from pulling the entire database into RAM.
A frame that was modified is marked dirty. It’s written back to disk when:
it’s evicted (before its frame is handed to another page), or
someone calls
flushPage/flushAllexplicitly.This should not be the case, unless the caller knows exactly why they are doing it.
It marks the frame as dirty and lets the buffer manager decide when. We’ll see later how to optimize this by performing our own file operations manually on Linux.
The buffer manager receives a policy type, while the frame has no awareness of the replacement policy. The policy keeps its own state, tied to the frame number, and the buffer manager calls its hooks on each hit, load, unpin, and removal.
I find it so interesting how Zig allows us to do so much during compile-time.
Clock approximates LRU without keeping a list. It uses a fixed circular buffer of frames: in our case a bit set with one bit per frame, plus a “hand” that points to the next frame to check. DefaultPolicy in buffer_manager.zig is ClockPolicy.
The LRU policy uses an intrusive doubly linked list of unpinned frames: the most recently unpinned frame is at the front, and eviction removes the back. Both policies are tested directly, and the buffer manager picks one using a single type parameter, enabling later benchmarking.
This is a must, otherwise it would have to scan the files to find free slots every time a new page is allocated. It maintains a stack of free page ids, so that allocatePage can O(1) when reusing a freed page.
deletePage pushes the id. allocatePage pops one before extending the file. The list isn’t persisted, if the process crashes, it organically rebuilds when the file is scanned for free slots.
The latch is not necessarily a a lock, it’s a high level synchronization primitive for any shared resource.
The pool has two levels of latching.
Pool latch (std.Io.Mutex): one mutex that protects the page table, the replacement policy’s state, and the pin counts. fetch, newPage, deletePage, flushPage, and the checked guard methods take it. flushAll and the count accessors do not.
Frame latch (std.Io.RwLock): one per frame, protecting frame.data. Many readers may hold it at once, or one writer holds it exclusively.
Ordering rule: never wait for the pool latch while holding a frame latch. The checked methods don’t nest the two. They pin the frame under the pool latch, release it, then take the frame latch. drop() releases the frame latch before it unpins. The pin keeps the frame from being evicted in between.
checkedReadPage and checkedWritePage are the safe API. They return a guard that releases the frame latch and unpins when you call drop():
disk_manager.zig, raw page I/O, free list:
Pages live at byte offset id * PAGE_SIZE in the file. allocatePage zeroes the region before returning the id; deletePage pushes onto free_pages so the next allocatePage reuses it instead of extending the file. slotted_page.zig, in-page row layout:
SlottedPage is a view over bytes someone else manages, here, the Frame.data buffer.
buffer_manager.zig, pool, eviction, latches:
It’s generic over the disk type and the replacement policy. The only disk here
is FileDisk, but we could implement a in memory disk for testing; I ended up just passing a struct that fails on the nth I/O call to test error paths.
Read that output carefully:
5 pages, 3 frames. The pool can only hold 3 pages, so creating the 4th and 5th evicted the first two. Reading them back works because the dirty frames were flushed to
buffer_manager.dbbefore being reused.free=8151on a page with two rows (12 + 13 bytes):8192 - 8 (header) - 8 (two slots) - 25 (rows) = 8151.free 8131 -> 8147: we inserted a 16-byte row, deleted it, and compacted. The data bytes (16) came back after compaction, but the slot entry (4 bytes) doesn’t, slot numbers are stable, so the directory never shrinks. Net gain: 16 bytes, not 20.
This groundwork allows us to build more complex structures, like sorting, skip lists, B+-trees, LSM, there are much to go through.