Sub topic 7
Blocks and Sparse Indexes Inside an SSTable
This chapter assumes you know binary search and sorted arrays. You should also know that disk reads happen in fixed-size pages, and you should have read the previous chapter on SSTables.
Why a whole file is the wrong unit
An SSTable is sorted, so you could binary search the whole file. On disk that costs many random reads, because each probe may land on a different page. The usual fix is to split the file into blocks and keep a small index in memory.
A block is a run of consecutive sorted entries, typically 4 to 64 KB. The block is the unit of disk reads, and engines often compress and cache it as a unit.
The sparse index
A sparse index holds one entry per block, not one per key. Each entry is the first key of a block and the block's position in the file. A dense index would list every key, which is nearly as large as the data.
To look up a key:
- Binary search the index for the last block whose first key is less than or equal to the target.
- Read that one block from disk.
- Search inside the block.
If the key exists, it must be in that block. Sorted order guarantees no other block can hold it.
A runnable sketch
This version keeps blocks in memory, but the lookup logic is the same as on disk.
import bisect
class BlockSSTable:
def __init__(self, items, block_size=4):
# items must already be sorted by key
self.blocks = [items[i:i + block_size]
for i in range(0, len(items), block_size)]
self.index = [block[0][0] for block in self.blocks] # first key per block
def get(self, key):
b = bisect.bisect_right(self.index, key) - 1
if b < 0:
return False, None # key is smaller than every key in the table
for k, v in self.blocks[b]: # on disk: one block read
if k == key:
return True, v
return False, None
table = BlockSSTable([(f"k{i:02d}", i) for i in range(10)])
print(table.index) # ['k00', 'k04', 'k08']
print(table.get("k05")) # (True, 5)
print(table.get("k055")) # (False, None)The miss for k055 still reads block 1, because the index can only say where the key would be. Bloom filters, covered later, avoid that wasted read.
Choosing a block size
Block size trades index memory against read cost.
| Block size | Index size | Cost per lookup | Range scan |
|---|---|---|---|
| Small | Larger | Less data read and decoded | More block reads |
| Large | Smaller | More data read and decoded | Fewer, larger reads |
Real engines also store the index and Bloom filter in the SSTable file, usually near the end. They load them into memory when the file is opened.
Exercise
A table has 1,000,000 entries in blocks of 100 entries. How many entries does the sparse index hold, and how many blocks does a point lookup read from disk?
Show answer
The index holds 10,000 entries, one per block. A point lookup reads exactly one block, after a binary search in memory.