Write-Ahead Log Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Write-Ahead Log runs in O(1) append time and O(n) space, in Rust as in every other language.
- ✓std::fs::OpenOptions::new().create(true).append(true).open(path) yields a File whose sync_data() is fdatasync and sync_all() is fsync including metadata.
- ✓Everything in the log path returns io::Result and no reviewer accepts unwrap there. write_all, never write.
- ✓The Rust trap: Wrapping the log in a BufWriter is the trap that costs data with no error anywhere: BufWriter's Drop implementation flushes on the way out and then throws the resulting io::Error away, so if that final flush fails your last records vanish while every function you called returned Ok.
- ✓There is no GC and no boxing, so the only allocation in an append is the record buffer. Keep one Vec<u8> in the writer and clear() it per record to retain its capacity, or skip it entirely with write_vectored over two IoSlices.
What Write-Ahead Log actually is
Write-Ahead Log in Rust: what you actually reach for
Rust implementation
use std::fs::{File, OpenOptions};
use std::io::Write;
pub struct Wal {
file: File,
hdr: [u8; 16],
}
impl Wal {
pub fn open(path: &str) -> std::io::Result<Self> {
let file = OpenOptions::new().create(true).append(true).open(path)?;
Ok(Wal { file, hdr: [0u8; 16] })
}
pub fn append(&mut self, lsn: u64, payload: &[u8]) -> std::io::Result<()> {
// crc32fast is the zlib/IEEE CRC-32, accelerated via PCLMULQDQ/PMULL.
let mut h = crc32fast::Hasher::new();
h.update(payload);
self.hdr[0..4].copy_from_slice(&h.finalize().to_le_bytes());
self.hdr[4..8].copy_from_slice(&(payload.len() as u32).to_le_bytes());
self.hdr[8..16].copy_from_slice(&lsn.to_le_bytes());
// Deliberately no BufWriter: its Drop flushes and discards the error.
// write_all, never write: write() may report a short write.
self.file.write_all(&self.hdr)?;
self.file.write_all(payload)
}
pub fn commit(&self) -> std::io::Result<()> {
self.file.sync_data() // fdatasync; sync_all() also forces metadata
}
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(1) append
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Write-Ahead Log?
std::fs::OpenOptions::new().create(true).append(true).open(path) yields a File whose sync_data() is fdatasync and sync_all() is fsync including metadata. Writes go through std::io::Write::write_all, or write_vectored with a pair of std::io::IoSlice for header plus payload. Framing needs no crate: u32::to_le_bytes and u64::from_le_bytes live in std. Durability of a freshly created segment also needs File::open(parent_dir)?.sync_all(). CRC is the one real gap, and the ecosystem answer is the crc32fast crate, whose Hasher computes the zlib/IEEE CRC-32 and is accelerated by carry-less multiply, PCLMULQDQ on x86_64 and PMULL on aarch64. It does not use the SSE4.2 crc32 instruction, which can only produce the Castagnoli CRC-32C.
What is the most common Rust mistake when implementing Write-Ahead Log?
Wrapping the log in a BufWriter is the trap that costs data with no error anywhere: BufWriter's Drop implementation flushes on the way out and then throws the resulting io::Error away, so if that final flush fails your last records vanish while every function you called returned Ok. Call flush() explicitly, or into_inner(), and check what comes back. The sibling trap is Write::write, which is permitted to write fewer bytes than you handed it and merely returns the count; used directly it truncates records under pressure. Use write_all. And sync_data on the file does not persist a newly created segment's directory entry, so open and sync the parent directory too.
How does Write-Ahead Log actually perform in Rust?
There is no GC and no boxing, so the only allocation in an append is the record buffer. Keep one Vec<u8> in the writer and clear() it per record to retain its capacity, or skip it entirely with write_vectored over two IoSlices. crc32fast runs at multiple gigabytes a second on its carry-less multiply path, so checksums are free next to the syscall. sync_data blocks the OS thread for milliseconds and std has no async fsync, so group commit means a dedicated syncer thread plus a channel of waiters, never a future. Time complexity is O(1) append and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.