In this lesson · topic 2 of 7
Topic 2
Memtable, SSTables and compaction
5 min read
The write path
A write goes to two places. It is appended to a write-ahead log, so a crash does not lose it, and it is inserted into the memtable, a sorted table in memory. When the memtable is full, the engine writes it as a sorted string table, or SSTable: a file of keys in order with an index. Then it starts a fresh memtable and discards the old log.
A key written twice before a flush appears once in the file, because the memtable keeps only the newest value. A delete is a write of a marker, a tombstone. Files are never edited.
The read path
A read checks the memtable, then the files from newest to oldest, and stops at the first version it finds. Each file has an index, so one check is a lookup in a small structure and at most one block read.
A key that is present is usually found early. A key that is absent must be ruled out in every file, so the cost of a miss is the number of files. In the lab, a miss with leveled compaction checks 3measured files.
Compaction
Compaction merges sorted files into a bigger sorted file. Because each input is sorted, the merge is one sequential pass. Where a key appears in several inputs, only the newest version is kept, and a tombstone removes the key and itself once nothing older could hold it. The output replaces the inputs.
That is the whole machine. The next topics are about when to merge and what to merge.