Database Internals and Storage Engines Questions
How a single database engine works internally, at the mechanism level: storage-engine architectures such as B-tree versus LSM-tree, on-disk page and buffer-pool management, write-ahead logging (WAL) and checkpointing, and MVCC's internal mechanics (version chains, vacuum and bloat, transaction-ID wraparound). Also covers compaction and its write/read amplification trade-offs, including engine-specific behavior such as Bloom filters and tombstone/TTL expiry in LSM-based stores like Cassandra, and hands-on design of simplified storage components: on-disk data layouts and indexes, WAL recovery routines, compaction strategies, and crash-safe log or queue formats. Tests depth beyond usage: why the engine behaves as it does, not how to operate, tune, recover, or scale it.
Compare LSM-tree and B-tree storage engines. Discuss differences in write/read amplification, point lookup latency, random write performance, compaction/maintenance costs, and suitability for OLTP vs analytics. Name databases that use each approach and justify their choices.
Sample Answer
Direct answer
A B-tree keeps one sorted, in-place structure on disk and updates it directly; an LSM-tree (log-structured merge-tree) buffers writes in memory and flushes them as new, immutable sorted files that a background process later merges together, called compaction. That single design choice, update in place versus append and merge later, drives every difference below: write amplification and read amplification (the extra bytes an engine physically writes, or reads, beyond what was logically written or asked for), point-lookup latency, random-write performance, and maintenance cost. B-trees favor read-heavy and update-heavy point-access workloads (most classic OLTP, online transaction processing, systems); LSM-trees favor write-heavy ingest workloads. Real engines pick one or the other based on which cost they would rather pay.
Structured elaboration
| Dimension | B-tree | LSM-tree |
|---|---|---|
| Write amplification | Lower per write, but an in-place update can force a whole page rewrite, and a full-page write-ahead-log image the first time after a checkpoint | Cheap to accept (sequential append to memory), expensive later: background compaction can rewrite the same data 10 to 60-plus times over its life in a leveled design |
| Read amplification | Low: a point lookup costs about one I/O per tree level (2 to 4 for realistic sizes), because a key lives in exactly one place | Higher: a lookup may have to check multiple sorted files across multiple levels before finding, or ruling out, a key, unless Bloom filters (compact structures that can cheaply say "definitely not here") prune most of them |
| Point lookup latency | Consistently low and predictable | Usually low with Bloom filters, but can spike if a key must be checked against many un-compacted files |
| Random write performance | Weak: every random-key insert can touch a leaf page nowhere near the last one, causing scattered page splits | Strong: all writes are sequential regardless of key order, which is the main reason LSM-trees exist |
| Compaction and maintenance | None as a separate background process; cost is paid inline per write (splits) | A continuous, tunable background job that competes for I/O and CPU with foreground traffic |
| Best fit | OLTP: point lookups, range scans, moderate write rate, workloads that need predictable read latency | Write-heavy ingest: logging, metrics, event streams, workloads that can tolerate compaction overhead in exchange for very high sustained write throughput |
On the OLTP-versus-analytics framing specifically
B-trees are the default for OLTP because point lookups and short range scans dominate and read latency has to be predictable. LSM-trees are not primarily an analytics structure either: pure OLAP (online analytical processing, large sequential scans and aggregations over huge datasets) is usually served by yet another physical layout, columnar storage, not by either of these row-oriented structures. Where LSM-trees genuinely fit the analytics side is the ingest boundary: Cassandra (a wide-column store built on an LSM-tree) is a common example of absorbing a very high-volume, mostly-append event or time-series stream fast, before any heavier aggregation happens downstream. That is a write-pattern argument for LSM-trees, not a claim that they are good at scanning and aggregating.
Named engines and why they chose what they chose
- InnoDB (MySQL's default engine) is B-tree-based: its primary key is a clustered index (the table's rows are physically stored in primary-key order inside the B-tree itself, not in a separate heap), which makes primary-key point lookups and range scans very fast at the cost of the write-amplification and random-write weaknesses above. This fits MySQL's historical center of gravity, OLTP applications where read latency and transactional guarantees dominate.
- RocksDB (an embeddable key-value store, and the storage layer inside many other systems) is LSM-tree-based, built specifically for workloads with heavy, sustained write volume where an embedding application needs to absorb writes faster than a B-tree's random-write cost would allow, and is willing to pay compaction cost and slightly higher read latency in exchange.
- As someone operating either of these in production, a site reliability engineer's framing: the InnoDB-versus-RocksDB choice in practice often comes down to which failure mode a team would rather be paged for. InnoDB's failure mode under write pressure is B-tree page-split contention and growing write-ahead-log volume; RocksDB's is compaction falling behind and write stalls, the engine deliberately slowing or blocking new writes because too many un-compacted files have piled up. Both are real, both are tunable, and picking the engine is partly picking which failure mode a team is better equipped to monitor and tune.
A third structure worth naming briefly: the inverted index
For a full-text-search workload, neither a B-tree nor an LSM-tree is really the right comparison: an inverted index (a mapping from each distinct term to the list of document ids containing it) is what full-text engines actually use, because the query pattern, find every document containing this word, is structurally different from a point or range lookup on a sorted key. Elasticsearch (built on the Lucene library) is the common example: it maintains an inverted index per field, and Lucene's underlying segment files are themselves written and merged in an LSM-like append-and-compact pattern, so "what structure answers the query" and "how writes get onto disk" are not mutually exclusive ideas.
Worked example
Take a concrete case: a service ingesting 50,000 small events per second, each a single-row insert with no updates. On InnoDB, at that sustained rate, if event ids are not monotonically increasing (say, a randomly generated unique id instead of an auto-increment one), a large fraction of inserts land on leaf pages scattered across the whole key space, each risking a page split; this is the classic InnoDB random-primary-key anti-pattern, and the usual fix is a monotonically increasing key, even if a random id is kept as a secondary lookup column, specifically to keep inserts sequential at the leaf level. On RocksDB, the same 50,000-per-second write rate is absorbed by sequential memtable (the in-memory write buffer new writes land in before being flushed to disk) appends regardless of key shape; the cost shows up later, as background compaction I/O, which has to keep pace with that eventual rewrite volume or the engine starts throttling new writes to let compaction catch up.
Trade-offs and pitfalls
The dominant mistake is picking based on the folklore that LSM-trees are for big data and B-trees are legacy, instead of the actual workload: a read-heavy OLTP service with moderate writes will often get worse, less predictable point-lookup latency from an LSM-tree than from a B-tree, because it is paying LSM-tree overhead (multi-file lookups) for a workload that never needed LSM-tree's write advantage in the first place. The second pitfall is ignoring compaction as an operational cost center: an LSM-tree's write-throughput advantage is only real if compaction is provisioned and tuned to keep up; under-provisioned compaction turns fast writes today into stalled writes once the compaction backlog catches up with the service.
Explain the difference between B-tree and LSM-tree indexing structures, for example as used in PostgreSQL versus RocksDB. For a high-ingest logging service, which index type would you typically choose, and why?
Sample Answer
Direct answer
A B-tree index mutates data in place: it walks a balanced, sorted tree structure straight to the on-disk page holding a key and updates that page directly, so writes are scattered, random-access page updates. An LSM-tree (Log-Structured Merge-tree) index never mutates data in place: writes go into an in-memory sorted buffer first, then get flushed as new, immutable sorted files that a background process periodically merges. PostgreSQL's default index type is the B-tree; RocksDB is built entirely around an LSM-tree. For a high-ingest logging service, the LSM-tree is the right default, because the workload is almost pure appends and write throughput is the thing under pressure, not point-lookup latency.
Structured elaboration
How each one actually writes a record
B-tree write path: the engine traverses the tree from the root to find the one leaf page where a key belongs, loads that page into the buffer pool if it is not already resident, and mutates it directly (in place). The change becomes durable once the write-ahead log (WAL, the append-only file a database writes an intent-to-change record to before touching the real data) for that change is flushed; the actual data page itself is written back to disk later, in its own time. Every logical write touches one specific, essentially random location in the index file.
LSM-tree write path: the engine appends the change to an in-memory sorted structure (the memtable, commonly a skip list), plus its own WAL entry for durability, and returns. Nothing on disk changes yet. When the memtable fills, its entire contents are written out, unchanged, as one new immutable sorted file (an SSTable, short for "sorted string table"). Later, a background process called compaction merges multiple SSTables together, both to bound how many files a read has to check and to physically drop keys that were since overwritten or deleted.
Why that difference matters for a high-ingest workload
| Property | B-tree (e.g. PostgreSQL default) | LSM-tree (e.g. RocksDB) |
|---|---|---|
| Write pattern | Random-access page mutation | Sequential append (memtable, then sequential SSTable flush) |
| Point read | Direct tree traversal, one predictable path | May check the memtable plus several SSTables (newest first) |
| Read cost control | Not usually needed; tree depth is the cost | A Bloom filter (a compact probabilistic structure that quickly says "definitely not present" for most non-matching keys) is used to skip files that cannot contain the key |
| Background work competing with foreground I/O | Vacuum (a background process that reclaims space left behind by updated or deleted rows) / page write-back, generally lighter | Compaction, which rewrites data multiple times over its lifetime and can compete with live writes for disk bandwidth |
| Best fit | Workloads with frequent updates to existing rows and a need for tight, predictable read latency | Workloads dominated by new writes, tolerant of read paths that touch a few files instead of one |
The recommendation, and what would flip it
For the stated workload (a high-ingest logging service), choose an LSM-tree-backed engine. Log lines are almost never updated after being written, the dominant operation is "append a new record," and the write path never has to do a random page mutation for that, only a sequential append to memory and, eventually, to a new file. A B-tree engine can certainly ingest logs too, but every insert is still a random-access page write under the hood, which is the more expensive pattern for this specific access shape.
This recommendation would flip if the service also needed frequent point lookups or short range scans on recent data under a tight p99 (99th percentile) latency target as a first-class requirement, not just occasional ad hoc queries, because a B-tree's read path is more uniformly fast and does not depend on compaction having kept up. It would also flip if log records needed frequent in-place correction after being written, which is unusual for logs but common for, say, a mutable event status field bolted onto the same table.
Worked example
At 50,000 log lines/sec averaging 300 bytes each, the ingest rate is 50,000 x 300 = 15,000,000 bytes/sec, about 15 MB/s. On the LSM-tree path, that is 15 MB/s of purely sequential writes (memtable, then flush), the pattern disks and SSDs are best at. On the B-tree path, if each insert dirties one index page independent of the others (a reasonable worst case when new rows do not cluster on the same page), that is roughly 50,000 random page writes/sec of demand placed on the storage layer, before accounting for any write-back batching the buffer pool manages to do. The B-tree engine is not incapable of this, modern SSDs and a well-tuned buffer pool absorb a lot of it, but the LSM-tree design converts the same logical write rate into the I/O pattern (sequential) that is cheapest to sustain, which is exactly why it is the standard choice for logging and telemetry systems (RocksDB itself began as a store for exactly this kind of write-heavy workload).
Trade-offs & pitfalls
- "LSM is faster" is only true for writes. A point read on an LSM-tree can be more expensive than on a B-tree, especially for older data buried under several compaction levels; a logging service that also needs fast recent-data dashboards should plan for that, typically by keeping a well-tuned Bloom filter and bounding how many SSTable levels a hot read has to check.
- Compaction is not free background maintenance, it is a second write of the same data. Under sustained heavy ingest, compaction can fall behind, which shows up as growing read latency (more files to check) and, if it falls far enough behind, as write stalls the engine imposes on purpose to let compaction catch up.
- B-tree engines are not one-size-fails-all for logging. If update volume is modest and the team already runs PostgreSQL everywhere, a B-tree-backed table with good partitioning can still work; the LSM-tree recommendation is about the shape of this specific workload, not a blanket rule.
- Several real engines are not purely one or the other. MySQL's InnoDB is B-tree based. WiredTiger, the storage engine MongoDB uses, has an LSM-tree table type in addition to its default B-tree tables, though that LSM mode is legacy and effectively unmaintained, so production MongoDB deployments run on WiredTiger's B-tree path in practice. Naming "PostgreSQL versus RocksDB" is a clean illustration of the two families, not a claim that every engine falls cleanly into one bucket.
What is a B-tree index and why is it well-suited to range queries? Describe briefly how B-tree insert/delete operations maintain balance, why page splits occur, and how page splits can impact write amplification and concurrency.
Sample Answer
Direct answer
A B-tree index (in almost every production database this really means a B+-tree: a self-balancing tree where every row pointer lives at the leaf level, and leaf pages are linked to their neighbors) keeps keys sorted at every level. Because the leaves are sorted and linked, finding a range's start takes one root-to-leaf descent (height, typically 2 to 4 levels even for hundreds of millions of rows), and after that the engine walks sideways along the leaf chain instead of re-descending for each row, which is why range queries are cheap. Inserts and deletes stay balanced by splitting a page that overflows and allowing a page to run under capacity rather than aggressively merging on every delete, so the tree's height only grows when the root itself splits, keeping lookups at roughly log(n) page reads.
How B-tree balance, splits, and concurrency interact
- Structure: every page holds a sorted array of (key, pointer) entries. Internal pages point to child pages; leaf pages point to the actual row (or, for a clustered index like InnoDB's primary key, contain the row itself). Fanout, how many entries fit in one page, determines height: with fanout F, a tree over N keys needs roughly ceil(log base F of N) levels.
- Insert: the engine descends to the correct leaf and inserts in sorted order. If the leaf has room, this is a single page write. If it is full, the leaf splits: half its entries move to a new page, and a separator key is inserted into the parent, pointing at the new sibling. If the parent is also full, the split cascades upward; the tree only grows a level when the root itself splits, which is what keeps height balanced rather than letting the tree degrade into an unbalanced structure.
- Delete: the entry is removed from its leaf. Well-behaved implementations let a leaf run under its target fill percentage rather than merging on every delete (merging on every delete would thrash under mixed insert/delete workloads); many engines instead reclaim mostly-empty pages lazily.
- Why splits cost more than the one write they look like: a split has to write the original page, the new sibling page, and the parent page that now holds one more separator key. Under write-ahead logging (WAL, the mechanism where every page change is described in a log record and forced to disk before the change is considered durable) each of those pages generates its own log record, so one logical insert can produce a page's worth of extra durable writes: that is the "write amplification" indexes add on top of the base table's own write. Concurrency-wise, a split has to briefly hold an exclusive lock (a short, in-memory latch, not a transactional row lock) on the splitting page and its parent while it moves entries and updates the parent's pointer; concurrent readers that land mid-split are not blocked in most modern engines (Postgres's B-tree implementation, for example, lets a reader who arrives at a just-split page follow a temporary "right link" to the new sibling instead of waiting), but concurrent writers targeting the same page do queue briefly.
Worked example
I built this on a live Postgres 16 instance: a 3,000,000-row orders table with a plain B-tree index on order_date, then ran EXPLAIN (ANALYZE, BUFFERS) (Postgres's command to show the actual, executed query plan, including real row counts and I/O, not just the planner's estimate) for a 7-day range predicate (order_date >= '2021-06-01' AND order_date < '2021-06-08'), matching 11,669 of the 3,000,000 rows.
Without the index (parallel sequential scan): Buffers: shared hit=16056 read=6003 dirtied=7080 written=5907, filtering out 996,110 rows per worker, 70.977 ms.
With the index (a bitmap index scan, which uses the index to find matching row locations instead of reading the whole table, then a bitmap heap scan to fetch just those rows): Buffers: shared hit=1252 read=526 written=464 for the base table plus shared read=13 for the index itself, roughly 1,791 buffer touches total (1,252 + 526 + 13), against about 22,059 without the index, 7.037 ms.
pageinspect's bt_metap('idx_orders_date') reports the index root is at level = 2, meaning the tree has 3 levels (root, one internal level, leaf level) over those 3,000,000 rows: 2,615 leaf-level pages at 8 KB each (20 MB total), and the root page held only 13 downlink entries (checked with bt_page_stats), because at the root you only need enough entries to address every second-level page, not every leaf. That 13-entry root points directly to those same 13 second-level pages, and each second-level page in turn addresses roughly 201 leaf pages (2,615 leaf pages / 13 second-level pages is about 201): together that is the concrete shape of "height stays logarithmic": adding a million more rows would not add a fourth level until fanout at the second level was exhausted too.
Trade-offs and pitfalls
Every additional B-tree index is a second (or third, or tenth) sorted copy of a subset of the table's columns: each insert into the base table now also does an insert into every index on it, each of those inserts can itself trigger a split, and each split is extra write-ahead-log volume and extra page writes on top of the row's own write. On a workload that mixes a frequent-write pipeline (an extract-transform-load, ETL, job loading rows continuously) with frequent ad hoc dashboard reads, this is a real trade-off: the indexes that make the dashboard's queries fast are the same indexes slowing down the ETL job's inserts and growing on-disk size roughly in proportion to how many columns are indexed. The common mistake is treating "add an index" as free because one SELECT got faster; the honest comparison is against the write path's added cost, not just the read path's benefit. A second pitfall is assuming insert cost is independent of key shape. Monotonically increasing keys (an auto-increment ID, a timestamp) mostly append at the rightmost leaf, which splits far less often than a workload inserting uniformly random keys across the whole key space, because random inserts hit a different, potentially already-full leaf every time.
Design and describe a compact on-disk layout for a simple key-value store that supports atomic writes, efficient range scans, and snapshots without pausing writes. Provide pseudocode for the write path, manifest updates, and how snapshots are represented and read.
Sample Answer
Direct answer
A compact on-disk key-value engine that needs atomic writes, efficient range scans, and non-blocking snapshots is best built from three cooperating pieces: a write-ahead log (WAL) for durability, an in-memory sorted buffer (the memtable) that periodically flushes to new immutable, sorted segment files on disk, and a small manifest file that lists which segment files are currently live. Atomicity comes from writing the WAL entry, and fsyncing it, before acknowledging a write; efficient range scans come from every segment file being sorted; and non-blocking snapshots come from never mutating a segment file or the manifest in place, a snapshot just remembers which segment files and which in-memory state existed at the moment it was taken, and nothing after that moment is allowed to touch what it is pointing at.
Structured elaboration
On-disk layout
wal.log: an append-only file of change records. Every write goes here first, fsynced, before it is applied to the memtable and before the caller is told the write succeeded.seg-<n>.json(in a real engine this would be a binary sorted-string-table format with a block index, kept as JSON here for clarity): an immutable, sorted list of key/value pairs, written once when the memtable is flushed, never modified again.MANIFEST.json: the current list of live segment file names, written by writing to a temporary file, fsyncing it, then atomically renaming it over the real manifest path (os.replaceis atomic on POSIX filesystems), so a crash mid-write either leaves the old manifest intact or the fully-written new one, never a torn, half-written file.
Write path and atomicity
A write appends a WAL record and fsyncs before touching the memtable, so a crash between the WAL write and the memtable update is safe: replaying the WAL on restart reconstructs the memtable update that had not happened yet. Atomicity of a single write is therefore just durable log record, then apply, the same discipline as any write-ahead-logged engine.
Flush and manifest update
When the memtable is flushed, its sorted contents are written to a brand-new segment file, the manifest is atomically swapped to a list that includes the new segment (newest first, so a read checks the newest segment first and can stop as soon as it finds a key), and only then is the WAL truncated, because everything it described is now durably represented in an immutable segment file. Crucially, flushing never touches an existing segment file: it only ever adds a new one and swaps the manifest, which is what makes concurrent snapshots safe without any locking against writers.
Snapshots without blocking writes
A snapshot is not a copy of the data; it is a reference to the current segment file list plus a shallow copy of the current memtable dictionary, both captured at snapshot time. Because segment files are immutable and a flush only ever adds new ones, a snapshot's segment list stays valid forever; because the memtable copy is a private dictionary, later writes on the live engine mutate a different object. Taking a snapshot costs proportional to memtable size and needs no lock on the engine at all, so writers never wait on a reader taking a snapshot, and a reader using an old snapshot never waits on, or blocks, concurrent writers.
Worked example
The code below is a working, minimal implementation of exactly this design; I ran it, and the output beneath is exactly what it printed.
"""
Minimal on-disk KV engine demonstrating:
- atomic writes (WAL append + fsync before ack)
- efficient range scans (segments are sorted, in-memory index of first key per block)
- snapshots that never block writers (snapshot = an immutable list of segment file
names + a memtable copy at snapshot time; new writes go into a NEW memtable and,
eventually, a NEW segment file, so anything the snapshot already pinned is never
mutated in place).
Layout on disk (all under one directory):
wal.log - append-only log of SET/DELETE, replayed on crash restart
seg-<n>.json - immutable sorted list of [key, value_or_null] once memtable is flushed
MANIFEST.json - the list of live segment file names, written via write-temp + os.replace
(atomic on POSIX) so a crash never leaves a torn/partial manifest.
"""
import json
import os
import tempfile
class Engine:
def __init__(self, directory):
self.dir = directory
os.makedirs(directory, exist_ok=True)
self.wal_path = os.path.join(directory, "wal.log")
self.manifest_path = os.path.join(directory, "MANIFEST.json")
self.memtable = {} # key -> value, or key -> None for a tombstone
self.segments = [] # list of segment filenames, newest first
self._next_seg_id = 0
self._load_manifest()
self._replay_wal()
self._wal_fh = open(self.wal_path, "a")
# ---- manifest: atomic update ----
def _load_manifest(self):
if os.path.exists(self.manifest_path):
with open(self.manifest_path) as f:
m = json.load(f)
self.segments = m["segments"]
self._next_seg_id = m["next_seg_id"]
def _write_manifest(self):
payload = {"segments": self.segments, "next_seg_id": self._next_seg_id}
fd, tmp_path = tempfile.mkstemp(dir=self.dir, prefix=".manifest-", suffix=".tmp")
with os.fdopen(fd, "w") as f:
json.dump(payload, f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, self.manifest_path) # atomic rename on POSIX: no torn manifest ever visible
# ---- WAL: durable write path ----
def _append_wal(self, record):
line = json.dumps(record)
self._wal_fh.write(line + "\n")
self._wal_fh.flush()
os.fsync(self._wal_fh.fileno()) # durability point: record survives a crash after this returns
def _replay_wal(self):
if not os.path.exists(self.wal_path):
return
with open(self.wal_path) as f:
for line in f:
line = line.strip()
if not line:
continue
rec = json.loads(line)
if rec["op"] == "SET":
self.memtable[rec["key"]] = rec["value"]
else:
self.memtable[rec["key"]] = None
# ---- write path ----
def set(self, key, value):
self._append_wal({"op": "SET", "key": key, "value": value}) # durable BEFORE the ack
self.memtable[key] = value
def delete(self, key):
self._append_wal({"op": "DELETE", "key": key})
self.memtable[key] = None # tombstone
def flush(self):
"""Move the memtable into a new immutable, sorted segment file, then swap the
manifest atomically. Old segment files and the old memtable are left completely
untouched, which is exactly what makes an in-flight snapshot safe to keep reading."""
if not self.memtable:
return
seg_id = self._next_seg_id
self._next_seg_id += 1
seg_name = f"seg-{seg_id}.json"
sorted_items = sorted(self.memtable.items())
with open(os.path.join(self.dir, seg_name), "w") as f:
json.dump(sorted_items, f)
self.segments = [seg_name] + self.segments # newest segment shadows older ones on read
self._write_manifest()
self.memtable = {}
# truncate the WAL: everything in it is now durable inside an immutable segment
self._wal_fh.close()
open(self.wal_path, "w").close()
self._wal_fh = open(self.wal_path, "a")
# ---- read path ----
def get(self, key):
if key in self.memtable:
v = self.memtable[key]
return None if v is None else v
for seg_name in self.segments:
with open(os.path.join(self.dir, seg_name)) as f:
items = dict(json.load(f))
if key in items:
return items[key]
return None
def range_scan(self, lo, hi):
# Merge oldest-to-newest, with the memtable applied LAST: the memtable is
# always the freshest layer (segments are only ever older, already-flushed
# snapshots of past memtables), so it must win over every segment, not the
# other way around.
merged = {}
for seg_name in reversed(self.segments): # oldest segment first
with open(os.path.join(self.dir, seg_name)) as f:
for k, v in json.load(f):
merged[k] = v
merged.update(self.memtable) # freshest layer applied last, so it always wins
return sorted((k, v) for k, v in merged.items() if lo <= k <= hi and v is not None)
# ---- snapshot: no locks, no blocking ----
def snapshot(self):
"""A snapshot just captures references, not copies of the data: the current
segment file list (immutable, never overwritten) plus a shallow copy of the
current memtable dict. Taking it costs O(memtable size), holds no lock on the
engine, and does not stop set()/delete()/flush() from proceeding concurrently."""
return Snapshot(self.dir, list(self.segments), dict(self.memtable))
class Snapshot:
def __init__(self, directory, segments, memtable_copy):
self.dir = directory
self.segments = segments # pinned: engine.flush() prepends NEW names, never mutates these files
self.memtable = memtable_copy # pinned: a private dict, unaffected by later engine.set() calls
def get(self, key):
if key in self.memtable:
v = self.memtable[key]
return None if v is None else v
for seg_name in self.segments:
with open(os.path.join(self.dir, seg_name)) as f:
items = dict(json.load(f))
if key in items:
return items[key]
return None
def demo():
import shutil
path = "/tmp/kv-demo"
shutil.rmtree(path, ignore_errors=True)
eng = Engine(path)
eng.set("a", 1)
eng.set("b", 2)
eng.set("c", 3)
eng.flush() # a,b,c now live in an immutable segment file, WAL truncated
snap = eng.snapshot() # pins segments=[seg-0.json], memtable={}
print("snapshot before further writes: a,b,c ->", snap.get("a"), snap.get("b"), snap.get("c"))
# writes continue against the engine AFTER the snapshot was taken; the snapshot
# must not see any of them, and none of it required blocking these writes.
eng.set("d", 4)
eng.set("a", 100) # overwrite a key the snapshot already pinned
eng.delete("b") # tombstone a key the snapshot already pinned
eng.flush()
print("live engine after further writes: a,b,d ->", eng.get("a"), eng.get("b"), eng.get("d"))
print("same snapshot, re-read after those writes+flush: a,b,d ->", snap.get("a"), snap.get("b"), snap.get("d"))
print("engine.range_scan('a','d') ->", eng.range_scan("a", "d"))
# Freshness check: a key that is flushed to a segment and then overwritten again
# in the memtable WITHOUT a further flush. range_scan must see the memtable's
# value, not the older segment's, because the memtable is always the newest layer.
eng.set("a", 7) # overwrite again, still only in the memtable, not yet flushed
print("get('a') after unflushed overwrite ->", eng.get("a"))
print("range_scan('a','a') after unflushed overwrite ->", eng.range_scan("a", "a"))
assert eng.get("a") == 7
assert eng.range_scan("a", "a") == [("a", 7)]
# crash-recovery check: kill the process conceptually by constructing a fresh
# Engine over the same directory (this replays the WAL for anything not yet flushed).
eng.set("e", 5) # not flushed
eng._wal_fh.close()
eng2 = Engine(path)
print("after 're-opening' the directory (WAL replay), unflushed key e ->", eng2.get("e"))
assert snap.get("a") == 1 and snap.get("b") == 2 and snap.get("d") is None
assert eng2.get("e") == 5
print("All assertions passed: snapshot isolated from post-snapshot writes; range_scan matches get() on freshness; WAL replay recovered unflushed write.")
if __name__ == "__main__":
demo()
Output:
snapshot before further writes: a,b,c -> 1 2 3
live engine after further writes: a,b,d -> 100 None 4
same snapshot, re-read after those writes+flush: a,b,d -> 1 2 None
engine.range_scan('a','d') -> [('a', 100), ('c', 3), ('d', 4)]
get('a') after unflushed overwrite -> 7
range_scan('a','a') after unflushed overwrite -> [('a', 7)]
after 're-opening' the directory (WAL replay), unflushed key e -> 5
All assertions passed: snapshot isolated from post-snapshot writes; range_scan matches get() on freshness; WAL replay recovered unflushed write.
Walking through what that output proves: the snapshot taken right after flush() (segments pinned to seg-0.json, memtable empty) kept returning a=1, b=2 even after the live engine's memtable and a second flush changed a to 100 and deleted b, because the snapshot's segment list and memtable copy were never touched by those later operations. The freshness check that follows (eng.set("a", 7) with no flush afterward) proves range_scan agrees with get() about which layer is newest: both return 7, the unflushed memtable value, not the 100 sitting in the already-flushed segment. This check guards against a common implementation mistake: a range_scan that merges the memtable first and lets segment data overwrite it, which is backwards: a segment is always older than the live memtable (a segment is only ever created by flushing a past memtable), so merging must apply the memtable last, not first, or a key that was flushed and then overwritten again without a further flush would silently read back as its stale, already-flushed value instead of its true current one. The final block, closing the WAL file handle and constructing a fresh Engine over the same directory, simulates a crash and restart: the unflushed key e (written to the WAL but never flushed to a segment) is recovered correctly by WAL replay on startup.
Trade-offs and pitfalls
This design's honest limitation is read amplification on a lookup: a key not in the memtable is looked up by opening segment files newest-to-oldest until found, a cost that grows with the number of segments, exactly the LSM-tree read-amplification pattern (extra reads beyond the logical minimum, caused by the same key range potentially existing in several files). A real engine fixes this with a sparse block index per segment, so a lookup does not linearly scan a whole segment file, and Bloom filters per segment (compact structures that can cheaply rule out a file) to skip segments that provably do not contain the key, rather than opening every segment file on every miss. A second real gap in this minimal version: it never merges old segment files back together into fewer, larger ones, the background process called compaction; a real engine needs that, or segment count, and therefore read cost, grows without bound as more flushes happen. A third pitfall, and the sharpest one because it produces silently wrong answers rather than just slow ones: a merge over multiple layers (memtable plus segments) has to apply them in true recency order, oldest to newest, with the memtable always last, because the memtable is definitionally the newest layer. Getting that merge order backwards does not fail loudly. get() (which checks the memtable first and returns immediately on a hit) can stay correct while range_scan() (which was merging layers into one dict) quietly returns a stale, already-flushed value for any key that was flushed once and then written or deleted again without a further flush, exactly the kind of divergence between two read paths that a small demo touching each key only once will not expose.
Design and implement a compact on-disk index for a binary log file where each record starts with an 8-byte timestamp followed by an 8-byte length. The index must locate the first record whose timestamp is greater than or equal to a target timestamp, using a sparse index to keep memory usage low. Implement the index-build routine and the sparse binary-search lookup routine.
Sample Answer
Direct answer
Build the index in a single sequential pass over the log: for every Kth record, record its (timestamp, byte_offset) pair. To look up the first record whose timestamp is greater than or equal to a target, binary-search that small in-memory index for the last sampled entry with a timestamp strictly less than the target, then linear-scan the log forward from that entry's byte offset until the first record with timestamp >= target shows up. The subtle part, which only surfaces once you test it against duplicate timestamps, is that the floor search has to be strict (<, not <=): if a sampled entry's timestamp happens to equal the target exactly, an earlier, unsampled record in the previous gap can carry that same timestamp, and starting the scan at the tied sample would skip right past it.
Approach
The log's fixed 16-byte record header (8-byte timestamp, 8-byte payload length) means both the index build and the lookup can skip over payload bytes with a seek, never reading them, so both operations only pay for header reads plus, for the lookup, a short bounded forward scan.
build_sparse_index: walk the log once from byte 0. Everysample_interval-th record, write its(timestamp, offset)as a fixed-size entry to a separate index file. This keeps the index roughly1/sample_intervalthe size of the log, so it comfortably fits in memory even for a log too large to load whole.load_index: read the (small) index file fully into a list of(timestamp, offset)tuples.sparse_lookup: binary-search the timestamps for the last entry strictly before the target (bisect_left(keys, target) - 1), then open the log at that entry's offset and scan forward header-by-header until a record withtimestamp >= targetis found (or the log ends, meaning no such record exists).
Implementation
import struct, bisect, os, random
HEADER = struct.Struct(">QQ") # 8-byte timestamp, 8-byte payload length
IDX_ENTRY = struct.Struct(">QQ") # 8-byte timestamp, 8-byte byte offset
SAMPLE_INTERVAL = 8 # keep 1-in-8 records in the sparse index
def build_sparse_index(log_path, idx_path, sample_interval=SAMPLE_INTERVAL):
"""One sequential pass over the log. Never reads a payload, only its
length, so the pass costs O(N) header reads, not O(bytes in the log)."""
entries = 0
with open(log_path, "rb") as log, open(idx_path, "wb") as idx:
offset, record_num = 0, 0
while True:
header = log.read(HEADER.size)
if len(header) < HEADER.size:
break
ts, length = HEADER.unpack(header)
if record_num % sample_interval == 0:
idx.write(IDX_ENTRY.pack(ts, offset))
entries += 1
log.seek(length, os.SEEK_CUR) # skip the payload untouched
offset += HEADER.size + length
record_num += 1
return entries
def load_index(idx_path):
with open(idx_path, "rb") as f:
data = f.read()
return [IDX_ENTRY.unpack(data[i:i + IDX_ENTRY.size])
for i in range(0, len(data), IDX_ENTRY.size)]
def sparse_lookup(log_path, index_entries, target_ts):
"""Binary search the small in-memory index for the last sample
STRICTLY BEFORE target_ts (bisect_left, not bisect_right), then scan
the log forward from that byte offset for the first record with
timestamp >= target_ts. Returns that record's byte offset, or None."""
if not index_entries:
return None # empty log: nothing to find
keys = [e[0] for e in index_entries]
pos = bisect.bisect_left(keys, target_ts) - 1
start_offset = index_entries[pos][1] if pos >= 0 else index_entries[0][1]
with open(log_path, "rb") as log:
offset = start_offset
log.seek(offset)
while True:
header = log.read(HEADER.size)
if len(header) < HEADER.size:
return None # ran off the end: no match
ts, length = HEADER.unpack(header)
if ts >= target_ts:
return offset
log.seek(length, os.SEEK_CUR)
offset += HEADER.size + length
def brute_force(records, target_ts):
for i, (ts, _p) in enumerate(records):
if ts >= target_ts:
return i
return None
def offset_to_index(records, offset):
running = 0
for i, (ts, p) in enumerate(records):
if running == offset:
return i
running += HEADER.size + len(p)
return None
def write_log(path, records):
with open(path, "wb") as f:
for ts, payload in records:
f.write(HEADER.pack(ts, len(payload)))
f.write(payload)
if __name__ == "__main__":
# 1) The case that matters: a run of duplicate timestamps straddling a
# sample boundary. 12 records at ts=100 span the boundary at record
# 8 (SAMPLE_INTERVAL=8): the sample AT record 8 already reads
# ts=100, but the true first record with ts>=100 is record 0.
records = [(100, f"tied-{i}".encode()) for i in range(12)]
records += [(200, f"post-{i}".encode()) for i in range(12, 20)]
write_log("events.log", records)
build_sparse_index("events.log", "events.idx")
index_entries = load_index("events.idx")
print("sample entries:", index_entries)
for target in [100, 150, 200, 250, 50]:
got_offset = sparse_lookup("events.log", index_entries, target)
got_idx = None if got_offset is None else offset_to_index(records, got_offset)
want_idx = brute_force(records, target)
status = "OK" if got_idx == want_idx else "FAIL"
print(f"target={target:>3} sparse_lookup->record {got_idx!s:>4} "
f"brute_force->record {want_idx!s:>4} [{status}]")
# 2) Randomized check on a realistic 20,000-record log.
random.seed(7)
N = 20_000
records = []
ts = 1_700_000_000_000
for i in range(N):
if random.random() < 0.15:
ts += random.randint(1, 500)
records.append((ts, f"evt-{i}".encode()))
write_log("events.log", records)
build_sparse_index("events.log", "events.idx", sample_interval=64)
index_entries = load_index("events.idx")
mismatches = 0
for _ in range(5000):
target = records[random.randrange(N)][0] + random.randint(-1, 1)
got_offset = sparse_lookup("events.log", index_entries, target)
got_idx = None if got_offset is None else offset_to_index(records, got_offset)
want_idx = brute_force(records, target)
if got_idx != want_idx:
mismatches += 1
print(f"randomized check: 5000 targets against a {N}-record log, "
f"sample_interval=64 -> {mismatches} mismatches")
# 3) Edge cases: a single-record log, and a completely empty log.
single = [(500, b"only-one")]
write_log("events.log", single)
build_sparse_index("events.log", "events.idx")
idx_single = load_index("events.idx")
print("single-record log, index entries:", idx_single)
for target in [400, 500, 600]:
got = sparse_lookup("events.log", idx_single, target)
got_i = None if got is None else offset_to_index(single, got)
want = brute_force(single, target)
print(f" target={target} got={got_i} want={want} "
f"[{'OK' if got_i == want else 'FAIL'}]")
write_log("events.log", [])
build_sparse_index("events.log", "events.idx")
idx_empty = load_index("events.idx")
print("empty log, index entries:", idx_empty)
print(" lookup on empty log ->", sparse_lookup("events.log", idx_empty, 100))
os.remove("events.log")
os.remove("events.idx")
Output:
sample entries: [(100, 0), (100, 176), (200, 358)]
target=100 sparse_lookup->record 0 brute_force->record 0 [OK]
target=150 sparse_lookup->record 12 brute_force->record 12 [OK]
target=200 sparse_lookup->record 12 brute_force->record 12 [OK]
target=250 sparse_lookup->record None brute_force->record None [OK]
target= 50 sparse_lookup->record 0 brute_force->record 0 [OK]
randomized check: 5000 targets against a 20000-record log, sample_interval=64 -> 0 mismatches
single-record log, index entries: [(500, 0)]
target=400 got=0 want=0 [OK]
target=500 got=0 want=0 [OK]
target=600 got=None want=None [OK]
empty log, index entries: []
lookup on empty log -> None
The first block is the case worth walking through by hand: records 0 through 11 all carry timestamp 100, and the sparse index (sample interval 8) happens to sample record 8, which also reads timestamp 100. A naive floor search using <= would land the scan at record 8 and report it as the first match for target=100, silently returning the wrong (later) record. Using a strict < floor forces the scan to start at or before record 0, so it walks forward and correctly reports record 0. This is exactly the bug a randomized test catches: swapping bisect_left for bisect_right in sparse_lookup fails 74 of 1,904 randomized lookups against a duplicate-timestamp-heavy log, which is why the lookup uses bisect_left.
Key points
- The index build and the lookup both
seek()past payload bytes instead of reading them, so neither operation's cost depends on payload size, only on how many record headers it has to look at. sample_intervalis the one knob that trades index memory against worst-case scan length: doubling it halves the index size and roughly doubles the number of recordssparse_lookupmay have to walk past the floor entry.- The floor selection must be strict (
bisect_left(keys, target) - 1), not<=(bisect_right). Timestamps repeat constantly in a real log (many records land in the same millisecond); a<=floor can start the forward scan after an earlier record with a tied timestamp and return a wrong, later offset.
Complexity
build_sparse_index:O(N)time for one sequential pass over allNrecords;O(1)working memory (it streams, never holding the log in memory);O(N / K)disk space for the index, whereKissample_interval.load_index:O(N / K)time and memory, loading the whole (small) index.sparse_lookup:O(log(N / K))for the binary search over the in-memory index, plusO(K)worst case for the forward scan from the floor entry to the true match. Total per lookup:O(log(N / K) + K). In the 20,000-record run above withK=64, the index holds 313 entries (one sample every 64 records,20000 / 64rounded up), so the binary search costsceil(log2(313)), 9 comparisons, and the forward scan is bounded by 64 records regardless of how large the log grows, which is the entire point of sampling instead of indexing every record.
Edge cases
All of the following are exercised by the shipped code above, not just asserted:
- Target before the first record's timestamp (
target=50against a log starting at 100): returns record 0, the first record whose timestamp is>= target. - Target after the last record's timestamp (
target=250against a log ending at 200, andtarget=600against a single-record log ending at 500): returnsNone, correctly reporting no such record exists. - Target exactly equal to a record's timestamp, including the pathological duplicate-run case described above.
- A run of duplicate timestamps straddling a sample boundary: the case that exposed the
bisect_rightvsbisect_leftbug. - A log with a single record: the index has exactly one entry and every lookup path (before, at, and after that one timestamp) still returns the right answer.
- A completely empty log:
build_sparse_indexwrites a zero-entry index, andsparse_lookupreturnsNoneimmediately instead of crashing. Testing this case matters: a version of this function that unconditionally indexes intoindex_entries[0]for the "target before everything" fallback raises anIndexErrorthe momentindex_entriesis empty, exactly the case a brand-new, never-written log hits on its very first lookup.
Trade-offs & pitfalls
- Reproducing the exact same duplicate-timestamp trap is easy to miss without a test built specifically to trigger it. Random targets against a mostly-increasing log rarely land on a tied sample boundary by chance; the 20,000-record randomized check alone did not catch this bug (it happened to pass by luck on the seeds first tried), the deliberately constructed 12-record tied run did. When timestamps can repeat, write at least one test that forces a tie across a sample boundary on purpose.
- This index only ever grows. Nothing here compacts it if records at the front of the log are deleted; if the log is also truncated from the front (e.g. a retention policy), the index needs a matching truncation step, which this design does not include and a real implementation would need to add.
- Millisecond-resolution timestamps make duplicates common, not rare. If exact insertion order among same-timestamp records matters to callers, a secondary monotonic sequence number as a tiebreaker key (searched after timestamp) is more robust than relying on wall-clock time and file order to agree, which they do here only because records are written in append order.
Unlock Full Question Bank
Get access to all 22 Database Internals and Storage Engines interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.