LevelDB and RocksDB, on disk

LevelDB and RocksDB are key-value stores built as log-structured merge trees. They never change a file once it is written: new writes go to a log and an in-memory table, which is written out as a sorted file, and sorted files are merged in the background. Every example below is read from the sample database, written by RocksDB 9.10.0.

The LSM tree

A write is appended to the write-ahead log (*.log) and inserted into the memtable, a sorted structure in memory. When the memtable is full it is written out, in key order, as an SST file on level 0, and a new log starts. Level-0 files can overlap, since each holds whatever was written in its time. A background compaction merges them into level 1, whose files cover disjoint key ranges, and so on down: each level holds about ten times more than the one above. Old versions and deleted keys are dropped only when a compaction merges them away.

memtablein memory; its writes are also in the WALL02 files, 18.0 KBL1emptyL2emptyL3emptyL4emptyL5emptyL6000009.sst1 file, 75.0 KB

That is the sample: 3,364 entries in 3 files. The bottom file, on L6, came from a full compaction of the first batch of writes; the two L0 files are later flushes; the last 32 writes are only in the log. A read looks in the memtable, then in every L0 file from newest to oldest, then in at most one file per level, newest data first, and stops at the first version it finds. Filters in each file let it skip most files without reading them.

The files in a database directory

CURRENTOne line: the name of the live MANIFEST.
MANIFEST-000005A log of version edits: which SST files are on which level. Replaying it gives the current tree.
000009.sst, … (LevelDB: .ldb)Sorted string tables: immutable, sorted key-value files.
000012.logThe write-ahead log: writes not yet flushed to an SST.
OPTIONS-…RocksDB only: the options the database was opened with, as text.
LOCK, LOG, IDENTITYA lock file, the human-readable info log, and the database's unique id.

SST files

An SST file is a sequence of blocks. The data blocks come first, holding the entries in key order, each about 4.0 KB before compression (the block size option). After them come the meta blocks: a filter, the range deletions, the properties. Then the index, with one entry per data block; the metaindex, which names the meta blocks; and the fixed-size footer, which is where a reader starts.

48 data blocks: 71,531 bytes at 048 data blocksfilter: 3,466 bytes at 71,531filtindex: 717 bytes at 74,997indeproperties: 971 bytes at 75,714propmetaindex: 113 bytes at 76,685metafooter: 48 bytes at 76,798foot

000009.sst from the sample, 75.0 KB: 48 data blocks, compressed with Snappy. Every block except the footer is followed by a 5-byte trailer: one byte for the compression type, and a 4-byte checksum of the block and that byte.

The footer

The last bytes of the file. LevelDB's footer is 48 bytes: the block handles (offset and size, as varints) of the metaindex and the index, zero padding to 40 bytes, and the 8-byte magic number 0xdb4775248b80fb57. RocksDB's is 53 bytes: a checksum-type byte first, then the two handles and padding, a 4-byte format version and its own magic number, 0x88e241b785f4cff7. From format version 6 (the default in recent RocksDB, and the sample's) the handles are gone: the footer holds its own checksum, the size of the metaindex (which sits just before the footer), and a random base context checksum that is mixed into every block's checksum with the block's offset, so a block copied to the wrong place fails its check.

The sample uses XXH3 checksums. RocksDB can use CRC-32C (LevelDB's only choice), xxHash32, xxHash64 or XXH3, its current default.

Blocks and prefix compression

Keys in a block are sorted, so neighbours share a prefix. Each entry stores how many bytes of its key it shares with the previous key, how many it adds, and the value's length, as varints; then the added key bytes and the value. Every 16th entry (the restart interval) shares nothing: a restart point. The block ends with the offsets of its restart points and their count, so a lookup binary-searches the restart points and then scans at most 16 entries.

The first two entries of the sample's first data block (decompressed: 4,079 bytes, 91 entries, 6 restart points):

OffsetPartBytes
0shared key bytes: 000
1unshared key bytes: 1913
2value length: 301e
3key: "album/00001" + 8 bytes (seq 61, type 1)61 6c 62 75 6d 2f 30 30 30 30 31 01 3d 00 00 00 00 00 00
22value: {"title":"Album 1","artist":8}7b 22 74 69 74 6c 65 22 3a 22 41 6c 62 75 6d 20 31 22 2c 22 61 72 74 69 …
52shared key bytes: 100a
53unshared key bytes: 909
54value length: 311f
55key: "2" + 8 bytes (seq 62, type 1)32 01 3e 00 00 00 00 00 00
64value: {"title":"Album 2","artist":15}7b 22 74 69 74 6c 65 22 3a 22 41 6c 62 75 6d 20 32 22 2c 22 61 72 74 69 …

The second key shares 10 bytes with the first, so only 9 are stored.

Internal keys, sequence numbers and types

The keys in an SST are internal keys: the user's key, then 8 bytes holding a 56-bit sequence number and an 8-bit type. Every write gets the next sequence number, so a key can appear many times, in many files, and the highest sequence number wins. Internal keys sort by user key, then by sequence number descending, so the newest version comes first. A snapshot is just a sequence number: reads at it ignore anything newer.

TypeNameMeaning
0x0deletionDelete: hides older versions of the key
0x1valuePut: the key's value
0x2mergeMerge operand: combined with older versions by the merge operator when read
0x7single deletionSingleDelete: cancels exactly one earlier Put
0xfrange deletionDeleteRange: hides every key from this one up to the end key (the value)
0x11blob indexValue stored in a separate blob file; this is its address
0x14deletion with timestampDelete, with a user-defined timestamp
0x16wide-column entityPutEntity: a row of named columns
0x18value with write timePut, carrying the time it was written

The key track/000001 in the sample, newest first:

WhereSeqTypeValue
000012.log (WAL)3416deletion
000011.sst (L0)2761value{"name":"Track 1","album":8,"genre":"jazz","ms":67919,"rev":…
000009.sst (L6)361value{"name":"Track 1","album":8,"genre":"jazz","ms":67919}

A read of track/000001 finds the newest version first and stops there. The older versions stay on disk until a compaction that includes them proves no snapshot still needs them. The sample also has 75 merge operands (counters to be added together when read or compacted), a range deletion and a SingleDelete.

The index and filters

The index block has one entry per data block: a separator key, at least the last key of that block and less than the first key of the next (RocksDB shortens it when it can), and the block's handle. From format version 3 the separators are user keys, without the 8-byte suffix, and from version 4 the handles are delta-encoded: blocks follow each other, so only the size difference is stored. A big file can split its index into partitions under a small top-level index, so that only the needed partition is loaded.

The filter lets a point lookup skip the file. RocksDB's default is a Bloom filter over the whole file, with each key's bits in one 64-byte cache line; the Ribbon filter saves about 30% of the space for more CPU. LevelDB's filter block has one small Bloom filter per 2 KB of data-block offsets. A filter can say "certainly not here" or "maybe here", never "certainly here".

Compression

Each block is compressed on its own, so a reader decompresses only the blocks it reads, and a block that does not shrink by at least an eighth is stored uncompressed (the trailer says which). LevelDB has Snappy; RocksDB adds zlib, LZ4, LZ4HC, ZSTD and others, and can use a different one per level: a common setup is a fast compressor such as LZ4 or Snappy for the upper levels and ZSTD for the bottom level, where most data lives. The sample's files all use Snappy; the viewer reads the others too. Compression types: 0 none, 1 Snappy, 2 zlib, 3 bzip2, 4 LZ4, 5 LZ4HC, 6 Xpress, 7 ZSTD, 64 ZSTD (pre-1.0).

The write-ahead log

The log is a sequence of 32 KB blocks. Each physical record has a 7-byte header: a masked CRC-32C, a 2-byte length and a type. A record that does not fit in what is left of a block is split into FIRST, MIDDLE and LAST fragments; a record that fits is FULL. The rest of a block too small for a header is zero-filled. RocksDB's recyclable logs add the log's number to each header, so that a reused file's stale records are recognised.

Each logical record of the WAL is a write batch: an 8-byte sequence number, a 4-byte count, and the operations, each a tag byte, then the key and value as length-prefixed strings. The first record of the sample's log, at offset 0:

00–3: CRCCRC4–5: length46–6: type7–14: sequencesequence15–18: countcount19–19: tag20–20: key len21–32: keykey

Sequence 3386, 1 operation: Put track/002601, a 65-byte value. After a crash, the database replays every log newer than the MANIFEST's log number into a memtable.

The MANIFEST

The MANIFEST uses the same log format, and each record is a version edit: a list of tagged fields such as the comparator's name, the next file number, the last sequence number, and the files deleted from and added to each level, with each file's size, smallest and largest internal key (RocksDB adds sequence-number ranges, creation times, checksums and more). Replaying the edits from the start gives the current set of files. The sample's MANIFEST has 12 edits; one that adds a file:

add file 9 to L0: 76,851 bytes, keys album/00001 @ 61 … track/002400 @ 2760

A new MANIFEST starts with one edit holding the whole current state; then CURRENT is replaced, by writing a temporary file and renaming it, so it always names a complete MANIFEST.

LevelDB and RocksDB

RocksDB began as a fork of LevelDB in 2012, and still reads LevelDB's files. What changed on disk:

LevelDBRocksDB
Table files.ldb (older: .sst).sst
Footer48 bytes, magic 0xdb4775248b80fb5753 bytes with checksum type and format version, magic 0x88e241b785f4cff7
ChecksumsCRC-32CCRC-32C, xxHash32, xxHash64, XXH3 (default)
CompressionSnappySnappy, zlib, LZ4, LZ4HC, ZSTD, per level
Properties blocknoneyes: counts, sizes, times, options
Indexinternal keys, full handlesuser keys, delta-encoded handles, optional partitions
Filtersone per 2 KB of datawhole-file Bloom or Ribbon, optionally partitioned
Entry typesPut, Deletealso Merge, SingleDelete, DeleteRange, wide-column entities, blob references
Column familiesnoyes: separate trees sharing one WAL

Many systems store their data in RocksDB: TiKV, Kafka Streams, Flink's state backend, MyRocks and others; CockroachDB uses Pebble, a Go rewrite that started with RocksDB's file format and has since added table formats of its own. LevelDB is inside Chrome (IndexedDB) and Bitcoin Core. SST files in RocksDB's or LevelDB's format, from any of them, open in the viewer.