A persistent, ordered key-value storage engine in modern C++17, built as a log-structured merge-tree (LSM) with a WAL for crash recovery, per-SSTable Bloom filters, size-tiered compaction, and a small REST API — the same architecture that backs LevelDB / RocksDB.
- Write-ahead log (WAL) — every
put/deleteis appended (andfsync'd) to an on-disk log before it becomes visible, so an acknowledged write is never lost to a crash. On startup the WAL is replayed to rebuild in-memory state. - Memtable — an in-memory, sorted (
std::map) write buffer. When it exceeds a byte threshold it is flushed to an immutable on-disk SSTable and the WAL is reset. - SSTable — immutable, sorted on-disk files with a defined binary format: a data block, a full key index for binary-search point lookups, a per-file Bloom filter, and a fixed footer. (Format documented below.)
- Reads —
getchecks the memtable first, then SSTables newest-to-oldest, using each SSTable's Bloom filter to skip files that provably cannot contain the key. Deletes are tombstones that shadow older values. - Compaction — size-tiered: once SSTables pile up they are merged (k-way heap merge) into a single new file, discarding overwritten values and dropping tombstones.
- Clean C++ API —
ferrodb::DBwithOpen/Put/Get(returnsstd::optional<std::string>) /Delete/GetStats/Close. Thread-safe via a single mutex. - REST server —
ferrodb-serverexposesGET/PUT/DELETE /kv/{key}andGET /stats(JSON) via the vendored single-headercpp-httplib. - Benchmark mode —
--bench Nmeasures put/get throughput on N keys. - Tested — 11 doctest cases wired through CTest covering put/get/delete, overwrite, tombstone visibility across flush boundaries, flush→SSTable, multi-SSTable reads, WAL crash recovery, Bloom filter correctness + serialization, and compaction correctness, plus a 5k-key mixed workload.
WRITE PATH
put(k,v) / del(k)
│
▼
┌──────────────┐ 1. append record (fsync)
│ Write-Ahead │◄──────────────────────────────┐ durability point:
│ Log (disk) │ │ write is safe here
└──────────────┘ │
│ 2. apply │
▼ │
┌──────────────┐ grows past threshold │
│ Memtable │ ─────────────────────────┐ │
│ (RAM, sorted)│ │ │
└──────────────┘ ▼ │
┌──────────────────┐
│ flush: write │ then reset WAL
│ sorted SSTable │
└──────────────────┘
│
too many SSTables ▼
┌───────────────────────┐ ┌───────────────────────────────┐
│ size-tiered compaction│──►│ SSTable_new SSTable SSTable …│ (disk, newest→oldest)
│ k-way merge, drop │ └───────────────────────────────┘
│ tombstones/overwrites │
└───────────────────────┘
READ PATH
get(k)
│
▼
Memtable ──found?──► return value
│ miss / (tombstone ⇒ return "absent")
▼
SSTable_newest ─[Bloom says maybe]→ index binary-search ─found?─► value
│ Bloom says "no" ⇒ skip file entirely
▼
… older SSTables …
│
▼
not found ⇒ std::nullopt
Why an LSM tree? It turns random writes into sequential disk writes (append to WAL, then flush a sorted file), which is dramatically faster than in-place B-tree updates on write-heavy workloads. The cost is read amplification (a key may live in several files), which the Bloom filters and compaction are there to contain.
All integers are little-endian, fixed width. See include/ferrodb/encoding.h.
[u32 crc32 of the bytes that follow]
[u8 type] 0 = Put, 1 = Delete
[u32 key_len][key bytes]
[u32 val_len][value bytes] (val_len == 0 for a Delete)
The CRC lets replay detect a torn tail — a record whose write was interrupted by a crash. Replay stops at the first record that fails to parse or whose checksum mismatches, discarding the partial tail. Everything before it is durable and recovered.
┌───────────────────────────────────────────────────────────┐
│ DATA BLOCK entries sorted ascending by key │
│ entry = [u8 type][u32 klen][key][u32 vlen][value] │
│ type: 0 = value, 1 = tombstone │
├───────────────────────────────────────────────────────────┤
│ INDEX BLOCK one record per key, sorted ascending │
│ record = [u32 klen][key][u64 data_offset] │
├───────────────────────────────────────────────────────────┤
│ BLOOM BLOCK serialized Bloom filter over all keys │
│ [u32 num_hashes][u32 num_bits][bit bytes] │
├───────────────────────────────────────────────────────────┤
│ FOOTER (fixed 48 bytes) │
│ [u64 index_off][u64 index_size] │
│ [u64 bloom_off][u64 bloom_size] │
│ [u64 num_entries][u64 magic = 0xF3EED0DB…] │
└───────────────────────────────────────────────────────────┘
A reader seeks to the last 48 bytes, validates the magic, then loads the index and Bloom filter into memory. A point lookup consults the Bloom filter, binary-searches the in-memory index, and reads exactly one entry from disk. The magic doubles as a "file is complete" check — a half-written SSTable (crash mid-flush) has no valid footer and is ignored on open.
The SSTable sequence number in the filename encodes recency: higher = newer. On open the directory is scanned and tables are ordered newest-first for reads.
Requires CMake ≥ 3.14 and a C++17 compiler. All third-party dependencies are single-header and vendored under third_party/ — no network needed to build.
cmake -S . -B build
cmake --build build -j
ctest --test-dir build --output-on-failureThis produces build/libferrodb.a (engine), build/ferrodb-server (REST server + benchmark), and build/ferrodb_tests.
./build/ferrodb-server --data ./ferrodb-data --host 127.0.0.1 --port 8080# store a value (body is the value)
$ curl -s -X PUT --data-binary 'hello world' http://127.0.0.1:8080/kv/greeting
stored
# read it back -> 200
$ curl -s http://127.0.0.1:8080/kv/greeting
hello world
# delete it -> 200
$ curl -s -X DELETE http://127.0.0.1:8080/kv/greeting
deleted
# read again -> 404
$ curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/kv/greeting
404
# engine stats -> JSON
$ curl -s http://127.0.0.1:8080/stats
{
"compactions": 0,
"flushes": 0,
"memtable_bytes": 0,
"memtable_entries": 0,
"sstable_count": 0,
"total_sstable_entries": 0,
"wal_bytes": 61
}./build/ferrodb-server --bench 100000 --data /tmp/ferrodb-benchMeasures sequential-put and random-get throughput with WAL fsync on (the durable, conservative measurement).
std::mapmemtable, not a hand-rolled skiplist. A red-black tree gives the same asymptotics (O(log n) insert/lookup, ordered iteration for flushing) with zero bug surface. A skiplist would be the natural next step for lock-free concurrent writes; that's noted under improvements.- Full key index per SSTable, not a sparse block index. Every key has an index entry, so a lookup is a single binary search + one
pread. This trades a little memory/space for simpler, predictable point-read code. Real engines use sparse indexes + data blocks to shrink the index; the format here has room to evolve toward that. - Bloom filter via Kirsch–Mitzenmacher double hashing. From one 64-bit FNV-1a hash we derive all k probe positions as
h1 + i·h2. This is the standard LevelDB/RocksDB trick: it avoids computing k independent hashes while keeping the false-positive rate at the theoretical optimum. Bits and hash-count are sized from the classicm = -n·ln(p)/(ln2)²,k = (m/n)·ln2formulas. - CRC32 on every WAL record. Durability isn't just "did we write it" — it's "can we tell a good record from a torn one after a crash." The checksum makes replay self-terminating at the corruption boundary instead of reading garbage.
- Full compaction (merge all → one). Size-tiered compaction that merges every table at once is the simplest form that is provably correct about dropping tombstones: because no older table survives the merge, a tombstone can be physically removed with no risk of resurrecting a shadowed value. Leveled compaction (RocksDB) has better space/write amplification but is far more intricate; the trade-off is deliberate for a readable reference implementation.
- Single global mutex. All operations serialize on one lock. This makes the concurrency model trivial to reason about and correct by construction. Reads and writes are thread-safe but do not run in parallel. Flush and compaction run synchronously inside the writing thread, which can cause a latency spike — the honest cost of the simple model.
fsyncon by default. Correct-by-default durability. It's a config flag (Options::sync_writes) because throughput-sensitive callers may accept losing the last few writes on a hard crash.
Building this made the LSM read/write amplification trade-off concrete: writes are cheap (sequential append) but a single get can, in the worst case, probe every SSTable — which is exactly why Bloom filters and compaction are not optional niceties but load-bearing parts of the design. Getting tombstone visibility right across flush and compaction boundaries was the subtlest part: a delete has to shadow an older on-disk value until compaction can safely retire both, and "safely" has a precise meaning (no older table survives the merge).
Concrete next steps I'd take:
- Background flush & compaction threads so writes never block on disk I/O, with a double-buffered (immutable) memtable during flush.
- Skiplist memtable to enable concurrent writers without a global lock.
- Leveled compaction for bounded space amplification, plus partitioned/sparse index + data blocks to shrink the in-memory index footprint.
- Block compression (Snappy/LZ4) and per-block CRCs in SSTables.
- A MANIFEST / versioned edit log so the set of live SSTables is recovered from a log rather than a directory scan, enabling atomic multi-file installs.
- Range scans / iterators over the merged keyspace (the SSTable iterator + heap merge already used by compaction is most of the machinery).
- Snapshots & MVCC via per-record sequence numbers.
ferrodb/
├── CMakeLists.txt
├── README.md
├── .gitignore
├── include/ferrodb/ public headers (encoding, bloom_filter, memtable, wal, sstable, db)
├── src/ engine implementation + server.cpp (REST + --bench)
├── tests/ doctest suite, wired via CTest
└── third_party/ vendored single-header deps (httplib, doctest, nlohmann/json)