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.
| Layer | Crate | Responsibility |
|---|---|---|
| Client | nusadb-cli, drivers, nusadb-capi | Interactive shell and batch runner, drivers for eight languages, a C API. |
| Protocol | nusadb-wire | Frames, TLS 1.3 through rustls, SCRAM-SHA-256, extended query, COPY, notices. |
| SQL engine | nusadb-sql | Parser, analyzer, cost-based planner, vectorized executor on 1,024-row batches. |
| Transactions | nusadb-btree | Version stamps, read views, no-wait row locks, row-level serializable snapshot isolation, savepoints, two-phase commit. |
| Storage | nusadb-btree | Clustered B-link tables, B+tree indexes, the page cache, purge of dead versions, HNSW graphs. |
| Log | nusadb-wal | Frame codec with CRC32, lz4 and optional AES-256-GCM-SIV sealing. |
| Files | nusadb-server | The 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.
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.
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.
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
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.
| Trigger | When |
|---|---|
| Open | A database whose log is past a few megabytes is checkpointed when it opens. |
CHECKPOINT | On demand, from any session. |
| Background worker | Every --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
- Check the data format recorded in
btree.wal.format; refuse a newer one untouched and upgrade an older one. - Open
btree.wal.ckpt: read the header, the segment names, the page directory and the logical records. No page is read yet. - 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.
- First pass: collect the transactions with a commit marker in that prefix.
- Second pass: re-apply, in log order, only the operations of those transactions. An uncommitted tail needs no undo; its operations are never replayed.
- Take back the locks of prepared transactions, which wait for
COMMIT PREPAREDorROLLBACK 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.
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
| Path | What it is |
|---|---|
global/cluster.lock | Held exclusively by the running server; a second server on the same directory exits at once. |
global/databases | The list of databases in the cluster. |
global/format | Data format of the cluster catalog. |
base/<db>/btree.wal | The log since the last checkpoint. |
base/<db>/btree.wal.ckpt | The checkpoint image. |
base/<db>/btree.wal.pages/ | Immutable page segments the image names. |
base/<db>/btree.wal.spill | Changed pages pushed out of a full cache. Scratch; recovery never reads it. |
base/<db>/btree.wal.format | Data format and the release that last opened the database: format 2 plain, format 3 encrypted. |
base/<db>/btree.wal.key | The sealed data key, only for an encrypted database. |
base/<db>/btree.wal.lock | Held while the database is open. |
base/<db>/engine | Which 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.