TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › Disks, Pages and the Case for B-Trees

Disks, Pages and the Case for B-Trees

Everything so far assumed that every memory access costs the same, the RAM model of The RAM Model. That is a good model while the data fits in main memory. A database index, a file system or a key-value store holds far more than that, on a solid-state drive or a spinning disk, and there the cost model changes completely: one access to storage costs as much as hundreds of thousands of instructions, but it brings back a whole page of data at once. Balanced binary trees are the wrong shape for that world. B-trees are the right one, and this lesson explains why with numbers.

The external-memory model

Storage is divided into pages (blocks) of a fixed size, typically 4 to 16 KiB. The device transfers whole pages: reading one byte costs as much as reading its whole page. An algorithm on such data has two costs:

  • the number of page accesses (DISK-READ and DISK-WRITE operations), and
  • the CPU time on pages already in memory.

Rough latencies make the point (orders of magnitude, they vary a lot between devices):

Operation Typical time In CPU cycles at 3 GHz
read from L1 cache 1 ns 3
read from main memory 100 ns 300
random 4 KiB read from an NVMe SSD 20 to 100 µs 60,000 to 300,000
random read from a spinning disk (seek + rotation) 5 to 10 ms 15 to 30 million

A disk seek costs about as much as tens of millions of instructions, so an algorithm that saves one page access can afford a great deal of computation inside each page. The design goal becomes: few page accesses, each one bringing as much useful information as possible.

In pseudocode, a node xx that lives on storage must be brought in with DISK-READ(x)(x) before its fields are used, and written back with DISK-WRITE(x)(x) after it changes. The root is usually kept in memory permanently.

Why binary trees waste pages

A red-black tree with a billion keys has height up to 2lg⁡(109+1)≈602 \lg(10^9 + 1) \approx 60, and even a perfectly balanced binary tree has 30 levels. If each node is a separate page, a search reads 30 pages to inspect 30 keys, while each page could have held hundreds of keys. The fix is to make each node as large as a page, with many keys and many children, so that one page access does the work of many binary decisions.

If a node holds up to 2t−12t - 1 keys and has up to 2t2t children (the B-tree definition in the next lesson), each node comparison step chooses among 2t2t branches instead of 2, and the height drops from about lg⁡n\lg n to about log⁡tn\log_t n:

python · try it yourself
import math

def btree_max_height(n, t):
    """the B-tree height bound h <= log_t((n + 1) / 2)"""
    return math.floor(math.log((n + 1) / 2, t))

print(f"{'n':>15} {'balanced binary':>16} {'red-black bound':>16} {'B-tree t=50':>12} {'t=500':>6} {'t=2000':>7}")
for n in [10 ** 3, 10 ** 6, 10 ** 9, 10 ** 12]:
    print(f"{n:>15,} {math.floor(math.log2(n)):>16} {math.floor(2 * math.log2(n + 1)):>16} "
          f"{btree_max_height(n, 50):>12} {btree_max_height(n, 500):>6} {btree_max_height(n, 2000):>7}")
              n  balanced binary  red-black bound  B-tree t=50  t=500  t=2000
          1,000                9               19            1      1       0
      1,000,000               19               39            3      2       1
  1,000,000,000               29               59            5      3       2
1,000,000,000,000               39               79            6      4       3

With t=500t = 500, a node with up to 999 keys fits in a page of about 16 KiB (16-byte keys and page pointers). A billion keys then need at most 3 levels below the root, and keeping the root and its children in memory leaves one or two page reads per search.

Counting page reads

The program makes the comparison concrete. It stores n=220n = 2^{20} sorted keys three ways, with 256 keys per page, and counts the distinct pages a search touches:

  • binary search over the sorted array, which is split into pages in order;
  • a balanced binary search tree whose nodes are laid out level by level, so the top few levels share pages and deeper nodes are scattered;
  • a B-tree-like layout where each page is one node with 255 keys and 256 children.
python · try it yourself
import math, random

n, PAGE = 2 ** 20, 256
rng = random.Random(1)
queries = [rng.randrange(n) for _ in range(2000)]

def binary_search_pages(q):
    pages, lo, hi = set(), 0, n
    while lo < hi:
        mid = (lo + hi) // 2
        pages.add(mid // PAGE)                     # array position -> page
        if mid == q: break
        if mid < q: lo = mid + 1
        else: hi = mid
    return len(pages)

def bst_pages(q):
    """implicit balanced BST over 0..n-1 in level order (heap layout): node i at page i // PAGE"""
    pages, lo, hi, i = set(), 0, n, 0
    while lo < hi:
        mid = (lo + hi) // 2
        pages.add(i // PAGE)
        if mid == q: break
        if q < mid: hi, i = mid, 2 * i + 1
        else: lo, i = mid + 1, 2 * i + 2
    return len(pages)

def btree_pages(q):
    """each node is one page with PAGE - 1 keys; the depth is ceil(log_PAGE(n + 1))"""
    return math.ceil(math.log(n + 1, PAGE))

for name, f in [("binary search on a sorted array", binary_search_pages),
                ("balanced BST, level-order pages", bst_pages),
                ("B-tree, one node per page", btree_pages)]:
    reads = [f(q) for q in queries]
    print(f"{name:32}: {sum(reads) / len(reads):5.2f} pages per search (max {max(reads)})")
print(f"comparisons per search are about lg n = {math.log2(n):.0f} in every case")
binary search on a sorted array : 12.00 pages per search (max 12)
balanced BST, level-order pages : 11.99 pages per search (max 13)
B-tree, one node per page       :  3.00 pages per search (max 3)
comparisons per search are about lg n = 20 in every case

All three make about 20 comparisons per search, but the B-tree reads 3 pages where the other two read 12. (Its count is the depth of a full tree with 256 children per node, ⌈log⁡256(n+1)⌉=3\lceil \log_{256}(n + 1) \rceil = 3, rather than a simulation.) Binary search only gets help at the end, when the range fits in one page; the level-order tree only at the top, where the first levels share pages. The B-tree uses every page fully on every level.

What B-trees are used for

  • Databases. Almost every relational database stores its tables and indexes as B-trees, usually the B+-tree variant that keeps all records in the leaves and links the leaves in key order, which makes range scans sequential. PostgreSQL's default index, MySQL's InnoDB tables and SQLite's tables and indexes are all B-tree variants.
  • File systems. Btrfs, XFS, NTFS and Apple's APFS keep directories, file extents or metadata in B-tree variants.
  • Key-value stores and caches use B-trees when reads dominate, and log-structured merge trees when writes dominate.

The same reasoning applies one level up the memory hierarchy: a node the size of a cache line (64 bytes) makes in-memory search trees faster too, which is why some modern sorted containers, such as Rust's BTreeMap, are B-trees even though they never touch a disk.

Test yourself

In the external-memory model, what is the main cost measure?

  1. the number of key comparisons
  2. the number of page (block) accesses
  3. the amount of memory used
  4. the number of rotations

A B-tree has minimum degree t=1000t = 1000. At most how many levels below the root does it need for n=109n = 10^9 keys?

  1. 2
  2. 3
  3. 9
  4. 30

Why does binary search on a sorted array stored in pages read many pages?

  1. Because it makes more comparisons than a B-tree
  2. Because its first probes are far apart, each in a different page, and only the last few share a page
  3. Because arrays cannot be stored on disk
  4. Because it scans the whole array