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.
You are asked to design a simple transactional storage engine prototype that supports ACID guarantees: describe the high-level architecture, core data structures (indexes, append-only log, memtable/sstable or pages), transaction logging (WAL), concurrency control approach (locking vs MVCC), checkpointing and background compaction, and crash recovery algorithm. Focus on the trade-offs for durability, latency, and throughput.
Sample Answer
Direct answer
A transactional storage engine prototype with ACID guarantees (atomicity, consistency, isolation, durability: the four properties a transaction is supposed to provide) needs five cooperating pieces: an in-memory buffer pool holding cached pages, a write-ahead log (WAL) for durability and crash recovery, a concurrency-control mechanism, locking or multi-version concurrency control (MVCC), that keeps concurrent transactions from corrupting each other's view of the data, a background checkpoint (periodically flushing recent changes to durable storage and marking how far crash recovery would need to replay from) and compaction process (merging accumulated on-disk files together so read cost does not grow unbounded) that bounds how much log has to be replayed after a crash, and a crash-recovery routine that rebuilds correct state from the WAL plus whatever made it to durable pages before the crash. The core design decision that shapes everything else is page-oriented in-place storage with a B-tree (favoring predictable read latency, higher per-write cost) versus log-structured storage with an LSM-tree (favoring high write throughput, higher and more variable read cost); this prototype describes the architecture in page and B-tree terms, since it generalizes cleanly to either.
Structured elaboration
graph TD
C[Client transaction] --> BUF[Buffer pool: cached pages]
C --> WAL[WAL: append change record + fsync at commit]
WAL --> BUF
BUF --> PAGES[Data pages / SSTables on disk]
CK[Checkpoint process] -->|flushes dirty pages| PAGES
CK -->|advances redo start point| WAL
CC[Concurrency control: 2PL or MVCC] --> C
CRASH[Crash recovery] -->|replay from last checkpoint| WAL
CRASH -->|reconstruct| PAGES
Core data structures
- Pages: fixed-size units (commonly 4 to 16 KB) holding either index entries (a B-tree's internal and leaf pages) or row data; the unit of I/O and of the buffer pool's caching.
- Buffer pool: an in-memory hash table of page id to cached page, with a dirty flag per page (has this page been modified since it was last written to disk) and an eviction policy (commonly a variant of least-recently-used) to decide what to evict under memory pressure.
- WAL: an append-only log of transaction id, page or key change, and before/after or redo/undo information, plus commit and abort markers.
- Index and data files: a B-tree, or, in the LSM variant, a memtable (in-memory write buffer) plus immutable sorted files merged by compaction.
Transaction logging (WAL)
Every change is written to the WAL and fsynced (forced out of the OS's write buffer and confirmed durably on disk, not just handed to the kernel) before the transaction is allowed to report success: the in-memory page can be modified immediately, but the durability guarantee comes entirely from the log record having reached disk, not from the page write, which can happen later.
Concurrency control: locking versus MVCC
- Two-phase locking (2PL: every transaction acquires all the locks it needs before releasing any of them, guaranteeing serializability but making readers and writers block each other) is simpler to reason about and gives strong isolation directly, at the cost of read and write contention: a long-running writer blocks readers of the same rows, and vice versa.
- MVCC (multi-version concurrency control: each transaction sees a consistent snapshot of committed data as of when it started, while writers create new versions rather than overwriting in place) lets ordinary readers and writers proceed without blocking each other, at the cost of needing a mechanism to garbage-collect old versions and, depending on the isolation level chosen (the rule governing how much of other transactions' concurrent changes a transaction is allowed to see), still needing some locking or conflict detection to prevent write-write conflicts and anomalies like write skew (two transactions each reading a valid individual snapshot but together violating an invariant neither would have permitted alone).
- This prototype's default: MVCC for reads, non-blocking, since read-heavy contention is the common case, combined with row-level or key-range locking specifically for write-write conflicts, the same hybrid most production engines actually use rather than a pure implementation of either extreme.
Checkpointing and background compaction
A checkpoint periodically forces all dirty pages up to some WAL position out to disk and records that position; crash recovery then only needs to replay WAL from the most recent checkpoint forward, not from the beginning of the log, which is what bounds recovery time. In the LSM variant, this same role is partly played by memtable flushing, turning in-memory writes into an immutable file, after which the WAL for those writes can be discarded, plus background compaction merging files together to keep read cost from growing unbounded as more files accumulate.
Crash recovery algorithm
A standard three-phase approach: (1) analysis, scan forward from the last checkpoint to determine which transactions were in progress and which pages were dirty at crash time; (2) redo, replay every logged change from the checkpoint forward, regardless of whether its transaction eventually committed, to bring the data files back to exactly the state they were in at the moment of the crash; (3) undo, roll back the changes made by any transaction still in progress, never committed, at crash time, using the before-image or inverse-operation information the WAL recorded for exactly this purpose. Redoing everything first and undoing incomplete transactions second, rather than trying to skip redoing transactions that look uncommitted, is deliberate: it is simpler and more robust, because it does not require correctly identifying every in-flight transaction before touching any data, only after reconstructing the full crash-time state.
Worked example
Trace a single transaction through this design: begin; update a row, modifying the cached page in the buffer pool and appending a WAL record describing the change, not yet fsynced; commit, which fsyncs the WAL up through this transaction's commit record and only then reports success to the client; the modified page in the buffer pool stays dirty and gets written to disk later, either because it is evicted under memory pressure or because the next checkpoint flushes it. If the process crashes one second after that commit, before the page itself was ever written to disk: on restart, recovery's redo phase replays the WAL record for this transaction's change, since its commit record is present, and reconstructs the modified page in memory correctly, even though the on-disk page file never physically received the write, exactly the property that a WAL record is what is durable and the page write is a lazy optimization on top of it.
Trade-offs and pitfalls
Durability, latency, and throughput pull against each other at almost every decision point here: fsyncing every commit's WAL individually gives the strongest per-transaction durability guarantee but the worst latency and throughput under concurrent load, unless group commit, batching multiple transactions' WAL flushes into one fsync, is implemented; choosing 2PL over MVCC gives simpler correctness reasoning but worse concurrency for read-heavy workloads; a short checkpoint interval bounds recovery time tightly but adds continuous background I/O competing with foreground traffic. The common design mistake is picking each of these independently, tightest possible durability, most concurrent possible reads, shortest possible checkpoint interval, without recognizing they compound: a system tuned that way pays every latency and I/O cost simultaneously instead of choosing where it can actually afford to spend budget for the workload it is built for.
Implement a simplified write-ahead log recovery routine in Python. Input: a list of log entries representing transactions with operations (BEGIN, SET key value, DELETE key, COMMIT, ABORT). The recovery routine should apply REDO for committed transactions and skip or UNDO uncommitted ones to rebuild final key-value state. Provide function(s) and ensure idempotence if the recovery runs twice. Show sample input and expected output.
Sample Answer
Direct answer
A write-ahead log (WAL) replay for crash recovery needs exactly two passes: first classify every transaction in the log as committed or not (a transaction with no COMMIT record at all, meaning the engine crashed mid-transaction, or one that reached an explicit ABORT, must be treated as if it never happened), then replay only the SET/DELETE operations belonging to committed transactions, in log order, to rebuild the final key-value state. Doing it as two passes over the same immutable log, rather than mutating state incrementally and trying to undo it later, is what makes the routine trivially idempotent: running it again from the same log produces the identical two-pass result every time.
Approach
- Pass 1 (analysis): scan every log entry once, tracking which transaction ids reach
COMMITand removing any that later hitABORT(an abort after a stray commit record, which should not happen in a correct log but is handled defensively, always wins). - Pass 2 (redo): scan the log again in order, applying only
SET/DELETEoperations whose transaction id is in the committed set from pass 1, building the final key-to-value dictionary from an empty starting state. - Because state is always rebuilt from empty rather than mutated on top of a previous partial run, calling recovery twice on the same log is guaranteed to produce the same output both times: there is no persistent recovery state to get out of sync.
Code (Python)
"""
Simplified write-ahead log (WAL) crash-recovery routine.
Log entry shapes (as plain dicts, matching a real WAL record layout):
{"op": "BEGIN", "txn": <int>}
{"op": "SET", "txn": <int>, "key": <str>, "value": <any>}
{"op": "DELETE", "txn": <int>, "key": <str>}
{"op": "COMMIT", "txn": <int>}
{"op": "ABORT", "txn": <int>}
Recovery contract:
- Only operations belonging to a txn that reached COMMIT are applied (REDO).
- Operations belonging to a txn that never reached COMMIT (no COMMIT record
at all, or an explicit ABORT) are skipped (equivalent to UNDO, since we
never applied them to the key-value state in the first place).
- Running recovery twice on the same log must produce the same final state
(idempotent), because recovery always rebuilds state from empty rather
than mutating a partially-applied state.
"""
def recover(log_entries):
"""Rebuild final key-value state from a WAL by replaying only committed txns."""
# Pass 1 (analysis): classify every txn id as committed or not.
committed_txns = set()
seen_txns = set()
for entry in log_entries:
txn = entry["txn"]
seen_txns.add(txn)
if entry["op"] == "COMMIT":
committed_txns.add(txn)
elif entry["op"] == "ABORT":
committed_txns.discard(txn) # explicit abort overrides any stray commit-before-abort ordering
# Pass 2 (redo): replay SET/DELETE only for committed txns, in log order.
state = {}
for entry in log_entries:
op, txn = entry["op"], entry["txn"]
if op in ("SET", "DELETE") and txn in committed_txns:
if op == "SET":
state[entry["key"]] = entry["value"]
else: # DELETE
state.pop(entry["key"], None)
aborted_or_incomplete = seen_txns - committed_txns
return state, aborted_or_incomplete
def demo():
log = [
{"op": "BEGIN", "txn": 1},
{"op": "SET", "txn": 1, "key": "a", "value": 10},
{"op": "SET", "txn": 1, "key": "b", "value": 20},
{"op": "COMMIT", "txn": 1},
{"op": "BEGIN", "txn": 2},
{"op": "SET", "txn": 2, "key": "a", "value": 99}, # will be aborted, must NOT be visible
{"op": "ABORT", "txn": 2},
{"op": "BEGIN", "txn": 3},
{"op": "SET", "txn": 3, "key": "c", "value": 30},
{"op": "DELETE", "txn": 3, "key": "a"},
{"op": "COMMIT", "txn": 3},
{"op": "BEGIN", "txn": 4},
{"op": "SET", "txn": 4, "key": "d", "value": 40},
# no COMMIT for txn 4: engine crashed mid-transaction, must NOT be visible
]
state1, incomplete1 = recover(log)
print("Recovery run #1 ->", state1)
print("Txns skipped (aborted/incomplete) ->", sorted(incomplete1))
# Idempotence check: recovering from the *same* log again (e.g. the
# engine crashes again during/after the first recovery, before any new
# writes happen) must yield an identical state.
state2, incomplete2 = recover(log)
print("Recovery run #2 ->", state2)
assert state1 == state2, "recovery is not idempotent!"
print("Idempotent: state1 == state2 ->", state1 == state2)
expected = {"b": 20, "c": 30, "d": None} # sanity check the intended semantics by hand
assert state1.get("b") == 20
assert state1.get("c") == 30
assert "a" not in state1 # txn3 deleted 'a' after txn1 set it, and txn3 committed
assert "d" not in state1 # txn4 never committed
print("Hand-derived assertions passed.")
if __name__ == "__main__":
demo()
Output
Recovery run #1 -> {'b': 20, 'c': 30}
Txns skipped (aborted/incomplete) -> [2, 4]
Recovery run #2 -> {'b': 20, 'c': 30}
Idempotent: state1 == state2 -> True
Hand-derived assertions passed.
Key points
- Two passes over the log, not one: whether a transaction's writes should be applied cannot be known until it is clear whether it eventually commits, which for a
SETrecorded early in the log might not be known until much later in the same log. ABORToverrides a same-transactionCOMMITseen earlier, defensively; a correct log should never actually contain both for the same transaction id, but the recovery routine does not have to trust that.- Recovery always rebuilds state from an empty dictionary rather than mutating whatever state existed before recovery ran, which is what guarantees idempotence: there is nothing in a prior partial recovery attempt for a second run to accidentally build on top of.
Complexity
Time: O(n) where n is the number of log entries, two linear passes. Space: O(t + k) where t is the number of distinct transaction ids seen (for the committed-set tracking) and k is the number of distinct keys in the final state (for the result dictionary); the log itself is streamed, not held beyond what pass 1 already returns.
Edge cases
- A transaction with writes but no
COMMITorABORTat all, the crash-mid-transaction case: correctly excluded, since it is simply absent from the committed set. - A
DELETEfor a key that was neverSETin a committed transaction: handled safely, removing a missing key is a no-op rather than an error. - Interleaved transactions (two transactions'
BEGIN/writes interleaved before either commits): works correctly because classification in pass 1 does not depend on ordering relative to other transactions, only on which records exist for a given transaction id. - A key written by an earlier committed transaction and then deleted by a later committed transaction: correctly ends up absent, since pass 2 replays operations in log order, so the later
DELETEis applied after the earlierSET. - An empty log: returns an empty state and an empty skipped set, no special-casing needed.
Trade-offs and pitfalls
The most common bug in a routine like this is applying SET/DELETE records as they are seen in a single pass and trying to undo a transaction's effects after discovering it aborted; that requires the engine to remember enough about the old value to reverse the change, a real UNDO, and gets significantly more complex than replaying committed transactions only, on a second pass, from a known-empty starting point. The second pitfall specific to interview settings: forgetting the idempotence requirement entirely, since it is easy to write a version that behaves correctly the first time but corrupts state if the process crashes again during a second recovery attempt; the two-pass, rebuild-from-empty design sidesteps that by construction rather than needing extra bookkeeping to detect whether recovery already ran.
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.
Implement a disk-backed, time-partitioned index for streaming events that supports append(event) and range_query(start_ts, end_ts), staying under a fixed memory budget. Use segment files for compact on-disk storage optimized for append speed, and include a periodic compaction step that merges segments. Explain your on-disk serialization strategy and how a range query locates the relevant segments without scanning the whole store.
Sample Answer
Direct answer
Structure this as a tiny log-structured merge (LSM) store: append(event) only ever writes to a small, size-bounded in-memory buffer, and once that buffer fills it is sorted and written out once as a new immutable, timestamp-sorted segment file on disk, so no on-disk data is ever mutated after it is written. A small in-memory manifest tracks each segment's (min_ts, max_ts) range, so range_query(start_ts, end_ts) can rule out every segment whose range does not overlap the query before opening a single file. Periodic compaction merges the oldest segments together, which bounds both the number of segment files (so the manifest itself stays small and fixed-size) and the number of files any one query has to open.
Approach
Three pieces working together keep the whole design under a fixed memory budget regardless of how much data has been appended:
- A bounded write buffer.
appendadds to an in-memory list capped atmax_buffer_events. Hitting the cap triggers a flush: the buffer is sorted by timestamp once (cheap, since it is small) and written to a new segment file, then cleared. Memory used by the buffer never grows past that cap. - A bounded manifest. Each flush adds one entry to an in-memory list of
{id, path, min_ts, max_ts, count}, one entry per segment file on disk. If this list were left to grow forever, both its own memory footprint and the number of files a range query has to check would grow without bound as more data arrives. Compaction caps it: whenever the segment count crosses a threshold, the oldest segments are merged (via a k-way merge of already-sorted files, so no file is ever loaded fully into memory) into one new segment, and the old ones are deleted. - Range-query pruning via the manifest, not the files. A query first filters the small in-memory buffer directly (cheap, it is already in memory), then filters the manifest by
[min_ts, max_ts]overlap to get a short list of candidate segments, and only opens those files. Because each segment is stored fully sorted by timestamp, scanning one is a straight sequential read with an early exit the moment a record's timestamp exceedsend_ts.
flowchart LR
E["append(event)"] --> B["In-memory buffer
bounded to N events"]
B -->|"buffer full: sort by ts, write once"| S["New segment file
header: min_ts, max_ts, count"]
S --> M["Manifest (in memory)
id, path, min_ts, max_ts, count"]
M -->|"too many segments"| K["Compaction: k-way merge
oldest segments into one"]
K --> S
Q["range_query(start_ts, end_ts)"] --> B
Q --> M
M -->|"prune: keep only overlapping segments"| R["Open only matching
segment files, sorted scan"]
R --> RES["Merged, sorted results"]
B --> RES
Implementation
"""
Disk-backed, time-partitioned event store.
append(event) -> event is a (timestamp, payload) pair;
buffers in memory, flushes to a new
immutable, timestamp-sorted segment
file once the buffer fills.
range_query(start_ts, end_ts) -> merges matches from the live buffer
with matches from only the segment
files whose [min_ts, max_ts] overlaps
the query range (read from a small
in-memory manifest, not the segments).
compact() -> merges the oldest segments into one
when the segment count crosses a
threshold, bounding both segment
count (manifest memory) and the
number of files a query must open.
On-disk segment format (each segment file is fully sorted by timestamp,
written once, never mutated after flush):
[0:8] min_ts (uint64 BE) -- segment footer/header for pruning
[8:16] max_ts (uint64 BE)
[16:24] count (uint64 BE)
then `count` records, each:
[0:8] timestamp (uint64 BE)
[8:12] payload length (uint32 BE)
[12:12+len] payload bytes
"""
import struct
import os
import heapq
SEG_HEADER = struct.Struct(">QQQ") # min_ts, max_ts, count
REC_HEADER = struct.Struct(">QI") # timestamp, payload length
class TimePartitionedStore:
def __init__(self, directory, max_buffer_events=200, max_segments=6):
self.directory = directory
os.makedirs(directory, exist_ok=True)
self.max_buffer_events = max_buffer_events
self.max_segments = max_segments
self.buffer = [] # list[(ts, payload)], unflushed, in memory
self.manifest = [] # list[dict(id, path, min_ts, max_ts, count)]
self._next_seg_id = 0
self.segments_opened_last_query = 0 # instrumentation for the demo
# ---------- write path ----------
def append(self, event):
ts, payload = event # event is a (timestamp, payload) pair
self.buffer.append((ts, payload))
if len(self.buffer) >= self.max_buffer_events:
self._flush()
def _flush(self):
if not self.buffer:
return
batch = sorted(self.buffer, key=lambda e: e[0])
self.buffer = []
self._write_segment(batch)
if len(self.manifest) > self.max_segments:
self.compact()
def _write_segment(self, sorted_events):
seg_id = self._next_seg_id
self._next_seg_id += 1
path = os.path.join(self.directory, f"seg_{seg_id:06d}.dat")
min_ts = sorted_events[0][0]
max_ts = sorted_events[-1][0]
with open(path, "wb") as f:
f.write(SEG_HEADER.pack(min_ts, max_ts, len(sorted_events)))
for ts, payload in sorted_events:
f.write(REC_HEADER.pack(ts, len(payload)))
f.write(payload)
self.manifest.append({
"id": seg_id, "path": path,
"min_ts": min_ts, "max_ts": max_ts,
"count": len(sorted_events),
})
# ---------- compaction ----------
def compact(self, n_oldest=None):
"""Merge the n_oldest segments (oldest = earliest flushed, front of
the manifest list) into a single new segment via a k-way merge of
already-sorted inputs. Bounds len(self.manifest), which is the only
thing scaling with total data volume in this design, so it bounds
the store's fixed in-memory metadata footprint regardless of how
much data has been appended."""
if n_oldest is None:
n_oldest = len(self.manifest) - self.max_segments // 2
n_oldest = max(2, min(n_oldest, len(self.manifest)))
victims = self.manifest[:n_oldest]
merged = list(self._merge_segments([v["path"] for v in victims]))
for v in victims:
os.remove(v["path"])
self.manifest = self.manifest[n_oldest:]
if merged:
# manifest order does not affect correctness: range_query
# filters every manifest entry by [min_ts, max_ts] overlap
# regardless of position, and the manifest is small (bounded
# by max_segments) so that filter is cheap either way.
self._write_segment(merged)
@staticmethod
def _merge_segments(paths):
"""k-way merge: each input file is already sorted, so this reads
each sequentially once and yields events in global sorted order
without loading any file fully into memory."""
def gen(path):
with open(path, "rb") as f:
min_ts, max_ts, count = SEG_HEADER.unpack(f.read(SEG_HEADER.size))
for _ in range(count):
ts, length = REC_HEADER.unpack(f.read(REC_HEADER.size))
payload = f.read(length)
yield (ts, payload)
iterators = [gen(p) for p in paths]
# key=lambda e: e[0] means heapq.merge compares only the extracted
# timestamp, never the (ts, payload) tuples themselves, so payload
# values are never compared at all and do not need to support
# ordering; ties are broken by heapq.merge's own stable internal
# bookkeeping, not by falling back to comparing the payload.
yield from heapq.merge(*iterators, key=lambda e: e[0])
# ---------- read path ----------
def range_query(self, start_ts, end_ts):
results = [(ts, p) for ts, p in self.buffer if start_ts <= ts <= end_ts]
candidate_segments = [
m for m in self.manifest
if m["max_ts"] >= start_ts and m["min_ts"] <= end_ts
]
self.segments_opened_last_query = len(candidate_segments)
for m in candidate_segments:
with open(m["path"], "rb") as f:
min_ts, max_ts, count = SEG_HEADER.unpack(f.read(SEG_HEADER.size))
for _ in range(count):
ts, length = REC_HEADER.unpack(f.read(REC_HEADER.size))
payload = f.read(length)
if ts > end_ts:
break # segment is sorted: nothing further qualifies
if ts >= start_ts:
results.append((ts, payload))
results.sort(key=lambda e: e[0])
return results
if __name__ == "__main__":
import random
import shutil
random.seed(42)
tmp_dir = "segment-store-demo"
shutil.rmtree(tmp_dir, ignore_errors=True)
store = TimePartitionedStore(tmp_dir, max_buffer_events=200, max_segments=6)
# Generate 10,000 events with a little out-of-order jitter (realistic
# for events arriving over a network), append them one at a time the
# way a real ingest loop would.
N = 10_000
base_ts = 1_700_000_000_000
all_events = []
for i in range(N):
ts = base_ts + i * 10 + random.randint(-5, 5) # mild jitter
payload = f"event-{i}".encode()
all_events.append((ts, payload))
for ts, payload in all_events:
store.append((ts, payload))
store._flush() # flush whatever remains in the buffer at the end
print(f"events appended: {N}")
print(f"segments after run: {len(store.manifest)} "
f"(bounded by max_segments={store.max_segments}, "
f"compaction fired whenever it was exceeded)")
print(f"segment files on disk: {len([f for f in os.listdir(tmp_dir) if f.endswith('.dat')])}")
# Correctness: run 20 range queries at random windows and compare
# against a brute-force filter of the original in-memory event list
# (ground truth, independent of the store's internals).
mismatches = 0
total_candidates_checked = 0
for _ in range(20):
lo_i = random.randrange(N)
window = random.randint(1, 2000)
start_ts = all_events[lo_i][0]
end_ts = start_ts + window
got = sorted(store.range_query(start_ts, end_ts))
want = sorted([(ts, p) for ts, p in all_events if start_ts <= ts <= end_ts])
if got != want:
mismatches += 1
total_candidates_checked += store.segments_opened_last_query
print(f"range queries checked: 20")
print(f"mismatches: {mismatches}")
print(f"avg segments opened per query: {total_candidates_checked / 20:.1f} "
f"out of {len(store.manifest)} total segments on disk at query time")
# Show the pruning explicitly on one narrow, known window.
probe_ts = all_events[N // 2][0]
got = store.range_query(probe_ts, probe_ts + 50)
print(f"narrow probe query opened {store.segments_opened_last_query} of "
f"{len(store.manifest)} segments and returned {len(got)} events")
# Edge cases.
before_all = store.range_query(base_ts - 10_000, base_ts - 1_000)
print(f"query entirely before all data: {len(before_all)} events, "
f"opened {store.segments_opened_last_query} segments")
after_all = store.range_query(all_events[-1][0] + 1_000, all_events[-1][0] + 2_000)
print(f"query entirely after all data: {len(after_all)} events, "
f"opened {store.segments_opened_last_query} segments")
empty_store = TimePartitionedStore(tmp_dir + "-empty", max_buffer_events=200, max_segments=6)
print(f"query on a brand-new empty store: {empty_store.range_query(0, 10**15)}")
unflushed_store = TimePartitionedStore(tmp_dir + "-unflushed", max_buffer_events=200, max_segments=6)
for ts, payload in all_events[:50]: # well under max_buffer_events: nothing flushed yet
unflushed_store.append((ts, payload))
unflushed_result = unflushed_store.range_query(all_events[0][0], all_events[49][0])
print(f"query hitting only the unflushed in-memory buffer: "
f"{len(unflushed_result)} events (expected 50), "
f"segments opened: {unflushed_store.segments_opened_last_query} (expected 0)")
shutil.rmtree(tmp_dir, ignore_errors=True)
shutil.rmtree(tmp_dir + "-empty", ignore_errors=True)
shutil.rmtree(tmp_dir + "-unflushed", ignore_errors=True)
Output:
events appended: 10000
segments after run: 5 (bounded by max_segments=6, compaction fired whenever it was exceeded)
segment files on disk: 5
range queries checked: 20
mismatches: 0
avg segments opened per query: 1.0 out of 5 total segments on disk at query time
narrow probe query opened 1 of 5 segments and returned 6 events
query entirely before all data: 0 events, opened 0 segments
query entirely after all data: 0 events, opened 0 segments
query on a brand-new empty store: []
query hitting only the unflushed in-memory buffer: 50 events (expected 50), segments opened: 0 (expected 0)
10,000 events were appended one at a time, which triggered 50 flushes (10000 / 200). Compaction kept the on-disk segment count at 5 the entire time (max_segments=6, so it fires the moment a flush would push the count to 7) instead of letting it climb to 50. The 20 randomized range queries all matched a brute-force scan of the original event list exactly, and on average each query opened only 1.0 of the 5 segments on disk, meaning the manifest pruning is doing its job: a query is not scanning the whole store, it is scanning the one segment (sometimes two, at a segment boundary) whose timestamp range actually overlaps the request.
Key points
- Segments are write-once. A flush sorts the buffer and writes it in one pass; nothing on disk is ever opened for modification again, only for reading or, during compaction, for reading followed by deletion of the whole file. This is what makes the design safe to reason about: a segment's
[min_ts, max_ts]header, once written, is permanently accurate. - The manifest, not the segment files, is what a query consults first.
range_queryfiltersself.manifest(a handful of small dictionaries) before touching disk at all; opening a segment file only happens for the segments that survive that filter. - Compaction uses a k-way merge, not a full-file sort. Since every input segment is already internally sorted,
heapq.mergeproduces the combined sorted output by always taking the smallest available head element across all inputs, without ever loading a whole file into memory, the same idea an LSM-tree's leveled compaction uses at a much larger scale. - The buffer is part of the read path, not just the write path. A record that has not been flushed yet still has to be visible to a query that asks for it, which is why
range_queryfiltersself.bufferdirectly before ever consulting the manifest.
Complexity
Let N be total events appended, B the buffer cap (max_buffer_events), and S the number of segments at query time (bounded by max_segments because of compaction).
append: amortizedO(1); a flush is triggered once everyBcalls and costsO(B log B)to sort the batch, so the amortized per-event cost isO(log B).range_query:O(B)to filter the buffer, plusO(S)to filter the manifest, plusO(matching segments x records per segment)to scan the segments that survive pruning. BecauseSis bounded bymax_segments(6 in the demo) regardless of how largeNgrows, the manifest-filtering part of every query costs the same no matter how much data the store holds; only the final segment scan scales with how much data actually falls in the query window, which is the expected, necessary cost of returning that data.compact: a k-way merge ofn_oldestsegments with a combinedMrecords costsO(M log n_oldest)using a heap, run only when the segment count crosses the threshold, so its cost is amortized across the flushes that triggered it.- Memory:
O(B)for the buffer plusO(S)for the manifest, both bounded constants independent ofN. This is the "fixed memory budget" the question asks for: nothing in this design holds a structure whose size is proportional to total data appended, except the data itself, which lives on disk.
Edge cases
All exercised by the shipped code and output above:
- Query entirely before any data exists: 0 events returned, 0 segments opened (the manifest filter rules out every segment immediately).
- Query entirely after all data: same, 0 events and 0 segments opened.
- Query against a brand-new, completely empty store: returns an empty list rather than erroring, since an empty buffer and an empty manifest both filter to nothing.
- Query that only the unflushed in-memory buffer can answer (fewer than
max_buffer_eventsappended so far): returns all 50 matching events while opening 0 segment files, confirming the buffer is actually consulted, not just the segments. - A query window that straddles two segments: the narrow probe query above returned 6 events by opening exactly 1 segment in this run, but a query positioned right at a segment boundary can legitimately need to open 2; the pruning filter handles that correctly because it is an overlap check, not an equality check, against each segment's
[min_ts, max_ts].
Trade-offs & pitfalls
- The out-of-order jitter in the demo (up to 5 units either side of the nominal timestamp) is realistic and deliberately not zero. If events always arrived in strictly increasing timestamp order, segment ranges would never overlap and pruning would always open exactly one segment. Real network events do not arrive perfectly ordered, so segment ranges will occasionally overlap slightly at their edges, and the design has to be correct under that, not just under the easy strictly-sorted case; this implementation handles it because pruning is a range overlap check, not an assumption of global order across segments.
- Compaction here is a simple oldest-N merge (size-tiered in spirit), not a leveled scheme. It bounds segment count, which is the property this question asks for, but it does not try to minimize total bytes rewritten over the store's lifetime the way a production LSM-tree's leveled compaction does. That is a legitimate follow-on optimization, not a correctness gap: the two compaction families trade write amplification against compaction complexity, and size-tiered is the right starting point for a design exercise.
- A very bursty write pattern can force back-to-back compactions. If
max_buffer_eventsis set too small relative to burst size, the store spends more time compacting than serving reads; sizing the buffer against the actual expected burst rate (the same kind of arithmetic used to size the segment in a comparable durable-queue design) matters in practice, not just picking a round number. - This design does not persist the manifest itself. On a real crash, the manifest would need to be rebuilt by scanning the segment directory and re-reading each file's header (cheap, since headers are tiny and fixed-size), which this implementation does not include; it is an in-memory-only structure for the scope of this exercise.
You're designing the compaction strategy for an LSM-based store (e.g., RocksDB) that must balance write throughput, read latency, and disk usage for a mixed workload. What compaction approaches would you consider and how would you choose between them, how would you throttle compaction under peak load, and what would you monitor to make sure compaction doesn't destabilize the service?
Sample Answer
Direct answer
For a write-heavy, mixed workload on an LSM-based store (a design that buffers writes in memory and later merges, or compacts, them into larger sorted files in the background), the real decision is between leveled compaction and size-tiered compaction, and it is a straight trade: leveled compaction keeps read amplification and space amplification low (the extra bytes read, or extra disk space held, beyond the logical minimum) by maintaining at most one sorted run per level, at the cost of high write amplification (extra bytes physically written to disk beyond what the application logically wrote) from repeated merging; size-tiered compaction keeps write amplification low by merging whole batches of similarly sized files together instead of merging into a much larger target, at the cost of higher read and space amplification because multiple un-merged sorted runs can coexist within one tier. For most services, anything where point-lookup latency matters to a user, leveled compaction is the safer default; size-tiered earns its keep specifically when the workload is dominated by writes and reads are rare, batch, or can tolerate checking more files.
Structured elaboration
Leveled compaction
Each level (L0, L1, L2, and so on) has a target size, typically each level roughly T times bigger than the one above it (T, the level size ratio, commonly 10). When a level exceeds its target, its data is merged with the overlapping key range in the next level down, producing one sorted run in the target level. Because each level holds at most one sorted run (L0 is the practical exception, since memtable flushes land there before the first real merge), a point lookup checks at most one file per level: read amplification and space amplification stay bounded and low. The cost is write amplification: RocksDB's own compaction documentation states this plainly, "the usual write amplification of leveled compaction... is often larger than 10," and there is a first-principles reason why: compacting level i into level i+1 has to rewrite roughly the overlapping portion of level i+1, which is about T times bigger than what came in from level i, so each level a piece of data passes through costs roughly another T times rewrite.
Size-tiered compaction
Instead of merging into a much bigger target, size-tiered compaction waits until it has several, commonly T, similarly sized files at one tier, merges them together into one new file at the next tier, and repeats. Each byte gets rewritten roughly once per tier it passes through, not T times, so write amplification scales with the number of tiers, not with the size ratio between tiers. The cost shows up on the read side: before enough files accumulate to trigger a merge, a tier can hold up to T-1 un-merged sorted runs, and a point lookup that does not hit a Bloom filter (a compact structure that can cheaply rule a file out) has to check all of them.
A first-principles worked derivation, not a citation, an explicit model
Assume a level size ratio T = 10 and L = 6 levels beyond the memtable (L0 through L5).
WAleveled≈T×L=10×6=60
That is consistent, in order of magnitude, with RocksDB's own documented figure of "often larger than 10" for leveled compaction. Size-tiered, same T and L, each of the 6 tiers contributing roughly one rewrite instead of T:
WAtiered≈L=6
an order of magnitude lower than leveled's 60 under the same assumptions, at the cost of up to T - 1 = 9 un-merged runs per tier a lookup might have to check before a merge clears them.
Throttling under peak load
Compaction has to run continuously to keep read and space amplification bounded, but it competes with foreground reads and writes for the same disk and CPU budget. The standard mechanisms: rate-limit compaction I/O explicitly (a byte-per-second cap on compaction reads and writes, separate from foreground I/O); prioritize compacting the levels closest to overflowing (an L0 about to accumulate too many files is a bigger risk than a deep level slightly behind schedule) over a strict oldest-first order; and, as a last resort, deliberately slow or stall new writes when the backlog, number of un-compacted L0 files or pending compaction bytes, crosses a hard threshold, because letting writes keep outpacing compaction indefinitely turns a temporary backlog into unbounded read amplification and eventually unbounded disk usage.
SSD endurance and two levels of mitigation
High write amplification is not just a throughput (the volume of reads and writes a disk can service per second) problem: on solid-state storage it directly consumes the device's rated write-endurance budget, since flash wears out per physical write and erase cycle, not per logical write, so a store running LSM compaction at 40 to 60 times write amplification is burning through an SSD's endurance rating tens of times faster than its logical write volume alone would suggest. There are two independent levers to pull, and confusing them is a common mistake: algorithm-level mitigations change how much gets rewritten in the first place (choosing size-tiered over leveled compaction, widening the level size ratio to reduce level count, using Bloom filters so reads do not force extra compaction just to keep lookups fast); operational-level mitigations change how much endurance headroom absorbs the amplification that is still there (over-provisioning the SSD, keeping meaningfully more raw flash capacity than the logical data size so the drive's own wear-leveling has more room to spread writes, and scheduling heavy compaction windows away from peak traffic rather than running it continuously at full rate). A team under endurance pressure should reach for the algorithm-level fix first, since it reduces the underlying cost, and treat over-provisioning as a buffer, not a substitute.
What to monitor, and how to verify a fix does not quietly cost you something else
Pending compaction bytes or un-compacted file count per level (the leading indicator: this climbing means compaction is losing the race against incoming writes, before it becomes a user-visible problem); actual write-stall time or write-stall event count (the trailing indicator: compaction already lost badly enough to throttle foreground writes); and per-level read amplification, files checked per point lookup, because compaction falling behind at any level directly degrades read latency for keys landing there. When verifying a compaction-tuning change, alter one parameter at a time, for example only the level size ratio, and watch both write amplification and per-level read amplification on the same before-and-after window, not just the metric you were trying to improve. A fix that halves write amplification by doubling the level size ratio can simultaneously double how many un-compacted files pile up before a merge clears them, invisible if only the write side was monitored.
Worked example
The numeric derivation above, T=10, L=6 giving leveled about 60x and size-tiered about 6x write amplification under identical assumptions, is the worked example: it shows the two strategies' relative costs come from the same two inputs, size ratio and level count, and it reproduces, in order of magnitude, the "often larger than 10" figure RocksDB's own documentation reports for real leveled-compaction deployments.
Trade-offs and pitfalls
The pitfall in picking a compaction strategy is optimizing for the write path in isolation: a service that switches to size-tiered compaction purely to cut write amplification, without checking whether its read latency budget can absorb checking several un-merged files per lookup, trades a capacity problem (disk wear, I/O budget) for a latency problem (unpredictable point-lookup tail latency) that may be worse for the actual product. The second pitfall is treating a write stall as a bug to eliminate rather than a safety valve: removing or disabling it without first fixing whatever is causing compaction to fall behind just moves the failure from temporarily slower writes to read amplification and disk usage growing without bound until the disk fills or reads time out, a strictly worse outcome.
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.