NusaDB

Documentation / How it works

How NusaDB works

What happens to a row between the wire and the disk: the layers it passes, the page it lands in, the versions it leaves behind, the log record that makes it durable, and the checkpoint that folds the log away. Written for people who operate the server and want to predict what it does.

Layers

The engine is a stack of crates with one dependency direction: the storage side never imports the SQL side. They meet at the StorageEngine trait in nusadb-core. Rows cross it as opaque bytes, so the SQL layer owns their encoding, and transactions are named by id rather than by a borrowed handle, which keeps statements such as INSERT ... SELECT simple to express.

Fig. 5  Crates by layer
Clientnusadb-cli · 8 drivers · C API Protocolnusadb-wire · TLS 1.3 · SCRAM SQL enginenusadb-sql · parse, plan, execute StorageEngine trait (nusadb-core) Transactionsnusadb-btree · MVCC, SSI Storagenusadb-btree · B-link tree, cache Lognusadb-wal · CRC32, lz4, AEAD Filesbase/<db>/ · global/ query COMMIT · fsync · ok
Fig. 5Crate names as they appear in the source tree. Rows travel as opaque bytes across the trait; the SQL layer owns their encoding.
LayerCrateResponsibility
Clientnusadb-cli, drivers, nusadb-capiInteractive shell and batch runner, drivers for eight languages, a C API.
Protocolnusadb-wireFrames, TLS 1.3 through rustls, SCRAM-SHA-256, extended query, COPY, notices.
SQL enginenusadb-sqlParser, analyzer, cost-based planner, vectorized executor on 1,024-row batches.
Transactionsnusadb-btreeVersion stamps, read views, no-wait row locks, row-level serializable snapshot isolation, savepoints, two-phase commit.
Storagenusadb-btreeClustered B-link tables, B+tree indexes, the page cache, purge of dead versions, HNSW graphs.
Lognusadb-walFrame codec with CRC32, lz4 and optional AES-256-GCM-SIV sealing.
Filesnusadb-serverThe data directory: a cluster catalog and one directory per database.

Pages and the B-link tree

Every table is a clustered B-link tree keyed by a 64-bit row id that the engine assigns. Rows sit in the leaves, so a lookup by row id ends at the leaf that holds the row. Each node is one 8 KiB page and carries two extra fields: a right link to its sibling and a high key, the exclusive upper bound of the keys it may hold. A reader that reaches a node at or past its high key follows the right link. A split that is in progress, or that a crash interrupted, is therefore invisible to readers, and they never restart a descent.

Fig. 2  Leaf page, little-endianbyte offsets above the cells; widths not to scale
0191719 kindu8 right_linku64 page id high_keyu64, exclusive countu16 entry 0sorted by row_id entry 1 entry … free space one page = 8,192 bytes +0+8+10+18+26+34 row_idu64, engine-assigned lenu16 xmincreating txn xmaxdeleting txn, 0 = live undoprevious version tuple bytesencoded by the SQL layer version header, 24 bytes high bit of len set: overflow stub, header inline
Fig. 2A leaf entry is the newest version of one row. Its 24-byte header decides visibility. A row too large for a leaf keeps a stub whose first 24 bytes are that header, with the rest in a chain of overflow pages, so a visibility check never reads the chain. Interior pages hold fixed 16-byte separator and child pairs.

Interior pages hold fixed 16-byte pairs of separator and child page id, plus a rightmost child. A row too large for one leaf becomes an overflow stub: the leaf keeps the first 24 bytes of the value (the version header), the total length and the first page of a chain; the high bit of the entry's length marks the stub. The chain is written before the stub is published and freed only when no reader can still hold the stub, so a reader that takes no latch never sees a torn value. The largest row is 32 MiB.

Primary-key and secondary indexes are B+trees in pages as well, with a map from row to key. Only index entries larger than about 2 KB are kept in memory instead.

Versions and visibility

The newest version of a row is the leaf entry. Its 24-byte header holds xmin, the transaction that created it, xmax, the one that deleted it (0 while it is live), and the arena index of the previous version. An UPDATE moves the old header and tuple into the undo arena and installs the new version in the leaf. A DELETE stamps xmax in place.

Fig. 3  Two readers, one row
leaf, row 7 xmin42 xmax0 undoa19 qty=15 undo arena, slot a19 xmin17 xmax0 undonone qty=10 reader Bsees 42 committed reader Asnapshot before 42 purge frees a19 once no open snapshot can still need it; a long transaction holds it back
Fig. 3A plain SELECT takes no locks and never waits for a writer. Write conflicts do not wait either: a second writer on a locked row gets 40001 at once, so deadlocks cannot form.

A reader takes a read view when its snapshot begins. If it cannot see the creator of the leaf version, it walks the chain newest first and takes the first version whose creator it can see; that version's xmax decides whether the row is deleted for this reader. Because a rollback restores the previous leaf bytes, every version in a chain was written by a transaction that committed or is still running, and visibility needs only the view's set of active transactions. The background purge frees arena slots that no view can reach, which is why a transaction left open delays it.

Writers take row locks that never wait. A second writer on a locked row fails at once with 40001, so deadlocks cannot form, and SERIALIZABLE adds row-level tracking of read-write dependencies that fails a transaction whose result no serial order could produce. Transactions covers the retry loop this asks of an application.

The log

Each database has one append-only log, btree.wal, holding logical redo records: an insert, an update, a delete, a commit, a schema change, a sequence step, a prepared transaction. A row operation is keyed by tag, transaction, table and row id.

Fig. 4  Log framebtree.wal
081216 lsnu64, log position lenu32, body bytes crc32of lsn, len, body bodyone record: insert, update, delete, commit, DDL, sequence, prepare … covered by the crccovered by the crc plain kind u8 payloadstored as is up to 64 bytes, lz4 above that --encryption-key-file nonce12 bytes AES-256-GCM-SIV ciphertextof kind + payload; aad = lsn tag16 bytes
Fig. 4Compress, then encrypt, then checksum. With encryption on, a torn tail is still recognised without the key, and a frame whose CRC is intact but whose tag fails cannot come from a crash, so recovery refuses the log at that point instead of truncating it.

A change is applied to its page first and its record appended right after, under the same per-object latch, so per object the log order is the replay order. This is the reverse of classic write-ahead ordering, and it is safe for one reason: a table page reaches durable storage only through a checkpoint, which runs with no transaction active, so every change in it is already logged. Changed pages that leave memory under pressure go to a scratch file that recovery never reads.

Records are coalesced in a buffer. COMMIT appends its marker, writes the buffer and calls fsync; the commit returns after that, and that call is the durability point. A large transaction writes its buffer early when it fills, but nothing is durable before the commit's fsync.

Checkpoints and segments

Fig. 1  Write path of one database directory 2 transactions committed, checkpoint pending
btree.wal redo log, append-only page cache 8 KiB pages in memory btree.wal.pages/ immutable segments btree.wal.ckpt checkpoint image frame: lsn u64 · len u32 · crc32 · body lsnlencrcinsert lsn 1201 · txn 7 lsnlencrcinsert lsn 1202 · txn 7 lsnlencrccommit lsn 1203 · txn 7 lsnlencrcupdate lsn 1204 · txn 8 lsnlencrccommit lsn 1205 · txn 8 fsync: txn 7 durable fsync: txn 8 p0p2p6p9p11 changed since last checkpoint clean: may be evicted (clock) a full cache spills changed pages to btree.wal.spill; recovery never reads it …620069-…-full.seg every live page ….seg next .seg CHECKPOINT writes changed pages only; past 32 segments, or dead pages over 2 × live + 1024, it writes a -full one header segment names page → segment, slot, crc32 logical records covers lsn 1200 restart replays the log after this lsn
Fig. 1Records are buffered and written with the commit, whose fsync is the durability point. Changed pages stay in the page cache; table pages reach disk only through a checkpoint, which copies them into a new segment, publishes an image naming every live page, and truncates the log to zero bytes. On restart the engine opens the image, loads pages as queries touch them, and replays only the log written after it.

A checkpoint writes every page changed since the previous one into a new, immutable segment under btree.wal.pages/, then publishes a checkpoint image, btree.wal.ckpt, which names the segments, maps every live page to its segment, slot and CRC32, and records the log position it covers. Once the image is in place, the log is truncated. Pages that did not change keep their segment and slot, so a small change produces a small segment.

The next checkpoint rewrites every page into one -full segment when the image would name more than 32 segments, or when the segments still named would hold more than twice the live pages plus 1,024. Dead pages and open files stay bounded that way.

TriggerWhen
OpenA database whose log is past a few megabytes is checkpointed when it opens.
CHECKPOINTOn demand, from any session.
Background workerEvery --checkpoint-interval (5 s) it checks each log against --checkpoint-threshold-bytes (64 MiB).

A checkpoint needs an instant with no transaction active. When the worker has been refused three times in a row, it holds new transactions for at most --checkpoint-max-pause (2 s) so the running ones can finish. A transaction held open for longer, such as an idle client inside BEGIN, defeats the pause, and the log keeps growing until it ends.

Page cache, eviction and spill

Pages are loaded from the segments on first use, checked against the CRC32 in the image, and kept in a page cache bounded by --max-resident-bytes. When the cache is full, a clock hand evicts pages that have not changed since the last checkpoint. If none is left, changed pages are written to btree.wal.spill and read back from there when needed. Table scans read a batch at a time, so neither tables nor B-tree indexes have to fit in memory.

Three things stay in memory whatever the bound: index entries too large for an index page, notes for index entries an update moved and the purge has not removed yet, and HNSW graphs. When the first two reach the bound, the next insert or update fails with an out-of-memory error before it starts; DELETE, TRUNCATE, CREATE INDEX and the purge are never refused, so space can always be freed. See limits.

Query memory is separate. A sort, DISTINCT, grouping, set operation, window or hash join over --work-mem streams its overflow to the spill directory. On a host with a detected memory budget that directory defaults to <data-dir>/tmp.

Recovery

  1. Check the data format recorded in btree.wal.format; refuse a newer one untouched and upgrade an older one.
  2. Open btree.wal.ckpt: read the header, the segment names, the page directory and the logical records. No page is read yet.
  3. Read the log after the position the image covers. A torn or corrupt frame at the end ends the durable prefix, and the file is cut there before new records are appended.
  4. First pass: collect the transactions with a commit marker in that prefix.
  5. Second pass: re-apply, in log order, only the operations of those transactions. An uncommitted tail needs no undo; its operations are never replayed.
  6. Take back the locks of prepared transactions, which wait for COMMIT PREPARED or ROLLBACK PREPARED.

Pages are loaded as queries touch them afterwards, so restart time grows with the log written since the last checkpoint, not with the size of the data. A partial ROLLBACK TO SAVEPOINT inside a transaction that later committed is logged as compensating operations, so replay ends in the state after the rollback.

Encryption at rest

With --encryption-key-file, each database gets a random data key when it is created, stored sealed under the operator's master key in btree.wal.key. Every file that holds row values, names or keys is sealed with AES-256-GCM-SIV: log records, the image's page directory and records, page segments, the page spill file and the executor's spill files. Archives and backups carry a copy of the key envelope.

Each sealed string is nonce (12) | ciphertext | tag (16) and is bound to its place through the associated data: a log record to its position, a page to its id, slot and segment name. A record or page moved to another place fails its tag. Nonces are drawn from a random base plus a counter and stored, never derived from a position, so a position written twice still gets a fresh nonce.

Not protected

Memory (the cache, keys, core dumps), a key file kept on the data disk, metadata such as file names, sizes and database names, and the completeness of the log: someone who can write the files can cut its tail or put back an older complete copy. The wire is protected separately by TLS. Losing the master key loses the data.

A database is encrypted when it is created; there is no conversion in place. --encrypt-from DIR copies a stopped data directory into a new, encrypted one, and --rotate-encryption-key reseals the envelopes under a new master key. See configuration.

Files in a data directory

PathWhat it is
global/cluster.lockHeld exclusively by the running server; a second server on the same directory exits at once.
global/databasesThe list of databases in the cluster.
global/formatData format of the cluster catalog.
base/<db>/btree.walThe log since the last checkpoint.
base/<db>/btree.wal.ckptThe checkpoint image.
base/<db>/btree.wal.pages/Immutable page segments the image names.
base/<db>/btree.wal.spillChanged pages pushed out of a full cache. Scratch; recovery never reads it.
base/<db>/btree.wal.formatData format and the release that last opened the database: format 2 plain, format 3 encrypted.
base/<db>/btree.wal.keyThe sealed data key, only for an encrypted database.
base/<db>/btree.wal.lockHeld while the database is open.
base/<db>/engineWhich storage engine wrote the directory (btree).

A checkpoint image with the segments it names is a consistent copy of one database even while the server writes, which is what hard-link backups rely on. Keep the data directory on a local file system: on some network file systems the locks are not enforced across machines.

How it is tested

nusadb-sim implements the page-store, clock and random-number ports in memory, with fault injection for torn writes, failed fsync calls and power loss. The same engine code runs against the real disk in production and against these adapters in tests, driven by one seed, so a failing fault sequence can be replayed exactly. End-to-end behaviour is pinned by a SQLLogicTest corpus of 160 files in nusadb-e2e, alongside each crate's own tests.