Database / LevelDB

Reading the LevelDB Source

Follow a write from the DB interface into the log, the memtable and an SSTable, then trace how LevelDB finds the value again.

· 12 min read· EN中文

Before we start

LevelDB is Google’s open-source embedded key-value database. It uses an LSM tree. A stripped-down version of Bigtable’s storage engine is one way to think of it.

Writes are fast. Appending to the log is sequential, and inserting into the in-memory skip list takes expected O(log n) time. Some of that cheap write path shows up on the read side. A lookup for a missing key can have to check candidate tables all the way down to the last level.

I’ll leave the overall design for another day. What I want to do here is read the code and see how the pieces fit together. Besides, how often do I get to read C++ written by Jeff Dean?

The front door, db.h

db.h defines the public interface to LevelDB, the DB class.

Here’s its declaration.

class LEVELDB_EXPORT DB {
public:
static Status Open(const Options& options,
const std::string& name,
DB** dbptr);
DB() = default;
DB(const DB&) = delete;
DB& operator=(const DB&) = delete;
virtual ~DB();
virtual Status Put(const WriteOptions& options,
const Slice& key,
const Slice& value) = 0;
virtual Status Delete(const WriteOptions& options, const Slice& key) = 0;
virtual Status Write(const WriteOptions& options, WriteBatch* updates) = 0;
virtual Status Get(const ReadOptions& options,
const Slice& key, std::string* value) = 0;
virtual Iterator* NewIterator(const ReadOptions& options) = 0;
virtual const Snapshot* GetSnapshot() = 0;
virtual void ReleaseSnapshot(const Snapshot* snapshot) = 0;
virtual bool GetProperty(const Slice& property, std::string* value) = 0;
virtual void GetApproximateSizes(const Range* range, int n,
uint64_t* sizes) = 0;
virtual void CompactRange(const Slice* begin, const Slice* end) = 0;
};

The familiar operations are here, including Put, Delete, Get and the batched Write. The same interface also exposes features like snapshots.

I’ll start with those basic operations and follow them into the implementation.

Put

What actually happens when you call Put with a value?

There are two parts to keep in mind as we read the write path.

  1. Append a record to the log.
  2. Check whether compaction is needed.

Let’s start at Put itself.

The implementation lives in db/db_impl.h and db/db_impl.cc.

Here’s Put.

Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) {
return DB::Put(o, key, val);
}

DBImpl overrides DB::Put, only to hand the arguments straight back to the base class.

Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) {
WriteBatch batch;
batch.Put(key, value);
return Write(opt, &batch);
}

So Put is just a Write with a batch it put together itself.

Let’s follow Write, then.

Here’s a cut-down version.

Status DBImpl::Write(const WriteOptions& options, WriteBatch* my_batch) {
Writer w(&mutex_);
w.batch = my_batch;
MakeRoomForWrite(my_batch == NULL);
uint64_t last_sequence = versions_->LastSequence();
Writer* last_writer = &w;
WriteBatch* updates = BuildBatchGroup(&last_writer);
WriteBatchInternal::SetSequence(updates, last_sequence + 1);
last_sequence += WriteBatchInternal::Count(updates);
log_->AddRecord(WriteBatchInternal::Contents(updates));
WriteBatchInternal::InsertInto(updates, mem_);
versions_->SetLastSequence(last_sequence);
return Status::OK();
}

The first call worth a closer look is MakeRoomForWrite.

Its job is to give Write a usable memtable and a log writer.

Inside MakeRoomForWrite there’s an open-ended loop. Its bool force argument is set when my_batch == nullptr, so the caller can force the memtable to turn over. These are the cases the loop works through.

  1. If force is false and too many level-0 files have piled up, slow the write down. The delay is 1 millisecond, at most once per call to MakeRoomForWrite.
  2. If the current memtable still has room and the caller hasn’t forced a flush, leave the loop. The write can use that memtable.
  3. Is there already an immutable memtable? Its compaction hasn’t finished yet. Wait.
  4. Check the level-0 file count. If it’s hit the stop threshold, wait for compaction to catch up.
  5. Otherwise, create a new log, mark the old memtable immutable, create a fresh memtable and call MaybeScheduleCompaction to arrange the flush. Here’s the scheduling code.
void DBImpl::MaybeScheduleCompaction() {
mutex_.AssertHeld();
if (background_compaction_scheduled_) {
// Already scheduled
} else if (shutting_down_.load(std::memory_order_acquire)) {
// DB is being deleted; no more background compactions
} else if (!bg_error_.ok()) {
// Already got an error; no more changes
} else if (imm_ == nullptr &&
manual_compaction_ == nullptr &&
!versions_->NeedsCompaction()) {
// No work to be done
} else {
background_compaction_scheduled_ = true;
env_->Schedule(&DBImpl::BGWork, this);
}
}

As you might have guessed from the name, MaybeScheduleCompaction is our way into compaction. It’s short enough to look at in full.

void DBImpl::MaybeScheduleCompaction() {
mutex_.AssertHeld();
if (background_compaction_scheduled_) {
// Already scheduled
} else if (shutting_down_.load(std::memory_order_acquire)) {
// DB is being deleted; no more background compactions
} else if (!bg_error_.ok()) {
// Already got an error; no more changes
} else if (imm_ == nullptr &&
manual_compaction_ == nullptr &&
!versions_->NeedsCompaction()) {
// No work to be done
} else {
background_compaction_scheduled_ = true;
env_->Schedule(&DBImpl::BGWork, this);
}
}

The actual Schedule call belongs to the environment. When there’s an immutable memtable, the background job handles minor compaction. It can also schedule work to compact files between levels when they need it. LevelDB has Windows and POSIX implementations of the environment. We’ll come back to the background work in a bit.

Once there’s room, log_->AddRecord(WriteBatchInternal::Contents(updates)) appends the serialized batch to the log. Then WriteBatchInternal::InsertInto(updates, mem_) applies the batch to the memtable.

I’ll get to the log format shortly. For now, writing to the memtable amounts to inserting an entry in its skip list.

And that’s a Put. There’s pleasantly little on the write path, which goes a long way toward explaining its speed.

Get

Reads are where we pay for that write performance.

A lookup works through these in order.

  1. The current memtable
  2. The immutable memtable, if there is one
  3. The level-0 files
  4. Files at higher-numbered levels

If the key is missing, the search has to rule out every file that could contain it.

The outline of Get is easy to follow. It’s a succession of lookups. Here’s the code with the bookkeeping stripped away.

// Lookup inside DBImpl::Get, after selecting the snapshot and pinning the tables.
Status s;
Version::GetStats stats;
LookupKey lkey(key, snapshot);
if (mem->Get(lkey, value, &s)) {
// Found a value or a deletion record.
} else if (imm != nullptr && imm->Get(lkey, value, &s)) {
// Found it in the immutable memtable.
} else {
s = current->Get(options, lkey, value, &stats);
}
// The caller receives s, including NotFound when appropriate.

First, the memtable’s Get.

Underneath the memtable there’s an ordinary skip list of sorted entries. Looking up a key means searching the list using the comparator supplied by the user.

One small detail matters here. Each entry carries a ValueType that says whether the operation was an insertion or a deletion.

Deleting a key appends another entry. A later compaction can discard the key’s obsolete records.

Get sees the newest data visible to the read first. Once it finds a deletion record for this key, it knows the key is gone.

The immutable memtable has the same layout as the active one. It’s read-only now and acts as a buffer while the data makes its way into an SSTable.

That brings us to Get on a version.

The type to look out for here is FileMetaData.

Here’s its definition.

struct FileMetaData {
int refs;
int allowed_seeks; // Seeks allowed until compaction
uint64_t number;
uint64_t file_size; // File size in bytes
InternalKey smallest; // Smallest internal key served by table
InternalKey largest; // Largest internal key served by table
FileMetaData() : refs(0), allowed_seeks(1 << 30), file_size(0) { }
};

smallest and largest give us the key range of the file. If the key falls outside it, we can skip that file altogether.

The rest of the search is fairly direct. Work down the levels until you find the key or run out of candidates.

Delete & Write

Delete follows the same path as Put, and we’ve already followed Put down to Write. I’ll leave those two there.

What makes append-only writes work? The log

An LSM tree gets much of its write performance from keeping a tree in memory and periodically flushing it to disk. Memory is volatile, of course. The log lets LevelDB recover writes that haven’t made it into an SSTable yet.

The files we’re interested in are log_format.h, log_reader.h and log_writer.h.

log_format.h

This is where the log format is defined.

enum RecordType {
// Zero is reserved for preallocated files
kZeroType = 0,
kFullType = 1,
// For fragments
kFirstType = 2,
kMiddleType = 3,
kLastType = 4
};
static const int kMaxRecordType = kLastType;
static const int kBlockSize = 32768;
// Header is checksum (4 bytes), length (2 bytes), type (1 byte).
static const int kHeaderSize = 4 + 2 + 1;

LevelDB appends records sequentially to get the most out of sequential I/O. The three fields in the header are a CRC checksum, the payload length and a type that tells us where this fragment belongs in the logical record.

The log is divided into fixed 32 KiB blocks, so a logical record can cross a block boundary. There are four cases.

  • The entire record fits in this block.
  • The record starts in this block.
  • This block holds a middle fragment, filling the block.
  • The record ends in this block.

So what’s kZeroType doing in that enum? As the comment says, zero is reserved for preallocated files. There’s a separate detail at the end of each block.

Suppose a write leaves fewer than seven bytes. There isn’t room for another header.

LevelDB pads that space with zero bytes (\x00).

If there are exactly seven bytes left and the next logical record is nonempty, there is room for a header. The writer emits a kFirstType fragment with an empty payload, then continues the record in the next block.

log_writer.h

log_writer.h defines Writer. Its main method is AddRecord, the log append we saw in Put.

Here’s how AddRecord works.

Status Writer::AddRecord(const Slice& slice) {
const char* ptr = slice.data();
size_t left = slice.size();
// Fragment the record if necessary and emit it. Note that if slice
// is empty, we still want to iterate once to emit a single
// zero-length record
Status s;
bool begin = true;
do {
const int leftover = kBlockSize - block_offset_;
assert(leftover >= 0);
if (leftover < kHeaderSize) {
// Switch to a new block
if (leftover > 0) {
// Fill the trailer (literal below relies on kHeaderSize being 7)
assert(kHeaderSize == 7);
dest_->Append(Slice("\x00\x00\x00\x00\x00\x00", leftover));
}
block_offset_ = 0;
}
// Invariant: we never leave < kHeaderSize bytes in a block.
assert(kBlockSize - block_offset_ - kHeaderSize >= 0);
const size_t avail = kBlockSize - block_offset_ - kHeaderSize;
const size_t fragment_length = (left < avail) ? left : avail;
RecordType type;
const bool end = (left == fragment_length);
if (begin && end) {
type = kFullType;
} else if (begin) {
type = kFirstType;
} else if (end) {
type = kLastType;
} else {
type = kMiddleType;
}
s = EmitPhysicalRecord(type, ptr, fragment_length);
ptr += fragment_length;
left -= fragment_length;
begin = false;
} while (s.ok() && left > 0);
return s;
}

The part to watch is what happens when the block runs out of room. That’s the boundary case we just walked through.

EmitPhysicalRecord appends the header and payload to the file and calls Flush. For a write that requests durability on disk, the write path also calls Sync.

log_reader.h

log_reader.h defines the other half, Reader.

The reader’s counterpart to AddRecord is ReadRecord.

There are two parts to ReadRecord.

  • Call ReadPhysicalRecord to read a fragment and verify its CRC when checksum verification is enabled.
  • Use the fragment type to decide how to assemble the logical record.

Compaction in LevelDB

In an LSM tree the merging work is called compaction. It comes in a few forms.

  • Minor compaction flushes the in-memory tree to a file on disk.
  • Major compaction merges SSTables across adjacent levels.
  • Full compaction merges everything.

LevelDB implements minor and major compaction.

We ran into MaybeScheduleCompaction earlier.

void DBImpl::MaybeScheduleCompaction() {
mutex_.AssertHeld();
if (background_compaction_scheduled_) {
// Already scheduled
} else if (shutting_down_.load(std::memory_order_acquire)) {
// DB is being deleted; no more background compactions
} else if (!bg_error_.ok()) {
// Already got an error; no more changes
} else if (imm_ == nullptr &&
manual_compaction_ == nullptr &&
!versions_->NeedsCompaction()) {
// No work to be done
} else {
background_compaction_scheduled_ = true;
env_->Schedule(&DBImpl::BGWork, this);
}
}

The function pointer passed to env_->Schedule is DBImpl::BGWork. Let’s see where it goes.

void DBImpl::BGWork(void* db) {
reinterpret_cast<DBImpl*>(db)->BackgroundCall();
}
void DBImpl::BackgroundCall() {
MutexLock l(&mutex_);
assert(background_compaction_scheduled_);
if (shutting_down_.load(std::memory_order_acquire)) {
// No more background work when shutting down.
} else if (!bg_error_.ok()) {
// No more background work after a background error.
} else {
BackgroundCompaction();
}
background_compaction_scheduled_ = false;
// Previous compaction may have produced too many files in a level,
// so reschedule another compaction if needed.
MaybeScheduleCompaction();
background_work_finished_signal_.SignalAll();
}

DBImpl::BGWork calls DBImpl::BackgroundCall, which in turn calls BackgroundCompaction.

DBImpl::BackgroundCompaction is fairly long. Stripped down, it has this shape.

void DBImpl::BackgroundCompaction() {
// Manual compaction omitted.
if (imm_ != nullptr) {
CompactMemTable();
return;
}
Compaction* c = versions_->PickCompaction();
if (c == nullptr) return;
CompactionState* compact = new CompactionState(c);
DoCompactionWork(compact);
CleanupCompaction(compact);
c->ReleaseInputs();
DeleteObsoleteFiles();
delete c;
}

Minor Compaction

Let’s start with CompactMemTable. This version is abbreviated too.

void DBImpl::CompactMemTable() {
VersionEdit edit;
Version* base = versions_->current();
base->Ref();
Status s = WriteLevel0Table(imm_, &edit, base);
base->Unref();
if (s.ok()) {
edit.SetPrevLogNumber(0);
edit.SetLogNumber(logfile_number_);
s = versions_->LogAndApply(&edit, &mutex_);
}
if (s.ok()) {
imm_->Unref();
imm_ = nullptr;
has_imm_.store(false, std::memory_order_release);
DeleteObsoleteFiles();
} else {
RecordBackgroundError(s);
}
}

Flushing a memtable takes two steps.

  1. Make the current memtable immutable.
  2. Turn the immutable memtable into an SSTable file.

Writes can carry on in a fresh memtable. The old one lives on as imm_, and WriteLevel0Table writes its contents to disk.

Here’s WriteLevel0Table.

Status DBImpl::WriteLevel0Table(MemTable* mem, VersionEdit* edit,
Version* base) {
FileMetaData meta;
meta.number = versions_->NewFileNumber();
pending_outputs_.insert(meta.number);
Iterator* iter = mem->NewIterator();
Status s;
s = BuildTable(dbname_, env_, options_, table_cache_, iter, &meta);
delete iter;
pending_outputs_.erase(meta.number);
int level = 0;
const Slice min_user_key = meta.smallest.user_key();
const Slice max_user_key = meta.largest.user_key();
level = base->PickLevelForMemTableOutput(min_user_key, max_user_key);
edit->AddFile(level, meta.number, meta.file_size,
meta.smallest, meta.largest);
return s;
}

The call that matters here is BuildTable. It writes the contents of the memtable to the designated file.

The calls get a little deeply nested at this point. BuildTable lives in builder.cc and mostly uses a TableBuilder to produce the SSTable, so let’s go straight there.

The two files to open are table_builder.h and table_builder.cc.

Here’s the TableBuilder declaration.

class TableBuilder {
public:
TableBuilder(const Options& options, WritableFile* file);
TableBuilder(const TableBuilder&) = delete;
void operator=(const TableBuilder&) = delete;
~TableBuilder();
Status ChangeOptions(const Options& options);
void Add(const Slice& key, const Slice& value);
void Flush();
Status status() const;
Status Finish();
void Abandon();
uint64_t NumEntries() const;
uint64_t FileSize() const;
private:
bool ok() const { return status().ok(); }
void WriteBlock(BlockBuilder* block, BlockHandle* handle);
void WriteRawBlock(const Slice& data, CompressionType, BlockHandle* handle);
struct Rep;
Rep* rep_;
};

The interface is straightforward. Construct a builder, call Add for each entry, then call Finish or Abandon before destroying it.

Here’s the part of Add I want to look at, with some details trimmed.

void TableBuilder::Add(const Slice& key, const Slice& value) {
Rep* r = rep_;
if (r->pending_index_entry) {
// We only get here when the data block is empty.
r->options.comparator->FindShortestSeparator(&r->last_key, key);
std::string handle_encoding;
r->pending_handle.EncodeTo(&handle_encoding);
r->index_block.Add(r->last_key, Slice(handle_encoding));
r->pending_index_entry = false;
}
if (r->filter_block != nullptr) r->filter_block->AddKey(key);
r->last_key.assign(key.data(), key.size());
r->num_entries++;
r->data_block.Add(key, value);
const size_t estimated_block_size = r->data_block.CurrentSizeEstimate();
if (estimated_block_size >= r->options.block_size) Flush();
}

It helps to keep the SSTable layout in view while reading this code. Logical layout of an SSTable, from data blocks through the footer

The file holds data blocks containing the actual key-value entries, plus a few other structures.

  • Filter block. A Bloom filter helps rule out keys during a lookup.
  • Metaindex block. Maps a metadata block’s name to its location, for example the handle for a filter block.
  • Index block. Holds the index entries for the data blocks.
  • Footer. Points to the metaindex and index blocks.

Here are the steps inside Add.

  1. Encode the block handle when there’s an index entry waiting.
  2. Add that index entry.
  3. Add the key to the filter if one is configured.
  4. Append the key and value to the data block.

Let’s look more closely at steps 2, 3 and 4.

Both the index entries and the key-value entries are built with BlockBuilder.

Its interface looks a lot like TableBuilder’s. Once again, the method I’m interested in is Add.

Here’s the implementation in outline.

void BlockBuilder::Add(const Slice& key, const Slice& value) {
Slice last_key_piece(last_key_);
size_t shared = 0;
if (counter_ < options_->block_restart_interval) {
const size_t min_length = std::min(last_key_piece.size(), key.size());
while (shared < min_length && last_key_piece[shared] == key[shared]) {
shared++;
}
} else {
restarts_.push_back(buffer_.size());
counter_ = 0;
}
const size_t non_shared = key.size() - shared;
PutVarint32(&buffer_, shared);
PutVarint32(&buffer_, non_shared);
PutVarint32(&buffer_, value.size());
buffer_.append(key.data() + shared, non_shared);
buffer_.append(value.data(), value.size());
last_key_.resize(shared);
last_key_.append(key.data() + shared, non_shared);
assert(Slice(last_key_) == key);
counter_++;
}

Here’s the layout of an index block. Index entries point to the offsets and lengths of data blocks

Each index entry holds an upper-bound key (the diagram calls it Max Key) together with a block offset and length.

There’s a small space saving worth noticing. When LevelDB stores a key-value pair, it can store just the part of the key it doesn’t share with the previous key.

Here’s the format of a data block entry. An entry stores a shared prefix length, an unshared key suffix and the value

Take the consecutive keys abc and acc. The unshared parts are abc for the first key in the block and cc for the second.

LevelDB also uses restart points. Every so often it stores a key in full. The default restart interval is 16 entries.

To add an index entry, the call is r->index_block.Add(r->last_key, Slice(handle_encoding)).

The value of r->last_key comes from r->options.comparator->FindShortestSeparator(&r->last_key, key).

FindShortestSeparator is a fun little function. It does what the name suggests and finds a short separator between two keys.

What’s the separator here? It’s that Max Key in the index block.

TableBuilder waits until it sees the first key in the next data block before deciding what key to put in the index for the block it just finished.

With the default bytewise comparator, take the last key of the previous block and the first key of the next one. Find their common prefix. If incrementing the following byte of the previous key still leaves it below the corresponding byte in the next key, increment it and drop the rest. Otherwise, keep the previous key.

Say the previous block ends with abcd and the next one starts with abcf. The common prefix is abc. Increment d to e and the index key becomes abce.

Every key in the previous block is at or below that upper bound, while the next block starts above it. You can shorten an index key and still send every lookup to the right block. Neat.

I’ll leave Bloom filters for another day.

Major Compaction

We’ve seen what minor compaction does with a memtable. What about major compaction on SSTables?

There’s more to it. Major compaction has to merge SSTables whose key ranges overlap across two levels.

That deserves a post of its own.