Internals

raftdb-table, the hash index

How the segmented hash table maps a 64-bit hash to a 32-bit slot, how buckets are searched and split, and its memory cost.

raftdb-table maps a 64-bit hash to a 32-bit slot number. The caller owns a slab with the keys and values; the table stores only one fingerprint byte and four slot bytes per entry and asks the caller to compare real keys. It has no dependencies. Its design follows the study of Dragonfly's DashTable.

Memory layout#

SlotTable { dir: Vec<*mut Segment>, shift: u32 (= 64 - global depth), len: usize }
Segment   (4,160 bytes, 64-aligned) { depth: u32, [pad to 64], b: [Bucket; 64] }
Bucket    (64 bytes = one cache line) { fp: [u8; 16] (12 used, 0 = empty), slot: [u32; 12] }

The hash is used in independent bit ranges: the directory index is the top global depth bits, the bucket is bits 8..14 ((h >> 8) & 63), and the fingerprint is the low 8 bits (0 is mapped to 1).

Operations#

CallBehaviour
get(h, eq)Search the home bucket and the next one: one SSE2 compare of 12 fingerprints, then eq(slot) for each match.
insert(h, slot, rehash)The caller guarantees the key is absent. The entry goes into the emptier of the two buckets. If both are full the segment splits (the directory doubles first if needed) and the insert is retried.
remove(h, eq)Clears the fingerprint; no tombstones are needed because lookups check both buckets anyway.
for_each(f)Visits every entry once, in arbitrary order.
prefetch(h)Starts loading the home bucket. Prefetching a batch of hashes and then calling get for each gave +30 % read throughput.

Splitting#

Entries whose next hash bit is 1 move to a new segment at the same bucket and slot position, so a split cannot fail. A guard (depth < 40) stops endless splitting when many keys share one hash.

Numbers and limits#

  • Memory per entry: 8.75 bytes measured at 1 M-2 M entries; 8.7-12.1 bytes from 0.3 M to 2 M entries. Right after every segment has split the fill is about 45 %.
  • Not thread-safe by design: one owner per shard. It is Send, so a shard can move between threads.
  • No shrinking or merging after deletes; freed slots are reused.
  • 32-bit slots: at most about 4.29 billion rows per shard.
  • unsafe is used for raw segment pointers, unchecked directory access and the SSE2 and prefetch intrinsics; each block has a safety comment.

Portable and fast paths#

The bucket search and the prefetch each have a portable version (mask_swar: 64-bit arithmetic that compares 8 bytes at once; an ordinary load for prefetch) and an x86_64 fast path (SSE2, _mm_prefetch). A test compares the fast, the portable and a one-byte-at-a-time version on 300,000 random fingerprint sets built from edge-case bytes. End to end, the portable build reads 11.1-12.0 M/s against 15.2 M/s. See Portability.

Tests#

Layout (bucket 64 bytes, segment 4,160 bytes); 400,000 random get, insert and remove steps against std::HashMap; 1,000,000 inserts then lookups plus a miss, in debug and release.