The storage engine decides which question is cheap. On one million records, one read scans 100 MB of a bare log but one 4 KB block of a B-tree. One write costs a B-tree 4,180 bytes of disk and an LSM-tree 828.
Pick an engine, then pick a question, and see how many bytes it moves on disk. Then we build each engine from zero: a log, a hash index, an LSM-tree, a B-tree and a column store.
You need a little Python and what a sorted list and a hash map are. We build the rest from zero.
Illustrative: 1,000,000 records of 100 bytes, 4,096-byte blocks, every index in RAM counted as free. Counts come from this lesson's Python engines. LSM: leveled, Bloom filters at 10 bits per key. B-tree: 256 children a page, a checkpoint every 1,000 writes.
Chapter 0
Build the simplest database, then watch its reads slow down as it grows
You need a key-value store. You give it a key like user:42 and a value, and later you ask for the value back. The simplest store that works is a file you only add to at the end.
pythondef db_set(key, value): with open("db.log", "a") as f: f.write(f"{key},{value}\n") # add one line at the end def db_get(key): result = None for line in open("db.log"): # read every line k, v = line.rstrip("\n").split(",", 1) if k == key: result = v # a later line overrides an earlier one return result
A write adds one line. The disk does not seek, and no old byte changes. A read is the problem. It must read the whole file, because the newest value for a key can be on the last line.
How long does one read take? Call the number of records N and the bytes in one record s. Call the speed at which the disk reads a file from start to end B. The read time is T.
T equals N times s, over B.
Multiply the record count N by the record size s to get the file size. Divide by the read speed B. That is T, and it grows with every write.
With made-up numbers: N = 1,000,000 and s = 100 bytes make a 100 MB file. At B = 500 MB/s, T = 0.2 s for one read. At a billion records, T = 200 s.
The purple strip is the log on disk. Drag the record count: the write stays one small blue append, and the yellow read scan grows with the file.
Illustrative: 100-byte records, a disk that reads and writes 500 MB/s in order. The write time is transfer time only; a real write also waits for the disk to confirm.
An index is extra data, derived from the log, that sends a read to the right place. Every index costs something on each write, because the write must update it too. This lesson follows Chapter 4 of Designing Data-Intensive Applications, 2nd edition, by Martin Kleppmann and Chris Riccomini (O'Reilly, 2026). The chapter covers how databases lay data out on disk and find it again, for transactions and for analytics. We explain it in our own words, with our own code and numbers. Chapter 3 chose the data model; this chapter stores it.
Failure. Symptom: reads get slower every week while writes stay fast. Measure: read time against the size of the log. Cause: every read scans the whole file. Fix: add an index, and remove old versions.
Chapter 1
Point each key at its newest record, then merge away the old ones
Keep the log, and keep in RAM a hash map from each key to the byte position of its newest record. A read looks up the position and reads one place on disk. A write appends, then updates the map. This is how Bitcask works, the storage engine Basho built for the Riak database (Sheehy and Smith, 2010). Bitcask calls the map the keydir.
The log is cut into segments. When the active file reaches a size limit, it closes and never changes again. A background merge reads the closed segments and writes only the newest value of each key. A delete appends a tombstone, a record that says the key is gone, and the merge drops the key.
Purple records are live on disk; pink ones are stale versions or tombstones. The teal keydir in RAM points at each key's newest record. Write, delete, then merge or restart.
Illustrative: one box stands for one record. The restart count compares reading every record with reading a hint file of keys and positions, as the Bitcask paper describes.
After a crash the keydir is gone, because it lived in RAM. Bitcask rebuilds it by reading the data files. Next to each merged file it writes a hint file that holds only keys and positions, so a restart reads far less.
The price is RAM. Call the number of distinct keys K. Call the RAM of one keydir entry e: the key, its file, position, size and timestamp, plus the hash table's overhead. The keydir needs M bytes.
M equals K times e.
Count the distinct keys K. Multiply by the size of one entry e. If M does not fit in RAM, the hash index does not work.
With made-up numbers: K = 50 million session ids at e = 100 bytes gives M = 5 GB, which fits. K = 1 billion gives 100 GB, more than most servers hold.
The other limit is order. A query for every key from user:1000 to user:2000 gets no help, because a hash map keeps keys in no order. The engine must test every key in the map.
Failure. Symptom: after a crash, the store takes many minutes to accept reads. Measure: bytes read at startup. Cause: the keydir is rebuilt by reading every value in every segment. Fix: write hint files at each merge, and merge often enough that few stale records remain.
Chapter 2
Sort each file in RAM before it reaches disk, then merge files like merge sort
Add one rule to the segments: each file keeps its keys in sorted order. Such a file is a Sorted String Table, or SSTable. Sorting buys three things. Files merge like merge sort. The index can be sparse. A range read is one read of neighbouring blocks.
Writes arrive in random order, so the engine sorts in RAM first. Each write goes into a sorted in-memory structure, the memtable (a balanced tree or a skip list). Each write is also appended to a log on disk, so a crash cannot lose the memtable. When the memtable is full, the engine writes it out in key order as a new SSTable and starts an empty one. LevelDB's design notes describe these three parts: a log file, a memtable and sorted tables.
A read checks the memtable, then the SSTables from newest to oldest, and stops at the first hit. This design is the log-structured merge-tree, or LSM-tree, named by Patrick O'Neil and others in 1996. LevelDB, RocksDB and Cassandra use it.
Three sorted files, newest on top. Each step takes the smallest key at the front of any file. A blue key goes to the output; an older copy of the same key turns pink and the merge drops it.
Illustrative keys. This is the merge our Python engine runs: one pass that reads each file once in order and writes sorted output with no sort step.
In a sorted file, the index needs one entry per block, not one per key. To find a key, the engine binary-searches the index for the last block that starts at or before it. Then it reads and scans that one block. Call the data size D, the block size b, and the bytes of one index entry e. The sparse index takes I bytes.
I equals D over b, times e.
Divide the data D into blocks of size b. Keep one entry of e bytes for each block. That is I.
With made-up numbers: D = 100 GB in b = 4,096-byte blocks is 24.4 million blocks; at e = 32 bytes, I = 781 MB. An index with one entry per key, for a billion 100-byte records, needs 32 GB: 40 times more, one for each record in a block.
Failure. Symptom: after a power cut, the last second of writes is gone. Measure: whether the write returns before the disk confirms its log record. Cause: the engine buffered the log, so the memtable died with the process. Fix: sync the log before you acknowledge a write, or accept the loss window on purpose.
Chapter 3
Skip the files that surely lack a key, and measure how often the filter is wrong
A read for a key that does not exist is the worst case for an LSM-tree. It checks every SSTable and finds nothing. A Bloom filter (Burton Bloom, 1970) keeps a few bits per key in RAM and answers, for each file, "surely not here" or "maybe here".
The filter is an array of m bits, all 0. To add a key, hash it k different ways and set those k bits to 1. To test a key, look at its k bits.
If any bit is 0, nobody added the key. If all are 1, the key is probably there, but other keys may have set those bits. That wrong "maybe" is a false positive. The filter never gives a false "no".
2,000 keys go into the filter; the grid shows its first bits, teal for 1. Then the device tests 20,000 keys that it never added. Change the bits per key and the hash count.
Runs in your browser: the same hash functions and keys as our Python check, so the measured rate matches it exactly. Keys added are 0, 2, 4 and so on; keys tested are the odd numbers.
What fraction of absent keys slip through? Call the number of keys added n, the number of bits m, and the number of hash functions k. The false positive rate is p.
p equals one minus e to the minus k n over m, all to the power k.
Find the chance that one bit is still 0: e to the minus k times n over m. One minus that is the chance it is 1. Raise it to the power k, because all k bits must be 1. The best k is m over n times 0.69.
With m/n = 10 bits per key and k = 7: p = (1 − e−0.7)7 = 0.82%. The device measures 0.93% on 20,000 absent keys. RocksDB's wiki lists 9.9 bits per key for a 1% rate. A billion keys at 10 bits take 1.25 GB of RAM.
The engine builds a filter for each SSTable when it writes the file, and asks it before reading a block. Most missing-key reads then touch no disk. A filter cannot help a range scan: it answers only "is this exact key here?".
Failure. Symptom: reads for missing keys hit the disk as often as reads for real keys. Measure: blocks read per missing-key lookup. Cause: nobody set a filter (RocksDB adds one only when you set a filter policy), or it has too few bits per key. Fix: set about 10 bits per key.
Chapter 4
Run one workload under two compaction strategies, and see which cost each one pays
Flushes add SSTables without end, and old versions pile up. Compaction merges SSTables in the background. It drops old versions and keeps the number of files a read must check small. Two strategies dominate.
Size-tiered: when a few files of similar size exist (4 here), merge them into one larger file. Leveled: level 1 has a size limit, and each deeper level may hold T times more (T = 10). A level that grows past its limit merges into the next. Below level 0, each key lives in at most one file per level. LevelDB sizes level L at 10 to the L megabytes and starts compacting level 0 at four files.
Judge a strategy by three ratios. Write amplification: bytes written to disk per byte the app wrote. Read amplification: files or blocks one read checks. Space amplification: disk used per byte of live data. Call the bytes on disk Ddisk and the bytes of the newest version of every key that still exists Dlive.
S-A equals D-disk over D-live.
Add up the size of every file, D-disk. Divide by the size of the live data, D-live. The excess is stale versions waiting for compaction.
From our Python run: 20,000 live keys are 2.0 MB. At its worst moment, size-tiered compaction held 4.98 MB, so SA = 2.49. Leveled peaked at 1.45.
Each bar is one SSTable on disk, longest at the bottom. Press Run: 100,000 random updates hit 20,000 keys. Watch the file count, then switch strategy and run again.
Runs in your browser, the same engine as our Python check: a 200-record memtable, 100-byte records, Bloom filters at 10 bits per key. A toy: each level is one sorted run and merges whole, where RocksDB merges file by file.
| Strategy | Write amp. | Space amp., mean / peak | Files a read may check, mean / peak |
|---|---|---|---|
| Leveled | 8.0 | 1.20 / 1.45 | 3.7 / 6 |
| Size-tiered | 4.9 | 1.54 / 2.49 | 6.1 / 12 |
A merge may drop a tombstone only when it reaches the oldest file that may hold the key. Dropped earlier, an older value would come back. Partitioning and Storage follows one leveled tree as it fills and counts its writes; here the same updates run under both strategies.
Failure. Symptom: a table used as a queue reads slower every day. Measure: tombstones skipped per read. Cause: each dequeue writes a tombstone, and reads step over all of them until compaction reaches the oldest level. Fix: compact that key range, or use a store built for queues.
Chapter 5
Insert keys into fixed-size pages, and watch a full page split in two
The B-tree, described by Rudolf Bayer and Edward McCreight in 1970, is the main index of most relational databases. Like an SSTable, it keeps keys sorted. Unlike one, it changes fixed-size pages in place. PostgreSQL's pages are usually 8 kB; InnoDB's default is 16 KB.
An inner page holds keys and pointers to child pages, one child for each key range. A leaf page holds the records. A read starts at the root and follows one pointer per level. The number of children of one page is the branching factor.
An insert finds its leaf. A full leaf splits into two half-full pages, and the parent gains a pointer. A full parent splits too. Only a root split adds a level.
A tiny tree: 4 records a leaf, 4 children a page. The blue path is the last insert; blue pages are the ones it wrote. Insert in random order, then in ascending order, and compare how full the leaves are.
Runs in your browser, the same B-tree code as our Python check with smaller pages. It splits every page in half; InnoDB leaves about 1/16 of a page free and fills pages about 15/16 when keys arrive in order.
How many records fit under a few levels? Call the depth, in pages from root to leaf, d; the children of an inner page f; and the records in a leaf r. The tree holds up to C records.
C equals f to the d minus one, times r.
Each level of inner pages multiplies the number of leaves by f. There are d minus 1 such levels. Multiply the leaves by r records each to get C.
With f = 256 and r = 40: d = 3 holds 256 × 256 × 40 = 2,621,440 records; d = 4 holds 671 million. Our Python B-tree with 1,000,000 random keys: depth 3, 35,746 leaves, 69.9% full.
A table can have several B-trees. InnoDB keeps each row inside the primary key's tree, the clustered index. Its secondary indexes store the primary key, so a lookup by email walks two trees. PostgreSQL keeps rows in an unordered heap that every index points into. A covering index also stores the columns a query needs (PostgreSQL's INCLUDE), so the query skips the table.
Failure. Symptom: an index on random UUIDs is about 1.3 times larger than the same index on time-ordered ids. Measure: leaf fill: 70% for random inserts against about 94% (15/16) for ordered ones. Cause: random keys land on random leaves, and each split leaves two half-full pages. Fix: use time-ordered primary keys.
Chapter 6
Pull the power between two page writes, and let the log repair the tree
A split changes three pages: the old leaf, the new right leaf and the parent. The disk writes them one at a time. If the power fails between two of them, the parent can miss its pointer to the new page, and those keys become unreachable.
The fix is a write-ahead log (WAL): an append-only file where the engine describes every change before it changes any page. After a crash, the engine replays the log from the last checkpoint. At a checkpoint, every changed page has reached the disk. A write counts as committed once its log record is on disk.
Inserting key 25 splits a full leaf. Choose when the power fails, with the log on or off, then press Recover. Red keys are lost; a red page is torn.
Illustrative: one split, four ordered writes (the log record, the right leaf, the left leaf, the parent). With the log on, the log record holds full page images, as PostgreSQL does after each checkpoint.
A torn page is one written halfway: its first part new, its rest old. A small log record cannot repair it, because it assumes a whole old page. PostgreSQL logs the full page on its first change after each checkpoint (full_page_writes, on by default). InnoDB first writes each page to a doublewrite buffer and finds a good copy there after a crash.
Recovery time depends on how much log follows the last checkpoint. Call that much log W, and the speed at which the engine replays it v. Recovery takes t.
t equals W over v.
Find how much log W came after the last checkpoint. Divide by the replay speed v. Frequent checkpoints shorten t, and each one costs a burst of page writes.
PostgreSQL checkpoints every 5 minutes by default, or sooner when the log nears max_wal_size, 1 GB by default. Replaying W = 1 GB at a made-up v = 100 MB/s takes t = 10 s.
Threads that change pages at the same time hold short locks on them, called latches. Databases that keep all data in RAM still log. Redis can append each write to an append-only file and sync it every second (the default), or take snapshots.
Failure. Symptom: after a power cut, some pages fail their checksums. Measure: checksum errors at startup. Cause: torn pages, after full_page_writes was turned off to save log volume. Fix: keep it on, unless the storage guarantees whole-page writes.
Chapter 7
Run the same operations on both engines and read what each one costs
Same keys, same operations, two engines. Each starts with 20,000 records. Then 20,000 operations run on both, in the mix of writes and reads you choose. The engines are the ones you built in Chapters 2 to 6.
Pick a mix and a key pattern, then Run. Blue: bytes written per app byte. Teal: disk blocks per read. Purple: disk used per byte of live data.
Runs in your browser; our Python copy gives the same numbers. Illustrative scale: 100-byte records, 4,096-byte pages, B-tree inner pages in RAM, a checkpoint every 1,000 writes, a 200-record memtable. The LSM run is short, so its compaction has not reached a steady state.
With half writes and uniform keys, the B-tree writes 22.7 bytes per app byte and the LSM-tree 6.2. Each B-tree write dirties a whole 4 KB page for a 100-byte record. A checkpoint every 1,000 writes flushes each dirty page once, so writes to the same page in between share one flush. With 200 hot keys, that sharing halves the B-tree's bytes to 11.9.
Reads cost the B-tree one leaf every time: its inner pages stay in RAM. The LSM-tree reads 1.02 blocks per read, thanks to its filters. Turn the filters off and it reads 3.57, one for each file that might hold the key. With hot keys, about half the LSM reads hit the memtable and touch no disk.
The B-tree has quieter strengths. Each key lives in one place, which makes it simpler to lock a key range for a transaction. It has no compaction running in the background, competing with reads for the disk. LSM files compress well, because they are rewritten in large sorted batches.
Failure. Symptom: an LSM database shows a fine median read time but a bad 99th percentile, and its disk use creeps up. Measure: bytes waiting for compaction, over hours. Cause: writes arrive faster than compaction can merge them. Fix: limit the write rate, add disk bandwidth, or tune compaction.
Chapter 8
Store each column in its own file, sort it, and compress the repeats
So far each request touches a few records by key: OLTP, online transaction processing. An analyst asks for total listening hours per country: a few columns of billions of rows. That is OLAP, online analytic processing, and it runs on a copy of the data, a data warehouse. Its star schema has one large fact table of plays, with keys into small dimension tables such as tracks.
A row store keeps each row's columns together, so a scan reads every column. A column store keeps each column in its own file, in the same row order, and a query reads only the columns it names. Parquet, an open file format, stores each group of rows as one chunk per column, with a footer that locates each chunk.
Call the number of rows N, and the width in bytes of a column c wc. A query that needs the set of columns Q reads B bytes.
B equals N times the sum over c in Q of w-c.
Add the widths w-c of the columns the query uses. Multiply by the row count N. A row store reads every column instead.
With made-up widths: 12 columns total 100 bytes a row. Hours per country needs played_at (8), ms_played (4) and country (2): 14 bytes. For N = 1 billion, B = 14 GB, against 100 GB in a row store: 7.1 times less.
The grid is the plays table. Blue cells are the bytes the query reads. Switch the layout, pick a query, then sort and compress.
Illustrative table of 1 billion rows. Run counts come from 10 million synthetic plays (200 countries, 5 devices) in NumPy; run counts do not grow with N once the column is sorted. Only country and device are compressed here.
A column holds one type of value, and it repeats. Dictionary encoding replaces 200 country codes with 1-byte numbers. Run-length encoding stores (value, count) pairs, and it needs a sorted column. In 10 million synthetic plays, country has 9,324,952 runs unsorted, worse than no encoding. Sorted, it has 200 runs: 1,200 bytes instead of 20 MB. A second sort key, device within country, keeps device at 1,000 runs.
Sorted, compressed files resist changes in place, so column stores buffer new rows in memory and write new sorted files, like a memtable. A materialized view stores a query's result, such as hours per country per day; the engine must refresh it when the data changes.
Failure. Symptom: a dashboard slows checkout for every customer. Measure: disk load on the main database during the report. Cause: an analytic scan on the transaction database. Fix: copy the data to a warehouse and query it there.
Chapter 9
Look up documents by the words they contain, then by what they mean
A B-tree finds a key by its exact value or a range. A search box asks for documents that contain words. A full-text index is an inverted index: for each term, the sorted list of document ids that contain it, called a postings list. A query for two words intersects two sorted lists, one pass each, like an SSTable merge.
| Term | Postings list | Query "ferry AND night" |
|---|---|---|
| ferry | 2, 5, 9, 14 | walk both lists: 5 and 14 |
| night | 1, 5, 7, 14, 20 |
Lucene, the library under Elasticsearch, adds new documents as new index segments and merges segments in the background, much like SSTables. Search by meaning needs another index. An embedding model turns a text or image into a vector of numbers, so that similar items lie close together. A vector index finds the nearest vectors to a query without comparing it with all of them.
One kind is IVF, the inverted file. It clusters the vectors with k-means into lists, each with a centre point. A query compares itself with every centre, then scans only the nearest lists. Call the number of vectors N, the number of lists L, and the lists scanned per query q. A query makes about K distance comparisons.
K equals L, plus q times N over L.
Compare the query with all L centres. Then scan q lists of about N over L vectors each. More probes find more true neighbours and cost more.
pgvector suggests about N/1000 lists up to a million rows, and about the square root of the lists as probes. N = 1,000,000, L = 1,000, q = 32: K = 1,000 + 32,000 = 33,000 comparisons, 30 times fewer than 1,000,000.
2,000 purple vectors in 16 lists, each with a teal centre. Tap to move the blue query. The probed lists light up; green rings are true nearest neighbours the index found, red rings the ones it missed.
Runs in your browser: synthetic 2-D points, k-means with 16 lists, the same code as our Python check. Real embeddings have hundreds of dimensions, so measure recall on your own data.
Over 200 random queries, one probe found 87.3% of the true ten nearest neighbours with 190 comparisons. Three probes found 99.9% with 457. pgvector also offers HNSW, a layered graph of near neighbours. Its docs say HNSW trades speed for recall better than IVFFlat, but builds more slowly and uses more memory.
Failure. Symptom: semantic search misses an obvious match. Measure: recall at 10 against exact search, on a sample of queries. Cause: too few probes, or centres built before most of the data arrived. Fix: raise the probes, and rebuild the index once the data has grown.
Chapter 10
Keep the numbers, the checklist and the code for the next engine you choose
A log writes cheaply and reads everything. A hash index reads one place but needs every key in RAM. SSTables sort in RAM and merge like merge sort; Bloom filters keep missing keys off the disk; compaction trades write, read and space amplification. A B-tree changes pages in place and needs a write-ahead log to survive a crash. Column stores read only the columns a query names, and sorting makes them compress. Inverted and vector indexes answer questions a key cannot.
| Idea | Rule | This lesson's number |
|---|---|---|
| Log scan | T = N · s / B | 1 M records, 500 MB/s: 0.2 s a read |
| Keydir RAM | M = K · e | 50 M keys at 100 B: 5 GB |
| Sparse index | I = (D / b) · e | 100 GB, 4 KB blocks: 781 MB, not 32 GB |
| Bloom filter | p = (1 − e−kn/m)k | 10 bits, k = 7: 0.82%; measured 0.93% |
| Space amplification | SA = Ddisk / Dlive | peak 1.45 leveled, 2.49 tiered |
| B-tree capacity | C = fd−1 · r | f 256, r 40: 2.6 M at depth 3 |
| Recovery | t = W / v | 1 GB at 100 MB/s: 10 s |
| Column scan | B = N · Σ wc | 14 of 100 bytes: 14 GB, not 100 GB |
| IVF cost | K = L + q · N / L | 1 M vectors, 1,000 lists, 32 probes: 33,000 |
full_page_writes on.pythonimport math, bisect class Bloom: def __init__(self, n, bits_per_key): self.m = int(n * bits_per_key); self.k = round(bits_per_key * math.log(2)) self.bits = bytearray(self.m) def _pos(self, key): a, b = hash((key, 1)), hash((key, 2)) | 1 return [(a + i * b) % self.m for i in range(self.k)] def add(self, key): for p in self._pos(key): self.bits[p] = 1 def may(self, key): return all(self.bits[p] for p in self._pos(key)) class TinyLSM: def __init__(self, mem_limit=200): self.mem, self.runs, self.limit = {}, [], mem_limit # runs: newest first def put(self, key, value): # value None = tombstone self.mem[key] = value # (a real engine also appends to a log) if len(self.mem) >= self.limit: keys = sorted(self.mem) bloom = Bloom(len(keys), 10); [bloom.add(k) for k in keys] self.runs.insert(0, (keys, [self.mem[k] for k in keys], bloom)) self.mem = {} def get(self, key): if key in self.mem: return self.mem[key] for keys, vals, bloom in self.runs: # newest first if not bloom.may(key): continue # surely not in this file i = bisect.bisect_left(keys, key) if i < len(keys) and keys[i] == key: return vals[i] return None def compact(self): # merge every run; newest wins best = {} for keys, vals, _ in reversed(self.runs): best.update(zip(keys, vals)) keys = sorted(k for k, v in best.items() if v is not None) bloom = Bloom(max(1, len(keys)), 10); [bloom.add(k) for k in keys] self.runs = [(keys, [best[k] for k in keys], bloom)] db = TinyLSM(mem_limit=3) for k, v in [("cat", 1), ("dog", 2), ("owl", 3), ("cat", 4), ("dog", None), ("emu", 5)]: db.put(k, v) print(db.get("cat"), db.get("dog"), len(db.runs)) # 4 None 2 db.compact(); print(db.runs[0][0]) # ['cat', 'emu', 'owl']
Now press Present or Teach and explain four things from memory. Why does a sorted file need only a sparse index? Why does a Bloom filter never say a false "no"? Why can a split without a log lose old keys? Why does a column store read 7 times less? Then go back to the hero and find the one question each engine wins.