Log on disk, hash in RAM

A Bitcask is exactly two structures: an append-only log of records on disk and a single in-memory hash (the keydir) mapping each live key to the byte offset of its newest record.

Scene 01

Log on disk, hash in RAM

  1. Watch
  2. Try it
  3. Predict
  4. Capture
DATA DIRECTORY001.dataclosed · immutable002.dataclosed · immutable003.dataactive · acceptingKEYDIR (in RAM)keyfile_idvalue_posvalue_szOPERATIONcell: crc · tstamp · ksz · vsz · key=valueidle — no operation in flightEmpty directory · empty keydir.
What to watch for

An empty Bitcask: no data files written, no keydir rows. Watch what a PUT actually does — one record lands on disk, one row appears in the keydir. Two structures, growing in lockstep.

Continue unlocks when the animation finishes.
Implementation

Highlighted lines are the ones running in the diagram right now.

Record on disk
fixed-size header + two variable blobs; appended at tail
# one entry in <file_id>.data, written end-to-end:
record = struct(
crc: u32, # checksum of the bytes that follow
tstamp: u32, # logical write time
ksz: u32, # key size in bytes
vsz: u32, # value size in bytes
key: bytes[ksz],
value: bytes[vsz],
)
# closed files are immutable forever; only the active file appends.
Bitcask.put
append a record at the active tail, then retarget the keydir slot
def put(key, value):
tstamp = now()
bytes = encode(crc, tstamp, len(key), len(value), key, value)
offset = active_file.size # current end-of-file
active_file.append(bytes) # sequential write
fsync_if_policy(active_file) # sync_strategy
keydir[key] = Entry(
file_id = active_file.id,
value_pos = offset + header_sz + len(key),
value_sz = len(value),
tstamp = tstamp,
) # one slot per LIVE key
return ok
Bitcask.get
one hash lookup; one pread at the recorded offset
def get(key):
entry = keydir.lookup(key)
if entry is None: return not_found
fd = open_or_reuse(entry.file_id)
bytes = pread(fd, entry.value_pos, entry.value_sz)
return bytes # at most one disk seek

Where this sits in Build a Bitcask-style KV store

Scene 01 of 9, in the Anatomy act — Log on disk, hash in RAM — and the four-step write.. A Bitcask is exactly two structures: an append-only log of records on disk + a single in-memory hash (the keydir). Every other property follows from this split.

Up next. Two structures, two responsibilities — but every PUT touches both, in a specific order. Get the order wrong and the ack means nothing. Time to look at the four steps the writer actually takes.

All 9 scenes in Build a Bitcask-style KV store · Every curriculum

Built with Arqly
Every scene in Build a Bitcask-style KV store builds on the one before it.All 9 Build a Bitcask-style KV store scenes