How it works
A hash index needs every key in memory and cannot answer range queries. Keeping data sorted on disk fixes both, since a small sparse index is then enough, but inserting into the middle of a sorted file is expensive. A log-structured merge tree (LSM tree) avoids this by never editing files. Each write goes to a write-ahead log and then to the memtable, a sorted in-memory structure. When the memtable reaches a set size, say 64 MB, the engine writes it out as an immutable sorted file and can discard the log that covered it.
A read checks the memtable, then files from newest to oldest, and the first match wins. A delete writes a tombstone, a marker that hides older versions. Looking up a key that does not exist would touch every file, so each file carries a Bloom filter: a compact bit array that answers “definitely absent” or “possibly present”. At 10 bits per key the false-positive rate is about 1%, so with 20 files a missing key costs about 0.2 needless file reads instead of 20.
Compaction is the background job that merges sorted files, keeps the newest version of each key, and drops overwritten values and tombstones with nothing older beneath them. It is also the main cost: it uses disk bandwidth and CPU, and needs free space while merging. If writes outrun it, files accumulate, reads slow down, and engines such as RocksDB throttle incoming writes. RocksDB, LevelDB, Cassandra, and HBase all use this design. It suits write-heavy workloads, though scans must merge several files.
Your metrics service runs on an LSM engine. After a week of heavier traffic, write latency is flat, but dashboard reads are twice as slow and the number of on-disk files has doubled. One teammate wants a bigger memtable; another wants to give compaction more disk bandwidth. Which do you try first?
Give compaction more bandwidth or threads. The symptoms point to compaction debt: reads slow down because each one checks more files. A bigger memtable flushes less often, which can ease the inflow, but it does not clear the backlog and it lengthens log replay after a crash. Confirm with pending-compaction metrics and check free disk, since merging needs temporary space. If the disk is already saturated, you need more capacity rather than a new setting.
Use this as a guide for self review; written answers are not graded.Keep in mind
- An LSM tree turns scattered writes into sequential file writes, then pays later in compaction.
- A Bloom filter can rule a file out; a “maybe” still needs a read.
- Compaction that falls behind shows up as slower reads and more disk use.