Unit 2 of 12 · about 4 hours · implement
Append-only log layout, write-ahead ordering and checksummed records
The log is the durability primitive for everything after it. Checkpoints, compaction and recovery all assume an ordered checksummed record stream.
You'll be able to
- Implement a length-prefixed append-only log with per-record checksums.
- Explain the write-ahead rule: the log record reaches stable storage before the data it describes.
- State what a checksum detects and which corruptions need more than a checksum.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Log-structured storageDDIA 2e - Chapter 4 Storage and Retrieval
Chapter 4, Storage and Indexing for OLTP with Log-Structured Storage, printed pp. 115-124: the two-bash-function store on p. 116, the in-memory hash map, SSTables and the LSM overview
- PostgreSQL WAL segments and XLOG recordsThe Internals of PostgreSQL - Buffer Manager, WAL and Recovery
Chapter 9, Sections 9.2 to 9.4: WAL segment files, the internal layout of a WAL segment, and the internal layout of an XLOG record (page read 2026-10-15)
Read for record layout and LSN ordering. Leave checkpoint processing and recovery for the recovery unit.
- OSTEP log-structured file systemOperating Systems: Three Easy Pieces - Crash Consistency and Data Integrity
Chapter 43, Sections 43.1 and 43.2: the sequential-write motivation and segment writing
Use it for why all writes become sequential.
- OSTEP checksumsOperating Systems: Three Easy Pieces - Crash Consistency and Data Integrity
Chapter 45, Sections 45.3 Detecting Corruption: The Checksum and 45.4 Using Checksums
Read the checksum mechanics only; misdirected and lost writes belong to the torn-writes unit.
Focus on
- Each record is a length prefix, a payload and a checksum. The reader never trusts a length or payload whose checksum fails.
- Write-ahead means the log record is stable before the change it describes becomes visible. A crash between the two replays the log; a crash before the log leaves nothing to replay.
- A checksum detects random corruption inside a record. It does not detect a record written to the wrong address or a write that never arrived; those need addresses and read-back checks.
- The Systems unit on write-ahead logging, recovery, checksums and durability taught the concept. Here the hours go to record layout and ordering at engine depth.
Common mistakes · 3
- Treating the Python
binascii.crc32demo value as a cross-system constant. It is CRC-32 IEEE; RocksDB and PostgreSQL WAL use CRC-32C with a different polynomial, so the values are not interchangeable. - Calling a log durable because
writereturned. The bytes may sit in the OS page cache; durability needs the next unit's sync step. - Letting one file grow forever. Real logs roll fixed-size segments so old data can be reclaimed; later units compact whole segments at a time.
Try it yourself
Closed-book, before checking anything
append(rec) and scan() over a file of length-prefixed records with a 4-byte checksum each. binascii.crc32(b'hello') must equal 0x3610a686, and flipping one payload bit must fail the check on rescan.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.What three fields does each log record need, and in what order are they written?Answer
Length prefix, payload, then checksum over both. The scanner reads the length, then the payload, then verifies the checksum before returning the record.
2.A crash lands between the log append and the in-memory index update. What does recovery do?Answer
It rescans the log and rebuilds the index from the records found. The log is the source of truth; the index is derived state.
3.A record has a valid checksum but holds another record's data. Did the checksum fail?Answer
No. The checksum proves the bytes arrived intact, not that they belong at this address. Misdirected writes need per-record identity such as a key or offset bound to the checksum.
4.Why does PostgreSQL give every WAL record a monotonically increasing LSN?Answer
The LSN orders records across segments, so replay, checkpoints and replication can name a position and agree on what comes before and after it.
Practice
- Building Distributed Systems TH-1: Implement a Write-Ahead Log
Task TH-1, Implement a Write-Ahead Log: append path with checksum
This is a free drill graded in the browser after login. Treat a pass as a drill and keep your local log implementation as the evidence.
You're done when
Your local log round-trips records, rejects a one-bit flip on rescan, and you can state the write-ahead rule in one sentence.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the section
- DDIA 2e - Chapter 4 Storage and RetrievalMartin Kleppmann and Chris Riccomini · required
Read "Storage and Indexing for OLTP" (log-structured storage, B-trees, their comparison and secondary indexes) and "Data Storage for Analytics" (column-oriented storage). Its Bloom filter, tombstone and write-ahead log coverage is brief, so take those from OSTEP and The Internals of PostgreSQL. Build a workload decision table, then connect each claim to a measurement from your small store.
- The Internals of PostgreSQL - Buffer Manager, WAL and RecoveryHironobu Suzuki · support
Read Chapter 1 Sections 1.2 to 1.4 (heap pages and tuples), Chapter 8 (buffer manager and dirty-page flushing) and Chapter 9 Sections 9.1 to 9.8 (WAL segments, XLOG records, checkpoints and recovery). Compare each mechanism with your simplified store. The site is revised often, so note the date you read it.
- Operating Systems: Three Easy Pieces - Crash Consistency and Data IntegrityRemzi and Andrea Arpaci-Dusseau · required
Read Chapter 42 (FSCK and journaling: the crash scenarios, data and metadata journaling and their write order) and Chapter 45 (data integrity: checksums, misdirected and lost writes, scrubbing; https://pages.cs.wisc.edu/~remzi/OSTEP/file-integrity.pdf). Turn each crash scenario into an injection point in your store.
Also in this section
- CMU 15-445 - Storage, Index and Recovery SequenceCarnegie Mellon Database Group · primary
Follow Fall 2025 lectures 3 to 10 and 21 to 22. Do the BusTub projects from tag v20251119-2025fall (https://github.com/cmu-db/bustub/tree/v20251119-2025fall): P1 (ARC replacer, disk scheduler and buffer pool manager) and P2 (B+ tree with a leaf tombstone buffer), with P0 (Count-Min Sketch) as the C++ warm-up. Tests ship with a
DISABLED_prefix to remove, and GCC 15 needs-DCMAKE_CXX_FLAGS="-include cstdint"at configure time. Use the storage and recovery homework for WAL reasoning, and keep C++ scope bounded to storage and recovery. - Hypothesis - Stateful TestingHypothesis · support
Use
RuleBasedStateMachinewith rules, bundles and invariants to drive your store and a dictionary model with the same random operation sequences, and check the machine catches a planted bug before trusting a pass. - Building Distributed Systems - The Logger and IndexesBuild Distributed Systems · optional
Only the first three tasks are free (a write-ahead log, its recovery and log segments). Tasks are graded in the browser after login, so treat a pass as a drill and keep your local harness as the evidence.
- HLD Handbook - Storage Engines and Data StructuresHLD Handbook · required
Read Part 0 data structures plus Part 4 storage engines and OLTP versus OLAP. Use its exercises for comparison, while the CMU project and local fault tests remain the implementation evidence.
- PostgreSQL 18 Documentation - WAL Configuration and InternalsPostgreSQL Global Development Group · support
Read "WAL Configuration" (checkpoints and the redo point crash recovery starts from), "WAL Internals" and "Reliability" for the official, versioned statement of the write-ahead and durability contract.
- ARIES: A Transaction Recovery Method (Mohan et al., 1992)ACM TODS (Stanford course copy) · support
Read the introduction, the overview and restart processing (analysis, redo by repeating history, undo) and the page LSN rule. The rest is 1992 storage detail beyond this section.
- Build Your Own RedisBuild Your Own · optional
Use the persistence and data-structure portions only if a second implementation is needed to cement parsing, indexing or append-log behavior. Do not replace the crash-tested stage artifact with tutorial completion.
- Replicated Log and Stream Processor - Storage SliceRoadmap-Final · support
Implement checksummed segments, indexes, acknowledgement states, recovery, retention and atomic metadata changes. Preserve every crash schedule and corrupted artifact needed to reproduce a failure.
- Apache Parquet File FormatApache Software Foundation · support
Read the File Format layout (row groups, column chunks, footer metadata) and the Page Index page (ColumnIndex and OffsetIndex with per-page min and max values for page skipping). Use it only for file layout and skipping; it does not cover table metadata or catalogs.
- Linux man-pages: fsyncLinux man-pages project · support
Read the DESCRIPTION for what
fsyncandfdatasyncguarantee and the directory-sync requirement for new file names, and the ERRORS section for what anEIOfrom write-back can refer to.