SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Common Database Types
  • SQL vs NoSQL
  • ACID Transactions
  • B-Trees and B+ Trees
  • LSM Trees
  • Transaction Isolation Levels
  • Locking and MVCC
  • Normalization
  • OLTP vs OLAP
  • BASE and PACELC
  • Write-Ahead Log (WAL)
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Basics

LSM Trees

Write fast to memory, flush to sorted files, and merge them later.

⏱ 14 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An LSM tree (Log-Structured Merge tree) is a way to store data that makes writes very fast. It never edits data in place. It collects writes in memory, saves them to disk as sorted files, and merges those files in the background.

  • New writes go to a sorted memtable in memory (plus a log for safety).
  • When it is full, it is flushed to disk as an immutable sorted file called an SSTable.
  • Background compaction merges files and throws away old versions.
  • Reads may check several files, so bloom filters help skip the useless ones.

02Concept: What is it?

A B-tree updates pages in place, which means many small random writes to disk. Disks (and SSDs) are much happier with big, sequential writes. An LSM tree is built around that idea: turn lots of small random writes into a few big sequential ones.

The life of a write
✍️Write
→↓1
📜Write-ahead logappend only, for crash safety
🧠Memtablesorted, in memory
→↓2 full: flush
📄SSTableimmutable sorted file
→↓3 merge
📚Bigger SSTablescompacted
Memory Safety log Disk files, never edited
A write is done as soon as it reaches the log and the memtable. Everything after that happens in the background.
🧠Immutable files
An SSTable (Sorted String Table) is written once and never changed. An update is just a newer record for the same key. A delete is a special marker called a tombstone. Compaction later removes the old versions and the tombstones.

03Real-Life Example

🍵The Shop Notebook and the Ledger
A shopkeeper jots each sale on a small notepad on the counter (fast, no need to find the right page). When the notepad is full, she copies it, sorted by customer name, onto a clean sheet and files it. At the end of the week she merges all the sorted sheets into one tidy ledger and crosses out old entries. To find a customer she checks the notepad first, then the newest sheets, then the old ledger. A short index card on each sheet tells her “this customer is definitely not on this sheet”, so she skips it.
Shop
LSM tree
Notepad on the counter
Memtable
A copy of every sale kept in a locked drawer
Write-ahead log
A sorted sheet filed away
SSTable (flushed memtable)
Weekly merge into a tidy ledger
Compaction
Crossing out old and cancelled entries
Dropping old versions and tombstones
Index card saying who is not on this sheet
Bloom filter
Checking newest sheets first
Reads search newest to oldest
Reading checks newest first
🔎Get key K
→↓
🧠Memtablemiss
→↓
📄Newest SSTablebloom: no
→↓
📄Older SSTablebloom: maybe, found
The first file that has the key wins, because it holds the newest version.

04Why Do We Need It?

🚀Very fast writes
A write is an in-memory insert plus a log append, so no random disk seeks.
📼Sequential disk use
Flushes and merges write big sorted chunks, which disks and SSDs like.
🗜️Good compression
Sorted, immutable files compress well, so less disk is used.
📈Huge write loads
Logs, metrics, messages and events arrive faster than a B-tree likes.
🧊Simple files
Immutable files are easy to copy, back up, and cache.
🗣️Interview favourite
Cassandra, RocksDB and HBase questions always lead here.
An LSM tree trades read work and background merging for very cheap writes.

05Where Do We Use It?

🏛️Cassandra and ScyllaDB
Wide column stores built for huge write rates.
🪨RocksDB and LevelDB
Embedded key-value engines used inside many other systems.
📚HBase and Bigtable
Big data stores that use memtables and SSTables.
📡Time series and metrics
InfluxDB and others use LSM-like designs for steady incoming points.
🗄️Distributed SQL
CockroachDB and TiDB keep their data in RocksDB or similar engines.
🧾Event and message stores
Fast append-heavy workloads.

06Types / Parts / How It Works

The moving parts

PartWhat it isJob
Write-ahead log (WAL)An append-only file on diskIf the machine crashes, replay it to rebuild the memtable
MemtableA sorted structure in memory (skip list or tree)Absorbs writes and serves the newest reads
SSTableAn immutable file of sorted key-value pairs, with an index and a bloom filterDurable storage, easy to binary search
Bloom filterA tiny bit array that can say “definitely not here” or “maybe here”Skip files that cannot hold the key
CompactionA background job that merges SSTablesDrops old versions and tombstones, keeps reads fast
TombstoneA marker that says the key was deletedHides older versions until compaction removes them

Compaction styles

Size-tiered
Merge files of similar size
  • Lower write amplification
  • Good for heavy writes
  • More files to check on a read
  • Needs spare disk space to merge (up to double)
Leveled
Levels, each about 10x bigger
  • Fewer files per read, lower read amplification
  • Better space use
  • Higher write amplification: data is rewritten many times
  • Good for read-heavy or update-heavy loads
Leveled layout
🧠Memtablememory
↓flush
📄Level 0few files, may overlap
↓compact
📚Level 1sorted, no overlap, ~10 MB x10
↓compact
📚Level 2about 10x bigger
Data starts in the small, fresh level and is merged down into bigger, older levels.
The three amplifications
Write amplification
Disk bytes written / user bytesdata is rewritten by flush and each compaction
Read amplification
Files read per lookupcan check memtable and several SSTables
Space amplification
Disk used / live dataold versions wait for compaction
Every storage engine pays in some of these. LSM trees lean towards cheap writes.
VisualizerWrite, flush and compact an LSM treePress Write several times and watch the memtable flush and compaction run. Then look up a key, and turn bloom filters off to see wasted reads.
Memtable holds (keys)
Compact when level 0 has
Memtable (in memory, sorted) 2/4
1118
↓ flush when full (one fast sequential write)
Level 0 on disk: SSTables (newest on the right) 2/3
181522
461320
↓ compaction: merge sorted files, drop old duplicates
Level 1 on disk: one big merged SSTable
not created yet
Bloom filters
User writes
10
Entries written to disk
8
2 flushes, 0 compactions
Write amplification
0.8x
disk entries per user write
Read: disk files read
0
2 files exist
Write 18: added to the memtable (memory) and to the write-ahead log.
Key 5 has not been written. Bloom filters say "definitely not here" for most files. Disk reads used: 0, and all of them were wasted.

A teaching model: writes follow a fixed, repeatable key order (keys repeat after 23 writes, which are updates), the memtable flushes by key count, and compaction merges all of level 0 into one level 1 file. Bloom filters are simulated with a fixed rule that never misses a stored key but gives a few false alarms. Real engines such as RocksDB and Cassandra use many levels or size tiers, and write-ahead logs for safety.

07How to Use It / Steps / Implementation

Using and tuning an LSM store

  1. 1
    Choose it for write-heavy data
    Events, logs, metrics, messages, activity feeds. If most of your work is reads and updates on a small set, a B-tree may be simpler.
  2. 2
    Pick a compaction style
    Size-tiered for the cheapest writes. Leveled for better read speed and space use. Some engines offer time-window styles for time series.
  3. 3
    Size the memtable
    A bigger memtable means fewer, larger flushes and fewer files. It also means more memory and a longer replay after a crash.
  4. 4
    Turn on bloom filters
    They are cheap (about 10 bits per key gives roughly a 1 percent false positive rate) and save many disk reads for missing keys.
  5. 5
    Cache hot blocks
    Use a block cache for recently read data, and keep indexes and filters in memory.
  6. 6
    Watch compaction
    Check pending compactions, disk throughput and number of files per read. Falling behind means slow reads and, in the end, write stalls.
  7. 7
    Leave disk headroom
    Compaction needs spare space to write new files before deleting old ones.
⚠️Deletes are not instant
A delete writes a tombstone. The old data stays on disk until compaction reaches it. Heavy deletes with many tombstones can slow reads and fill the disk.

08Key Terms to Know

TermMeaning in easy words
LSM treeLog-Structured Merge tree: memory plus immutable sorted files merged in the background
MemtableThe sorted in-memory table that takes new writes
SSTableSorted String Table: an immutable sorted file on disk
Write-ahead log (WAL)An append-only file used to rebuild the memtable after a crash
FlushWriting a full memtable out as a new SSTable
CompactionMerging SSTables to drop old versions and keep reads fast
TombstoneA marker that records a delete
Bloom filterA compact structure that says “definitely not present” or “maybe present”
Write amplificationBytes written to disk per byte the user wrote
Read amplificationHow many files or pages are read for one lookup

09Pros, Cons and Trade-offs

✅ Pros
  • Very high write throughput
  • Mostly sequential disk writes, kind to SSDs and HDDs
  • Compact files, good compression
  • Immutable files are easy to back up and replicate
  • Scales well for append-heavy data
⚠️ Cons
  • Reads may touch several files
  • Compaction uses CPU, disk and can cause latency spikes
  • Write amplification from repeated merging
  • Needs extra disk space during compaction
  • Tombstones and old versions linger for a while

Trade-offs

ChoiceWe gainWe lose
Bigger memtableFewer flushes and filesMore memory, longer crash recovery
Size-tiered compactionCheap writesMore files per read, more space
Leveled compactionFast reads, less spaceMore write amplification
Bloom filtersFewer wasted readsA little memory, and a small false positive rate
Lazy compactionMore write capacity nowSlower reads and a bigger backlog later
LSM tree (vs B-tree)Write speedRead simplicity and steady latency
B-tree
Update in place
  • Fast, predictable reads
  • Random writes to disk
  • Each key lives in one place
  • Good for mixed loads and range queries
LSM tree
Append and merge
  • Very fast writes
  • Sequential writes only
  • A key may exist in many files until compaction
  • Good for heavy write loads

10Common Problems and Mistakes

Common mistakes

  1. Ignoring compaction. If merging cannot keep up with writes, files pile up, reads slow down and writes may be throttled (a write stall).
  2. Deleting a lot with tombstones. Queries must skip many tombstones. A queue built on deletes is a known anti-pattern in Cassandra.
  3. No bloom filters. Lookups for missing keys read every file.
  4. Choosing LSM for read-mostly data. A B-tree is usually simpler and has steadier latency.
  5. Running out of disk during compaction. Merging needs room for the new file before the old ones are removed.
  6. Setting the memtable too small. You get many tiny files and constant merging.

Things to watch

🧯Write stalls
When compaction falls behind, the engine slows or stops writes to catch up.
📈Latency spikes
A big compaction competes with live traffic for disk and CPU.
💽Space use
Old versions and tombstones stay until compaction removes them.
🔁Crash recovery
The WAL must be replayed to rebuild the memtable. A big memtable means a longer replay.

11Real-World Examples

🏛️Apache Cassandra
Uses a commit log, memtables and SSTables, with size-tiered, leveled and time-window compaction.
🪨RocksDB
A Facebook (Meta) fork of Google's LevelDB, embedded in many databases, stream processors and storage systems.
🐘HBase and Bigtable
The Bigtable paper (Google, 2006) made memtables and SSTables famous.
🍃MongoDB WiredTiger
Is B-tree based by default, but WiredTiger also has an LSM option (general idea).
🗄️TiDB and CockroachDB
Distributed SQL databases that store their data in LSM-based engines (RocksDB or Pebble).
📡InfluxDB and others
Use LSM-like designs for steady streams of time-stamped points (details vary by version).
📝Note
Product details change between versions. These are general ideas to build intuition.
Mini case: a metrics pipeline
📡Sensors50,000 writes/s
→↓append
🧠Memtable + WAL
→↓flush every few seconds
📄SSTables
→↓background
📚Compacted dataqueries read here
Thousands of sensors write constantly. The LSM tree absorbs them in memory and writes big sorted files.

12Related Topics to Read Next

B-Trees and B+ Trees→

The in-place alternative to LSM trees.

Wide Column Databases→

Cassandra and Bigtable are built on LSM ideas.

Time Series Databases→

Append-heavy data that suits LSM designs.

Indexing→

How storage engines support fast lookups.

ACID Transactions→

The write-ahead log idea, used again here.

Replication→

Immutable files are easy to copy to other nodes.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Write path: WAL append plus memtable insert. Done.
  • ✔Flush: a full memtable becomes an immutable sorted SSTable.
  • ✔Read path: memtable, then newest to oldest SSTables. Bloom filters skip files.
  • ✔Compaction: merge files, keep newest versions, drop tombstones.
  • ✔Delete: a tombstone, removed later by compaction.
  • ✔Styles: size-tiered (cheap writes) vs leveled (better reads, more rewriting).
  • ✔Costs: write amplification, read amplification, space amplification.
  • ✔One line: “Write to memory, flush sorted files, and merge later: fast writes now, tidy-up work later.”
← Previous
B-Trees and B+ Trees
Next →
Transaction Isolation Levels