← All notes

Exploring LSM Trees and SSTables

ddiadatabasesstorage-enginesdistributed-systems

When classifying databases based on their storage engines/mechanisms, we have two main categories:

  1. Update-in-place (eg: B-Trees)
  2. Log-structured (eg: LSM Trees)

In this note, we will explore the latter category.

When reading about distributed databases like Apache Cassandra, ScyllaDB, or RocksDB, one of the first things that stands out is their write throughput. They can absorb hundreds of thousands of writes per second on commodity hardware without breaking a sweat, rarely running into the write-lock bottlenecks common in traditional relational setups.

I haven't run Cassandra clusters in production myself, but while working through Designing Data-Intensive Applications by Martin Kleppmann, understanding the storage engine that makes this possible was one of those lightbulb moments.

The secret behind that write performance lies in the storage engine architecture: Log-Structured Merge-Trees (LSM Trees) and their on-disk file format, Sorted String Tables (SSTables).

To see why this architecture works so well, it helps to step back and look at how databases actually handle disk I/O. Almost every storage engine boils down to one fundamental tension: how do you structure data so that writing it is fast, without making reading it impossibly slow?

In Chapter 3 of DDIA, Kleppmann introduces what he jokingly calls the world's simplest database: two bash functions that wrap an append-only text file.

#!/bin/bash

db_set () {
  echo "$1,$2" >> database
}

db_get () {
  grep "^$1," database | sed -e "s/^$1,//" | tail -n 1
}

If you call db_set 12 '{"name":"London"}', it appends a line to the end of the file. That write operation is O(1) and blazingly fast because appending to a file sequentially is the most efficient disk I/O you can do. Spinning disks don't need random head seeks, and SSDs write sequential blocks with minimal write amplification.

The catch, of course, is db_get. To find a key, grep has to scan the entire file from start to finish (O(n) cost). If your log has 50 million events, your read latency goes through the roof.

To make reads fast, you need an index - an auxiliary data structure derived from the primary data. But how you design that index splits OLTP storage engines into two completely different schools of thought:

  1. Update-in-place (B-Trees): Break the disk into fixed-size pages (typically 4KB to 8KB) and overwrite pages in-place. This is what PostgreSQL and MySQL InnoDB do. It favors read latency at the expense of random-write overhead.
  2. Log-structured (LSM-Trees): Never overwrite an existing file. Only append sequentially, and reconcile state later. This is the engine powering systems like Cassandra, ScyllaDB, LevelDB, and RocksDB.

What We Will Explore

In this note, we'll unpack the core machinery behind LSM-tree storage engines by following the lifecycle of a write and a read:

  • The Naive Fix: How in-memory hash indexes (Bitcask) make append-only logs searchable, and why RAM limits and range queries break them.
  • Enter SSTables: What Sorted String Tables are, and how sorting keys on disk unlocks lightweight sparse indexes.
  • The Write Path (MemTable vs. WAL): Why you never write directly to an SSTable, and how the Write-Ahead Log keeps in-memory writes durable.
  • The Immutability Rule & Compaction: Why successive flushes create brand-new SSTable files rather than appending to existing ones, and how background merge-sorting reconciles them.
  • The Sparse Index Lifecycle: How sparse indexes are constructed on the fly with zero post-creation maintenance.
  • Shielding the Read Path: Why having 10 SSTables doesn't mean doing 10 index lookups, and how Bloom filters and Min/Max bounds eliminate read amplification.

Step 1: The In-Memory Hash Index (Bitcask)

The most direct way to fix the append-only read bottleneck is to keep an in-memory hash map that tracks the exact byte offset of every key in the file.

In-memory hash index with append-only log Figure 1: Appending key-value pairs to a log while maintaining an in-memory hash map of byte offsets.

Whenever you write a key with db_set, you append to the log on disk, note the new byte offset, and update your in-memory hash table. When db_get comes in, you look up the offset in RAM (O(1)) and perform a single seek to disk to grab the value.

This is the exact design of Bitcask (the default storage engine in Riak). It works surprisingly well for workloads where:

  • The total volume of distinct keys fits entirely in RAM.
  • Values are updated frequently (e.g., video view counters, user session data).

Where the Hash Index breaks down

  1. RAM is the ceiling: If you have 500 million keys, your hash map must fit in memory. Storing hash tables on disk is notoriously slow due to random I/O and costly collision resolution.
  2. Range queries are impossible: If you want all keys between user_100 and user_200, a hash map cannot help you. You have to look up each key individually.
  3. Wasted disk space: Updating a key appends a new record to the end. The old value is now dead weight on disk until a background compaction process runs to reclaim it.

To solve both the RAM ceiling and the range query problem, we need to sort the keys.


Step 2: SSTables (Sorted String Tables)

What if we impose one simple rule on our log segments: within each segment file on disk, all key-value pairs must be sorted by key, and each key can appear at most once per segment?

This file format is called a Sorted String Table (SSTable).

Sorting the keys seems like a minor tweak, but it completely changes what is possible:

The Sparse Index

Because the file on disk is sorted, you no longer need an in-memory index for every single key. Instead, you build a sparse index that stores offsets for only a subset of keys - for example, one key every few kilobytes.

SSTable with sparse in-memory index Figure 2: An SSTable segment on disk with a sparse in-memory index pointing to compressed block offsets.

Think of it like the thumb-index tabs in a physical dictionary:

  • If your sparse index knows that handbag is at byte offset 0, and handsome is at byte offset 4096, and you want to look up handiwork:
  • You know handiwork must lie between offset 0 and 4096.
  • You jump straight to offset 0 and scan the 4KB block.

Because you only index a few keys per megabyte, the in-memory footprint drops by orders of magnitude.

Free Compression

Since you are reading a chunk of several kilobytes between sparse index entries anyway, you can compress that chunk on disk (using lightweight algorithms like LZ4 or Zstandard). This saves disk space and drastically reduces disk I/O bandwidth.

(Aside: If you're curious about how file compression algorithms work under the hood, Computerphile has a great visual explainer on how compression shrinks data.)

How the Sparse Index is Constructed and Maintained

A question that naturally arises is: how does the database construct and maintain this sparse index?

The sparse index is built on the fly exactly when the SSTable is being written to disk (either during a MemTable flush or compaction), and because SSTables are immutable, the index requires zero maintenance once created:

  1. Construction: As the database streams sorted data onto disk to create an SSTable, it groups the records into chunks called Data Blocks (typically 4KB to 64KB in size). At the start of each block, the database records the first key and its start byte offset in memory. When all blocks are written, this in-memory list of [Key, Byte Offset] pairs is written to the end of the SSTable file (or into a companion .idx file).
  2. Lifecycle: When the SSTable is finalized, its sparse index is loaded into RAM. Because it only stores 1 key per 64KB block, it easily fits in memory even for terabytes of on-disk data. It is never rebalanced or updated. When compaction eventually merges this SSTable into a newer one, the old sparse index is simply evicted from RAM and the file deleted.

Step 3: The Write Path - MemTable vs. Write-Ahead Log (WAL)

This brings up two critical questions:

When you write to an LSM-tree database like Cassandra, do you write directly into the SSTable or into a quick-append log?

Is the SSTable derived from the log file, or is that the actual log file?

When you write to an LSM-tree database, you do not write directly to an SSTable.

If writes were written directly to an SSTable on disk in sorted order, the database would have to perform random insertions on disk, completely destroying write performance.

Instead, the SSTable is derived from an in-memory data structure called the MemTable, and every write is processed through two distinct structures simultaneously:

Cassandra and LSM-Tree write flow Figure 3: The write path in an LSM-tree engine (Cassandra / RocksDB) balancing in-memory sorting with append-only disk durability.

The Lifecycle of a Write:

  1. The Write-Ahead Log (WAL): When a write request arrives, the engine immediately appends the raw record to an append-only log on disk (called the CommitLog in Cassandra). This write is strictly sequential - it doesn't care about sorting. Its sole purpose is crash recovery. If the server suddenly loses power, the database can replay this log on startup.
  2. The MemTable: At the exact same time, the write is inserted into the MemTable in RAM. The MemTable is a sorted in-memory tree (typically a Red-Black tree or a Skip List). Because it lives in memory, keeping keys sorted on insertion is fast (O(log N)).
  3. The Flush: Once the MemTable reaches a size threshold (typically 32MB to 64MB), the database stops accepting new writes to it, opens a brand-new MemTable for incoming traffic, and flushes the full, sorted MemTable to disk.
  4. SSTable Creation: This flushed file is the SSTable. Because the MemTable was already sorted in memory, writing the SSTable is a fast, sequential disk operation. Once written, an SSTable is 100% immutable - it is sealed forever and never modified.
  5. Log Deletion: Because the data is now safely persisted on disk inside the new SSTable, the database safely truncates or deletes the older segment of the WAL to reclaim disk space.

Step 4: Multiple Flushes & The Immutability Rule

Now consider what happens next:

In the first flush, MemTable 1 was sorted and pushed into SSTable 1.

Now, new writes come in, and MemTable 2 is full. Do we flush to SSTable 1, or to a new SSTable 2? Even though SSTable 1 was sorted, to keep the combined data sorted, don't we have to merge-sort them together?

The answer is: you flush to a brand-new SSTable 2.

The golden rule of LSM-trees is that SSTables are 100% immutable. Once SSTable 1 is written to disk, it is sealed forever. The database will never open it back up to append new blocks, modify existing blocks, or insert new data.

Here is how the database solves the sorting dilemma:

1. The Flush (Optimized for Write Speed)

When MemTable 2 is full, it is simply dumped sequentially to disk as SSTable 2. At this exact moment, the database does not touch SSTable 1.

By avoiding a merge operation during the flush, the database ensures that writing to disk remains blisteringly fast and never blocks incoming writes. At this point, you have two separate files on disk: SSTable 1 and SSTable 2. Both are sorted internally, but their key ranges might overlap.

2. Compaction (The Background Merge-Sort)

The data eventually does need to be combined and sorted together - this just happens asynchronously in a background process called Compaction.

When the database accumulates too many SSTable segments (or they hit specific size/tier thresholds), a background thread kicks in:

  1. It reads SSTable 1 and SSTable 2 sequentially side-by-side.
  2. Because both files are already sorted internally, it performs a classic, highly efficient MergeSort in memory.
  3. If a key exists in both tables (e.g., an updated value or a deletion marked with a "tombstone"), it keeps only the newest version based on timestamp.
  4. It writes the combined, fully sorted result into a brand-new SSTable 3.
  5. Once SSTable 3 is safely on disk, it drops the old sparse indexes from RAM and deletes SSTable 1 and SSTable 2 from disk.

By separating the flush (immediate, write-optimized) from compaction (background, CPU-intensive), the database ingests massive write spikes without degradation.


Step 5: The Read Path & Shielding the Sparse Indexes

Now imagine the database has flushed and compacted for a few hours. We might have 10 SSTable files sitting on disk, meaning 10 separate sparse indexes loaded into memory.

When a read request arrives for key K, do we have to binary-search every single sparse index?

No. If the database had to binary-search the sparse index of every SSTable for every read, performance would plummet as data grew. This problem is known as Read Amplification.

To prevent this, production engines use two in-memory shields before ever touching a sparse index:

1. Min/Max Key Boundaries

Every SSTable keeps a tiny piece of metadata in memory: the absolute minimum and maximum keys it contains. If you are searching for the key Mango, and SSTable 7 only covers keys from Apple to Grape, the database skips it immediately without touching its sparse index.

2. The Bloom Filter (The Primary Shield)

Alongside the sparse index, every SSTable gets a corresponding Bloom Filter loaded into RAM. A Bloom Filter is a space-efficient probabilistic data structure that answers a single question: "Is Key K in this SSTable?"

It has an essential mathematical property:

  • It can return "Definitely Not": If it says this, it is 100% accurate. The database instantly skips this SSTable.
  • It can return "Maybe": False positives are possible, but usually tuned to be very rare (around 1%).

The Actual Read Execution for Key K:

  1. Check the MemTable: Always check memory first, in case K was written recently and has not been flushed yet.
  2. Check the Filters (Newest to Oldest): Inspect the Bloom Filters and Min/Max boundaries of the SSTables, starting with the most recently created one (so updates take precedence).
  3. Filter Rejection: For 9 out of your 10 SSTables, the Bloom Filter will instantly return "Definitely Not", or the key will fall outside the Min/Max range. The database completely ignores their sparse indexes.
  4. Filter Match: When checking the relevant SSTable (say, SSTable 3), the Bloom Filter returns "Maybe", and K falls within the Min/Max bounds.
  5. Sparse Index Lookup: Now the database binary-searches the in-memory sparse index for SSTable 3 to find the candidate block.
  6. Disk Seek & Scan: It finds the byte offset, does a single disk read to grab the 64KB Data Block, scans it, finds K, and returns the result.

Thanks to Bloom Filters, a read across 10 SSTables usually results in checking only 1 (or sometimes 0) sparse indexes.


Summary & Real-World Tradeoffs

This architecture - an in-memory balanced tree (MemTable) backed by an append-only log (WAL) that flushes into immutable sorted on-disk files (SSTables) consolidated via background merge-sorting - is the Log-Structured Merge-Tree (LSM-Tree).

It was originally introduced by Patrick O'Neil, Edward O'Neil, and Gerhard Weikum in 1996, and it powers almost all modern write-heavy distributed databases:

The Tradeoffs:

  • The Superpower: Blazing write throughput. Writes never wait for random disk seeks; they hit an append-only WAL and an in-memory tree.
  • The Cost: Reads may have to inspect multiple segments across disk (read amplification), and background compaction continuously uses disk I/O to merge segments (write amplification).

Understanding this makes it much easier to reason about database performance in production: why write latency in Cassandra remains flat under heavy load, why compaction spikes disk I/O, and why Bloom filters are essential to keep read latency from degrading over time.