B-Trees and B+ Trees

Matt George

Fractional CTO · Founder of Injuria.ai

•16 min read•

A B-tree is a self-balancing tree data structure that maintains sorted data and allows searches, sequential access, insertions, and deletions in logarithmic time. Unlike binary search trees, which restrict nodes to a maximum of two children, B-trees are multi-way trees where a single node can possess a large number of children and contain multiple keys. This structural design directly aligns with the physical characteristics of block-oriented storage systems, such as hard disk drives and solid-state drives, where reading a large contiguous chunk of data is significantly more efficient than reading multiple small, scattered bytes. By packing many keys into a single node that matches the size of a disk block, the B-tree drastically reduces the height of the tree, thereby minimizing the number of expensive disk access operations required to locate a specific record [1].[25]

The B+ tree is the most widely implemented variation of the original B-tree design. It distinguishes itself by storing all data records, or pointers to the actual data rows, exclusively in the leaf nodes. The internal nodes of a B+ tree contain only routing keys used to guide the search process. Additionally, the leaf nodes in a B+ tree are typically linked together in a doubly linked list. This modification enables highly efficient sequential range queries, as the system can simply traverse the linked list at the leaf level once the starting key is found, rather than repeatedly navigating up and down the tree branches [2].

Both structures exist to solve a fundamental bottleneck in computer science: the memory hierarchy problem. Because accessing secondary storage is orders of magnitude slower than accessing main memory, optimizing algorithms to perform fewer, larger reads yields lower latency than the frequent, small reads characteristic of unbalanced or binary trees. Today, B-trees and B+ trees form the foundational storage architecture for nearly all relational database management systems and modern file systems [3].[26]

The Memory Hierarchy Problem

To understand the mechanics of multi-way trees, one must examine the physical constraints of computer storage. In a standard von Neumann architecture, data resides in secondary storage (such as a magnetic disk or flash memory) and must be loaded into primary main memory (RAM) before the central processing unit can operate on it. The latency difference between these two layers is massive. Accessing data in RAM takes tens of nanoseconds, while accessing data on a magnetic hard drive takes several milliseconds, a difference of five to six orders of magnitude [4].

Storage devices do not read or write data one byte at a time. Hardware controllers and operating systems manage data in fixed-size blocks, commonly ranging from 4 kilobytes to 16 kilobytes. When a program requests a single byte from disk, the hardware retrieves the entire block containing that byte. The time required to read a 4-kilobyte block is nearly identical to the time required to read a single byte, because the mechanical seek time and rotational latency dominate the operation [5].

Binary search trees, such as AVL trees or Red-Black trees, are optimized for in-memory operations where pointer dereferencing is nearly instantaneous. In a binary search tree, each node contains one key and two pointers. A balanced binary tree containing one billion elements has a depth of approximately 30. Searching for a single element requires traversing 30 nodes. If these nodes are scattered randomly across a disk, the search requires 30 distinct block reads, resulting in severe performance degradation [3].

The B-tree solves this by packing multiple keys and child pointers into a single node, sized to match the operating system's page size or the disk's block size. A single B-tree node might contain hundreds of keys. This drastically increases the branching factor (the number of children per node). A B-tree with a branching factor of 100 containing one billion elements has a depth of only 4 or 5. Consequently, a search requires only 4 or 5 disk reads. In practice, the root node and upper levels of the tree are usually cached in RAM, meaning a search might require only one or two physical disk reads [6].

Discovery and History

The B-tree was invented by computer scientists Rudolf Bayer and Edward M. McCreight in 1970 while they were working at Boeing Scientific Research Laboratories in Seattle, Washington. They formalized the data structure to address the growing need to manage large, dynamically changing random-access files on magnetic disks. Their foundational paper, "Organization and Maintenance of Large Ordered Indexes," was published in the journal Acta Informatica in 1972 [7].[25]

The origin of the letter "B" in the name remains a subject of historical curiosity. Bayer and McCreight never formally explained what the "B" stands for. Speculation among computer scientists suggests it could stand for Boeing, Bayer, balanced, broad, or bushy. McCreight has stated in interviews that the ambiguity was intentional and that the mystery added to the structure's appeal [1].[27]

The B-tree did not emerge in a vacuum. It generalized earlier concepts, most notably the 2-3 tree introduced by John Hopcroft in 1970. A 2-3 tree is a specific, small-scale instance of a B-tree where every internal node has either two or three children. Bayer and McCreight invented the B-tree independently of Hopcroft's 2-3 tree, rather than expanding his concept, providing the mathematical proofs for the splitting and merging algorithms that keep the tree perfectly balanced during dynamic updates [7].

Following the initial publication, the database industry rapidly adopted and modified the structure. In 1973, IBM introduced the Virtual Storage Access Method (VSAM) for its mainframe operating systems. VSAM utilized a heavily modified B-tree structure that separated the index set from the sequence set, effectively creating what is now known as a B+ tree . The terminology and formal analysis of the B+ tree were later standardized by Douglas Comer in his highly influential 1979 paper, "The Ubiquitous B-Tree," published in ACM Computing Surveys. Comer's paper categorized the emerging variants and cemented the B+ tree as the definitive standard for file organization [8].

Structural Definition of a B-Tree

A B-tree is defined by a strict set of structural properties that guarantee its balance and bound its worst-case performance. The tree is parameterized by an integer known as the order, often denoted as m, which dictates the maximum number of children a single node can possess [3].

The formal properties of a B-tree of order m are as follows:

  1. Every node has at most m children.
  2. Every non-leaf node (except the root) has at least the ceiling of m/2 children.
  3. The root has at least two children if it is not a leaf node.
  4. A non-leaf node with k children contains exactly k - 1 keys.
  5. All leaf nodes appear at the exact same depth, ensuring the tree is perfectly balanced.

Within any given node, the keys are stored in strictly non-decreasing order.[27] The keys act as separation values that divide the subtrees. If an internal node contains keys K_1, K_2, up to K_n, it will contain pointers P_0, P_1, up to P_n. The pointer P_0 leads to a subtree where all keys are strictly less than K_1. The pointer P_i leads to a subtree where all keys are greater than or equal to K_i and strictly less than K_{i+1}. The final pointer P_n leads to a subtree where all keys are greater than or equal to K_n [3].

Because the tree remains perfectly balanced and the branching factor is large, the height of the tree grows logarithmically with the number of elements. For a tree containing n elements, the time complexity for search, insertion, and deletion operations is O(log n). The space complexity to store the tree is O(n) [3].

Core Operations and Complexity

The algorithms for searching, inserting, and deleting records in a B-tree are designed to maintain the strict structural properties defined above.

Search

Searching a B-tree is a generalization of searching a binary search tree. The operation begins at the root node. The algorithm scans the keys within the current node to find the first key that is greater than or equal to the target value. Because the keys within a node are sorted, this intra-node search can be performed using a linear scan or a binary search. If the target key is found within the node, the search terminates successfully. If the target key is not found, the algorithm follows the child pointer corresponding to the correct interval and repeats the process recursively. If the algorithm reaches a leaf node and fails to find the key, the target does not exist in the tree [3].

function btree_search(node, target_key):
    i = 1
    while i <= node.num_keys and target_key > node.keys[i]:
        i = i + 1
    if i <= node.num_keys and target_key == node.keys[i]:
        return (node, i)
    if node.is_leaf:
        return null
    else:
        read_disk_block(node.pointers[i])
        return btree_search(node.pointers[i], target_key)

Insertion

Insertions always occur at the leaf level. The algorithm first performs a search to locate the correct leaf node for the new key. If the target leaf node has fewer than m - 1 keys, the new key is inserted into the node in its correct sorted position.

If the leaf node is already full (containing exactly m - 1 keys), a structural violation would occur. To resolve this, the node undergoes a split operation. The full node is divided into two separate nodes. The median key of the overfull node is not kept in either new node; instead, it is pushed upward and inserted into the parent node. The remaining keys are divided equally between the two new sibling nodes.

If pushing the median key upward causes the parent node to exceed its capacity, the parent node must also split. This splitting process can cascade upward all the way to the root. If the root node splits, a new root is created containing only the single median key, and the height of the entire tree increases by one. This bottom-up growth mechanism is what guarantees that all leaf nodes remain at the exact same depth [7].

Deletion

Deletion is the most complex operation because it can cause a node to fall below the minimum required number of keys (the ceiling of m/2 minus 1).

If the key to be deleted resides in a leaf node, it is simply removed. If this removal causes an underflow, the node must be repaired. The algorithm first attempts to borrow a key from an immediate sibling (left or right). If a sibling has surplus keys, the tree performs a rotation: a key moves from the sibling to the parent, and a key from the parent moves down into the underflowing node.

If both immediate siblings have only the minimum number of keys, borrowing is impossible. In this case, the underflowing node is merged with one of its siblings. The key separating the two siblings in the parent node is pulled down and becomes the median key of the newly merged node. Because a key was removed from the parent, the parent might now underflow, causing the merge process to cascade upward. If the root node loses its last remaining key during a merge, the root is deleted, and its single child becomes the new root, decreasing the height of the tree by one [3].

The B+ Tree Evolution

While the original B-tree successfully minimized disk I/O, it possessed inefficiencies regarding sequential access and node capacity. In a standard B-tree, data records (or pointers to physical disk locations) are stored alongside the keys in every node, including internal nodes. Because data records are typically much larger than the keys themselves, storing them in internal nodes consumes valuable space, reducing the number of keys that can fit into a single block. A lower key capacity results in a lower branching factor, which in turn increases the height of the tree and requires more disk reads [8].

The B+ tree resolves this by strictly separating the routing structure from the data storage. In a B+ tree, internal nodes contain only keys and child pointers. These keys act exclusively as traffic signals to guide searches. All actual data records, or pointers to the data, are stored entirely in the leaf nodes.

This architectural change yields two major advantages. First, the internal nodes can hold significantly more keys, maximizing the branching factor. A B+ tree is typically wider and shallower than a standard B-tree containing the same data, leading to faster lookups. Second, the leaf nodes are linked together using next and previous pointers, forming a doubly linked list. When an application needs to perform a range query (for example, retrieving all records between the values 100 and 500), the database searches the tree once to locate the leaf containing 100. It then traverses the linked list horizontally across the leaf level until it reaches 500. In a standard B-tree, the same query would require a complex in-order traversal, repeatedly reading internal nodes and leaf nodes [2].

Important Variants

Over the decades, researchers have developed several specialized variants of the B-tree to optimize specific performance characteristics.

The B* Tree

The B* tree was described by Donald Knuth in 1973 in his work, "The Art of Computer Programming, Volume 3: Sorting and Searching." The B* tree modifies the insertion algorithm to delay node splitting. Instead of requiring nodes to be half full, a B* tree requires non-root nodes to be at least two-thirds full. When a node becomes full, it does not immediately split. Instead, it attempts to redistribute its keys with an adjacent sibling. Only when both the node and its sibling are completely full do they split, dividing their combined keys across three new nodes rather than two. This increases the average space utilization of the tree and reduces the frequency of split operations [9].

The B-link Tree

In highly concurrent database systems, multiple threads must read and write to the index simultaneously. Standard B-tree modifications require locking multiple nodes along the traversal path to prevent race conditions during a split, which severely limits concurrency. In 1981, Philip L. Lehman and S. Bing Yao introduced the B-link tree (often written as B^link tree). This variant adds a right-sibling pointer to every internal node. If a search process reaches a node that has just been split by another thread, the search can follow the link pointer to the new right sibling to find the correct path. This innovation allows concurrent operations to proceed by locking only one node at a time, drastically improving database throughput [10].

Prefix B-Trees

Introduced by Rudolf Bayer and Karl Unterauer in 1977, the Prefix B-tree optimizes space when the keys are long strings. Instead of storing the entire string in the internal routing nodes, the tree stores only the shortest prefix necessary to distinguish between the left and right subtrees. This compression technique further increases the branching factor of the internal nodes [11].

Cache-Oblivious B-Trees

Traditional B-trees must be explicitly tuned to match the block size of the underlying hardware. Cache-oblivious B-trees, formalized by Michael A. Bender and others in 2000, use an algorithmic layout that performs asymptotically optimally across all levels of the memory hierarchy without knowing the specific page sizes of the CPU cache, RAM, or disk [12].

Real-World Applications

The theoretical efficiency of B-trees and B+ trees has translated into near-universal adoption across data storage systems.

Relational Databases

PostgreSQL utilizes a B-tree as its default index type. The PostgreSQL implementation is heavily based on the Lehman and Yao B-link tree protocol, allowing it to handle massive concurrent read and write workloads without severe lock contention. The implementation also includes advanced features like bottom-up index deletion and deduplication for repeated keys [13].

MySQL, specifically its default InnoDB storage engine, relies entirely on B+ trees. In InnoDB, every table is physically organized as a B+ tree, a structure known as a clustered index. The primary key of the table functions as the routing key, and the full row data is stored in the leaf nodes. Secondary indexes are also implemented as B+ trees, but their leaf nodes store the primary key value rather than the row data, requiring a secondary lookup in the clustered index to retrieve the full record. InnoDB defaults to a 16-kilobyte page size, optimizing the B+ tree nodes for standard storage hardware [14].

SQLite, the most widely deployed database engine globally, stores an entire database within a single cross-platform file. The internal format of this file is a collection of B-trees. SQLite uses standard B-trees to store index data and B+ trees to store table data. SQLite does not use sibling links in its B-trees; it traverses the tree using a cursor that maintains a stack of parent pages [15].

File Systems

Modern operating systems rely on B-trees to manage the massive catalogs of files and directories on storage drives. Microsoft's NTFS (New Technology File System) uses B-trees to index directory entries, allowing the operating system to quickly locate a specific file within a folder containing millions of items [16].

In the Linux ecosystem, the ext4 file system uses a specialized B-tree variant called an Htree (hashed B-tree) for directory indexing, while the XFS file system uses B+ trees extensively for tracking free space, allocated blocks, and directory contents [17] [18]. Apple's APFS (Apple File System) similarly relies on B-trees to manage file metadata, snapshots, and directory structures across macOS and iOS devices [19].

Significance and Tradeoffs

The widespread use of the B-tree family stems from its balance of read and write performance on block-based storage. By minimizing disk I/O, maintaining strict balance, and supporting efficient range queries, the B+ tree provides a general-purpose solution that performs well under a wide variety of transactional workloads [20].[28]

However, the structure is not without tradeoffs. B-trees suffer from write amplification and random write latency when subjected to massive, high-velocity insertion workloads. When a new key is inserted, the database must read the corresponding leaf node from disk, modify it in memory, and write the entire block back to disk. If the insertions are random, this results in a continuous stream of random disk writes, which can overwhelm the storage hardware [21].

For applications that require extreme write throughput, such as time-series databases or event logging systems, the Log-Structured Merge-tree (LSM-tree) is often preferred. Formalized by Patrick O'Neil and colleagues in 1996, the LSM-tree buffers incoming writes in main memory and periodically flushes them to disk in large, sequential batches. This avoids the random write penalty of the B-tree. Systems like Apache Cassandra, RocksDB, and LevelDB utilize LSM-trees to achieve write speeds that B-trees cannot match [22].

The tradeoff for the LSM-tree's write performance is slower read performance and the CPU overhead required for background compaction operations. Because data is spread across multiple sequential files, searching an LSM-tree often requires checking multiple locations, whereas a B-tree guarantees a strict, bounded search path [23]. Consequently, while LSM-trees dominate specialized write-heavy domains, the B-tree and B+ tree remain the standard for general-purpose relational databases and file systems, providing a highly predictable, balanced approach to data storage and retrieval [24].

Sources (28)
  1. B-tree - Wikipedia
  2. B+ tree - Wikipedia
  3. Introduction to Algorithms (3rd ed.)
  4. Database System Concepts
  5. Database Management Systems
  6. The Evolution of Effective B-tree: Page Organization and Techniques
  7. Organization and Maintenance of Large Ordered Indexes
  8. The Ubiquitous B-Tree
  9. The Art of Computer Programming, Volume 3
  10. Efficient Locking for Concurrent Operations on B-Trees
  11. Prefix B-Trees
  12. Cache-oblivious string B-trees
  13. PostgreSQL Documentation: B-Tree Indexes
  14. MySQL 8.0 Reference Manual: InnoDB Indexes
  15. SQLite Database File Format
  16. NTFS Overview
  17. ext4 Filesystem Documentation
  18. XFS Filesystem Documentation
  19. Apple File System Reference
  20. Architecture of a Database System
  21. A Survey of B-Tree Logging and Recovery Techniques
  22. The Log-Structured Merge-Tree (LSM-Tree)
  23. Log-structured merge-tree - Wikipedia
  24. PostgreSQL Documentation: Index Types
  25. Michael J. Folk, Bill Zoellick, File Structures (Reading, Mass. : Addison-Wesley Publishing Company, 1987)
  26. François Bancilhon, David J. DeWitt, Proceedings 1988 VLDB Conference (Morgan Kaufmann, 1988)
  27. Andrew Binstock, John Rex, Practical Algorithms for Programmers (Addison-Wesley Professional, 1995)
  28. Seppo Sippu, Eljas Soisalon-Soininen, Transaction Processing (Springer, 2015)

Recommended reading