Video in progress

You have to write an append-only journal (WAL) file for your service yourself. How do you design the format and the write order so that it recovers correctly after a crash?

You write each record as length + checksum + data; on recovery you drop the last incomplete or corrupt record. You batch fsync with group commit, split the file into segments, and delete old segments after a checkpoint.

📖 Answer

A crash can happen at any byte. So the main question is: "if the end of the file is incomplete, how do I know where to stop?"

The record format:

[len: int32][crc32c: int32][type: byte][payload: len bytes]

On recovery you read the records from the start; if len runs past the end of the file or the CRC doesn't match, you treat everything after that point as "not written" and cut the file there (truncate). Without a CRC you can't recognize an incomplete record: the sector may be filled with zeros or old garbage. In Java, java.util.zip.CRC32C is ready-made and fast at the hardware level.

The write order:

  1. Add the record to the buffer.
  2. FileChannel.write: into the page cache.
  3. force(false): to disk.
  4. Only after that, "OK" to the caller.

If you fsync every record, throughput is limited by disk latency. Group commit: writer threads put records in a queue, a single flush thread writes the gathered ones, does one force, and completes all their CompletableFutures. As load grows, a single fsync covers more records.

Segments: instead of one endless file, say, 256 MB files like 000000001234.log. Inactive segments are immutable, so they are easy to delete, archive and replicate. When a new segment is created, don't forget to fsync the directory too.

Additional questions to settle: the record version (you have to be able to read old segments if the format changes), what to do on an fsync error (the safest is to stop the process, not retry), and a full disk.

And most importantly: do you really need this? In many cases a PostgreSQL table, a Kafka topic or a ready-made library like Chronicle Queue gives the same guarantees with code that has been tested for years. Go for writing your own only when latency or deployment constraints really force you to, and add crash tests (kill -9 on the process, filling the disk) to CI.