Storage engines: B-trees, LSM-trees and the write-ahead log
Three jobs under every database
Section titled “Three jobs under every database”Whatever its data model, a database has to do three things with a disk. It has to find data quickly. It has to change data without losing track of where everything is. And it has to survive a crash: the machine can lose power at any instant, and what the database told a client was saved must still be there afterwards.
The part of the database that does this is its storage engine. Two layouts dominate, and one idea is shared by almost all of them.
- A B-tree keeps data in fixed-size pages arranged as a tree, and changes a page where it sits.
- An LSM-tree (log-structured merge-tree) never changes data on disk. It buffers writes in memory, writes them out as new sorted files, and merges files in the background.
- A write-ahead log (WAL) is a record of every change, written to disk before the change itself. It is what makes a crash survivable, and B-tree and LSM-tree engines both use one.
Mental model. A write has two jobs: be safe, and be findable. The log makes it safe at the cost of one sequential append. The layout, a B-tree or an LSM-tree, makes it findable, and decides when and how often the disk is written for that.
B-trees: change the page where it sits
Section titled “B-trees: change the page where it sits”PostgreSQL stores every table and index as an array of pages of a fixed size, usually 8 kB. Its tables are heaps of pages, and its indexes are B-trees by default. A B-tree is a multi-level tree: each internal page holds entries that point to the next level down, and each leaf page, on the lowest level, holds entries that point to table rows. A lookup starts at the top and follows one pointer per level until it reaches a leaf. The tree is shallow, because each page holds many entries: the next lesson counts the levels.
A write changes the page in memory, and the page is written to its place in the file later. When a leaf page has no room for a new entry, PostgreSQL’s documentation says, a page split moves part of the entries to a new page, and the parent page gets a new pointer, which can make the parent split in turn.
The cost shows up in the disk. PostgreSQL typically writes 8,192 bytes at a time. So a change of a 100-byte row can mean writing a whole page: in the worst case, where every change lands on a different page, that is 8,192 ÷ 100 ≈ 82 bytes written for every byte changed. This ratio is the write amplification of the layout: the bytes written to disk divided by the bytes the application changed. Many changes to the same page before it is written share one page write, so 82 is the ceiling for this example, not the typical figure.
LSM-trees: never change a file, merge instead
Section titled “LSM-trees: never change a file, merge instead”An LSM-tree turns every write into an append. Cassandra’s documentation describes the path. A write is recorded in an append-only commit log on disk, and added to the memtable, a sorted buffer in memory. When the memtable reaches its limit, it is flushed to disk as an SSTable, a sorted file that, in the documentation’s words, is immutable and never written to again.
Files pile up, so a background process called compaction reads several SSTables, merges them, applies updates and deletes, and writes a new one. Cassandra’s documentation says plainly that compaction creates write amplification, and RocksDB’s documentation says the write amplification of its leveled compaction is often larger than 10. The data is written again and again, but always in large sequential runs.
Reads pay for the layout. A key can be in the memtable or in any of several SSTables, so a read may have to look in more than one place, and Cassandra uses Bloom filters to avoid reading files that cannot hold the key. The original LSM-tree paper states the trade-off itself: finds that need an immediate response can lose I/O efficiency, so the structure is most useful where inserts are more common than finds.
| B-tree | LSM-tree | |
|---|---|---|
| A write | Changes a page in place, in memory first | Appends to the log and a memory buffer |
| Reaches the disk as | Page writes, to scattered places in the file | New sorted files, written in sequence |
| A read | Follows a few levels of pages | Checks the memory buffer and possibly several files, with Bloom filters to skip files |
| Background work | Page splits | Compaction, which rewrites data |
| The price | A whole page written for a small change | Reads that look in several places, and compaction’s rewrites |
| Often chosen for | Reads that must be fast, including ranges of keys | Workloads with many more inserts than reads |
The last row is a tendency, not a rule. Which layout wins depends on the workload, the sizes, the memory and the settings, and has to be measured on the real system.
The write-ahead log: safe first, findable later
Section titled “The write-ahead log: safe first, findable later”Both layouts have the same problem: the changed data is in memory, and memory is lost when the power goes. If the database had to write every changed page to disk before saying “committed”, commits would be slow and scattered over the file.
PostgreSQL’s documentation states the answer as the central concept of WAL: changes to data files must be written only after those changes have been logged, that is, after WAL records describing the changes have been flushed to permanent storage. Then there is no need to flush the data pages on every commit, because after a crash the database can recover using the log: any changes that have not been applied to the data pages can be redone from the WAL records. The documentation calls this roll-forward recovery, also known as REDO.
It is cheap because of how the log is written. The documentation says the WAL file is written sequentially, so the cost of syncing it is much less than the cost of flushing the data pages, and only the WAL file has to be flushed to guarantee that a transaction is committed.
The LSM-tree needs the same protection for a different reason: its memtable is memory too. Cassandra’s commit log is its write-ahead log, and on startup the mutations in it are applied to the memtables again.
Sort what belongs where
Section titled “Sort what belongs where”Ten statements, three ideas. One of them looks like it belongs to the LSM-tree and does not. Sort each statement under the idea it describes, and read the reasons.
Challenge
B-tree, LSM-tree or log?
A storage engine is a layout plus a log. Sort ten statements under the idea each one describes: the B-tree, the LSM-tree or the write-ahead log. Read carefully: the idea a statement describes is not always the one of the engine it comes from.
Sorting needs JavaScript.
Categories
- B-tree
- Fixed-size pages in a tree, changed where they sit.
- LSM-tree
- Writes buffered in memory, flushed as sorted files that are never changed, and merged later.
- Write-ahead log
- A sequential record of each change, flushed before the change is acknowledged.
Check your answers at least once before looking at the answers.
What happens if the power fails after a commit?
Section titled “What happens if the power fails after a commit?”A client commits a transaction, the database answers “committed”, and a moment later the power fails. The changed pages were only in memory. Follow the commit under three settings of PostgreSQL.
- The defaults. The commit returns only after the WAL record is flushed to permanent storage. When the server restarts it replays the log, and the transaction is back. No transaction that was reported as committed is lost, provided the storage honours the flush: PostgreSQL’s documentation warns that the memory in a disk controller’s cache is volatile and loses its contents in a power failure, that many solid-state drives have volatile write-back caches, and that it is the administrator’s responsibility to make sure the storage really keeps what it was told to write.
- Asynchronous commit. The database answers before the log is flushed. The documentation says the transaction may be lost if the database crashes, but that the risk is of data loss, not data corruption: the database recovers to a self-consistent state, without the last few transactions. The window is bounded: the maximum is three times
wal_writer_delay, and the default of that setting is 200 milliseconds, so up to 3 × 200 = 600 ms of the latest commits. fsyncturned off. The server stops making sure that its writes reach the disk. The documentation says this is often a performance benefit, and that it can result in unrecoverable data corruption in the event of a power failure or system crash.
Three settings, three different promises: nothing acknowledged is lost, the last 600 milliseconds may be lost but the data is sound, and nothing can be said. The price of the first is that every commit waits for one flush of a sequential log. That is the trade-off behind durability, and it is a setting that you choose, not a law of databases.
- A storage engine does three jobs: find data quickly, change it without losing track of it, and survive a crash.
- A B-tree keeps fixed-size pages in a tree and changes them in place. A page change can write 8,192 bytes for a 100-byte row, about 82 times the data changed in the worst case.
- An LSM-tree appends writes to a log and a memory buffer, flushes immutable sorted files, and merges them in the background. It trades cheap, sequential writes for reads that may look in several places and for compaction’s rewrites.
- A write-ahead log records each change before the change reaches the data files, and a commit is acknowledged once the log is flushed. After a crash the log is replayed. Both layouts use one.
- Acknowledging before the flush can lose the last few commits, up to 600 ms of them with PostgreSQL’s default delay. Turning off fsync can corrupt the database.
Next: how an index finds a row without reading the table, and what the query planner does with it.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.