Video in progress
You're choosing a storage structure for data with a huge number of writes that is read by time. What is the algorithmic difference between a B-tree, an LSM-tree and a skip list, and how do you decide?
A B-tree updates in place: reads are fast and predictable, but random writes are expensive. An LSM collects writes in memory and flushes them to sequential files: writes are cheap, reads and compaction cost more. A skip list is an in-memory sorted structure, usually used as an LSM's memtable or as an in-memory index.
📖 Answer
I think in terms of three kinds of amplification: write (how many bytes go to disk to write one byte), read (how many places you have to check for one key) and space (how much room stale versions take).
In a B-tree / B+tree (PostgreSQL, MySQL InnoDB indexes) each key lives in one place. Lookup is O(log_B n); because B is large, that's 3-4 pages. A write means finding the page, modifying it and writing to the WAL; with random keys (UUIDv4), pages split and are frequently evicted from the cache. Write amplification is high, read amplification is low.
An LSM-tree (RocksDB, Cassandra; ClickHouse's MergeTree is also similar): a write goes to the WAL and the memtable; when the memtable fills up, it's flushed to disk as a sorted SSTable; compaction merges them in the background. Writes are sequential and very fast. Reading a key may have to check several levels, so each SSTable has a Bloom filter. Compaction eats CPU and disk, and if it's configured badly, it causes periodic latency spikes.
A skip list is a probabilistic multi-level linked list with expected O(log n). In Java, ConcurrentSkipListMap is lock-free, sorted and concurrent. A Redis sorted set also relies on a skip list. It lives in memory, not on disk.
This is how I decide for time series:
- the write/read ratio: sensor data and metrics are 95% writes, almost append-only → LSM or a dedicated TSDB;
- the shape of reads: "a single key" or "a time range"; both need a sorted structure, but for range scans, columnar storage (ClickHouse) wins;
- updates/deletes: in an LSM a delete is a tombstone, which takes space until compaction and slows reads; if there are many deletes, I'm careful;
- team experience: in PostgreSQL, partitioning and a BRIN index are often enough, without introducing a new DB.
That last point is often decisive for me: the cost of supporting a new storage system can exceed the algorithmic gain. First I measure the existing DB with real load.
Sign up to mark studied questions and save your progress.