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
- Watch
- Try it
- Predict
- Capture
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.
Highlighted lines are the ones running in the diagram right now.
# one entry in <file_id>.data, written end-to-end:record = struct(crc: u32, # checksum of the bytes that followtstamp: u32, # logical write timeksz: u32, # key size in bytesvsz: u32, # value size in byteskey: bytes[ksz],value: bytes[vsz],)# closed files are immutable forever; only the active file appends.
def put(key, value):tstamp = now()bytes = encode(crc, tstamp, len(key), len(value), key, value)offset = active_file.size # current end-of-fileactive_file.append(bytes) # sequential writefsync_if_policy(active_file) # sync_strategykeydir[key] = Entry(file_id = active_file.id,value_pos = offset + header_sz + len(key),value_sz = len(value),tstamp = tstamp,) # one slot per LIVE keyreturn ok
def get(key):entry = keydir.lookup(key)if entry is None: return not_foundfd = 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