Write-Ahead Log Implementation in C#
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 C# as in every other language.
- ✓FileStream opened with FileMode.Append plus Flush(flushToDisk: true), which is the fsync, and FileOptions.WriteThrough when you want the OS cache bypassed on Windows.
- ✓The append signature takes ReadOnlySpan<byte> and builds its header with stackalloc, so the hot path allocates nothing.
- ✓The C# trap: Disposal is not durability. using or Dispose flushes FileStream's managed buffer into the OS and returns, so a process that shut down cleanly can still lose its tail to a power cut; only Flush(true) forces the device.
- ✓stackalloc plus BinaryPrimitives makes append allocation-free, and Crc32.HashToUInt32 over a span never materialises an array.
What Write-Ahead Log actually is
Write-Ahead Log in C#: what you actually reach for
C# implementation
using System.Buffers.Binary;
using System.IO.Hashing; // NuGet: System.IO.Hashing
public sealed class Wal : IDisposable
{
private readonly FileStream _fs;
public Wal(string path) =>
_fs = new FileStream(path, FileMode.Append, FileAccess.Write,
FileShare.Read, bufferSize: 64 * 1024,
FileOptions.SequentialScan);
public void Append(ulong lsn, ReadOnlySpan<byte> payload)
{
Span<byte> hdr = stackalloc byte[16]; // ref struct: cannot cross await
BinaryPrimitives.WriteUInt32LittleEndian(hdr, Crc32.HashToUInt32(payload));
BinaryPrimitives.WriteUInt32LittleEndian(hdr[4..], (uint)payload.Length);
BinaryPrimitives.WriteUInt64LittleEndian(hdr[8..], lsn);
_fs.Write(hdr);
_fs.Write(payload);
}
// The ONLY durable call. Dispose() and FlushAsync() are not commit points.
public void Commit() => _fs.Flush(flushToDisk: true);
public void Dispose() => _fs.Dispose();
}
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 C#-specific trap
Performance in C#, beyond the O(1) append
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Write-Ahead Log?
FileStream opened with FileMode.Append plus Flush(flushToDisk: true), which is the fsync, and FileOptions.WriteThrough when you want the OS cache bypassed on Windows. Since .NET 6 the leaner path is File.OpenHandle returning a SafeFileHandle driven by the static RandomAccess.Write and RandomAccess.Read, which skips FileStream's own buffer. Checksums come from the System.IO.Hashing NuGet package: Crc32.HashToUInt32 over a ReadOnlySpan<byte>. Framing is BinaryPrimitives.WriteUInt32LittleEndian and WriteUInt64LittleEndian into a stackalloc Span<byte>, with ArrayPool<byte>.Shared staging payloads.
What is the most common C# mistake when implementing Write-Ahead Log?
Disposal is not durability. using or Dispose flushes FileStream's managed buffer into the OS and returns, so a process that shut down cleanly can still lose its tail to a power cut; only Flush(true) forces the device. Worse, no asynchronous overload forces to disk, so FlushAsync is not a commit point and awaiting it proves nothing. And because Span<byte> is a ref struct that cannot live across an await, the natural header-building code will not even compile inside an async method, which quietly pushes the whole log path back to synchronous code. FileOptions.WriteThrough is a Windows FILE_FLAG_WRITE_THROUGH concept; do not assume identical semantics on Linux or macOS.
How does Write-Ahead Log actually perform in C#?
stackalloc plus BinaryPrimitives makes append allocation-free, and Crc32.HashToUInt32 over a span never materialises an array. FileStream adds one memcpy through its internal buffer that RandomAccess.Write on a SafeFileHandle avoids entirely. Flush(true) blocks a thread, and if that is a thread-pool thread under load you get pool starvation, so run commits on one dedicated thread and let callers await a TaskCompletionSource. Payload buffers above 85 KB land on the large object heap; rent from ArrayPool instead. 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.