B-Trees Revisited: Optimal Search on Disk
Part I introduced B-trees as balanced search trees with high fan-out, designed so that each node fills a disk page. In the DAM model that design can be proved optimal: a B-tree with keys per node answers a search in I/Os, and no comparison-based structure does better. Updates are a different story: they can be made much cheaper than searches by buffering, which is how modern write-optimized databases work.
Search:
Upper bound. A node with between and keys fits in one block (or a constant number), and the height of the tree is (B-Trees: Definition, Height and Search). A search reads one node per level.
Lower bound. Consider any comparison-based search structure in the DAM model. A predecessor query has possible answers, so the algorithm must learn bits about where the query falls. Reading one block brings at most keys into the cache, and comparing the query with them reveals where it falls among those keys: one of outcomes, at most bits. Hence
The sketch ignores what is already in the cache; with a cache of words the top levels can be kept there and the bound becomes , still matched by a B-tree.
The program builds a static B+-tree (leaves of keys, internal nodes with children) over about keys and compares its block reads with binary search on the sorted array, for three block sizes, counting each distinct block a query touches.
import bisect, math, random
class BNode:
__slots__ = ("keys", "children") # one node = one block of B words
def __init__(self, keys, children=None):
self.keys, self.children = keys, children
def build(keys, B):
"""Static B+-tree: leaves hold B keys; an internal node holds the B - 1 separators of its B children."""
level = [BNode(keys[i:i + B]) for i in range(0, len(keys), B)]
lows = [n.keys[0] for n in level]
while len(level) > 1:
parents, plows = [], []
for i in range(0, len(level), B):
parents.append(BNode(lows[i + 1:i + B], level[i:i + B]))
plows.append(lows[i])
level, lows = parents, plows
return level[0]
def btree_pred(root, x): # largest key <= x, and the blocks read
node, ios = root, 0
while True:
ios += 1
j = bisect.bisect_right(node.keys, x)
if node.children is None:
return (node.keys[j - 1] if j else None), ios
node = node.children[j]
def array_pred(a, x, B): # binary search, counting distinct blocks touched
lo, hi, blocks = 0, len(a), set()
while lo < hi:
mid = (lo + hi) // 2
blocks.add(mid // B)
if a[mid] <= x: lo = mid + 1
else: hi = mid
return (a[lo - 1] if lo else None), len(blocks)
rng = random.Random(1972)
N = 1 << 18
keys = sorted({rng.getrandbits(40) for _ in range(N)})
for B in [8, 64, 512]:
root = build(keys, B)
bt = ar = 0
for _ in range(500):
x = rng.getrandbits(40)
p1, i1 = btree_pred(root, x)
p2, i2 = array_pred(keys, x, B)
assert p1 == p2
bt, ar = bt + i1, ar + i2
n = len(keys)
print(f"B = {B:3}: B-tree {bt / 500:4.1f} I/Os per search (log_B N = {math.log(n, B):4.1f}), "
f"binary search {ar / 500:4.1f} (lg(N/B) = {math.log2(n / B):4.1f})")B = 8: B-tree 6.0 I/Os per search (log_B N = 6.0), binary search 15.0 (lg(N/B) = 15.0)
B = 64: B-tree 3.0 I/Os per search (log_B N = 3.0), binary search 12.0 (lg(N/B) = 12.0)
B = 512: B-tree 2.0 I/Os per search (log_B N = 2.0), binary search 9.0 (lg(N/B) = 9.0)
A factor of 2.5 to 4.5 fewer block reads than binary search, and the gap grows with : binary search saves only the last steps, a B-tree divides the whole height by .
In C++
The same static B+-tree over a million 44-bit keys, with nodes stored level by level so that the child index is computed rather than stored (an implicit B-tree, the layout used by fast in-memory search libraries).
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
// Static B+-tree stored level by level: node i of a level has children B*i .. B*i + B - 1 one level down.
class StaticBTree {
std::size_t B;
std::vector<std::vector<std::vector<std::uint64_t>>> levels; // levels[0] = root level
public:
StaticBTree(const std::vector<std::uint64_t>& keys, std::size_t b) : B(b) {
std::vector<std::vector<std::uint64_t>> level;
std::vector<std::uint64_t> lows;
for (std::size_t i = 0; i < keys.size(); i += B) {
level.emplace_back(keys.begin() + i, keys.begin() + std::min(keys.size(), i + B));
lows.push_back(keys[i]);
}
levels.push_back(level);
while (level.size() > 1) {
std::vector<std::vector<std::uint64_t>> parents;
std::vector<std::uint64_t> plows;
for (std::size_t i = 0; i < level.size(); i += B) {
parents.emplace_back(lows.begin() + i + 1, lows.begin() + std::min(lows.size(), i + B));
plows.push_back(lows[i]);
}
level = parents; lows = plows;
levels.push_back(level);
}
std::reverse(levels.begin(), levels.end());
}
// Largest key <= x (or 0 if none); ios = blocks read.
std::uint64_t pred(std::uint64_t x, int& ios) const {
std::size_t idx = 0;
for (std::size_t d = 0;; ++d) {
const auto& node = levels[d][idx];
++ios;
std::size_t j = std::upper_bound(node.begin(), node.end(), x) - node.begin();
if (d + 1 == levels.size()) return j ? node[j - 1] : 0;
idx = idx * B + j;
}
}
};
int main() {
std::mt19937_64 rng(1972);
std::vector<std::uint64_t> keys(1 << 20);
for (auto& k : keys) k = 1 + (rng() >> 20);
std::sort(keys.begin(), keys.end());
keys.erase(std::unique(keys.begin(), keys.end()), keys.end());
for (std::size_t B : {16, 128, 1024}) {
StaticBTree t(keys, B);
int ios = 0, wrong = 0;
for (int q = 0; q < 1000; ++q) {
std::uint64_t x = rng() >> 20;
auto it = std::upper_bound(keys.begin(), keys.end(), x);
std::uint64_t want = it == keys.begin() ? 0 : *std::prev(it);
wrong += t.pred(x, ios) != want;
}
std::printf("B = %4zu: %.1f blocks per search, log_B N = %.2f, wrong answers %d\n",
B, ios / 1000.0, std::log(double(keys.size())) / std::log(double(B)), wrong);
}
}B = 16: 5.0 blocks per search, log_B N = 5.00, wrong answers 0
B = 128: 3.0 blocks per search, log_B N = 2.86, wrong answers 0
B = 1024: 2.0 blocks per search, log_B N = 2.00, wrong answers 0
Updates: buffering beats the search bound
A B-tree insertion also costs I/Os: it searches for the leaf. That is optimal for a search, but an insertion does not need to know its answer immediately. Batching changes the picture completely.
Buffer trees (Arge, 2003) and B-trees (Brodal and Fagerberg, 2003) attach a buffer of pending updates to each internal node. An update is appended to the root's buffer. When a buffer is full, its updates are flushed to the children's buffers in one go. With fan-out (for a constant ), a flush moves updates and costs I/Os, so about updates move one level down per I/O. Each update travels down levels:
is a B-tree. keeps searches within a factor 2 of a B-tree while making inserts about times cheaper. A search must also look at the buffers on its root-to-leaf path, which is why the fan-out has to shrink to make room for them. Brodal and Fagerberg proved that this trade-off between insert and search cost is optimal for comparison-based external dictionaries.
import math
N, B = 2 ** 30, 2 ** 10 # a billion keys, blocks of 1024 keys
logB = math.log(N, B)
print(f"N = 2^30, B = 2^10: B-tree search and insert cost log_B N = {logB:.1f} I/Os")
print(f"{'epsilon':>8} {'fan-out B^eps':>14} {'query I/Os':>11} {'insert I/Os (amortized)':>24}")
for eps in [1.0, 0.5, 1 / 3, 0.2]:
fan = B ** eps
query = math.log(N, fan) # height of a tree with fan-out B^eps
insert = query / B ** (1 - eps) # each flush moves about B^(1-eps) items per I/O
print(f"{eps:8.2f} {fan:14.0f} {query:11.1f} {insert:24.4f}")N = 2^30, B = 2^10: B-tree search and insert cost log_B N = 3.0 I/Os
epsilon fan-out B^eps query I/Os insert I/Os (amortized)
1.00 1024 3.0 3.0000
0.50 32 6.0 0.1875
0.33 10 9.0 0.0886
0.20 4 15.0 0.0586
For a billion keys in 1024-key blocks, takes inserts from 3 I/Os down to about 0.19 amortized, while searches go from 3 to 6. This is the design of TokuDB's fractal trees and of several file systems and key-value stores. Log-structured merge trees (LSM trees, O'Neil, Cheng, Gawlick and O'Neil, 1996), used by LevelDB, RocksDB and Cassandra, reach a similar trade-off with sorted runs merged in the background.
Why not a binary tree with a big cache?
A tempting alternative is to keep a balanced binary tree and rely on the cache to hold its top levels. With a cache of words, the top levels fit, and a search then touches about uncached nodes, each in a different block: for and , ten I/Os. A B-tree with needs I/O for the same cache. The difference is that a B-tree packs levels of binary decisions into each block, so every I/O delivers bits of information instead of one. The same reasoning explains the van Emde Boas layout: it keeps the binary tree but arranges it so that each block, whatever its size, contains a connected piece of about to levels.
Summary
| Structure | Search | Insert/delete | Range query of items |
|---|---|---|---|
| sorted array (binary search) | |||
| B-tree | , optimal | ||
| B-tree / buffer tree | amortized | ||
| hash table on disk | expected | expected | not supported |
All of these need to know . The cache-oblivious lessons show that search can be achieved without knowing it.
Test yourself
Why can no comparison-based search structure beat I/Os per search in the DAM model?
- Because blocks hold words
- Because each block read compares the query with at most keys and so reveals at most bits, while bits are needed
- Because the tree has height
- Because caches are LRU
How do buffer trees and B-trees make insertions cheaper than searches?
- By caching the whole tree
- By collecting updates in node buffers and flushing many of them to a child with each I/O, so each update costs a fraction of an I/O per level
- By hashing keys
- By deleting old keys lazily
With , how does a B-tree compare with a B-tree?
- Searches and inserts are both times faster
- Searches cost about twice as much; inserts cost about times less (amortized)
- Both cost the same
- Searches are faster, inserts slower