In this lesson · topic 1 of 7
Topic 1
Random writes are the expensive kind
3 min read
The cost of writing in place
A B-tree changes pages where they live. Each insert can dirty a different page, so the disk sees a stream of small writes in random places. Sequential writes are far cheaper on spinning disks and still help on flash, where they wear the device less and keep its internal housekeeping simple.
A log-structured design takes the opposite view. Never change a file. Put new writes in memory, and when memory fills, write it out in one sequential pass as a sorted, immutable file. A write is then one entry in a memory table plus one append to a log.
What you owe afterwards
This is a log-structured merge tree, an LSM tree. It has two debts.
The first is reads. The newest value of a key may be in memory, or in any of the files, so a read may check several places.
The second is the files themselves. The same key can sit in many files, the oldest copies are stale, and deleted keys still occupy space. A background job called compaction merges files to fix this, and every merge rewrites data that was already on disk.
In the lab, 40,000 writes make 198measured flushes of a 200measured-entry memtable. Compaction then rewrites entries so that, with leveled compaction, the disk sees 7.7xmeasured as many entry writes as the application made.
Predict first