Unit 8 of 12 · about 5 hours · implement

Compaction policy, tombstones, atomic manifests and segment compaction with atomic swap

An LSM without compaction is an ever-growing pile of overlapping files. Compaction policy decides what stalls, what resurrects and what the disk holds.

You'll be able to

  • Contrast leveled and tiered compaction on read, write and space amplification.
  • Explain tombstone resurrection and the rule that prevents it.
  • Implement segment compaction with an atomic manifest swap.

Covers

Compaction policy and write stallsTombstones and resurrection riskSnapshots and atomic manifest replacementSegment compaction with atomic swap
1

Read

In this order, only the parts listed

0 of 3 done

  1. HLD Handbook compaction strategiesHLD Handbook - Storage Engines and Data Structures

    Compaction strategies: leveled with 10-30x write amplification and 10% space overhead, size-tiered with lower write amplification and about 100% transient space overhead, and time-windowed for TTL data

  2. SSTable merging and compactionDDIA 2e - Chapter 4 Storage and Retrieval

    Chapter 4, Log-Structured Storage, printed pp. 118-124: the SSTable merge walkthrough and compaction notes, with the write-stall and backpressure discussion at printed pp. 129-131

  3. CMU 15-445 Fall 2025 B+ tree tombstone bufferCMU 15-445 - Storage, Index and Recovery Sequence

    Project 2: the leaf tombstone buffer with its recency rule across merge, split and redistribute

    Read the tombstone survival rule as the small-scale version of LSM tombstone handling. Leave concurrent latch behavior for later.

2

Focus on

  • Leveled compaction bounds reads to one file per level and space to about 10% overhead, at 10-30x write amplification. Tiered compaction writes less but reads more and transiently doubles disk use.
  • A tombstone is a deletion marker with a sequence number. Dropping it before it meets every older copy resurrects the deleted key on later reads.
  • The manifest lists the live files. Compaction writes new files, syncs them, then swaps the manifest atomically; a crash before the swap keeps the old list, never a half-published merge.
  • Write stalls are backpressure, not a bug. When compaction cannot keep up with flushes, the engine suspends writes rather than letting overlapping files grow without bound.
Common mistakes · 3
  • Deleting a tombstone at the first merge that sees no copy in the files being merged. Deeper levels are unchecked, so the key resurrects.
  • Publishing compacted files in place. New files must be complete and synced before the manifest swap names them live.
  • Reading a stall as lost throughput to tune away. The stall protects read amplification bounds; removing it trades a latency spike for permanent read debt.
3

Try it yourself

Closed-book, before checking anything

Merge two sorted runs on paper: L0 holds (a, 1) and a tombstone for b; L1 holds (a, 0) and (c, 3). Newest wins per key, so the output is (a, 1) and (c, 3) with the b tombstone retained because levels below L1 may still hold an older b.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.When is a tombstone safe to drop during compaction?Answer

    Only when the merge covers every level that can hold an older copy of the key, so no stale version survives below the tombstone.

  2. 2.A crash lands between writing compacted files and swapping the manifest. What does recovery see?Answer

    The old manifest and old files. The new files are orphans until the next compaction relists or cleans them; no reader ever saw a half-published merge.

  3. 3.Why does leveled compaction amplify writes more than tiered compaction?Answer

    Each level merge rewrites overlapping data from the next level down. Aggressive re-sorting keeps reads bounded but recopies bytes through every level.

  4. 4.Memtable pressure rises while compaction lags. What should the engine do?Answer

    Apply backpressure and suspend writes until a flush completes. Accepting unbounded L0 overlap trades a short stall for permanently slower reads.

You're done when

Your compaction merges two runs with a tombstone correctly and a crash before the manifest swap loses nothing acknowledged.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 10 more in the 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.

  • 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.

  • 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.

Also in this section

  • Hypothesis - Stateful TestingHypothesis · support

    Use RuleBasedStateMachine with 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.

  • 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.

  • 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.

  • 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.

  • 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 fsync and fdatasync guarantee and the directory-sync requirement for new file names, and the ERRORS section for what an EIO from write-back can refer to.