Building a Crash-Safe Storage Engine for a Single-Node Key-Value Service
System DesignModel answerLast updated
Design the storage engine of a single-node persistent key-value store covering indexing, large values, thread-safe access and cheap durability for acknowledged writes.
You are asked to design the storage layer of a single-machine key-value service that keeps its data on disk and serves many client threads at once.
Interface
get(key)returns the value stored underkey, or a not-found result.put(key, value)storesvalueunderkeyand replaces any earlier value for that key.
Requirements
- Durability: once
puthas returned success, the write must still be there after a crash or power loss. - Throughput: the store must serve a large volume of reads and writes.
- Larger than RAM: lookups must stay efficient even when the full dataset is far bigger than memory.
Assumptions
- Keys are strings. Values are arbitrary binary blobs and some can be very large.
- The hot subset of keys fits in memory, while the complete dataset lives on disk.
- Many threads call the store at the same time.
What to cover
Describe the storage engine and explain your reasoning on these four points:
- How you index keys so that a lookup needs as few disk seeks as possible.
- How you deal with very large values without putting heavy pressure on memory.
- How you let threads share the store safely while keeping throughput high.
- How you guarantee durability without paying for a full disk sync on every single write.
State your assumptions about scale (dataset size, RAM, request rates, latency targets) up front and discuss the trade-offs of your choices.
Hints
Hint 1
Start by putting numbers on the problem (dataset size, RAM, key count, request rates). Check whether a full in-memory index of every key would even fit, because the answer decides between a dense and a sparse index.
Hint 2
Think about which on-disk data can be made immutable. Immutable sorted files plus a small mutable in-memory structure make both concurrency and crash recovery much simpler.
Hint 3
Separate large values from the key index so that background reorganisation of the index never has to copy huge blobs.
Hint 4
An fsync is expensive but its cost does not depend much on how many bytes it covers. Ask how many client writes can share a single one, and what ordering of file syncs makes recovery correct.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is a single-node storage-engine problem. The key ideas are the disk cost model (sequential vs. random I/O, fsync latency), making most data immutable so that concurrency is cheap, and being explicit about read, write and space amplification.
1. Requirements and scale
Assume 10 TB on NVMe, 128 GB RAM, about 2 billion keys of ~32 B, values with a ~1 KB median and a tail up to 100 MB, 100K puts/s and 500K gets/s. Targets: p99 get under 2 ms on a cache miss (one SSD read), p99 put under 5 ms, and acknowledged puts survive power loss.
A Bitcask-style index holding every key in RAM would need roughly 2B x 50 B = 100 GB. That leaves almost no memory for caching, so a dense hash index is out. A sparse index over sorted files, that is an LSM tree, is the better fit. Also assume deletes exist (as tombstones), no range scans are required, and single-key consistency is enough.
2. Architecture
put -> WAL (group commit, fsync) -> memtable (concurrent skiplist)
memtable full (~64 MB) -> immutable memtable -> flush -> L0 SSTables
background compaction -> L1..Ln (sorted, non-overlapping)
Large values (> ~4 KB) -> append-only blob files; SSTables hold pointers
get -> memtable -> immutable memtable -> L0 -> L1.. (bloom + sparse index) -> block cache
Each record carries (key, seqno, PUT|DEL, value-or-pointer). A global increasing sequence number decides which version of a key is newest.
3. Indexing to minimise seeks
- Memtable: recent writes sit in a sorted in-memory structure, so reading recent data costs no I/O.
- SSTables: immutable sorted files of 4-16 KB blocks. Each has a sparse index (first key and offset per block) held in RAM. At 10 TB with 16 KB blocks that is tens of GB, so use a partitioned two-level index and pin only the top level, or use larger blocks.
- Bloom filters: about 10 bits per key gives ~1% false positives and costs ~2.5 GB for 2B keys. A get skips almost every file that lacks the key.
- Leveled compaction: levels L1 and up do not overlap, so a lookup touches at most one file per level. Combined with Bloom filters, a cache-miss get costs about one SSD read.
- Block cache: LRU or CLOCK over decoded blocks serves the hot working set without I/O.
4. Large values
Use key-value separation (the WiscKey idea).
- Values above a threshold (say 4 KB) are appended to blob log files. The LSM tree stores a ~20 B pointer
(file, offset, length). - Memtables and compactions now move only keys and pointers, which cuts write amplification dramatically.
- Reads of huge values stream with
preador chunked iterators rather than loading the whole blob onto the heap. Keep blobs out of the block cache, or give them a small separate cache, so one big value cannot evict the hot set. - For very large puts, write and fsync the blob first and only then log the pointer in the WAL, so the WAL never points at non-durable bytes.
- Cost: blob files need their own garbage collection, and range reads of large values become random reads.
5. Concurrency
The central principle is that disk files are immutable, so readers never lock them.
- Memtable: a lock-free (CAS-based) skiplist, or N shards chosen by
hash(key) % N, each with its own lock. - Versions: the set of memtables and SSTables per level forms an immutable, reference-counted
Version. A reader grabs the current version, bumps the refcount and reads lock-free. Flush and compaction build a new version and swap the pointer under a short mutex. Files are deleted only when their old version's refcount drops to zero. - Writers: requests enter a group-commit queue. A leader batches them, assigns contiguous sequence numbers and does one WAL append. Writers then insert into the memtable in parallel.
- Visibility: the latest sequence number is published only after the memtable insert, so readers see a consistent snapshot.
- Avoid: a single global read-write lock. At hundreds of thousands of ops/s its cache line becomes the bottleneck.
6. Durability without an fsync per write
- Group commit: an NVMe fsync costs roughly 50-500 microseconds. Gather writes arriving within ~1 ms (or up to ~1 MB), do one
writeplusfdatasync, then acknowledge them all. Throughput grows with batch size and latency rises only by the batching window. - Cheaper syncs: preallocate and recycle WAL files so
fdatasyncneed not flush size metadata. - Torn writes: every WAL record has a length and CRC32C. Recovery replays the log into a memtable and stops at the first bad record.
- Flush ordering: write the SSTable, fsync it, fsync the directory, append the change to the MANIFEST and fsync that, and only then delete the old WAL. Any crash between steps leaves a recoverable state.
- Optional relaxed mode: a per-write
sync=falseflag for callers who accept losing about a millisecond of data. It must be an explicit contract, never the default.
7. Trade-offs to mention
- LSM vs. B+tree: the LSM gives sequential writes and good compression, but reads may probe several files and compaction burns background I/O. A B+tree reads well but does random in-place writes and still needs a WAL. For write-heavy SSD workloads the LSM wins.
- Leveled vs. tiered compaction: leveled has low read and space amplification but higher write amplification; tiered is the reverse. Pick leveled for a read-heavy mix like this one.
- Bloom filter size: more bits per key means fewer wasted reads but more RAM.
- Group-commit window: a longer window raises throughput and p99 put latency together.
Common mistakes
- Proposing a full in-memory hash index without checking that it fits in RAM.
- Calling fsync once per put and then wondering about throughput.
- Using one global lock around the whole store.
- Rewriting huge values during every compaction.
- Deleting the WAL before the flushed SSTable and its manifest entry are durable.
- Ignoring torn-write detection during recovery.