fsync — pick two of safe, fast, simple
sync_strategy is a three-way trade: o_sync, interval=N, none. CRCs make the surviving log valid in every case — fsync controls recency, not corruption.
CRCs answered VALIDITY — the log is parseable no matter what. fsync answers RECENCY — how much of the most-recent tail you keep. Two separate guarantees, and Bitcask makes you pick the recency budget.
Scene 06a
fsync — pick two of safe, fast, simple
- Watch
- Try it
- Predict
- Capture
A 100k writes/sec stream lands in the active file. Watch the durable-up-to marker walk behind the write head; the yellow glow between them is the vulnerable region — bytes the OS hasn't flushed to disk yet. The interval=1s policy is showing here; you'll switch policies in a moment.
Highlighted lines are the ones running in the diagram right now.
def append_with_policy(record, policy):active_file.write(encode(record)) # append to tailif policy == 'o_sync':os.fsync(active_file.fd) # block until on platterdurable_up_to = active_file.tell()elif policy == 'interval':pass # interval_fsync_thread handles itelse: # 'none' — Riak defaultpass # OS writeback decides; loss window 5-30sreturn ack
def interval_fsync_thread(active_file, interval_s):while running:sleep(interval_s)os.fsync(active_file.fd)last_fsync_time = now()durable_up_to = active_file.tell()# vulnerable bytes = bytes appended since last_fsync_time;# bounded by interval_s seconds at line rate
def validate_log(file):valid_end = 0for record, offset in scan(file):expected = crc32(record.body)if record.crc != expected:break # torn tail — drop everything from herevalid_end = offset + record.sizefile.truncate(valid_end) # log is now parseablereturn valid_end
Where this sits in Build a Bitcask-style KV store
Scene 06a of 9, in the Crash & sync act — Recovery, hint files, fsync — pick two.. sync_strategy is a three-way trade (o_sync / interval / none). fsync controls RECENCY; CRC controls VALIDITY — two separate guarantees.
Up next. fsync decides what survives the crash. The next question: what survives merge — and what's the bug when merge and the crash recovery scanner disagree about a deleted key?
All 9 scenes in Build a Bitcask-style KV store · Every curriculum