TExcelTAD
Home › Advanced & Succinct Data Structures › B-Trees Revisited: Optimal Search on Disk

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 Θ(B)\Theta(B) keys per node answers a search in Θ(log⁡BN)\Theta(\log_B N) 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: Θ(log⁡BN)\Theta(\log_B N)

Upper bound. A node with between B/2B/2 and BB keys fits in one block (or a constant number), and the height of the tree is O(log⁡BN)O(\log_B N) (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 N+1N + 1 possible answers, so the algorithm must learn lg⁡(N+1)\lg (N + 1) bits about where the query falls. Reading one block brings at most BB keys into the cache, and comparing the query with them reveals where it falls among those BB keys: one of B+1B + 1 outcomes, at most lg⁡(B+1)\lg (B + 1) bits. Hence

#I/Os≥lg⁡(N+1)lg⁡(B+1)=log⁡B+1(N+1)=Ω(log⁡BN)\#\text{I/Os} \ge \frac{\lg (N + 1)}{\lg (B + 1)} = \log_{B+1} (N + 1) = \Omega(\log_B N)

The sketch ignores what is already in the cache; with a cache of MM words the top log⁡BM\log_B M levels can be kept there and the bound becomes Ω(log⁡B(N/M))\Omega(\log_B (N/M)), still matched by a B-tree.

The program builds a static B+-tree (leaves of BB keys, internal nodes with BB children) over about 2182^{18} keys and compares its block reads with binary search on the sorted array, for three block sizes, counting each distinct block a query touches.

python · try it yourself
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 BB: binary search saves only the last lg⁡B\lg B steps, a B-tree divides the whole height by lg⁡B\lg B.

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).

cpp · try it yourself
#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 Θ(log⁡BN)\Theta(\log_B N) 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ε^\varepsilon-trees (Brodal and Fagerberg, 2003) attach a buffer of Θ(B)\Theta(B) 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 BεB^\varepsilon (for a constant 0<ε≤10 < \varepsilon \le 1), a flush moves Θ(B)\Theta(B) updates and costs O(Bε)O(B^\varepsilon) I/Os, so about B1−εB^{1-\varepsilon} updates move one level down per I/O. Each update travels down O(log⁡BεN)=O(1εlog⁡BN)O(\log_{B^\varepsilon} N) = O(\frac{1}{\varepsilon} \log_B N) levels:

insert: O ⁣(log⁡BNεB1−ε) amortized I/Os,search: O ⁣(log⁡BNε) I/Os\text{insert: } O\!\left(\frac{\log_B N}{\varepsilon B^{1-\varepsilon}}\right) \text{ amortized I/Os}, \qquad \text{search: } O\!\left(\frac{\log_B N}{\varepsilon}\right) \text{ I/Os}

ε=1\varepsilon = 1 is a B-tree. ε=1/2\varepsilon = 1/2 keeps searches within a factor 2 of a B-tree while making inserts about B\sqrt{B} 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.

python · try it yourself
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, ε=1/2\varepsilon = 1/2 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 MM words, the top lg⁡M\lg M levels fit, and a search then touches about lg⁡N−lg⁡M\lg N - \lg M uncached nodes, each in a different block: for N=230N = 2^{30} and M=220M = 2^{20}, ten I/Os. A B-tree with B=210B = 2^{10} needs log⁡BN−log⁡BM=3−2=1\log_B N - \log_B M = 3 - 2 = 1 I/O for the same cache. The difference is that a B-tree packs lg⁡B\lg B levels of binary decisions into each block, so every I/O delivers lg⁡B\lg B 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 12lg⁡B\frac{1}{2} \lg B to lg⁡B\lg B levels.

Summary

Structure Search Insert/delete Range query of kk items
sorted array (binary search) O(lg⁡(N/B))O(\lg (N/B)) O(N/B)O(N/B) O(lg⁡(N/B)+k/B)O(\lg (N/B) + k/B)
B-tree O(log⁡BN)O(\log_B N), optimal O(log⁡BN)O(\log_B N) O(log⁡BN+k/B)O(\log_B N + k/B)
Bε^\varepsilon-tree / buffer tree O(1εlog⁡BN)O(\frac{1}{\varepsilon}\log_B N) O(log⁡BNεB1−ε)O(\frac{\log_B N}{\varepsilon B^{1-\varepsilon}}) amortized O(1εlog⁡BN+k/B)O(\frac{1}{\varepsilon}\log_B N + k/B)
hash table on disk O(1)O(1) expected O(1)O(1) expected not supported

All of these need to know BB. The cache-oblivious lessons show that O(log⁡BN)O(\log_B N) search can be achieved without knowing it.

Test yourself

Why can no comparison-based search structure beat Ω(log⁡BN)\Omega(\log_B N) I/Os per search in the DAM model?

  1. Because blocks hold BB words
  2. Because each block read compares the query with at most BB keys and so reveals at most lg⁡(B+1)\lg(B + 1) bits, while lg⁡(N+1)\lg(N + 1) bits are needed
  3. Because the tree has height log⁡BN\log_B N
  4. Because caches are LRU

How do buffer trees and Bε^\varepsilon-trees make insertions cheaper than searches?

  1. By caching the whole tree
  2. 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
  3. By hashing keys
  4. By deleting old keys lazily

With ε=1/2\varepsilon = 1/2, how does a Bε^\varepsilon-tree compare with a B-tree?

  1. Searches and inserts are both B\sqrt{B} times faster
  2. Searches cost about twice as much; inserts cost about B/2\sqrt{B}/2 times less (amortized)
  3. Both cost the same
  4. Searches are faster, inserts slower