Storage engines and indexes
How a database keeps data on disk and finds it again. B-trees and LSM trees, the write-ahead log, fsync and group commit, read and write amplification, and how to design the indexes you add.
ConceptCore45 min readUpdated
- 1 architecture diagram
- 1 sequence flow
- 9 code samples
- 9 interviewer follow-ups
- 4 self-checks
On this page12 sectionsHLDLLDSenior depth
- Explain how a B-tree and an LSM tree store and find data, and what each pays for it in reads, writes and space.
- Describe how a write-ahead log makes a commit durable and a crash recoverable, and why group commit lets a slow fsync serve thousands of commits a second.
- Choose a storage engine for a workload, and say which numbers to watch (write amplification, files per read, compaction backlog).
- Design a composite index for a query: equality columns first, then the column you range over or sort by, and know when a covering or partial index helps.
9 code samples (611 lines), collapsed so the explanation stays in focus.
A database is two things stacked. On top is the part you talk to: SQL or a key-value API, transactions, replication. Underneath is the storage engine, which decides where bytes sit on disk, how a key is found again and what survives a power cut. Almost every engine is built on one of two ideas. A B-tree keeps data sorted in fixed-size pages and updates pages in place. An LSM tree (log-structured merge tree) never updates in place: it appends changes to sorted files and merges them later.
The choice explains things that otherwise look like trivia. Why PostgreSQL and MySQL slow down when you insert random UUIDs. Why Cassandra and RocksDB swallow writes but show wobbly read latency during compaction. Why an index speeds up a read and slows down every write. Why a database can commit tens of thousands of transactions a second on a disk that takes a millisecond to flush.
Three facts about storage shape every design in this lesson.
- Data moves in pages. Engines read and write fixed-size blocks of 4 KB to 16 KB (SQLite defaults to 4 KB, PostgreSQL and SQL Server to 8 KB, InnoDB to 16 KB). Asking for one 100-byte row reads a whole page.
- Sequential beats random. A hard disk spends milliseconds moving its head for each random access. An SSD has no head, but it writes in pages and erases in much larger blocks, so many small scattered overwrites make the drive copy data around inside itself. Large sequential writes are what both kinds of device like best.
- Written is not durable. A
writecall usually hands bytes to the operating system's cache. They survive a power cut only afterfsync(or an equivalent flush) returns, and that call is slow: from tens of microseconds on drives with power-loss protection to several milliseconds on consumer SSDs and many cloud volumes. Measure your own device; PostgreSQL shipspg_test_fsyncfor exactly this.
Engines are compared with three ratios:
- Read amplification: disk reads needed per lookup.
- Write amplification: bytes written to disk per byte the application wrote. The same data may go to a log, to a data file and again during background merges, so ratios of ten or more are normal.
- Space amplification: bytes on disk per byte of live data. Old versions, half-empty pages and dead entries all count.
These pull against each other. The RUM conjecture (read, update, memory) states it as a rule of thumb: an access method that caps two of the three overheads pays a hard minimum on the third. It is a conjecture, not a theorem, and a useful one. Every engine below is a choice about which two to protect.
A B-tree stores keys in sorted order inside fixed-size pages and links the pages into a shallow tree. The kind databases use is the B+tree: inner pages hold only separator keys and child pointers, and leaf pages hold the keys with their rows (or pointers to the rows), chained left to right so a range scan reads leaves in order. When a database manual says "B-tree", it almost always means this.
A lookup starts at the root, searches the page for the child whose key range contains the key, and repeats until it reaches a leaf. Pages hold hundreds of children, so the tree is very shallow.
page: 16 KB, ~100 rows per leaf, ~500 children per inner page
1M rows: 3 levels (100 x 500 x 500 reaches 25M rows)
1B rows: 10M leaves = 160 GB; inner pages: ~20,000 + 40 + 1
inner total: ~20,000 pages x 16 KB = ~330 MB, so it fits in memory
point read: 1 disk read (the leaf); the 3 inner levels are cached
100x more: 100B rows need 5 levels: one more page read, not 100 times moreTwo consequences follow. Point reads are cheap and predictable, because the inner levels live in memory and a lookup is typically one disk read. And depth hardly depends on size: a hundred times more rows costs one more level. The same arithmetic as code:
C# · How many pages does a lookup touch? Every level multiplies the reach by the fan-out.
using System;
using System.Diagnostics;
// How many pages does a lookup touch? Every level multiplies the reach by the fan-out.
static int TreeLevels(long rows, int rowsPerLeaf, int fanout)
{
int levels = 1; // one leaf page holds the whole table
long reach = rowsPerLeaf; // rows a tree of this height can hold
while (reach < rows) { reach *= fanout; levels++; }
return levels;
}
Debug.Assert(TreeLevels(1_000_000, 100, 500) == 3);
Debug.Assert(TreeLevels(1_000_000_000, 100, 500) == 4);
Debug.Assert(TreeLevels(100_000_000_000, 100, 500) == 5); // a hundred times more rows, one more page readInserts and splits. To insert, find the leaf and put the key in its sorted place. If the page is full it splits into two half-full pages and the parent gains a separator key. If the parent is full it splits too, and a split of the root puts a new root above it. That is the only way a B-tree grows, which is why every leaf stays at the same depth.
before: parent [ 40 ]
/
[ 10 20 30 35 ] full: 25 does not fit
after: parent [ 25 | 40 ] the separator 25 is copied up
/ \
[ 10 20 ] -> [ 25 30 35 ] two half-full leaves, still linkedUpdated in place, and what that costs. The engine changes the page where it sits. Changing a 100-byte row eventually rewrites a 16 KB page, 160 times the data, although several changes to the same page can share one write. A split touches several pages, and a crash between those writes would leave a broken tree. That is why every update-in-place engine needs a log, covered in the next section.
Page fill. After random inserts, pages average about 69% full, because splits leave halves, and deletes leave gaps. That unused space is why a B-tree table is larger than its data, and why engines offer a rebuild (REINDEX, OPTIMIZE TABLE) and a fill factor setting.
Key order decides what an insert costs. The experiment below inserts the same 200,000 keys into a tree whose cache holds about a tenth of the leaves, once in random order and once in ascending order. It also runs ascending keys through a tree without the right-edge optimisation that real engines have.
C# · A page cache that remembers the most recently used pages. A miss stands for one read…
using System;
using System.Collections.Generic;
// A page cache that remembers the most recently used pages. A miss stands for one read from disk.
public sealed class BufferPool
{
private readonly int capacity;
private readonly LinkedList<int> recent = new LinkedList<int>();
private readonly Dictionary<int, LinkedListNode<int>> nodes = new Dictionary<int, LinkedListNode<int>>();
public int Misses { get; private set; }
public BufferPool(int capacity) { this.capacity = capacity; }
public void Touch(int pageId)
{
if (nodes.TryGetValue(pageId, out var node)) { recent.Remove(node); recent.AddFirst(node); return; }
Misses++;
Admit(pageId);
}
public void Admit(int pageId) // a page created in memory costs no read
{
nodes[pageId] = recent.AddFirst(pageId);
if (nodes.Count > capacity) { nodes.Remove(recent.Last.Value); recent.RemoveLast(); }
}
}
public sealed class Page
{
public readonly int Id;
public readonly bool IsLeaf;
public readonly List<int> Keys = new List<int>();
public readonly List<Page> Children = new List<Page>(); // an inner page has Keys.Count + 1 children
public Page(int id, bool isLeaf) { Id = id; IsLeaf = isLeaf; }
}
public sealed class BPlusTree
{
private readonly int maxKeys;
private readonly bool splitAtTheEnd;
private readonly BufferPool pool;
private int nextId;
private Page root;
public int Splits { get; private set; }
public BPlusTree(int maxKeys, BufferPool pool, bool splitAtTheEnd)
{
this.maxKeys = maxKeys; this.pool = pool; this.splitAtTheEnd = splitAtTheEnd;
root = NewPage(true);
}
private Page NewPage(bool leaf) { var page = new Page(nextId++, leaf); pool.Admit(page.Id); return page; }
public void Insert(int key)
{
var split = InsertInto(root, key, true);
if (split == null) return;
var newRoot = NewPage(false); // the tree grows at the top, so every leaf stays at one depth
newRoot.Keys.Add(split.Value.Separator);
newRoot.Children.Add(root);
newRoot.Children.Add(split.Value.Right);
root = newRoot;
}
private (int Separator, Page Right)? InsertInto(Page page, int key, bool onRightEdge)
{
pool.Touch(page.Id); // every page on the way down must be in memory
if (page.IsLeaf)
{
int at = page.Keys.BinarySearch(key);
at = at >= 0 ? at : ~at;
page.Keys.Insert(at, key);
return page.Keys.Count <= maxKeys ? null : SplitLeaf(page, onRightEdge && at == page.Keys.Count - 1);
}
int slot = page.Keys.BinarySearch(key);
slot = slot >= 0 ? slot + 1 : ~slot;
var split = InsertInto(page.Children[slot], key, onRightEdge && slot == page.Children.Count - 1);
if (split == null) return null;
page.Keys.Insert(slot, split.Value.Separator);
page.Children.Insert(slot + 1, split.Value.Right);
return page.Keys.Count <= maxKeys ? null : SplitInner(page);
}
private (int Separator, Page Right)? SplitLeaf(Page left, bool appendedAtTheEnd)
{
Splits++;
var right = NewPage(true);
// Ever-increasing keys always land in the rightmost leaf. Splitting it down the middle would leave every finished
// leaf half empty, so engines keep the old leaf full and start the new one with the new key alone.
int keep = splitAtTheEnd && appendedAtTheEnd ? left.Keys.Count - 1 : left.Keys.Count / 2;
right.Keys.AddRange(left.Keys.GetRange(keep, left.Keys.Count - keep));
left.Keys.RemoveRange(keep, left.Keys.Count - keep);
return (right.Keys[0], right);
}
private (int Separator, Page Right)? SplitInner(Page left)
{
Splits++;
var right = NewPage(false);
int middle = left.Keys.Count / 2;
int separator = left.Keys[middle]; // the middle key moves up and stays in neither half
right.Keys.AddRange(left.Keys.GetRange(middle + 1, left.Keys.Count - middle - 1));
right.Children.AddRange(left.Children.GetRange(middle + 1, left.Children.Count - middle - 1));
left.Keys.RemoveRange(middle, left.Keys.Count - middle);
left.Children.RemoveRange(middle + 1, left.Children.Count - middle - 1);
return (separator, right);
}
public int Height() { int height = 1; for (var p = root; !p.IsLeaf; p = p.Children[0]) height++; return height; }
// The share of the leaf space that holds keys, and how many leaves there are.
public (double Fill, int Leaves) LeafStats()
{
long keys = 0; int leaves = 0;
var stack = new Stack<Page>();
stack.Push(root);
while (stack.Count > 0)
{
var page = stack.Pop();
if (page.IsLeaf) { leaves++; keys += page.Keys.Count; }
else foreach (var child in page.Children) stack.Push(child);
}
return ((double)keys / ((long)leaves * maxKeys), leaves);
}
}C#
using System;
using System.Diagnostics;
using System.Linq;
const int InsertCount = 200_000;
var scattered = Enumerable.Range(0, InsertCount).ToArray(); // the same keys in random order
var shuffler = new Random(42);
for (int i = scattered.Length - 1; i > 0; i--)
{
int j = shuffler.Next(i + 1);
(scattered[i], scattered[j]) = (scattered[j], scattered[i]);
}
var ascending = Enumerable.Range(0, InsertCount).ToArray();
// Pages of 64 keys, and a cache that holds 500 of them: roughly a tenth of the leaves.
(BPlusTree Tree, int Misses) LoadTree(int[] order, bool splitAtTheEnd)
{
var pool = new BufferPool(500);
var tree = new BPlusTree(64, pool, splitAtTheEnd);
foreach (int key in order) tree.Insert(key);
return (tree, pool.Misses);
}
var randomKeys = LoadTree(scattered, true);
var orderedKeys = LoadTree(ascending, true);
var orderedNaive = LoadTree(ascending, false);
var randomStats = randomKeys.Tree.LeafStats();
var orderedStats = orderedKeys.Tree.LeafStats();
var naiveStats = orderedNaive.Tree.LeafStats();
Debug.Assert(randomStats.Fill > 0.62 && randomStats.Fill < 0.76); // random inserts leave leaves about 69% full
Debug.Assert(orderedStats.Fill > 0.95); // the right-edge split keeps them full
Debug.Assert(naiveStats.Fill > 0.45 && naiveStats.Fill < 0.55); // without it, half empty
Debug.Assert(randomKeys.Misses > InsertCount / 2); // random keys read a cold leaf for most inserts
Debug.Assert(orderedKeys.Misses == 0); // ascending keys only ever touch the cached right edge
Debug.Assert(randomKeys.Tree.Height() == orderedKeys.Tree.Height());| Insert order | Leaf fill | Leaves | Cold-page reads |
|---|---|---|---|
| Random | 70% | 4,474 | 131,875 (66% of inserts) |
| Ascending, right-edge split | 100% | 3,125 | 0 |
| Ascending, plain half split | 50% | 6,249 | 0 |
Random keys make every insert land on an arbitrary leaf. Once the tree outgrows memory that leaf is usually not cached, so each insert waits for a disk read (and later causes a random page write) and the leaves end up two-thirds full. Ascending keys always land on the rightmost leaf, which stays in memory, and engines special-case the split so finished leaves stay full. This is the real reason to prefer an auto-increment or time-ordered primary key (UUIDv7, ULID or a Snowflake-style ID) over a random UUIDv4 in a B-tree engine. The trade-off is that every insert hits the same page, which can become a latch hotspot at very high insert rates; sharding or prefixing the key spreads it.
Other B-tree designs exist. Copy-on-write B-trees (LMDB, bbolt) never overwrite a page. They write new copies of the pages on the path from the changed leaf to the root and then flip a root pointer, so a crash leaves the old tree intact and no log is needed. The price is writing the whole path for each change and, in those two engines, a single writer at a time.
Pages are changed in memory and written to disk later, when the buffer pool decides to. Writing them at every commit would be slow (random writes) and unsafe (a split spans pages). So at commit the engine writes something cheaper: a description of the change, appended to a sequential file called the write-ahead log (WAL, also known as the redo log or journal). Because the log records every change in order, replicas replay it, and change data capture tools read it to stream a database's changes (see logs, streams and Kafka).
Three rules make it work:
- Log first. A log record reaches disk before the data page it describes. This is the write-ahead rule.
- Commit means the log is on disk. The engine answers "committed" only after the log up to that transaction has been flushed.
- Replay on restart. After a crash the engine reads the log from the last checkpoint and reapplies every change the data pages are missing. Each record carries an increasing log sequence number (LSN), and each page stores the LSN of the last record applied to it, so a record is applied only if the page is older. Replay can be run twice, or interrupted and restarted, and give the same result.
A checkpoint flushes dirty pages and notes how much of the log can be ignored, so recovery time depends on the log written since the last checkpoint and not on the age of the database. Frequent checkpoints shorten recovery and cost more write I/O. Real engines add transaction ids, commit records and an undo pass for changes of transactions that never committed but whose pages were written early (the ARIES design: redo everything, then undo the losers; the transactions and isolation levels lesson builds on this). The sample below is the redo core.
C# · LogRecord, Disk, MiniEngine
using System;
using System.Collections.Generic;
public sealed record LogRecord(long Lsn, int Page, int Value, uint Checksum)
{
public static LogRecord Make(long lsn, int page, int value) => new LogRecord(lsn, page, value, Sum(lsn, page, value));
public bool IsIntact => Checksum == Sum(Lsn, Page, Value);
private static uint Sum(long lsn, int page, int value) // FNV-1a over the three fields
{
uint hash = 2166136261;
foreach (long part in new[] { lsn, page, value })
for (int shift = 0; shift < 64; shift += 8) hash = (hash ^ (byte)(part >> shift)) * 16777619;
return hash;
}
}
public sealed class Disk // everything here survives a crash
{
public readonly Dictionary<int, (int Value, long Lsn)> Pages = new Dictionary<int, (int Value, long Lsn)>();
public readonly List<LogRecord> Log = new List<LogRecord>();
}
public sealed class MiniEngine
{
private readonly Disk disk;
private readonly Dictionary<int, (int Value, long Lsn)> cache = new Dictionary<int, (int Value, long Lsn)>(); // lost in a crash
private readonly List<LogRecord> logBuffer = new List<LogRecord>(); // lost in a crash
private long nextLsn = 1;
public long FlushedLsn { get; private set; }
public int LogFlushes { get; private set; }
public MiniEngine(Disk disk) { this.disk = disk; }
public void Write(int page, int value)
{
var record = LogRecord.Make(nextLsn++, page, value);
logBuffer.Add(record); // 1. describe the change in the log
cache[page] = (value, record.Lsn); // 2. change the page, in memory only
}
public void Commit() => FlushLog(); // "committed" may be said only after this returns
private void FlushLog()
{
if (logBuffer.Count == 0) return;
disk.Log.AddRange(logBuffer); // one sequential write and one fsync, however many records
FlushedLsn = logBuffer[logBuffer.Count - 1].Lsn;
logBuffer.Clear();
LogFlushes++;
}
public void FlushPage(int page) // the buffer pool may write a dirty page whenever it likes
{
if (!cache.TryGetValue(page, out var entry)) return;
if (entry.Lsn > FlushedLsn) FlushLog(); // write-ahead rule: its log record reaches the disk first
disk.Pages[page] = entry;
}
// After a crash only the Disk is left. Replay the log; a page's own LSN says whether a record is already applied.
public static Dictionary<int, int> Recover(Disk disk)
{
foreach (var record in disk.Log)
{
if (!record.IsIntact) break; // a torn write at the end of the log: stop there
if (!disk.Pages.TryGetValue(record.Page, out var page) || page.Lsn < record.Lsn)
disk.Pages[record.Page] = (record.Value, record.Lsn);
}
var state = new Dictionary<int, int>();
foreach (var pair in disk.Pages) state[pair.Key] = pair.Value.Value;
return state;
}
}The test below crashes the toy engine at 500 random points, tearing the last log record half of the time, and checks that recovery produces exactly the writes whose log records had reached the disk. It also asserts the write-ahead rule (no page on disk is newer than the flushed log) and that recovering a second time changes nothing.
C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
var crashRandom = new Random(2024);
for (int trial = 0; trial < 500; trial++)
{
var diskState = new Disk();
var mini = new MiniEngine(diskState);
var written = new List<(int Page, int Value)>(); // the write with LSN n is written[n - 1]
int steps = crashRandom.Next(5, 80);
for (int step = 0; step < steps; step++)
{
switch (crashRandom.Next(10))
{
case 0: mini.Commit(); break;
case 1: case 2: mini.FlushPage(crashRandom.Next(8)); break;
default:
int page = crashRandom.Next(8), value = crashRandom.Next(1000);
mini.Write(page, value);
written.Add((page, value));
break;
}
}
// The crash: memory is gone, and half of the time the last log write was torn.
if (crashRandom.Next(2) == 0)
{
var torn = LogRecord.Make(mini.FlushedLsn + 1, 3, 999);
diskState.Log.Add(torn with { Checksum = ~torn.Checksum });
}
var expected = new Dictionary<int, int>(); // exactly the writes whose log record reached the disk
for (int i = 0; i < mini.FlushedLsn; i++) expected[written[i].Page] = written[i].Value;
Debug.Assert(diskState.Pages.Values.All(p => p.Lsn <= mini.FlushedLsn), "a page reached the disk before its log record");
var recovered = MiniEngine.Recover(diskState);
Debug.Assert(recovered.Count == expected.Count && expected.All(pair => recovered[pair.Key] == pair.Value), "recovery lost or invented a write");
var recoveredAgain = MiniEngine.Recover(diskState); // a crash during recovery is just another recovery
Debug.Assert(recoveredAgain.Count == recovered.Count && recovered.All(pair => recoveredAgain[pair.Key] == pair.Value));
}
// Fifty transactions that commit together share one flush.
var alone = new MiniEngine(new Disk());
var together = new MiniEngine(new Disk());
for (int n = 0; n < 1_000; n++)
{
alone.Write(n % 8, n);
alone.Commit();
together.Write(n % 8, n);
if (n % 50 == 49) together.Commit();
}
Debug.Assert(alone.LogFlushes == 1_000 && together.LogFlushes == 20);Torn pages and checksums
A 16 KB page is bigger than the unit a disk writes atomically, so a crash in the middle of a page write can leave half of the old page and half of the new one. Engines defend differently. InnoDB writes pages twice, first into a doublewrite area and then in place. PostgreSQL puts a full copy of the page in the log the first time it changes after a checkpoint (full_page_writes). Copy-on-write designs never overwrite. Log records carry checksums, so a half-written record at the tail is recognised and ignored, as the sample does.
fsync, and what a commit costs
"Committed" has to mean the log is on stable storage, and that costs one flush. If a flush takes 1 ms and every commit paid for its own, the whole database could not commit more than about 1,000 transactions a second. Real systems do far better by group commit: while one flush is in progress, other transactions finish their work and queue for the next one, and a single flush then covers all of them.
With 50 transactions sharing each flush, the same 1,000 flushes a second carry 50,000 commits a second. The sample counts it: 1,000 commits flushed one by one need 1,000 flushes, and 1,000 commits that share a flush 50 at a time need 20. Each commit waits for at most about two flush times (the flush already running, then its own). PostgreSQL and MySQL group commits automatically, and PostgreSQL's commit_delay can add a short wait to gather more.
Durability is also a setting. PostgreSQL's synchronous_commit = off, MySQL's innodb_flush_log_at_trx_commit = 2 and Redis's appendfsync everysec acknowledge before the flush, so a crash can lose the last fraction of a second of acknowledged commits, but the log still keeps the data consistent. That is a business decision, not a free speed-up. In a replicated system, durability often comes from a quorum of replicas holding the write rather than from one machine's flush (see consistency and availability).
When fsync fails
Do not retry a failed fsync. In 2018 PostgreSQL developers found that after a failed write-back Linux can drop the dirty pages and report success on the next fsync, so a retry "succeeds" while the data is gone. PostgreSQL now treats an fsync failure as fatal: it crashes and recovers from the log. The same caution applies to any code that writes files and trusts a flush.
A B-tree pays for sorted order on every write by finding the right page. An LSM tree keeps the sorting but defers it. A write goes into a sorted structure in memory, the memtable, and into a write-ahead log for durability. When the memtable reaches a size, usually tens of megabytes, it is written out as one immutable sorted file, a sorted run (an SSTable in Bigtable's vocabulary). Files accumulate, and background compaction merges them into larger ones, dropping overwritten values and deleted keys.
A write is one sequential log append and one in-memory insert, with no random I/O. A read is where the bill arrives: look in the memtable, then in files from newest to oldest, and stop at the first hit. A key that does not exist must be checked against every file, which is read amplification. Engines keep it in check with three tools:
- A Bloom filter per file: a small in-memory bit array that answers "definitely not here" or "maybe here". About 10 bits per key gives roughly a 1% false-positive rate, so almost all useless file reads are skipped without touching the disk. The probabilistic data structures lesson derives the numbers.
- A sparse index and a block cache per file, so a probe reads one block.
- Compaction itself, which keeps the number of files bounded.
Deletes are writes. Deleting a key appends a marker called a tombstone, and the space comes back only when compaction merges the tombstone with the data it covers. Distributed stores keep tombstones for a grace period so every replica learns of the delete (Cassandra's gc_grace_seconds defaults to ten days). A workload that writes and deletes constantly, such as a queue stored in a table, makes range scans wade through tombstones; Cassandra warns at 1,000 tombstones in one read and aborts at 100,000 by default.
Leveling and tiering
Two policies decide when files merge. Leveling keeps one sorted run per level and merges every arrival into it, so reads are cheap and space is tight, but data is rewritten again and again. Tiering lets runs pile up in a level and merges them only when enough have gathered, so each entry is rewritten once per level, but reads must check more runs and old versions linger. Real engines refine both: LevelDB and RocksDB split each level into many small files and merge only the files that overlap, and Cassandra's size-tiered strategy merges files of similar size.
The sample below models both policies with a memtable of 1,000 keys and a size ratio of 10 between levels, and counts what happens.
C# · Bloom, Run, MergePolicy, …
using System;
using System.Collections.Generic;
using System.Linq;
public sealed class Bloom
{
private readonly ulong[] bits;
private readonly int size;
private readonly int hashes;
public Bloom(int expectedKeys, int bitsPerKey)
{
size = Math.Max(64, expectedKeys * bitsPerKey);
hashes = Math.Max(1, (int)Math.Round(bitsPerKey * Math.Log(2))); // the best count for this many bits per key
bits = new ulong[(size + 63) / 64];
}
private static ulong Mix(ulong x) // a well-known 64-bit finalizer (splitmix64)
{
x += 0x9E3779B97F4A7C15UL;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9UL;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBUL;
return x ^ (x >> 31);
}
private IEnumerable<ulong> Positions(long key)
{
ulong h1 = Mix((ulong)key), h2 = Mix(h1) | 1; // two hashes make as many as we like
for (int i = 0; i < hashes; i++) yield return (h1 + (ulong)i * h2) % (ulong)size;
}
public void Add(long key) { foreach (ulong bit in Positions(key)) bits[bit >> 6] |= 1UL << (int)(bit & 63); }
public bool MightContain(long key) => Positions(key).All(bit => (bits[bit >> 6] & (1UL << (int)(bit & 63))) != 0);
}
// An immutable sorted file (an "SSTable"). Probing it costs one block read, unless the Bloom filter rules the key out.
public sealed class Run
{
public readonly long[] Keys;
private readonly Bloom filter;
public Run(long[] sortedKeys, int bitsPerKey)
{
Keys = sortedKeys;
if (bitsPerKey == 0) return;
filter = new Bloom(sortedKeys.Length, bitsPerKey);
foreach (long key in sortedKeys) filter.Add(key);
}
public bool Probe(long key, ref int blockReads)
{
if (filter != null && !filter.MightContain(key)) return false; // answered from memory
blockReads++;
return Array.BinarySearch(Keys, key) >= 0;
}
}
public enum MergePolicy { Leveling, Tiering }
// Leveling: one run per level, and every arrival is merged into it. Tiering: up to `ratio` runs per level, merged only when full.
public sealed class Lsm
{
private readonly MergePolicy policy;
private readonly int memtableLimit, ratio, bitsPerKey;
private readonly SortedSet<long> memtable = new SortedSet<long>();
private readonly List<List<Run>> levels = new List<List<Run>>(); // each level lists its runs, newest first
public long Ingested { get; private set; }
public long Written { get; private set; } // entries written to files: flushes and merges
public Lsm(MergePolicy policy, int memtableLimit, int ratio, int bitsPerKey)
{
this.policy = policy; this.memtableLimit = memtableLimit; this.ratio = ratio; this.bitsPerKey = bitsPerKey;
}
public void Put(long key)
{
Ingested++;
memtable.Add(key);
if (memtable.Count >= memtableLimit) Flush();
}
private void Flush()
{
var run = new Run(memtable.ToArray(), bitsPerKey);
memtable.Clear();
Written += run.Keys.Length;
Place(run, 0);
}
private long Capacity(int level) => (long)memtableLimit * (long)Math.Pow(ratio, level + 1);
private void Place(Run incoming, int depth)
{
while (levels.Count <= depth) levels.Add(new List<Run>());
var level = levels[depth];
if (policy == MergePolicy.Leveling)
{
var merged = incoming;
if (level.Count > 0)
{
merged = new Run(MergeTwo(incoming.Keys, level[0].Keys), bitsPerKey);
Written += merged.Keys.Length;
level.Clear();
}
if (merged.Keys.Length > Capacity(depth)) Place(merged, depth + 1); // full: push it down a level
else level.Add(merged);
}
else
{
level.Insert(0, incoming);
if (level.Count < ratio) return;
var merged = new Run(level.Select(r => r.Keys).Aggregate(MergeTwo), bitsPerKey);
Written += merged.Keys.Length;
level.Clear();
Place(merged, depth + 1);
}
}
private static long[] MergeTwo(long[] a, long[] b) // both sorted; a key in both is kept once
{
var result = new List<long>(a.Length + b.Length);
int i = 0, j = 0;
while (i < a.Length && j < b.Length)
{
if (a[i] < b[j]) result.Add(a[i++]);
else if (a[i] > b[j]) result.Add(b[j++]);
else { result.Add(a[i]); i++; j++; }
}
while (i < a.Length) result.Add(a[i++]);
while (j < b.Length) result.Add(b[j++]);
return result.ToArray();
}
public bool Get(long key, out int blockReads)
{
blockReads = 0;
if (memtable.Contains(key)) return true;
foreach (var level in levels)
foreach (var run in level)
if (run.Probe(key, ref blockReads)) return true;
return false;
}
public int RunCount => levels.Sum(level => level.Count);
public long StoredKeys => memtable.Count + levels.Sum(level => level.Sum(run => (long)run.Keys.Length));
}C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
const int LoadCount = 295_000;
var loadOrder = Enumerable.Range(0, LoadCount).Select(i => (long)i).ToArray();
var loadShuffler = new Random(5);
for (int i = loadOrder.Length - 1; i > 0; i--)
{
int j = loadShuffler.Next(i + 1);
(loadOrder[i], loadOrder[j]) = (loadOrder[j], loadOrder[i]);
}
Lsm LoadLsm(MergePolicy policy, int bitsPerKey)
{
var lsm = new Lsm(policy, 1_000, 10, bitsPerKey); // 1,000 keys in memory, each level ten times larger
foreach (long key in loadOrder) lsm.Put(key);
return lsm;
}
double AverageBlockReads(Lsm lsm, IEnumerable<long> keys)
{
long reads = 0; int count = 0;
foreach (long key in keys) { lsm.Get(key, out int blockReads); reads += blockReads; count++; }
return (double)reads / count;
}
var leveling = LoadLsm(MergePolicy.Leveling, 10);
var tiering = LoadLsm(MergePolicy.Tiering, 10);
double levelingWriteAmp = (double)leveling.Written / leveling.Ingested;
double tieringWriteAmp = (double)tiering.Written / tiering.Ingested;
Debug.Assert(levelingWriteAmp > 8 && levelingWriteAmp < 20); // every entry rewritten about five times per level
Debug.Assert(tieringWriteAmp > 2 && tieringWriteAmp < 4); // once per level
Debug.Assert(leveling.RunCount == 3 && tiering.RunCount == 16); // the price of tiering: more files to consult
var missing = Enumerable.Range(0, 20_000).Select(i => 10_000_000L + i).ToList(); // keys that were never written
var present = Enumerable.Range(0, 20_000).Select(i => (long)(i * 14)).ToList(); // keys that were
var levelingPlain = LoadLsm(MergePolicy.Leveling, 0); // no Bloom filters
var tieringPlain = LoadLsm(MergePolicy.Tiering, 0);
Debug.Assert(AverageBlockReads(levelingPlain, missing) == 3.0 && AverageBlockReads(tieringPlain, missing) == 16.0);
Debug.Assert(AverageBlockReads(leveling, missing) < 0.06 && AverageBlockReads(tiering, missing) < 0.25); // filters skip almost every file
Debug.Assert(AverageBlockReads(tieringPlain, present) > 10 && AverageBlockReads(tiering, present) < 1.3);
double SpaceAmplification(MergePolicy policy)
{
var lsm = new Lsm(policy, 1_000, 10, 10);
var overwrites = new Random(8);
for (int i = 0; i < 400_000; i++) lsm.Put(overwrites.Next(20_000)); // 400,000 writes to 20,000 distinct keys
return (double)lsm.StoredKeys / 20_000;
}
Debug.Assert(SpaceAmplification(MergePolicy.Leveling) < 1.6 && SpaceAmplification(MergePolicy.Tiering) > 5);| Measured in the sample | Leveling | Tiering |
|---|---|---|
| Entries written per entry ingested | 12.4 | 2.7 |
| Runs to consult after 295,000 keys | 3 | 16 |
| Block reads for a missing key, no filters | 3.00 | 16.00 |
| Block reads for a missing key, 10-bit filters | 0.03 | 0.13 |
| Space used after 400,000 overwrites of 20,000 keys | 1.47x | 6.69x |
Read the table as a trade, not a ranking. Tiering writes about a quarter as much as leveling and keeps far more data around that is no longer live. Bloom filters change the read side completely: with them a missing key costs a fraction of a block read, and a present key costs about one. Smaller size ratios shrink the tiering columns and grow the leveling ones, and that ratio is one of the main tuning knobs.
For time-series data with a time-to-live, Cassandra's time-window strategy puts each window's data in its own files, so expired data is dropped by deleting whole files and is never rewritten at all.
Compaction is the cost you schedule
Compaction runs in the background, competing with foreground reads and writes for disk bandwidth. If writes arrive faster than compaction can merge them, level-0 files pile up and every read has to consult more of them. Engines respond by throttling writes before things get worse. RocksDB, for example, by default starts compacting level 0 at 4 files, slows incoming writes at 20 and stops them at 36. These are write stalls, and they show up as latency spikes in an otherwise fast system. Give compaction I/O headroom, alert on pending compaction bytes, and leave free disk space: a merge writes the new files before it deletes the old ones, and size-tiered compaction in the worst case needs roughly half the disk free.
Large values. Merging rewrites values along with keys, which wastes bandwidth when values are big. The WiscKey design keeps keys and small pointers in the LSM tree and appends the values to a separate log, which cuts write amplification sharply at the cost of an extra read and a garbage collector for the value log. RocksDB's BlobDB and TiKV's Titan implement the idea.
| B-tree | LSM tree | |
|---|---|---|
| Write path | Find the page, change it, log it; write the page later | Append to the log, insert in memory; flush sequentially |
| Bytes written per user byte | A whole page per change plus the log | Rewritten by compaction: about once per level (tiering) to several times per level (leveling) |
| Point read | One to two page reads | Memtable and a few files; filters keep a hit near one block |
| Range scan | Excellent, leaves are chained | Good, but merges several sorted files |
| Space | About 70% page fill, plus fragmentation | Compact and compressible, with temporary extra during compaction |
| Latency | Steady; splits and checkpoints add bumps | Fast writes; spikes when compaction falls behind |
| Typical engines | PostgreSQL, MySQL (InnoDB), SQL Server, Oracle, SQLite, MongoDB (WiredTiger) | RocksDB, LevelDB, Cassandra, HBase, Bigtable, ScyllaDB; CockroachDB (Pebble) and TiKV build on LSM engines |
Bytes written per byte stored can be higher or lower on either side, depending on row size and policy. What differs is the shape of the I/O: an LSM tree issues large sequential writes, which is what disks and SSDs do best, and compresses well because its files are sorted and immutable, while a B-tree issues many small random page writes.
How to choose:
- General transactional workloads with secondary indexes, range queries and moderate write rates: a B-tree engine. It is the default for good reasons.
- Heavy ingest (events, metrics, messages, logs) read by key or key prefix, on SSDs: an LSM engine.
- Time series with expiry: an LSM engine with time-window compaction, or time partitions you can drop whole. At metrics scale, a purpose-built time-series store that compresses each series and indexes labels.
- Read-mostly with a strict latency target: a B-tree, or a leveled LSM with a large block cache and Bloom filters.
- Large blobs: neither. Store the blob in object storage and keep a pointer in the database.
Do not pick from a benchmark headline. Run your own mix and watch write amplification at the device, p99 latency while compaction runs, and recovery time after a crash.
An index is another sorted structure, usually a B-tree, keyed by the indexed columns and holding a pointer to the row. How that pointer works differs by engine, and it matters:
- InnoDB stores the table itself as a B+tree on the primary key (a clustered index). A secondary index stores the primary key value, so a lookup through it walks two trees, and a wide primary key makes every secondary index entry bigger.
- PostgreSQL stores rows in an unordered heap. Every index, including the primary key, points at a row version in the heap, and an update writes a new row version, which needs new index entries unless the change qualifies as a heap-only update.
Either way, every index must be updated by every insert, and by every update that touches its columns. Five indexes mean about six trees written per insert, plus the space. Add an index when a measured query needs it, and drop the ones the usage statistics say nothing reads.
Composite indexes: equality first, then the range or the sort
A composite index on (a, b, c) is sorted by a, then b within each a, then c. It serves a search on a, on a and b, or on all three, and a range on the first column that is not an equality. It cannot seek on b alone. This is the leftmost prefix rule. The practical recipe:
- Put the columns tested with equality first.
- Then the column you range over or sort by.
- Columns after that can only filter entries the scan already reads, or sit there so the index covers the query.
The sample builds three indexes over the same 100,000 orders (100 customers; 10% open, 30% paid, 50% shipped, 10% cancelled) and counts how many index entries each query has to read.
C# · Col, Order, CompositeIndex
using System;
using System.Collections.Generic;
using System.Linq;
public enum Col { User, Status, Created }
public sealed record Order(int User, int Status, int Created) // Status: 0 open, 1 paid, 2 shipped, 3 cancelled
{
public int Get(Col column) => column switch { Col.User => User, Col.Status => Status, _ => Created };
}
// A B-tree index over several columns, kept as a sorted array of entries so a lookup is a binary search plus a walk.
public sealed class CompositeIndex
{
private readonly Col[] columns;
private readonly Order[] entries;
public CompositeIndex(IEnumerable<Order> rows, params Col[] columns)
{
this.columns = columns;
entries = rows.ToArray();
Array.Sort(entries, (a, b) =>
{
foreach (var column in columns) { int d = a.Get(column).CompareTo(b.Get(column)); if (d != 0) return d; }
return 0;
});
}
// "The newest `limit` orders with these column values and created >= since." Returns how many index entries were read.
public (int Read, List<Order> Rows) Newest(IReadOnlyDictionary<Col, int> equal, int since, int limit)
{
// Only a leading run of equality columns narrows the search; the next column narrows it too if it is the date.
int prefix = 0;
while (prefix < columns.Length && equal.ContainsKey(columns[prefix])) prefix++;
bool dateNarrows = prefix < columns.Length && columns[prefix] == Col.Created;
int ComparePrefix(Order entry, bool withDate)
{
for (int i = 0; i < prefix; i++)
{
int d = entry.Get(columns[i]).CompareTo(equal[columns[i]]);
if (d != 0) return d;
}
return withDate && entry.Created < since ? -1 : 0;
}
int Partition(Func<Order, bool> before) // the first entry for which `before` is false
{
int lo = 0, hi = entries.Length;
while (lo < hi) { int mid = (lo + hi) / 2; if (before(entries[mid])) lo = mid + 1; else hi = mid; }
return lo;
}
int from = Partition(e => ComparePrefix(e, dateNarrows) < 0);
int to = Partition(e => ComparePrefix(e, false) <= 0);
bool Matches(Order e) => e.Created >= since && equal.All(pair => e.Get(pair.Key) == pair.Value);
var rows = new List<Order>();
int read = 0;
if (prefix < columns.Length && columns[prefix] == Col.Created)
{
// The entries come out oldest to newest, so walk back from the end and stop as soon as there are enough.
for (int i = to - 1; i >= from && rows.Count < limit; i--) { read++; if (Matches(entries[i])) rows.Add(entries[i]); }
}
else
{
// Otherwise every candidate must be read, then sorted: a "filesort" in a real database's plan.
for (int i = from; i < to; i++) { read++; if (Matches(entries[i])) rows.Add(entries[i]); }
rows = rows.OrderByDescending(o => o.Created).Take(limit).ToList();
}
return (read, rows);
}
}C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
var orderRandom = new Random(9);
int PickStatus() { int x = orderRandom.Next(10); return x == 0 ? 0 : x <= 3 ? 1 : x <= 8 ? 2 : 3; } // 10% open, 30% paid, 50% shipped, 10% cancelled
var orders = Enumerable.Range(0, 100_000).Select(i => new Order(orderRandom.Next(100), PickStatus(), i)).ToList();
var userStatusDate = new CompositeIndex(orders, Col.User, Col.Status, Col.Created);
var userDateStatus = new CompositeIndex(orders, Col.User, Col.Created, Col.Status);
var statusUserDate = new CompositeIndex(orders, Col.Status, Col.User, Col.Created);
// "Customer 7's ten newest open orders."
var openOfUser = new Dictionary<Col, int> { [Col.User] = 7, [Col.Status] = 0 };
var q1a = userStatusDate.Newest(openOfUser, 0, 10);
var q1b = userDateStatus.Newest(openOfUser, 0, 10);
var q1c = statusUserDate.Newest(openOfUser, 0, 10);
Debug.Assert(q1a.Read == 10 && q1c.Read == 10); // both equalities first, then the date: ten entries read
Debug.Assert(q1b.Read > 40 && q1b.Read < 400); // the date comes before the status: read until ten open ones turn up
Debug.Assert(q1a.Rows.SequenceEqual(q1b.Rows) && q1a.Rows.SequenceEqual(q1c.Rows)); // same answer, different cost
// "Customer 7's ten newest orders", whatever the status.
var ofUser = new Dictionary<Col, int> { [Col.User] = 7 };
var q2a = userStatusDate.Newest(ofUser, 0, 10);
var q2b = userDateStatus.Newest(ofUser, 0, 10);
var q2c = statusUserDate.Newest(ofUser, 0, 10);
Debug.Assert(q2b.Read == 10); // (user, date): already in the right order
Debug.Assert(q2a.Read > 500); // (user, status, date): every order of the customer, then a sort
Debug.Assert(q2c.Read == 100_000); // (status, user, date): no usable prefix, the whole index
Debug.Assert(q2a.Rows.SequenceEqual(q2b.Rows) && q2b.Rows.SequenceEqual(q2c.Rows));
// "Customer 7's open orders from the last 5% of the time range, newest ten."
int recent = 95_000;
var q3a = userStatusDate.Newest(openOfUser, recent, 10);
var q3b = userDateStatus.Newest(openOfUser, recent, 10);
var q3c = statusUserDate.Newest(openOfUser, recent, 10);
Debug.Assert(q3a.Read <= 10 && q3c.Read == q3a.Read); // equality, equality, then a range on the date: a tight slice
Debug.Assert(q3b.Read > q3a.Read && q3b.Read <= 60); // the range on the date is tight; the status is still filtered| Query (newest ten) | (user, status, date) | (user, date, status) | (status, user, date) |
|---|---|---|---|
| Customer 7, open | 10 | 93 | 10 |
| Customer 7, any status | 1,023 | 10 | 100,000 |
| Customer 7, open, last 5% | 5 | 49 | 5 |
Every cell returns the same rows; the numbers are index entries read. The first index is perfect for the first and third queries and poor for the second, because the status sits between the customer and the date, so the entries for one customer are not in date order and the engine must read them all and sort. The second index serves "newest orders for a customer" with or without a status filter, at the price of reading more entries when it filters by status. The third has no use for a query that does not name a status. The usual answer is the index that matches your most frequent query, which here is probably (user, created) plus the status check done on the rows already read, or (user, status, created) if the status filter is almost always present.
Covering, partial and expression indexes
- A covering index contains every column the query needs, so the engine answers from the index alone and never visits the row (an index-only scan). PostgreSQL 11 and later and SQL Server have
INCLUDE (columns)for payload columns that are stored but not sorted. MySQL has noINCLUDE: add the columns at the end of the key. In PostgreSQL an index-only scan also needs the page to be marked all-visible by vacuum. - A partial index (PostgreSQL, SQLite; a filtered index in SQL Server) covers only the rows matching a condition, for example
WHERE status = 'open'. It is small, cheap to maintain and fast to scan. MySQL does not have it. - An expression index indexes a computed value, such as
lower(email), so a query on that exact expression can use it (MySQL 8.0.13 and later supports functional key parts).
Why the planner ignores your index
- The predicate matches too much. Reading a large share of a table through an index means many random page reads, and a sequential scan wins. The break-even is often a few percent to a few tens of percent, depending on storage and caching.
- The column is wrapped in a function or cast.
WHERE lower(email) = ...or a number compared to a string cannot use a plain index onemail. - A leading wildcard, as in
LIKE '%abc', cannot seek in sorted order. - Statistics are stale, so the planner misjudges how many rows match. Refresh them (
ANALYZE) and readEXPLAINoutput for the estimated rows against the actual ones.
For paging through results, an index on the sort key supports keyset pagination (continue from the last key you returned) at constant cost per page, where OFFSET has to read and discard every earlier row. The news feed lesson shows the bug offset paging causes.
Changing indexes on a live table
Building an index on a large table reads the whole table and can block writes. PostgreSQL's CREATE INDEX CONCURRENTLY and MySQL's online DDL build it while writes continue, at the cost of more time, more I/O and replication lag to watch. A failed concurrent build in PostgreSQL leaves an invalid index that must be dropped. For changes that rewrite the table itself, tools such as gh-ost and pt-online-schema-change copy the table in the background while capturing changes, then swap.
Other index families exist for other questions: hash indexes for exact matches only, inverted indexes for text (the search and inverted indexes lesson builds one, and its immutable segments and background merges are the LSM idea again), and spatial trees for location. LSM-based databases index secondary keys by writing more LSM entries, so a uniqueness check on a secondary index forces a read that a plain insert would have avoided.
| Situation | What happens | Defence |
|---|---|---|
| Power loss mid-write | A torn page or a half-written log record | WAL with checksums; doublewrite or full-page logging |
| fsync reports an error | The kernel may drop dirty data and report success next time | Treat as fatal, restart and recover from the log; never retry |
| Disk write cache lies | "Durable" commits vanish after a power cut | Drives with power-loss protection; test with pg_test_fsync or similar |
| Silent corruption | A wrong value is read with no error | Page and block checksums, scrubbing, replicas (or erasure-coded fragments, see erasure coding and durability) to repair from |
| LSM write stall | Writes slow, then stop; p99 spikes | Compaction I/O budget, headroom, alert on pending compaction bytes |
| Tombstone pile-up | Range scans slow down; memory spikes | Avoid queue-in-a-table, use TTL with time-window compaction |
| Disk fills during compaction | Compaction cannot finish; the node stalls | Alert on free space well before it is full |
| Hot right edge | Contention on the last leaf at very high insert rates | Shard or prefix keys, batch inserts |
| Index bloat | Large, half-empty indexes after churn | Rebuild (REINDEX), a lower fill factor where updates are common |
| Long index build | Blocked writes or replica lag | Concurrent or online build, off-peak, watch replication |
Interviewer follow-upL5Why are LSM trees good at writes, and what do you pay for it?How to answer
A write is an in-memory insert plus a sequential log append, so there is no random I/O on the write path. The cost moves elsewhere. Reads may consult several files, which Bloom filters, block caches and compaction keep in check. Compaction rewrites data in the background, so bytes written to disk exceed bytes written by the application, and it competes with foreground traffic and can stall writes if it falls behind. Deletes are tombstones, so space comes back only after compaction.
Interviewer follow-upL5A query filters on user and status and sorts by date. What index do you create, and why that order?How to answer
(user_id, status, created_at): both equalities first, then the sort column. The engine seeks to the first entry for that user and status and reads the newest ten in order, with no sort. It also serves queries on user_id alone. If the status filter is rarely present, (user_id, created_at) serves both the filtered and the unfiltered query and checks status on the rows it reads. Confirm with EXPLAIN, and add INCLUDE columns if the query only needs a few more fields.
Interviewer follow-upL6Insert throughput falls as the table grows, and the primary keys are random UUIDs. Why?How to answer
Random keys put every insert in a random leaf. Once the tree outgrows memory that leaf is usually a cold page, so each insert needs a disk read and later a random write, and splits leave pages about two-thirds full. In a clustered engine such as InnoDB it also scatters the table's rows, and every secondary index entry carries the wider key. Use a time-ordered ID (UUIDv7, ULID, Snowflake-style) or an auto-increment key so inserts append at the right edge, and keep any external UUID as a secondary unique column. Mention the trade-off: one hot right edge can contend at extreme insert rates.
Interviewer follow-upL6How can a database commit 50,000 transactions a second when an fsync takes a millisecond?How to answer
Group commit. Transactions that finish while a flush is running wait for the next one, and one flush covers all of them, so 1,000 flushes a second carry tens of thousands of commits, and each commit waits for about two flush times. The log is sequential, so each flush is one cheap write. Drives with power-loss protection make the flush itself much faster. If the business accepts losing the last fraction of a second, asynchronous commit removes the wait, and a replicated system can treat a quorum of replicas as the durable copy.
Interviewer follow-upL6What happens if the database crashes halfway through a page split?How to answer
The split's changes were described in the log before any page was written. On restart the engine reads the log from the last checkpoint and reapplies records to pages whose LSN is older, which finishes the split. A page that was torn mid-write is repaired from a full-page image in the log (PostgreSQL) or from the doublewrite area (InnoDB). A torn record at the end of the log fails its checksum and is discarded, which is safe because its commit was never acknowledged.
Interviewer follow-upL6Cassandra read latency climbs for an hour every few hours, then recovers. What do you check?How to answer
Work from the read path outward. How many SSTables does a read touch, and has the pending-compaction backlog grown? Is a repair or a big compaction using the disk? How many tombstones does each read scan? Are there long garbage-collection pauses, or oversized partitions? The Bloom filter false-positive ratio and cache hit rates tell you whether reads are needlessly reaching disk. The fix follows the finding: a different compaction strategy (time-window for TTL data), throttled repair and compaction, a bounded data model, or more headroom.
Interviewer follow-upL7Choose an engine for ingesting a million small events a second, mostly read by recent time and key.How to answer
An LSM-based store, partitioned by time so expiry drops whole files. Size the I/O first: a million 200-byte events a second is about 200 MB/s of user writes. At a write amplification near 3 (tiering, as in the sample) that is roughly 600 MB/s of device writes per copy, and at 12 (leveling) about 2.4 GB/s, so the compaction policy decides the hardware and the SSD wear. Batch writes, rely on replication for durability instead of an fsync per event, keep secondary indexes few, and monitor write amplification and compaction backlog from day one.
Interviewer follow-upL7You must add an index to a 2 TB production table with no downtime. How?How to answer
Use the engine's online build (CREATE INDEX CONCURRENTLY in PostgreSQL, online DDL in MySQL) so writes continue, rehearse it on a clone to estimate duration and I/O, and run it off-peak with replication lag and free disk space on a dashboard. Do not let the application depend on the index until the build is valid, and have a rollback (drop the invalid index). If the change rewrites the table, use a shadow-table tool such as gh-ost that copies in the background, captures changes, and cuts over in a short lock.
Interviewer follow-upL7State the RUM conjecture and use it to argue about a design.How to answer
Read, update and memory overheads cannot all be minimised: bounding two forces a minimum on the third. A B-tree keeps reads and space reasonable and pays on updates (page rewrites, splits). Leveled LSM protects reads and space and pays on updates through compaction. Tiered LSM protects updates and pays on reads and space. Bloom filters and caches spend memory to buy read speed. Say which two your workload needs and which cost you will watch.
When a design needs a database, state the access pattern before the product name: how many writes and reads a second, whether reads are by key or by range, how large the data is, whether the data expires, and what must survive a crash. Then choose the engine family and say why. "Mixed transactional reads and writes with range queries and secondary indexes, so a B-tree engine such as PostgreSQL; the write-ahead log makes commits durable and group commit keeps it fast." Or "a million small events a second, mostly appended and read by recent time, so an LSM store with time-window compaction; I would watch write amplification and compaction backlog."
A storage engine stores data in pages, finds it again quickly and keeps it safe through a crash. A B-tree keeps sorted pages and updates them in place, so lookups are cheap and predictable, inserts want ordered keys, and a write-ahead log with group commit makes commits durable. An LSM tree appends to a log and a memtable, flushes sorted immutable files and merges them in the background, which gives it fast sequential writes and compact files, and costs it extra reads, compaction work and tombstones. Leveling trades write cost for read and space cost, tiering the reverse, and Bloom filters make reads cheap in both. Indexes are more sorted structures: order composite columns with equality first and the range or sort column next, cover only what a query needs, and remember that every index taxes every write.
Try answering out loud before you reveal each answer.
QuestionA table has 1 billion rows and a B-tree primary key. Roughly how many disk reads does a lookup by key take, and why?Reveal answer
About one. The tree is four levels deep, but the inner pages are a few hundred megabytes in total and stay cached, so only the leaf must be read from disk. A hundred times more rows adds one level, not a hundred times the reads.
QuestionAn application inserts random UUIDv4 primary keys into a large InnoDB table and gets slower as the table grows. What would you change and why?Reveal answer
Switch to a time-ordered key (UUIDv7, ULID or an auto-increment) so inserts append to the right edge of the tree. Random keys land on a random leaf, which is usually not in memory, so every insert pays a disk read, leaves fill to about two-thirds, and the wider key is copied into every secondary index.
QuestionWhy must a log record reach disk before the data page it describes, and what lets recovery run twice safely?Reveal answer
If the page reached disk first and the machine crashed before the log record did, the engine would hold a change it cannot explain or undo. The write-ahead rule prevents that. Each page stores the LSN of the last record applied to it, and recovery applies a record only when the page is older, so applying the log again, or after an interrupted recovery, changes nothing.
QuestionWhy does a missing key cost more in an LSM tree than a present one, and what makes it cheap again?Reveal answer
A present key stops the search at the first file that has it, while a missing key must be checked against every file. A Bloom filter per file answers "definitely not here" from memory, so with about 10 bits per key almost all of those file reads are skipped. In the sample a missing key fell from 16 block reads to 0.13 under tiering.
- Martin Kleppmann, Designing Data-Intensive Applications (opens in a new tab): the storage and retrieval chapter is the standard introduction to B-trees, LSM trees and indexes.
- Patrick O'Neil, Edward Cheng, Dieter Gawlick and Elizabeth O'Neil, The Log-Structured Merge-Tree (LSM-Tree) (opens in a new tab) (Acta Informatica, 1996): the original design.
- Fay Chang et al., Bigtable: A Distributed Storage System for Structured Data (opens in a new tab) (2006): the memtable and SSTable vocabulary the open-source engines inherited.
- Niv Dayan and Stratos Idreos, Dostoevsky (opens in a new tab) (SIGMOD 2018): the leveling and tiering design space, with the cost of each.
- Manos Athanassoulis et al., Designing Access Methods: The RUM Conjecture (opens in a new tab) (EDBT 2016).
- C. Mohan et al., ARIES (opens in a new tab) (ACM TODS, 1992): write-ahead logging with redo, undo and fine-grained locking.
- Lanyue Lu et al., WiscKey: Separating Keys from Values in SSD-conscious Storage (opens in a new tab) (FAST 2016).
- PostgreSQL documentation: Write-Ahead Logging (opens in a new tab) and CREATE INDEX (opens in a new tab) (concurrent builds,
INCLUDE, partial indexes). - PostgreSQL wiki, Fsync Errors (opens in a new tab), and Dan Luu's account, fsyncgate (opens in a new tab): why a failed fsync must not be retried.
- RocksDB wiki: Leveled Compaction (opens in a new tab), Universal Compaction (opens in a new tab) and Write Stalls (opens in a new tab).
- SQLite, Database File Format (opens in a new tab): a complete B-tree page layout in a small, readable specification.
- Markus Winand, Use The Index, Luke (opens in a new tab): a free book on designing SQL indexes.