Internals

raftdb-store, the in-memory collection

The arena and index layout of the in-memory key-to-document map, its operations, compaction, snapshots and measured speed.

raftdb-store joins the slot index (raftdb-table) and the document bytes (raftdb-doc) into one key-to-document map. It has no unsafe code.

Layout#

  • Arena: one Vec<u8>. Each record is [key_len varint][doc_len varint][key][doc], padded with zeros so that the next record starts on an 8-byte boundary.
  • Index: a SlotTable mapping hash_bytes(key) to the record offset divided by 8, as a u32. An arena therefore holds at most 32 GiB; larger data is split across collections or shards (append asserts the limit).
  • The index asks the collection to compare the real key in the arena (find) and to rehash a key when a segment splits (rehash), so no key is stored twice.
  • hash_bytes is a 64-bit multiply-fold hash over little-endian 8-byte words (wyhash constants), pinned by a golden test.

Operations#

CallBehaviour
insert(key, doc)Add; Err(Exists) if present.
put(key, doc)Insert or replace. A same-length document is overwritten in place, otherwise appended and the old record becomes garbage.
get(key)The document bytes.
get_batch(keys, out)Hashes once and requests index buckets in windows of 32 so cache misses overlap. This is the server's read path.
snapshot()A frozen list of live documents (4 bytes each); it implements raftdb_exec::Docs, so filters scan it.
snapshot_cached(&mut SlotCache)Reuses the sorted list between scans; rebuilt only after records were added, removed or moved.
slot_of(key), generation(), snapshot_of(slots)What a secondary index stores, the number of compactions (positions are renumbered at each), and a snapshot of given positions.
delete(key)The record becomes garbage.
compact()Rewrites the arena without garbage and rebuilds the index. Runs automatically when garbage exceeds half the arena and 64 KiB.

Measured#

raftdb-bench store, 1 M entries, 13-byte keys, 100-byte documents, Windows 11:

MetricResultTarget
Overhead beyond key and document15.69 bytes per entryat most 24
Point read, 32-key window5.97 M/sat least 5 M/s
Point read, one at a time4.70 M/sno target
Insert (pre-sized)5.3 M/sn/a
Update, same size / size changes4.3 M/s / 3.4 M/sn/a

A single read costs two dependent memory misses (bucket, then record) on a 130 MB working set. The single-read figure is under the 5 M/s target and the threshold was not changed; the windowed get_batch, which the server uses, is the path that has a target.

Scan, 2 M documents of the sample corpus (111 MB): snapshot build 38 ms; one thread 13.8 M docs/s; six threads 59.7 M docs/s against a target of 50 M.

Tests#

Seven tests, including 300,000 random operations against HashMap with periodic compaction, and get_batch equal to single get.

Open#

Multi-versioning with raftdb-mvcc headers (see MVCC); an arena above 32 GiB.