How it works · key-value storage library
How LevelDB works
A store for keys and values that makes writing fast by never changing a file: it only adds, and tidies up later.
Think of it like this. A desk with an inbox. New papers go on the pile at once. When the pile is tall it is sorted into a folder, and now and then folders are merged into bigger ones.
- 📓 The log Every write is added to the end of a file first, so nothing is lost in a crash. db/log_writer.cc
- 🧠 The memtable The newest writes, kept sorted in memory. db/memtable.cc
- 🗂️ Table files Sorted files on disk that are written once and never changed. table/table_builder.cc
- 🪜 Levels Keeps track of which files exist, level by level, each level about ten times bigger. db/version_set.cc
- 🧹 Compaction In the background, merges files down a level and drops what was overwritten or deleted. db/db_impl.cc
Follow one thing through: db->Put("name", "Ada"), then db->Get("name")
- Writes waiting at the same moment are grouped into one batch.db/db_impl.cc
- The batch is added to the end of the log file.db/log_writer.cc
- Then it is put into the memtable. The write is done.db/memtable.cc
- When the memtable is full it is frozen, a fresh one takes over, and the frozen one is written out as a table file.db/db_impl.cc
- A read looks in the memtable, then the frozen one, then the files, newest first. The first answer wins.db/db_impl.cc
- Inside a file, an index says which block could hold the key, so only that block is read.table/table.cc
The clever bit: A sorted list that needs no rebalancing
The memtable is a skip list: a sorted linked list where some nodes also have links that jump further ahead. How tall a node is gets decided by chance, one in four for each extra level, up to twelve. That is enough to make a search skip most of the list, like a tree would, with none of a tree’s rebalancing. It also means readers never have to wait for a writer.
Words you’ll meet
- memtable
- The newest data, sorted, in memory.
- SSTable
- A sorted file of keys and values that is never changed after it is written.
- compaction
- Merging files and throwing away old versions of keys.
- write-ahead log
- A file every write goes to first, to replay after a crash.
Good questions to ask next
- How is a delete stored if files never change?
- Why are there levels at all?
- How does a Bloom filter save a disk read?
Open LevelDB in Bento and ask them there. It reads the project in your browser, draws its parts as a map you can press, and opens the real code behind each one.
Take LevelDB apart yourself.
Free and open source. Nothing to install, no account.
Ideas inside it
More projects, taken apart
Written by hand from the code as it was on 2026-11-12 (commit 2946558). LevelDB belongs to its authors; this page is an independent explanation. Spot a mistake? Tell us.