Lately I’ve been working on NubSQL, an transactional database whose goal is to be as minimal as possible, for that I’ve been playing around with the concept of Copy On Write B+ trees, they’re just like regular B+ Trees but their nodes are immutable once written, I came across this a while ago when exploring LMDB’s architecture. 1
And the best thing about them is the core implementation is not so different than vanilla B+ trees and we can offload the whole “snapshot isolation” job to Pager(read buffer manager).
B+ Trees
A small refresher on B+ trees, there are branches and leafs, the actual data is stored in the leafs and branches help us search and route to keys, each leaf contains a pointer to the next key which is useful for row scans.

Coming back to NubSQL, some context: each Node in the tree has a unsigned 32bit id, and instead of pointers, the nodes uses NodeID for referencing each other in the tree, and we use the Pager to convert that NodeID to Node data, which gives Pager quite some creative freedom on what to return when the query engine asks it for data for some NodeID depending on context, for instance, we can make it return different node data for the same NodeID depending on which transaction is asking for it.
In NubSQL we skip keeping that pointer for next leaf (we’ll come back to why later). Some more context on what a tree looks like in NubSQL, each node in the tree can be one of three things:
pub const Node = union(enum) {
leaf: Leaf, // this actually stores the data
branch: Branch,
overflow: Overflow,
}
In our system, Leafs are just:
const Leaf = struct {
const MAX_INLINE_VAL_SIZE = 512;
const ValueType = union(enum) {
bytes: []u8,
blob: NodeID, // the head of overflow pages linked list
};
keys: std.ArrayList(u64) = .empty,
values: std.ArrayList(ValueType) = .empty,
}
We don’t keep large values inline inside the leaf, if some value is larger than 512 bytes, we put it inside a linked list of overflow pages (each storing 4kb of data each) and inside the leaf we just store the NodeID of head Overflow page.
a minimal sketch of overflow pages:
const Overflow = struct {
data: []u8,
next: ?u32 = null, // NodeID of next Overflow leaf
};
Branches don’t store actual data, they just store routing information so that queries can route to the correct leafs
const Branch = struct {
keys: std.ArrayList(u64) = .empty,
children: std.ArrayList(NodeID) = .empty,
};
Why use this over vanilla B+ Trees ?
Off the top of my mind:
-
snapshots are dirt cheap, we don’t need any coordination, a read only transaction can just get the latest database snapshot (which is published by the last comitted write txn).
-
minimal reader and writer txn interaction, since we never overwrite a page in place, we can avoid using row level latches.
-
no need for a WAL, if we crash before commit returns, the pager metadata is never updated, so the half written pages (which are unreachable since the txn never comitted) can just be overwritten.
Transactions
Each Transaction carries an context, A minimal version of that looks something like:
pub const TxnCtx = struct {
is_read_only: bool = true,
tx_start_page_allocator_state: u32 = 0, // we store this just for recovery in case of abort
page_map: std.AutoHashMapUnmanaged(u32, u32) = .empty, // PageID -> Txn Private PageID (only in case of mutated page)
};
Starting a Transaction
When we start a transaction, we:
pub fn start_txn(self: *TxnManager, allocator: Allocator, is_read_only: bool) !*BtreeVersionManager.DbSnapshotCtx {
var ctx: TxnCtx = .{ .is_read_only = is_read_only };
if (!is_read_only) {
// NubSQL is a single writer system!
self.write_txn_lock.lockUncancelable(self.io);
ctx.tx_start_page_allocator_state = self.pager.next_page_id;
}
errdefer {
if (!is_read_only) self.write_txn_lock.unlock(self.io);
}
// this is just a map(table_id,table_snapshot) and the Catalog
return self.btree_version_manager.get_latest_db_snapshot(allocator, ctx);
}

get_latest_db_snapshot() returns a read only snapshot of each table whose nodes still point into the same pages as the original version, and the moment a transaction has to mutate a page, it calls into the page to get a writeable version of it (along with the transaction context), after that point in time, every further access to that page (whether read or write) from that txn will return that new mutated page.

and inside the buffer manager we can just do some version of:
/// either return the txn private page or the normal page
pub fn read(self: *Pager, page_id: NodeID, txnCtx: *TxnCtx) ?PagerVal {
const resolved_id = txnCtx.page_map.get(page_id) orelse page_id;
...do some stuff to pull that page in buffer
self.map_lock.lockSharedUncancelable(self.io);
defer self.map_lock.unlockShared(self.io);
return self.map.get(resolved_id);
}
This way we can ensure snapshot isolation and that transactions don’t step on each other’s toes while they’re at it.
Write Amplification Is No Joke
It’s not all fun and games though, All this might look simple, but the drawback comes in the form of write amplification, any page you touch inside a transaction gets forked, and it gets worse in some cases when you mutate an overflow page, in that scenario, (at least)two new private pages are formed, one for the overflow page itself and other for leaf node which owns a reference to that overflow linked list.
This is the core reason why we skipped storing references to next leafs in leaf nodes, imagine appending a new row to a table, that makes the last leaf dirty, means that it would have to be forked, but since there its previous leaf node is also pointing to it, we’d have to update that node’s reference too, but doing that forks that node as well… and before we know it, we’re rewriting the whole tree just to append a single row. That’s just not acceptable, by skipping those inter leaf references, we can just update the path from dirty leaf to the root and that’s about it.
This creates a bunch of mess to clean up and shifts some complexity to commit time, since during commit, we have to swap ALL references of mutated PageIDs with the new PageIDs from the transaction context and deal with the reclamation of the (now)stale pages later (As some read transaction might be reading them). 2*
Commits
During commit time we ensure that we properly promote all private pages to regular pages in our private snapshot, ensure those things are disk, once those are Fsynce’d along with its metadata, we publish our in-memory snapshot for new readers to see.
pub fn commit_txn(self: *TxnManager, txn: *BtreeVersionManager.DbSnapshotCtx, allocator: std.mem.Allocator) !void {
const read_only = txn.ctx.is_read_only;
defer {
txn.on_txn_end(allocator); // txn ctx destructor
if (!read_only) self.write_txn_lock.unlock(self.io);
}
if (read_only) return;
errdefer self.pager.abort_txn(&txn.ctx) catch unreachable;
errdefer txn.latest_tables_snapshot.deinit(allocator);
// ordering is important here:
// 1. ensure new pages are on disk first
// 2. ensure on disk pager metadata is updated (we do that in the same flush_txn call)
// 3. then update things in-mem
// you mess the ordering and an crash at just the right moment renders you unrecoverable
var tables = txn.latest_tables_snapshot.valueIterator();
while (tables.next()) |snapshot| {
// for each dirty leaf, ensure its parent is forked
try self.make_dirty_leaf_paths_writable(&snapshot.tree, &txn.ctx);
}
// just swap regular pages with private pages in the snapshot
try self.make_dirty_leaf_paths_writable(&txn.latest_catalog_snapshot.tables_definitions, &txn.ctx);
try self.swap_page_ids(&txn.ctx);
try self.pager.commit_and_flush_txn_pages(&txn.ctx);
try self.btree_version_manager.update_latest_db_snapshot(txn); // publish our snapshot
}
Conclusion
Will be sharing more about the rest of interesting things in NubSQL, have to leave as the cafe is closing now.