Storage Engines and Indexes
Why is Cassandra so good at writes and Postgres so good at range queries with many indexes? Why does adding an index make reads faster and writes slower? Why does a time-series database compress data 10x better than a general-purpose one? The answers all come from the storage engine: the part of a database that decides how bytes are laid out on disk and in memory, and how they're found again.
You don't need to build a storage engine in a system design interview. But the moment you choose a database, design a schema, or justify why a write-heavy workload needs a particular store, you're relying on how storage engines work. And "design a key-value store" questions often go straight into memtables, SSTables and compaction (/system-design/key-value-store).
We'll build up from the simplest possible engine:
- An append-only log, and why it needs an index.
- B-trees: the update-in-place design behind most relational databases.
- LSM trees: the log-structured design behind Cassandra, RocksDB and most write-heavy stores, plus compaction and Bloom filters.
- How the two compare, and the amplification trade-off.
- Indexes in practice: clustered, secondary, composite and covering.
- Column-oriented storage for analytics.
Start With a Log
The simplest database there is: append every write to the end of a file.
db_set() { echo "$1,$2" >> database; }
db_get() { grep "^$1," database | tail -n 1 | cut -d, -f2-; }
Writes are as fast as they can possibly be: one sequential append. Sequential writes matter even on SSDs, which handle large sequential writes far more efficiently than scattered small ones, and on spinning disks they're orders of magnitude faster than random writes.
Reads are terrible: db_get scans the entire file, O(n). We need an index: an extra data structure, derived from the data, that lets us find a key without scanning. Every index makes reads faster and writes slower, because each write must now update the index too. That trade-off runs through everything below.
Hash Index
The simplest index: keep an in-memory hash map from each key to the byte offset of its latest value in the log. A write appends to the log and updates the map; a read looks up the offset and does one disk seek.
This is exactly how Bitcask (Riak's original storage engine) works, and it's excellent when all keys fit in memory and there are many writes per key, like counters or session data. To stop the log growing forever, it's split into segments: when the current segment reaches a size limit, close it and start a new one. A background process compacts old segments, keeping only the latest value for each key and merging small segments together. Deletes are recorded as a special tombstone entry that compaction uses to drop the key.
Two limitations push us further: the hash map must fit in memory, and range queries are impossible. Finding all keys between user:1000 and user:2000 means checking every key.