Write-Ahead Log Implementation in Python
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 Python as in every other language.
- ✓Work at the descriptor level: os.open with os.O_WRONLY|os.O_CREAT|os.O_APPEND, then os.write, os.pwrite and os.writev for a vectored header plus payload.
- ✓Reviewers reject the built-in open() file object for a log: it adds an io.BufferedWriter layer whose flush() is not durability, and text mode is unthinkable.
- ✓The Python trap: There are two buffers between your bytes and the platter and the language shows you only one.
- ✓The interpreter costs tens of microseconds per record; the fsync costs 0.5 to 10 milliseconds, so group commit dominates every micro-optimization you might attempt.
What Write-Ahead Log actually is
Write-Ahead Log in Python: what you actually reach for
Python implementation
import os, struct, zlib
HDR = struct.Struct("<IIQ") # crc32, payload_len, lsn - compiled once
class Wal:
def __init__(self, path: str) -> None:
# O_APPEND keeps each write atomic against other appenders
self.fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)
def append(self, lsn: int, payload: bytes) -> None:
crc = zlib.crc32(payload) # already unsigned on Python 3
os.writev(self.fd, [HDR.pack(crc, len(payload), lsn), payload])
def commit(self) -> None:
# fdatasync is Linux-only; on macOS fsync stops at the drive cache
if hasattr(os, "fdatasync"):
os.fdatasync(self.fd)
else:
import fcntl
fcntl.fcntl(self.fd, fcntl.F_FULLFSYNC)
def replay(path: str):
with open(path, "rb", buffering=0) as f:
while len(hdr := f.read(HDR.size)) == HDR.size:
crc, n, lsn = HDR.unpack(hdr)
body = f.read(n)
if len(body) != n or zlib.crc32(body) != crc:
break # torn tail: stop here, never trust EOF alone
yield lsn, body
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 Python-specific trap
Performance in Python, beyond the O(1) append
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Write-Ahead Log?
Work at the descriptor level: os.open with os.O_WRONLY|os.O_CREAT|os.O_APPEND, then os.write, os.pwrite and os.writev for a vectored header plus payload. Durability is os.fsync(fd) and, on Linux only, os.fdatasync(fd); on macOS you additionally need fcntl.fcntl(fd, fcntl.F_FULLFSYNC) from the fcntl module. Record framing is a reused struct.Struct("<IIQ"), checksums are zlib.crc32, a C implementation returning an unsigned int on Python 3. Segment creation is persisted by opening the parent directory with os.open(dir, os.O_RDONLY) and calling os.fsync on that descriptor.
What is the most common Python mistake when implementing Write-Ahead Log?
There are two buffers between your bytes and the platter and the language shows you only one. f.write() lands in Python's io.BufferedWriter, f.flush() pushes it to the kernel, and only os.fsync(f.fileno()) forces the device, so code that flushes and calls it committed loses data on power loss. os.fdatasync simply does not exist on macOS, so a portable commit path referencing it raises AttributeError at runtime rather than at import. And asyncio has no async fsync: a bare os.fsync inside a coroutine stalls the whole event loop for milliseconds. Push it through asyncio.to_thread, which is real concurrency here because CPython releases the GIL around os.write and os.fsync.
How does Write-Ahead Log actually perform in Python?
The interpreter costs tens of microseconds per record; the fsync costs 0.5 to 10 milliseconds, so group commit dominates every micro-optimization you might attempt. zlib.crc32 runs in C at gigabytes per second and is never the bottleneck. What does hurt is per-record allocation: header + payload builds a fresh bytes object each append, so preallocate a bytearray and hand os.writev a list of memoryview slices instead. Because the GIL is released across os.write and os.fsync, a dedicated syncer thread genuinely overlaps with interpreter work. 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 Devin 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.