1. Home
  2. Explore
  3. Computer Science
  4. Build a Database from Scratch

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Build a Database from Scratch

Building a Database Storage Engine from Scratch

Motivation: Why Databases Are Complex

Databases are foundational software. Internally, a database like MySQL organizes data into files on disk. When a database is created, a folder is created; when a table is created, a file is created inside that folder. This file stores two things: table data and an index (typically a B‑Tree or B+Tree) that enables fast lookups by primary key. Without an index, searching requires a linear scan (O(n)), which is unacceptable for large datasets because disk I/O is orders of magnitude slower than memory access.

Row Storage Approaches

The CSV Approach (Inefficient)

A naïve method is to store rows in CSV-like format using delimiters. However, this makes it impossible to jump directly from one row to the next — the system must scan byte by byte to locate delimiters. This is extremely slow.

Fixed-Length Records

To enable fast row addressing, rows can be forced to a fixed size. For a table with an integer primary key and a string name:

  • Primary key (integer): 4 bytes

  • String length: 1 byte (can store values up to 255, hence 255 is the common maximum for short strings)

  • String data: 255 bytes (maximum capacity)

Total row size = 4+1+255=2604 + 1 + 255 = 2604+1+255=260 bytes.

With fixed-size rows, searching by primary key means reading the first 4 bytes, comparing, and if no match, skipping exactly 260 bytes to read the next primary key. This is still linear search — O(n) — and does not scale to millions of rows.

The Need for Indexing

An index reduces search time to O(log n). A natural thought is to use a balanced binary tree stored in memory. Each node stores a primary key value and a pointer (row number) to the file location. However, this approach has two fundamental problems:

  1. Balancing: If primary keys are inserted in ascending order, a normal binary tree degenerates into a linked list — worst case O(n).

  2. Disk persistence: If the index grows larger than available RAM (gigabytes), it cannot be kept entirely in memory. It must be stored on disk, but binary trees are not designed for efficient disk‑based storage (node sizes do not align with disk blocks).

B‑Trees: The Solution

A B‑Tree solves both the balancing and disk storage problems.

Structure

Each node can hold multiple keys and have multiple children. The minimum number of children per node is a constant CCC (e.g., C=2C = 2C=2). From CCC we derive:

  • Maximum number of keys per node: 2C−12C - 12C−1 (for C=2C=2C=2, max keys = 3)

  • Maximum number of children: 2C2C2C

Internal nodes (except root and leaves) must have at least CCC children. The tree is self‑balancing: all leaves are at the same depth.

Self‑Balancing Insertion Algorithm

Assume C=2C=2C=2, so a node can hold at most 3 keys. Insertion proceeds as follows:

  1. Insert keys into a node in ascending order until the node reaches its maximum capacity (3 keys).

  2. On the next insertion, the node is full. Promote the median key to the parent. If there is no parent, create a new root.

  3. Split the full node into two nodes: left node contains keys less than the median, right node contains keys greater than the median.

  4. Insert the new key into the appropriate child node.

This algorithm is recursive: splitting a node may cause the parent to become full, requiring further splits up to the root. The result is that the tree never becomes a linked list — search is always O(log n).

The animation illustrates inserting keys 1 through 10 sequentially. The tree stays balanced, and each split increases the height evenly.

Disk Storage: Pages and Blocks

When reading from disk, data must be read in blocks (typically 512 or 4096 bytes). To avoid being constrained by the physical block size, databases define their own storage unit called a page (often a power of two, e.g., 4 KiB, 8 KiB, 16 KiB).

  • A page consists of one or more physical blocks.

  • The database file is a sequence of pages (e.g., 4 KiB each).

  • B‑Tree nodes are stored as pages. A node’s child pointers are page numbers (e.g., "page 3" means the 3rd page in the file).

  • Because each node fits in exactly one page, traversing the B‑Tree requires reading only one page per level — sequential disk operations are minimized.

Slotted Pages for Variable-Length Data

In practice, rows have variable length (e.g., names of different lengths). Fixed-size rows waste space. However, storing variable-length records directly in a page complicates binary search and insertion. A slotted page solves this.

Structure of a Slotted Page

  • Slot array (at the beginning of the page): an array of 2‑byte pointers (offsets) that point to the actual records.

  • Cells (at the end of the page): the variable-length records, stored contiguously from the end toward the beginning.

  • The slot array grows rightward; the cells grow leftward. The page is full when the two regions meet.

Advantages

  • Binary search is performed on the slot array, which has fixed-size entries (2 bytes each). This preserves O(log n) lookup within a node.

  • Insertion with variable-length data: the new cell is appended at the end (leftmost free space), and only the slot array is shifted. Shifting 2‑byte pointers is much cheaper than moving large variable-length records.

  • Children pointers in B‑Tree nodes are stored in the cell header of each key. For example, the cell for key 50 also stores a page number that points to a child node containing keys between 40 and 50.

Storing Tables and Indexes

Two main approaches exist for storing table data:

Heap Storage (Used by PostgreSQL)

  • A table file stores rows in slotted pages, but these pages are not organized as a B‑Tree — they are just a sequence of pages.

  • A separate page directory tracks free space and page locations.

  • Indexes (B‑Trees) store row locations (page number + slot index) as the pointer to the actual row.

  • Advantage: secondary index lookups find the row directly (one additional read).

  • Disadvantage: requires three separate disk structures (table file, page directory, B‑Tree index).

Index-Organized Storage (Used by SQLite)

  • Tables are stored as B‑Trees sorted by primary key. Each cell in the B‑Tree is a full row.

  • The primary key index is automatic — searching by primary key reads the table B‑Tree directly.

  • Secondary indexes (e.g., on email) store the primary key as the pointer, not the row location. To find the row, first search the secondary index (O(log n)) to obtain the primary key, then search the table B‑Tree (O(log n)) — a double lookup.

  • Advantage: only one B‑Tree structure is needed for both tables and indexes; no separate page directory.

  • Disadvantage: secondary index lookups require an extra B‑Tree traversal.

The choice is a trade‑off. Many toy databases (and this project) adopt the index‑organized approach for simplicity and code reuse.

Overflow Pages

If a single row is larger than a page (e.g., 4 KiB), the row is split into chunks. The first chunk is stored in a B‑Tree cell, and the last few bytes of that cell store a pointer to an overflow page. The overflow page contains the next chunk, plus a pointer to the next overflow page, forming a linked list. When reading the row, the chunks are reassembled sequentially.

B‑Tree Balancing with Variable-Length Cells

When rows have variable length, the number of keys that fit in a page is dynamic — there is no fixed maximum. This complicates the split algorithm because pages may become only half‑full when inserting sequentially (median split leaves left node at 50% capacity, and subsequent inserts fill the right node, not the left).

To reduce wasted space, databases use a more sophisticated rebalancing algorithm that attempts to reorganize keys across siblings before splitting. For example, when a node is full, keys can be redistributed to a sibling node to delay splitting. If redistribution fails, then split. This algorithm (based on SQLite’s implementation) is recursive and handles variable‑length data efficiently.

SQL Parsing and Query Plans

From SQL String to Abstract Syntax Tree (AST)

  1. Tokenizer: converts the raw SQL string into tokens (keywords, identifiers, operators, literals).

  2. Parser: builds an Abstract Syntax Tree (AST) from the tokens. One technique is Top‑Down Operator Precedence (TDOP) parsing, which uses mutually recursive functions to handle operator precedence naturally.

  3. Analyzer: performs context‑dependent checks (e.g., verifying that referenced tables and columns exist, checking data types).

  4. Optimizer: simplifies the AST to avoid redundant computations. For example, constant folding: WHERE 1 = 1 becomes a no‑op.

Query Plan: The Interpreter’s Instruction

Rather than compiling to machine code, the AST is translated into a query plan tree. Each node in this tree represents a step in executing the query. The plan follows the iterator model (also used by PostgreSQL).

  • Every node is an iterator that produces tuples (rows) one at a time.

  • The top‑level node calls .next() on its child, which calls .next() on its grandchild, and so on, until a scan node (leaf) reads tuples from the B‑Tree cursor.

  • This pipeline model processes data one tuple at a time without loading the entire result into memory — essential for large datasets.

A typical plan has three stages:

  1. Scan – read data from disk. Can be a full scan (sequential) or an index scan.

  2. Filter – evaluate WHERE conditions.

  3. Projection – select only required columns (relational algebra term).

Handling Operations That Need the Full Dataset (e.g., Sorting)

Some operations, like sorting or aggregation, require access to the entire result set. A collect plan reads all tuples into a temporary file on disk, processing them in chunks if they exceed available RAM.

Sorting on Disk: K‑Way External Merge Sort

When the data to sort does not fit in memory, a K‑Way External Merge Sort is used.

Algorithm

  • The dataset is divided into fixed‑size runs (groups of pages).

  • Pass 0: Read KKK pages into memory, sort them internally, and write out a sorted run of KKK pages.

  • Pass 1: Merge KKK sorted runs into one sorted run of K2K^2K2 pages, using KKK input buffers and one output buffer.

  • Continue until the entire file is sorted. The number of passes is log⁡K(N)\log_K(N)logK​(N) where NNN is the number of initial runs.

Example with K=2K=2K=2

  • Pass 0: 2‑page runs (each run is sorted).

  • Pass 1: 4‑page runs.

  • Pass 2: 8‑page runs.

  • Pass 3: 16‑page runs, etc.

The passes multiply by KKK each time, reducing I/O logarithmically. More buffers (larger KKK) mean fewer passes at the cost of more memory.

Implementing this algorithm requires careful management of fixed‑size buffers and multiple nested loops (e.g., while while while for for). It gracefully handles terabytes of data by loading only KKK pages at a time.

Caching: Clock Algorithm

A page cache keeps frequently accessed B‑Tree pages in memory, reducing disk reads. The clock algorithm is a simple replacement policy.

Data Structures

  • A circular array of page frames.

  • Each frame has a reference bit (set to 1 when the page is accessed) and a dirty bit (set to 1 if the page was modified).

  • A clock hand (pointer) sweeps through the circular array.

Replacement Policy

  1. When a new page must be loaded, the clock hand moves clockwise.

  2. At each frame:

    • If the page is referenced (ref bit = 1), reset the ref bit to 0 and continue.

    • If the page is not referenced (ref bit = 0), this page is a candidate for eviction:

      • If dirty, write it to disk.

      • Replace with the new page from disk.

  3. The clock ensures that frequently accessed pages survive multiple sweeps.

Additionally, to improve I/O performance, dirty pages are often grouped and written sequentially rather than one at a time.

Transactions: Journal File Approach

A transaction groups multiple write operations so they either all commit or all roll back (atomicity). A simple implementation uses a journal file (inspired by older versions of SQLite).

How It Works

  • Before modifying any page, its original content is written to a separate journal file.

  • The transaction modifies pages in the cache; dirty pages are written back to the database file during the transaction.

  • Rollback: read the journal file and overwrite the database pages with their original content, then delete the journal.

  • Commit: simply delete the journal file, making all modifications permanent.

Crash Recovery

If the server crashes during a transaction, the journal file remains. On restart, the database detects the journal and replays the rollback to restore the state before the transaction.

Limitations

  • Works only for single‑writer scenarios (one transaction at a time). If two transactions run simultaneously, the journal approach does not isolate them.

  • Production systems use a Write‑Ahead Log (WAL) that supports concurrent writers and provides more robust crash recovery.

Network Protocol

The database exposes its services over TCP. A custom text‑based protocol (inspired by the Redis protocol) handles client commands. Clients send lines of text; the server parses them and responds accordingly.

  • Multiple clients can connect, but only one transaction is active at a time (due to a global mutex). Each statement outside an explicit transaction is itself a transaction.

  • The protocol is simple, allowing clients to be written in any language.

Conclusion

Building a database from scratch reveals the immense complexity hidden behind familiar SQL commands. Key challenges include:

  • Variable‑length data: forces the use of slotted pages and complex B‑Tree balancing algorithms.

  • Large datasets: algorithms must work on disk, not only in memory (e.g., external merge sort, overflow pages).

  • Concurrency and recovery: require transaction management (journals, WAL) and careful locking.

  • I/O efficiency: demands page‑aligned B‑Tree nodes, grouping writes, and caching strategies.

The project described here (MKDB) is a toy database with no joins, foreign keys, or subqueries, but its internals mirror those of production systems. The source code is heavily documented and includes ASCII diagrams and over 270 tests, serving as a learning resource for understanding database internals.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent