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.
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.
Discuss Bloom filters: what they solve, how false positive rate is calculated, how to choose the bit-array size (m) and number of hash functions (k) given expected element count (n) and desired false-positive probability (p), and examples of how databases use them.
Sample Answer
Direct answer
A Bloom filter is a compact, probabilistic structure that answers whether a key might be in a set using far less memory than storing the actual keys, at the cost of allowing false positives, it can wrongly say "maybe present" for a key that is not there, but never false negatives, it never wrongly says "definitely absent" for a key that is there. Databases use this asymmetry specifically to skip expensive work: check the Bloom filter first, and only pay for an actual disk read or file open when it says "maybe," which is exactly the shape of the read-amplification problem log-structured merge-tree (LSM-tree, a storage design that buffers writes in memory and periodically merges them into new sorted on-disk files rather than updating a file in place) engines have, checking whether a key exists in a given on-disk file before deciding whether to open it.
Structured elaboration
What it solves
Without a Bloom filter, checking whether a key exists in a given file means either scanning the file or at least opening it and checking an index; for a point lookup that might not even find the key, a true negative, that is pure wasted I/O. A Bloom filter, held entirely in memory, lets the engine skip opening files that provably do not contain the key, at the cost of occasionally, controlled by the false-positive rate, opening a file that turns out not to have it after all, a wasted read, but far rarer than checking every file unconditionally.
How it works and how the false-positive rate is derived
A Bloom filter is a bit array of size m, all initialized to 0. Inserting a key sets k bits, each chosen by a different hash function applied to the key. Checking a key reads the same k positions: if any bit is 0, the key is definitely not in the set, a bit can only be 0 if nothing ever set it; if all k bits are 1, the key is maybe in the set, because those bits could have all been set by some combination of other keys' insertions rather than this one. The probability of that false collision, the false-positive rate, follows directly from a fill-rate argument: after inserting n keys with k hash functions into m bits, the expected false-positive probability is:
p≈(1−e−kn/m)k
Choosing m and k given n and p
Solving that relationship for the parameters actually chosen, given a target false-positive probability p and an expected element count n, the standard closed-form sizing is:
m=−(ln2)2nlnp
k=nmln2
Examples of how databases use Bloom filters
RocksDB and Cassandra (a distributed, wide-column NoSQL database built on an LSM-tree storage engine) both attach a Bloom filter to every on-disk sorted file, an SSTable, specifically to skip files during a point lookup; some analytic engines and block-level indexing tools use Bloom-filter-style structures at the storage-block or partition level to skip whole blocks or partitions that provably do not contain a value being filtered on. The common thread is always the same: a cheap, in-memory "definitely not here" check in front of an expensive I/O operation.
Worked example
Computed directly, not estimated, for n = 100,000 expected elements and a target false-positive probability p = 0.01:
m=−(ln2)2100,000×ln(0.01)≈958,506 bits≈117.0 KiB
k=100,000958,506ln2≈6.64→7 hash functions (rounded)
That is about 9.6 bits per element, roughly a hundred times less memory than storing even short string keys directly, for a 1 percent or better false-positive rate.
I then built and ran an actual Bloom filter with exactly these parameters, m = 958,506, k = 7, using two independent cryptographic hashes combined via double hashing to generate the k bit positions, rather than Python's built-in general-purpose hash function, which produced visibly correlated, worse-than-predicted results in an earlier draft of this same test, inserted 100,000 distinct keys, and probed it with 50,000 keys guaranteed absent from the inserted set:
import hashlib
import math
def bloom_params(n, p):
"""n = expected element count, p = target false-positive probability.
Returns (m bits, k hash functions), both rounded to usable integers."""
m = -(n * math.log(p)) / (math.log(2) ** 2)
k = (m / n) * math.log(2)
return math.ceil(m), max(1, round(k))
def proper_hashes(key, k, m_bits):
# k bit positions via double hashing (Kirsch-Mitzenmacher): derive h1, h2 from two
# independent cryptographic digests (md5/sha1) instead of Python's built-in hash(),
# which is not designed for this and showed correlated collisions in an earlier draft.
kb = key.encode()
h1 = int.from_bytes(hashlib.md5(kb).digest()[:8], "big") % m_bits
h2 = int.from_bytes(hashlib.sha1(kb).digest()[:8], "big") % m_bits
if h2 == 0:
h2 = 1 # avoid degenerate double-hashing when h2 == 0 mod m_bits
return [(h1 + i * h2) % m_bits for i in range(k)]
def empirical_fp_rate(m_bits, k, inserted_keys, absent_probe_keys, hashfn=proper_hashes):
# hashfn takes (key, k, m_bits) and returns the k bit positions to check/set;
# it defaults to proper_hashes so the Worked example calls below need no change,
# and it is exactly the seam the Trade-offs section below plugs naive_hashes into
# to reproduce a correlated-hash failure with the identical m, k, and key sets.
bitset = bytearray((m_bits + 7) // 8)
def set_bit(i):
bitset[i // 8] |= (1 << (i % 8))
def get_bit(i):
return (bitset[i // 8] >> (i % 8)) & 1
for key in inserted_keys:
for i in hashfn(key, k, m_bits):
set_bit(i)
false_positives = sum(
1 for key in absent_probe_keys if all(get_bit(i) for i in hashfn(key, k, m_bits))
)
return false_positives / len(absent_probe_keys)
if __name__ == "__main__":
n = 100_000
p_target = 0.01
m, k = bloom_params(n, p_target)
print(f"n={n}, target p={p_target} -> m={m} bits ({m/8/1024:.1f} KiB), k={k} hash functions")
print(f"bits per element (m/n) = {m/n:.2f}")
inserted = [f"key-{i}" for i in range(n)]
absent_probes = [f"absent-{i}" for i in range(50_000)]
fp_rate = empirical_fp_rate(m, k, inserted, absent_probes)
print(f"measured false-positive rate over 50,000 absent probe keys: {fp_rate:.4%}")
print()
print("how m and k move as the target false-positive rate changes (n fixed at 100,000):")
for p in (0.10, 0.01, 0.001):
m2, k2 = bloom_params(n, p)
print(f" p={p:<6} -> m={m2:>9} bits ({m2/8/1024:7.1f} KiB), k={k2}")
Output:
n=100000, target p=0.01 -> m=958506 bits (117.0 KiB), k=7 hash functions
bits per element (m/n) = 9.59
measured false-positive rate over 50,000 absent probe keys: 0.9660%
how m and k move as the target false-positive rate changes (n fixed at 100,000):
p=0.1 -> m= 479253 bits ( 58.5 KiB), k=3
p=0.01 -> m= 958506 bits ( 117.0 KiB), k=7
p=0.001 -> m= 1437759 bits ( 175.5 KiB), k=10
0.966 percent measured against a 1 percent target, close agreement, and the small gap is expected sampling noise from probing with a finite number of keys rather than the formula's infinite-population assumption.
Trade-offs and pitfalls
Setting the false-positive rate too loosely, a bigger p, smaller m, saves memory but defeats the filter's purpose operationally: more false positives means more wasted I/O actually opening files that turn out empty, eroding exactly the read-amplification benefit the filter exists to provide. Too tight, a very small p, burns memory that could otherwise cache actual data, for a marginal improvement once the overwhelming majority of unnecessary reads are already being skipped. The sizing table above, for the same n = 100,000, shows tightening p by 10x roughly doubling m and adding a few more hash functions, a real cost for a shrinking marginal benefit.
A second pitfall: a Bloom filter's correctness depends on its k hash functions behaving close to independently, and a cheap or correlated hash scheme silently produces a worse real-world false-positive rate than the sizing formula promises, without any error or warning, because the formula's derivation assumes hash independence the implementation did not actually provide. This is not a hypothetical: swapping the same test's proper double hashing (two independent cryptographic hashes) for a scheme that derives all k positions from a single Python hash() call, multiplied by small integers, something that looks like double hashing but is not, since every position is then a linear function of the same one underlying value, reproduces the failure directly, for the identical m and k:
def naive_hashes(key, k, m_bits):
# Looks like double hashing but is not: every position is a linear function
# of the SAME single hash() call, so the k positions are correlated with
# each other instead of behaving independently.
h = hash(key)
return [(h * (i + 1)) % m_bits for i in range(k)]
naive_fp = empirical_fp_rate(m, k, inserted, absent_probes, naive_hashes)
print(f"naive (single hash() multiplied by i) measured FP rate: {naive_fp:.4%} (target {p_target:.2%})")
print(f"naive scheme is {naive_fp/p_target:.1f}x worse than the target, for identical m and k")
Output (this run; the exact figure moves a little run to run because Python randomizes string-hash seeding by default, but it lands in the same range every time, since the correlation is structural, not incidental):
naive (single hash() multiplied by i) measured FP rate: 14.3700% (target 1.00%)
naive scheme is 14.4x worse than the target, for identical m and k
Same m, same k, same inserted and probed keys as the proper version above, roughly 14x the target false-positive rate instead of matching it, purely from how the k positions were derived. That is the concrete shape of the pitfall: nothing in the API surface of "call hash k times" tells you whether those k calls are actually independent, and the sizing formula's guarantee silently stops holding when they are not.
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.
Compare storage engines like InnoDB, RocksDB, and WiredTiger. How does each handle write amplification, compaction, concurrency, and crash recovery, and what kinds of workloads does each excel at? Now suppose you need low-latency point updates AND fast analytic aggregation on the same data: how would your recommendation change, and would a distributed transactional key-value store (e.g., TiKV) change the calculus?
Sample Answer
Direct answer
InnoDB (MySQL's default engine, B-tree-based) and WiredTiger (MongoDB's default engine, also B-tree-based by default) both prioritize predictable point-lookup and update latency at the cost of higher write amplification (extra physical bytes written beyond the logical change) from in-place updates; RocksDB (an embeddable key-value store built on a log-structured merge-tree, or LSM-tree, a design that buffers writes in memory and periodically merges them into new sorted on-disk files instead of updating in place) inverts that trade, absorbing very high write throughput cheaply and paying for it later in background compaction and less predictable read latency. For a workload needing both low-latency point updates and fast analytic aggregation on the same data, none of the three is a full answer by itself, and a distributed transactional key-value store like TiKV changes the calculus by adding horizontal scale and, in practice, by being commonly paired with a separate columnar replica for the analytic side rather than trying to serve both access patterns well from one row-oriented engine.
Structured elaboration
Write amplification, compaction, concurrency, crash recovery
| Engine | Structure | Write amplification | Compaction | Concurrency | Crash recovery |
|---|---|---|---|---|---|
| InnoDB | B-tree, clustered index (rows physically stored in primary-key order) | Lower baseline, but in-place page rewrites plus a doublewrite buffer (a protective pre-write of pages guarding against a torn write mid-page) add real overhead per write | None; cost is paid inline as page splits, not as a separate background process | Row-level locking plus MVCC (multi-version concurrency control) for reads, implemented via hidden DB_TRX_ID/DB_ROLL_PTR columns and undo logs that reconstruct older row versions on demand rather than keeping full old rows in the table | WAL-based (write-ahead log: an append-only record of changes written before they take effect) redo and undo, replaying committed changes and rolling back in-flight transactions from the log since the last checkpoint (the periodic point up to which all changes are already durably saved, so recovery need not replay further back) |
| WiredTiger | B-tree by default | Similar profile to InnoDB: in-place page updates | None in the default B-tree mode | MVCC with document-level, not full-collection, locking; optimistic concurrency, where a write conflict causes an automatic retry rather than blocking | Checkpoints every 60 seconds by default; the log (oplog/journal) since the last checkpoint replayed on restart |
| RocksDB | LSM-tree | High: leveled compaction write amplification is commonly cited, in RocksDB's own documentation, as "often larger than 10" | A continuous, tunable background process; central to the design, not incidental | MVCC via multiple immutable file versions; readers never block writers, writers never block readers, at the cost of read amplification (a single logical read having to check multiple on-disk files before finding the current value) across un-compacted files | Replays the write-ahead log for anything not yet flushed to an immutable file; immutable files themselves need no recovery, since they were never partially written by definition |
Workload fit
InnoDB and WiredTiger fit OLTP (online transaction processing): many small, latency-sensitive point reads and writes, where in-place B-tree updates give predictable cost regardless of how many times a row has changed. RocksDB fits write-heavy embedded or ingest-shaped workloads, commonly used as the storage layer inside other systems, stream processors, metadata stores, rather than as a standalone application database, where sustained write throughput matters more than the read-latency predictability a B-tree gives.
The hybrid workload: low-latency point updates and fast analytic aggregation
This is the classic hybrid transactional and analytical processing (HTAP) problem, and it is hard precisely because the two access patterns want opposite physical layouts: point updates want a row-oriented structure so one row's worth of data is together on one page or in one place; aggregation over many rows wants a column-oriented layout so a query touching only three of a table's forty columns does not have to read the other thirty-seven. None of InnoDB, WiredTiger, or RocksDB solves this by being row-oriented harder; the realistic answer is architectural, not picking a better single engine: either accept that analytic queries run against the row store with degraded scan performance, fine at small-to-moderate analytic scale, or replicate changes, via change-data-capture, reading the WAL or a similar change stream, into a separate column-oriented store built for aggregation, accepting some replication lag between the transactional and analytical views in exchange for both sides being fast at what they do.
Does a distributed transactional key-value store like TiKV change the calculus?
TiKV backs each node with RocksDB as the local storage engine, replicates data by splitting it into key-range shards, called Regions, each managed by a Raft consensus group (a leader plus followers, so the region stays available and durable across node failure), and layers distributed ACID transactions on top using a Percolator-style protocol, a two-phase commit scheme built on multi-version timestamps, originally designed at Google for exactly this kind of distributed transactional key-value system. That solves horizontal scale and distributed transactions cleanly, genuinely useful if a single-node point-update workload has outgrown one machine, but it does not by itself solve the row-versus-column layout problem: it inherits RocksDB's LSM-tree, row-oriented-at-heart storage underneath. In practice, the systems built on TiKV that actually claim HTAP, TiDB is the common example, pair it with a separate columnar storage engine and replicate into it, the same change-data-capture pattern described above, rather than making one row-oriented engine equally fast at both jobs. So TiKV changes the calculus for scale and distributed transactions, but the row-versus-column tension the original question is really about still needs the same architectural answer, a second, column-oriented store fed by replication, whether the primary engine is InnoDB or a distributed store built on RocksDB.
Worked example
Concretely: a payments table needing both single-row balance updates under 10 ms and a daily aggregate, total volume by merchant category over the last 30 days, over hundreds of millions of rows. Serving the aggregate directly off InnoDB means a full or near-full clustered-index scan, reading far more data, every column of every row, than the aggregate actually needs; the realistic fix is a nightly, or streaming via change-data-capture, replication of just the needed columns into a column-oriented analytic store, keeping the InnoDB table exclusively for the point-update path it is actually good at. The same shape holds if the primary store were TiKV instead of InnoDB: point updates stay fast on the row-oriented, Raft-replicated primary, and the aggregate query runs against a separately maintained columnar replica, not against TiKV directly.
Trade-offs and pitfalls
The pitfall is chasing a single-engine HTAP solution because managing two systems, a transactional store plus a replicated analytic store, feels like more operational surface area: it usually is more moving parts, but trying to make one row-oriented engine, InnoDB, WiredTiger, RocksDB, or a TiKV-backed distributed store, serve both access patterns well tends to produce an engine that is mediocre at both rather than good at either, because the physical layout decision, row-oriented versus column-oriented, is the one thing none of these engines can change without becoming a fundamentally different kind of engine. The second pitfall: underestimating replication lag as a correctness issue, not just a staleness inconvenience, if the analytic side is used for anything beyond reporting; a decision that depends on whether a transaction is reflected yet needs the transactional store directly, not the lagging replica.
Explain MVCC (Multi-Version Concurrency Control) and how it enables non-blocking reads. Describe PostgreSQL's autovacuum process, why table bloat occurs, how to detect it, and mitigations to prevent vacuum-related performance issues. Include operational knobs and metrics you would monitor to prevent transaction ID wraparound.
Sample Answer
Direct answer
Postgres implements multi-version concurrency control (MVCC) by never modifying a row in place: every INSERT or UPDATE writes a brand-new physical row version stamped with the id of the transaction that created it (xmin), and an UPDATE or DELETE marks the version it replaces with the id of the transaction that superseded it (xmax) rather than erasing it. A transaction's snapshot is a fixed rule, computed once, for which transaction ids count as already committed, and a row version is visible to that transaction only if its xmin is in that committed set and its xmax, if set, is not. Because old versions are left in place rather than deleted, something has to come back later and physically remove them, that something is autovacuum, and if it falls behind for long enough on a very old row version, the consequence is not just wasted space but a hard correctness deadline called transaction id wraparound.
Structured elaboration
Row versioning and snapshot visibility
Every physical row (a "tuple" in Postgres's heap storage) carries xmin and xmax as hidden system columns. A fresh INSERT sets xmin to the inserting transaction's id and leaves xmax at 0 (unset). An UPDATE does not touch the old row's data; it sets the old row's xmax to the updating transaction's id and writes a completely new row with a new xmin and xmax = 0. A transaction's snapshot, taken once at the start of a REPEATABLE READ or SERIALIZABLE transaction (two isolation levels that pin one snapshot for the whole transaction, so every statement inside it sees the same consistent view) or once per statement under the default READ COMMITTED (which takes a fresh snapshot for each individual statement, so a later statement in the same transaction can see commits made by other transactions in between), is the set of transaction ids already committed as of that instant; a row is visible if xmin is in that set and xmax is either unset or belongs to a transaction not in that set. This is exactly what lets two concurrent transactions get consistent, non-blocking answers from the same table: a writer's new version simply is not in an already-running reader's committed set yet.
Why table bloat happens
Because an UPDATE leaves the old version physically on the page (it is only marked invisible via xmax, not deleted), a table that is updated heavily accumulates dead row versions between vacuum runs. This is "bloat": the table's on-disk size grows to hold both live and dead versions even though the logical row count has not changed, and every sequential scan or index-then-heap lookup has to skip past the dead versions to find the live one.
Detecting bloat
Two views tell you this directly: pg_stat_user_tables.n_dead_tup (dead row versions Postgres's statistics collector currently estimates for a table) versus n_live_tup, and the pgstattuple extension's pgstattuple('table'), which physically scans the table and reports exact dead_tuple_percent and free_percent.
Mitigations and operational knobs
- Autovacuum tuning:
autovacuum_vacuum_scale_factor(fraction of the table's live rows that must be dead before autovacuum triggers, default 0.2, i.e. 20 percent) andautovacuum_vacuum_threshold(a flat row-count floor added on top, default 50) together decide how often autovacuum runs on a given table; a large, heavily updated table often needs a lower scale factor set per-table so autovacuum does not wait for 20 percent of a hundred-million-row table to go dead before acting. VACUUMdoes not shrink the file on disk by default; it marks dead-version space as reusable for future inserts or updates on the same table. OnlyVACUUM FULL(which rewrites the table into a new, smaller file and takes an exclusive lock while doing so) or an online tool likepg_repackactually returns space to the operating system.- Transaction id wraparound: Postgres transaction ids are a 32-bit counter, so they eventually wrap around. To keep old row versions from becoming ambiguous, Postgres periodically "freezes" old-enough row versions, marking them as permanently visible regardless of transaction id comparisons, and tracks the oldest un-frozen transaction id per table (
relfrozenxid) and per database (datfrozenxid).autovacuum_freeze_max_age(default 200,000,000 transactions) is the hard ceiling: if a table's age crosses it, autovacuum is forced to run an aggressive freeze on that table regardless of the normal dead-tuple threshold, specifically to avoid the database refusing new writes to protect against wraparound corruption. - What to monitor:
age(relfrozenxid)per table andage(datfrozenxid)per database, both meaning "how many transactions old is the oldest unfrozen row," watched againstautovacuum_freeze_max_age. A long-running transaction is the classic cause of a stuck vacuum, because Postgres cannot freeze or remove any row version a still-open transaction might still need to see, so one forgotten open transaction can single-handedly stall cleanup across the whole database while age keeps climbing.
Worked example
All of this from a live Postgres 16 instance.
Version-chain proof: table acct(id, balance). INSERT gives xmin=749, xmax=0. UPDATE balance=150 gives the new visible row xmin=750, xmax=0. Reading the raw page directly with pageinspect's heap_page_items shows both versions physically present: line pointer 1 has t_xmin=749, t_xmax=750 (the old, now-dead version, its t_ctid pointing forward to the new one), line pointer 2 has t_xmin=750, t_xmax=0 (the live version). That forward-pointing t_ctid chain is literally the version chain this question asks about; nothing was deleted, the old version is still on the page until vacuum removes it.
Bloat proof: a fresh table with 50,000 rows, updated in place 5 times (UPDATE bloat_demo SET v = v + 1, run 5 times, each rewriting every row as a new version). pg_stat_user_tables then shows n_live_tup=50000, n_dead_tup=250000 (5 times 50,000). pgstattuple confirms physically: table_len=10,878,976 bytes, dead_tuple_percent=73.54, free_percent=0.38. Running VACUUM (VERBOSE) reports tuples: 250000 removed, 50000 remain, removes 250,000 dead entries from the index too, and afterward n_dead_tup=0 and free_percent=83.07, but table_len is still exactly 10,878,976 bytes: the space was marked reusable, not returned to the operating system, which only VACUUM FULL would do.
Wraparound proof: on this fresh instance, age(datfrozenxid) for the database reads 32 (only 32 transactions old, essentially no wraparound risk yet), age(relfrozenxid) for the just-vacuumed table reads 2, and autovacuum_freeze_max_age is confirmed at its documented default of 200,000,000. A production table sitting at, say, 150,000,000 and climbing, with no long-running transaction to explain it, is the concrete shape of approaching the point autovacuum will force an aggressive freeze whether or not the maintenance window is convenient.
Trade-offs and pitfalls
The most damaging real-world mistake is a long-running transaction, a reporting query left open, a connection that never commits, an abandoned interactive session, sitting idle for hours or days: because Postgres cannot remove or freeze any row version that transaction's snapshot might still need, one forgotten open transaction silently disables cleanup for every table in the database, not just the one it queried, and both bloat and wraparound age climb together until something is noticed, often as sudden query slowdowns, or, in the worst case, the database refusing new transactions to protect against wraparound. A second pitfall is tuning autovacuum's scale factor globally and assuming it is fine everywhere: a flat 20 percent dead-tuple threshold is reasonable on a small table and much too lax on a hundred-million-row table, where 20 percent dead is tens of millions of bloated rows before cleanup even starts.
Unlock Full Question Bank
Get access to all 20 Database Internals and Storage Engines interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.