Design a Single-Node Durable Key-Value Engine
System DesignModel answerLast updated
Design an embeddable single-node key-value storage engine providing durability, high write throughput, crash recovery, and single-key transactions.
Provide an architectural design for a single-node, durable key-value store supporting put(key, value), get(key), and delete(key) operations.
Your proposal should cover:
- Target Workload & Scale Constraints: Hardware specs, throughput targets, key/value size assumptions, and explicit durability/consistency definitions.
- Storage Architecture & Data Layout: In-memory and on-disk data structures (e.g., WAL, MemTable, SSTables), internal block structures, and indexing/filter mechanisms.
- Write/Read Execution Paths: Step-by-step trace of how writes, deletes, and point reads are processed across memory and disk structures.
- Durability, Group Commit & Crash Consistency: Mechanics of the Write-Ahead Log (WAL), handling disk-syncing trade-offs, dealing with torn/truncated writes, and step-by-step recovery logic after an ungraceful shutdown.
- Garbage Collection & Data Compaction: Compaction strategies, write/read amplification trade-offs, space reclamation, and tombstone handling.
- Concurrency Model: Synchronization strategy for concurrent reads and writes, isolation level, and how locks or lock-free structures are utilized.
- Verification & Failure Injection: Strategy for testing crash consistency and data integrity.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
High-Performance Single-Node Key-Value Store Architecture
1. System Requirements & Scale Assumptions
Functional Interface
put(key, value): Inserts or updates the mapping forkey.get(key): Returnsvalueif found, orNotFound.delete(key): Removes the entry associated withkey.
SLA & Scale Targets
- Node Capabilities: 1× modern server node with 32 CPU cores, 64 GB RAM, and a high-end NVMe drive capable of 500,000 random read IOPS and 3 GB/s sequential write bandwidth.
- Dataset Target: 1 TB total storage (~1 billion entries at 1 KB average record size).
- Workload Mix: 80% Reads (200K ops/sec), 20% Writes/Deletes (50K ops/sec).
- Key/Value Dimensions: Keys: 16–128 Bytes (avg 32 B). Values: 100 Bytes–10 KB (avg 1 KB).
Guarantees
- Durability (Strict): A return code of
Successfor a write operation guarantees that the modification survives immediate host power failure or kernel panic (fsync/fdatasyncflushed to non-volatile media). - Consistency: Single-node linearizability (Sequential Consistency with real-time ordering). Every completed write is immediately visible to subsequent reads across all threads.
2. Core Architecture: Log-Structured Merge-Tree (LSM)
A Log-Structured Merge-Tree (LSM) architecture is chosen over a B+ Tree to optimize for write bandwidth on flash storage. High random write activity on a B+ Tree causes high write amplification and costly random disk updates. An LSM converts random writes into sequential disk operations.
+-------------------------------------------------------------------------+
| WRITE PATH |
+-------------------------------------------------------------------------+
│
▼
+---------------+ Batch Flush +-------------------+
| Group Commit | ------------------> | Write-Ahead Log | (Disk append + fdatasync)
| Queue | | (WAL) |
+---------------+ +-------------------+
│
▼
+---------------+
| MemTable | (In-Memory Concurrent SkipList / Lock-free Index)
+---------------+
│
│ (When MemTable reaches ~64 MB threshold)
▼
+---------------+
| Immutable |
| MemTable |
+---------------+
│
│ Background Flush Thread
▼
+-------------------------------------------------------------------------+
| DISK |
| |
| L0: [SSTable] [SSTable] <-- Overlapping Key Ranges |
| |
| L1: [SSTable] [SSTable] [SSTable] <-- Non-overlapping Key Ranges |
| |
| L2: [SSTable] [SSTable] [SSTable] [SSTable] ... |
+-------------------------------------------------------------------------+
Components
In-Memory
- Active MemTable: Lock-free Concurrent SkipList storing recent updates. Sorted by
(user_key, sequence_number DESC). - Immutable MemTables: Read-only copies of previous MemTables waiting to be flushed to disk.
Disk-Based
- Write-Ahead Log (WAL): Append-only sequential file ensuring durably committed operations survive crashes prior to MemTable flushing.
- SSTables (Sorted String Tables): Immutable, block-oriented files structured hierarchically into levels ($L_0, L_1, \dots, L_k$).
- MANIFEST & CURRENT: Metastore tracking active SSTable files, level assignments, active WAL identifiers, and schema versions via an append-only log of metadata edits.
3. Data Layout & Formats
Write-Ahead Log Structure
The WAL is organized as a sequence of fixed-size 32 KB blocks to facilitate payload alignment and corruption isolation.
+-------------------+--------------------+------------------+---------------------+
| CRC32C (4 Bytes) | Payload Len (2 B) | Record Type (1 B)| Payload Data (...) |
+-------------------+--------------------+------------------+---------------------+
- Record Types:
FULL(entire record fits in block),FIRST,MIDDLE,LAST(record fragmented across 32 KB boundaries). - Payload Structure:
| SequenceNumber (8 B) | Record Type Flag (1 B: Put=1, Delete=2) | Key Length (2 B) | Key | Value Length (4 B) | Value |
SSTable File Format
Each SSTable is written as an immutable single file:
+-------------------------------------------------------------+
| Data Block 0 |
| Data Block 1 |
| ... |
| Data Block N |
+-------------------------------------------------------------+
| Filter Block (Bloom Filters for each Data Block) |
+-------------------------------------------------------------+
| Index Block (Data Block offsets & high-keys) |
+-------------------------------------------------------------+
| Properties Block (Stats: total entries, raw sizes) |
+-------------------------------------------------------------+
| Footer (Fixed 48 bytes: Index Offset, Filter Offset, Magic) |
+-------------------------------------------------------------+
-
Data Block Structure (~4 KB decompressed): Entries are stored sorted by
(user_key, sequence_number DESC). To conserve space, keys use delta encoding against preceding keys:| Shared Key Prefix Len (varint) | Unshared Key Len (varint) | Value Len (varint) | Key Delta Bytes | Value Bytes |Each Data Block ends with a restarting point offset array (every 16 keys) to allow fast binary searches without scanning from the block start.
-
Index Block: Contains an array of entries mapping the highest key of each Data Block to its physical byte offset and length within the SSTable.
-
Bloom Filter Block: A bit array calculated using dynamic MurmurHash3 functions allocating ~10 bits/key (~1% false positive rate). A single bloom filter is computed for the whole SSTable or broken into per-block fragments.
4. Operation Paths
Write Path (put / delete)
- Assign Sequence Number: Acquire a globally unique, monotonically increasing 64-bit sequence number ($SeqNum$).
- Package Entry: Wrap payload. A
deleteis represented as a tombstone record (Type = Delete,Value = NULL). - Group Commit Queue: Append payload to the active write-batch queue (see Section 5).
- WAL Append: Write the batch to the active WAL file. Issue
fdatasync()to force physical storage persistence. - MemTable Write: Insert entries into the active MemTable using $SeqNum$.
- Acknowledge: Return
Successto client.
Read Path (get)
- MemTable Search: Query the active MemTable. If found, return value (or
NotFoundif tombstone). - Immutable MemTables: Search immutable MemTables in reverse chronological order.
- Disk $L_0$ SSTables: Search files in Level 0 (newest to oldest). Because $L_0$ files can have overlapping key ranges, all candidate $L_0$ SSTables whose key ranges encompass the requested key must be evaluated.
- Optimization: Check the Bloom Filter in RAM/Cache before reading any SSTable disk block.
- Disk $L_1$ to $L_k$ SSTables: For each non-overlapping lower level, perform binary search on the level's key bounds to locate the single candidate SSTable. Check Bloom Filter, read Index Block, locate and read Data Block.
- Resolve Latest Key: The first matching record encountered across the step order guarantees the latest $SeqNum$. If record payload is marked
Delete, returnNotFound.
5. Durability, Group Commit & Crash Recovery
The Durability Bottleneck & Group Commit Strategy
Issuing fdatasync() on every single write locks latency to physical disk sync bounds (~50–200 µs on NVMe), capping single-threaded throughput at ~10,000 ops/sec.
To reach 50,000+ durable writes/sec, we implement Group Commit:
Client Threads Group Leader Disk
│ │ │
├──► Enqueue(Write1) ──┐ │ │
├──► Enqueue(Write2) ──┼─► [Lock Free] │
└──► Enqueue(Write3) ──┘ Batch Queue │
│ │
├──► Take Batch (Write1..3) │
├──► Write Batch to WAL File │
├──► fdatasync() --------------------> │ (Flushed to NVMe)
├──► Insert Batch into MemTable │
└──► Wakeup Followers & Return Success │
- Concurrent caller threads push their write requests to a lock-free queue.
- The first thread to enter an empty queue becomes the Group Leader. Subsequent arrivals wait on a condition variable.
- The Leader collects all pending write requests up to a max batch size (e.g., 4 MB or 1,000 operations).
- The Leader appends the batch to the WAL in a single
write()call, and issuesfdatasync(). - After
fdatasync()completes, the Leader writes all items into the active MemTable and notifies waiting followers. - All threads in the batch return to their callers simultaneously.
Crash Recovery Protocol
When the storage engine starts after an ungraceful shutdown:
+-------------------------+
| Read CURRENT & MANIFEST |
+-------------------------+
│
▼
+-------------------------+
| Verify & Rebuild |
| Active SSTable Map |
+-------------------------+
│
▼
+-------------------------+
| Locate Unflushed WALs |
| (SeqNum > Last Manifest)|
+-------------------------+
│
▼
+-------------------------------------+
| Read WAL Record Block by Block |
+-------------------------------------+
│
┌─────────────────────┴─────────────────────┐
│ │
[CRC Check Succeeded] [CRC Fail / Truncated]
│ │
▼ ▼
+---------------------------+ +---------------------------+
| Replay Op into MemTable | | Is Last Record in Log? |
+---------------------------+ +---------------------------+
│ │ │
│ (Yes) (No)
│ │ │
│ ▼ ▼
│ +----------------+ +----------------+
│ | Truncate Tail | | Fatal Error: |
│ | (Unacknowledged| | Corruption in |
│ | Write Drop) | | Mid-Log Body |
│ +----------------+ +----------------+
│ │
└───────────────────┬──────────────┘
│
▼
+-------------------------+
| Flush MemTable to L0 |
| Update MANIFEST |
+-------------------------+
- Reconstruct Metadata: Read
CURRENTfile to locate the activeMANIFEST. ReplayMANIFESTentries to obtain the precise state of SSTable distribution across levels, maximum written sequence number ($SeqNum_{max}$), and active log files. - Discover Orphan Files: Identify SSTables on disk not tracked by
MANIFEST(due to interrupted compactions). Safely delete these files. - Replay Unflushed WALs: Identify WAL files containing sequence numbers higher than the last flush checkpoint recorded in
MANIFEST. Read and parse sequential 32 KB blocks:- Torn Write at Tail: If reading the final block encounters a CRC mismatch or incomplete payload length (a direct result of a power loss mid-write), discard the partial trailing record. Because the group commit never returned
Successfor an interrupted payload, durability is not violated. - Corruption in Mid-Log: If CRC validation fails on an intermediate block followed by valid blocks, treat this as severe storage corruption. Halting engine initialization is required to prevent data contamination.
- Torn Write at Tail: If reading the final block encounters a CRC mismatch or incomplete payload length (a direct result of a power loss mid-write), discard the partial trailing record. Because the group commit never returned
- Restore MemTable State: Populate a fresh MemTable with all valid replayed operations. Once completed, issue an explicit flush to an $L_0$ SSTable to clean the WAL, then accept incoming traffic.
6. Maintenance & Compaction Policies
As modifications accumulate, reading requires querying multiple files ($L_0 \dots L_k$). Furthermore, obsolete updates and tombstones consume storage. A Background Compaction Worker cleans up data and organizes SSTables.
Leveled Compaction Strategy
- Level Configuration: $L_0$ file count is capped (e.g., 4 files). $L_1$ has a total capacity of 10MB, $L_2$ has 100MB, $L_3$ has 1GB... each level scaling by $10\times$.
- Compaction Trigger:
- $L_0 \to L_1$: Triggered when $L_0$ file count exceeds 4.
- $L_n \to L_{n+1}$: Triggered when aggregate byte size of $L_n$ exceeds its target capacity.
L1: [ File A: Key 00-30 ] [ File B: Key 31-60 ] [ File C: Key 61-90 ]
│
▼ Merge Overlapping Files
L2: [ File 1: Key 20-40 ] [ File 2: Key 41-55 ] [ File 3: Key 56-75 ]
Output L2 (Sorted, Split into uniform ~2MB files):
[ New File X: Key 20-45 ] [ New File Y: Key 46-75 ]
Compaction Execution Steps
- Select candidate SSTable from $L_n$.
- Identify all SSTables in $L_{n+1}$ whose key boundaries overlap with the chosen $L_n$ file.
- Perform an $N$-way merge-sort stream across chosen SSTables.
- Resolution Rules:
- If identical user keys exist, write only the entry with the highest $SeqNum$.
- Drop tombstone records only if the key does not exist in any lower level ($L_{n+2} \dots L_k$).
- Output streaming merged keys into new ~2–4 MB SSTables at level $L_{n+1}$.
- Atomically update the storage topology by logging a
VersionEdittoMANIFEST(adding new SSTables, deleting merged input SSTables), then syncingMANIFEST.
7. Concurrency Model
To sustain high read-throughput without locking out ongoing writes, we enforce an MVCC (Multi-Version Concurrency Control) Read-Path combined with a Single-Writer Pipeline.
WRITES READS
+-------------------+ +-------------------+
| Thread 1 Thread 2| | Thread 3 Thread 4|
+---------┬---------+ +---------┬---------+
│ │
▼ │
[Group Commit Queue] │
│ │
▼ │
(Single Mutex / │
Group Leader) │
│ │
Update Sequence # │
Write WAL & MemTable │
│ │
▼ ▼
+-----------------------------------------------------------------+
| Dynamic Shared Snapshot State |
| |
| - Pointer to active MemTable (Lock-Free Read Concurrent Map) |
| - Active SSTable Manifest Version Pointer (Atomic reference) |
+-----------------------------------------------------------------+
Writer Synchronization
- Write operations queue into a lock-free queue managed by a single active Group Leader.
- Updating sequence numbers and inserting into the MemTable requires no global read locks. The active MemTable uses a lock-free SkipList using Compare-And-Swap (CAS) operations for internal node updates.
Reader Isolation
- Lock-Free Reads: Readers fetch a shared reference to the engine's state—including active pointers to current MemTables and the immutable manifest
Versionstruct—via atomic reference counting (std::shared_ptr/ atomic pointers). - Snapshot Reads: When a point-read or iterator starts, it records the current global $SeqNum_{read}$. The read path filters out any record whose sequence number is $> SeqNum_{read}$.
- Lock Elimination: Compaction and flush routines generate completely new SSTable files on disk without modifying existing active files. When a compaction finishes, an atomic swap updates the global
Versionpointer. Readers referencing olderVersionstructures continue uninterrupted until their operation terminates, at which point unreferenced SSTable files are unlinked.
8. Quantitative Resource & Performance Model
Memory Allocation Breakdown (64 GB System)
- MemTables: 2 Active/Immutable buffers $\times$ 64 MB = 128 MB.
- Block Cache: Uncompressed Data Blocks cached via LRU = 32 GB.
- Index & Bloom Filter Cache: Pin top-level block indexes and Bloom Filters in RAM = 12 GB.
- OS Page Cache Overhead: Remaining system RAM (~19.8 GB) used by OS kernel for raw block caching.
Write Amplification & IOPS
- WAL Ingest: $50\text{K writes/sec} \times 1.05\text{ KB/entry} \approx \mathbf{52.5\text{ MB/s}}$ sequential write bandwidth.
- Compaction Amplification ($WA$): With Leveled Compaction ($10\times$ ratio), worst-case write amplification is $\approx 10-15\times$.
- Storage I/O target = $52.5\text{ MB/s} \times 15 \approx \mathbf{787.5\text{ MB/s}}$. Modern NVMe drives easily handle this throughput.
- Read Amplification ($RA$): Point-reads check $1 \text{ MemTable} + \text{Files in } L_0 (\sim 4) + 1 \text{ file per level } (L_1..L_5) \approx \mathbf{10 \text{ potential file checks}}$. Bloom filters reduce actual disk IOPS per read to $\approx 1.05$ block reads per
get()call under normal operating conditions.
9. Reliability Verification & Fault Injection
To validate data integrity, the storage engine should undergo continuous integration testing paired with simulated failures:
1. Crash-Consistency Verification (Jepsen-style / Fault Injection)
- Process Interruption: Run a multi-threaded workload firing concurrent
put/deletecalls while a test harness sendsSIGKILLto the process every $N$ seconds. Upon restart, verify:- The engine successfully completes recovery.
- Every acknowledged write prior to
SIGKILLis retrievable with correct values. - No partial or corrupted operations are visible.
- Power Loss Emulation: Run storage workloads on virtualized infrastructure supporting power-cut injection (
dm-log-writesor Linux kernel fault injection). Verify that un-flushed volatile caches drop data gracefully without breaking historical consistency or corrupting existing SSTables.
2. File Corruption & Bit-Rot Scenarios
- Block Poisoning: Inject zeroed-out blocks or random bit swaps inside WAL files or SSTables. Verify that:
- Read calls detect CRC check mismatches and return explicit read errors instead of corrupted values.
- The recovery process flags mid-log WAL corruption cleanly and halts engine startup.
3. Property-Based Linearizability Checking
- Execute concurrent randomized operations against both the LSM storage engine and an in-memory reference model (e.g., a single-threaded hash map protected by a global lock).
- Record operation start time, end time, inputs, and outputs. Run an offline linearizability checker to guarantee that output histories strictly adhere to sequential consistency rules.