Documentation / Configuration
Configuration
Every server flag, how authentication and roles fit together, memory limits and capacity, the container image, systemd, TLS, metrics, encryption at rest, checkpoints, backup, point-in-time recovery and standby.
NusaDB ships as a single server binary (nusadb-server) plus an interactive client (nusadb-cli). The server is configured entirely by command-line flags; there is no configuration file. All durable state is under --data-dir; Backup describes how to copy it while the server runs.
Server flags
| Flag | Default | Purpose |
|---|---|---|
--listen | 0.0.0.0:5678 | TCP listen address for the wire protocol. |
--data-dir | ./data | Durable data directory: the write-ahead log, checkpoint image and page segments of every database, under base/<name>/. Created if absent. One server at a time: a second server started on a directory in use exits at once, saying so. |
--auth-user USER:PASSWORD | none | Require SCRAM-SHA-256 for this user. Repeatable. Once any is set, every connection must authenticate; with none, the server trusts every client and logs a warning. |
NUSADB_USER + NUSADB_PASSWORD (environment) | none | The same as one --auth-user, for containers. Setting only one of the pair is a start-up error. |
--tls-cert / --tls-key | none | PEM certificate chain and private key; TLS is on when both are set, on the same port. |
--tls-client-ca | none | PEM CA for mutual TLS: every client must present a certificate signed by it. |
--max-connections | 25 | Cap on concurrent connections; excess connections wait for a slot. 0 is unlimited. |
--reject-excess-connections | off | Refuse a connection past the cap at once with SQLSTATE 53300 instead of queueing it, so a pool can back off. |
--idle-timeout | 0 | Close a connection idle this many seconds. 0 is no limit. |
--handshake-timeout | 60 | Drop a connection that has not finished the start-up and authentication exchange within this many seconds, so a stalled client cannot hold a slot. |
--statement-timeout | 0 | Cancel any statement running longer than this many seconds (57014). Sessions can lower it with SET statement_timeout. |
--drain-timeout | 30 | On Ctrl-C or SIGTERM (the signal docker stop and Kubernetes send), wait this long for in-flight connections to finish before aborting them, then exit cleanly. 0 waits indefinitely. |
--mem-budget | 0 | Total memory budget in bytes. 0 auto-detects on Linux as the smaller of host RAM and the cgroup limit, so a container limit is honoured; on other systems 0 means no budget. The budget derives the limits below. |
--max-resident-bytes | derived | Bound on each database's page cache. Past it, clean pages are evicted and changed pages spill to a scratch file; a row insert or update is refused, with an error naming the limit, only once what cannot leave memory reaches it. Derived from the memory budget (floor 256 MiB); unlimited when no budget is known. |
--work-mem | 0 | Per-query memory for one sort, aggregate or join stage. Past it a stage spills (with --spill-dir) or fails with an error naming the limit. 0 is unlimited unless a budget derives a value. |
--spill-dir | <data-dir>/tmp with a memory budget, otherwise none | Directory for transient spill files. Sorts, DISTINCT, DISTINCT ON, GROUP BY (grouping sets included), window functions, set operations and hash joins over --work-mem stream to it instead of failing. When a memory budget is known (detected on Linux, or --mem-budget), spilling is on by default into <data-dir>/tmp. Stale files from a crash are removed at start-up. |
--maintenance-work-mem | 0 | Bytes of index entries a CREATE INDEX buffers before flushing a sorted batch. 0 uses a built-in bound. |
--max-txn-write-bytes | 0 | Ceiling on the uncommitted writes one transaction may buffer; past it the transaction fails with XX000 instead of growing until the host kills the process. 0 derives 25% of the budget (floor 128 MiB). |
--copy-max-bytes | derived | Ceiling on one COPY ... FROM STDIN. Derived as about 20% of the budget, capped at 1 GiB; 0 is unbounded. |
--autoanalyze-interval | 60 | Seconds between sweeps of the background worker that re-analyzes tables whose statistics went stale. 0 disables it. |
--autoanalyze-scale / --autoanalyze-threshold | 0.1 / 50 | A table is re-analyzed once its writes since the last analyze exceed threshold + scale * rows. |
--checkpoint-threshold-bytes | 67108864 (64 MiB) | Log length past which the background checkpoint worker folds a database's log into a fresh image and truncates it. 0 disables the worker. |
--checkpoint-interval | 5 | Seconds between the checkpoint worker's checks of each database's log. 0 disables the worker. |
--checkpoint-max-pause | 2 | Once the log is past its threshold and three checks in a row found transactions active, hold new transactions for at most this many seconds (capped at 60) so the checkpoint can run. 0 never pauses. |
--wal-archive-dir | none | Archive every checkpoint's log segment and image under this directory, one subdirectory per database, for point-in-time recovery. |
--wal-archive-retain | 0 | Prune the archive hourly to what a restore to any moment in the last this many seconds needs (see Point-in-time recovery). 0 keeps everything. |
--backup-dir | none | Take a backup of every database into this directory on a schedule (see Scheduled backups). |
--backup-interval | 86400 | Seconds between scheduled backups; the first is taken one interval after start-up. |
--backup-keep | 7 | How many complete scheduled backups to keep; older ones are removed after each new one. |
--restore-database / --restore-to-time / --restore-to-lsn / --restore-live-log | none | Offline: rebuild one database from its archive as of a moment or a log position, then exit. See Point-in-time recovery. |
--max-prepared-transactions | 64 | How many prepared transactions (PREPARE TRANSACTION) may wait at once in each database; one more is refused with 53400. 0 disables two-phase commit (55000). A prepared transaction holds its locks and holds back version reclamation until it is finished, so the cap bounds what forgotten ones can pin. See two-phase commit. |
--standby-from | none | Serve as a read-only standby of the primary whose --wal-archive-dir root this is. Writes, CREATE DATABASE and DROP DATABASE are refused. See Standby. |
--standby-poll | 5 | Seconds between a standby's checks for new archived segments. |
--standby-max-pause | 2 | Seconds a standby may hold new transactions while the running ones end so a segment can be applied. |
--metrics-listen | none | Serve Prometheus metrics on this address, for example 127.0.0.1:9100. |
--encryption-key-file PATH | none | Encrypt every database at rest under the master key in this file (see Encryption at rest). The file must not be readable by others nor writable by group or others. |
NUSADB_ENCRYPTION_KEY_FILE / NUSADB_ENCRYPTION_KEY (environment) | none | The same as --encryption-key-file, or the key itself as 64 hex digits. Give the key in one place only. Prefer the file: a key in the environment stays readable for the life of the process to anyone who can read its environment. |
--generate-encryption-key PATH | none | Write a new random master key to PATH, readable by its owner only, and exit. An existing file is never overwritten. |
--rotate-encryption-key PATH | none | Offline: seal every database's data key under the key in PATH instead of the current one, in the data directory, --wal-archive-dir and --backup-dir, then exit. |
--encrypt-from DIR / --encrypt-from-key-file PATH | none | Offline: copy every database of the data directory DIR into --data-dir, encrypted, then exit. --encrypt-from-key-file names the master key of DIR when it is itself encrypted. |
--storage-engine | btree | The only value. A data directory written by the removed lsm engine is refused with a migration hint. |
RUST_LOG sets log verbosity (tracing filter syntax, for example RUST_LOG=info or RUST_LOG=nusadb_wire=debug). NUSADB_DISABLE_SIMD=1 forces the portable executor path on a host where the AVX2 path is suspect; results are identical either way. On a CPU without AVX2 the fallback is automatic.
Set at least one --auth-user (or the environment pair); terminate TLS with --tls-cert / --tls-key; keep --data-dir on a persistent, backed-up volume; keep the metrics port private; and read Memory limits and capacity before loading a large dataset.
Authentication and users
Authentication and authorization are two separate lists.
- Who may connect is the
--auth-userlist (orNUSADB_USER/NUSADB_PASSWORD). Each entry is a user name and a password verified with SCRAM-SHA-256; the password never crosses the wire. A wrong password and an unknown user return the sameauthentication failed, so the error does not reveal which names exist. Changing a password means restarting the server with the new--auth-uservalue. - What a connected user may do is decided by SQL roles and grants inside each database. Create a role with the same name as the
--auth-userentry and grant it what it needs;PASSWORDinCREATE ROLEis refused because it would never be checked. A user with no matching role can create its own tables and read nothing else.
nusadb-server --data-dir /var/lib/nusadb \ --auth-user nusadb-root:ROOT_SECRET \ --auth-user app:APP_SECRET
-- as nusadb-root CREATE ROLE app LOGIN; GRANT SELECT, INSERT, UPDATE, DELETE ON orders TO app;
NUSADB_PASSWORD=APP_SECRET nusadb-cli --user app
nusadb-root is the bootstrap superuser and bypasses every grant; list it in --auth-user with a strong password, since with authentication on it cannot connect otherwise. Without any --auth-user the server runs trust-on-startup: any name is accepted with no password, and the start-up log prints a warning.
Memory limits and capacity
The default limits suit a host with about 2 GB of RAM and one or two cores. On a larger machine, raise them with the flags below.
Table data: a page cache over the checkpoint image
Table pages live in a page cache backed by the last checkpoint image. The image (btree.wal.ckpt) names every page of the database and where it lies in the page segments of the pages directory beside it (btree.wal.pages/). A page is read from there on first use, so a restart does not load the whole database before serving, and a page that has not changed since the last checkpoint (a clean page) can leave the cache again when memory is needed.
A page changed since the last checkpoint (a dirty page) is not in the image yet. When the cache holds nothing clean to evict, a dirty page is written to a scratch file beside the log (btree.wal.spill) and leaves memory; it is read back from there when needed. The scratch file is not a durable copy: recovery never reads it, and it is emptied at open (on Linux and macOS it is unlinked as soon as it is created, so it does not appear in the directory). The write-ahead log and the image remain the only durable copies of the data, and the next checkpoint writes every changed page into the new image and empties the scratch file.
--max-resident-bytes (derived from the memory budget when unset) bounds the cache. Clean pages are evicted first, then dirty pages spill, so the pages changed between checkpoints are bounded by disk rather than memory. The scratch file grows to at most the pages changed since the last checkpoint, which the checkpoint threshold keeps in proportion to the log. What still counts against the bound is the few index entries too large for an index page, and notes of index entries awaiting purge (see below). Once they reach it, the next insert or update is refused before it starts (a write already under way always completes) with an error that names the limit and the bytes held:
ERROR XX000: out of memory: the engine reached its resident-memory limit of 858993440 bytes (859001088 bytes held by index entries); free rows (DELETE/TRUNCATE), drop indexes that are not needed, raise the limit, or use a larger host
Reads keep working at the bound: a page loaded for a read may briefly overshoot it and is the first to leave again. If the scratch file cannot be written (a full disk), the page stays in memory and the cache grows past the bound until the next checkpoint instead of failing the write. DELETE, TRUNCATE, CREATE INDEX and the background purge are not refused at the bound, so space can always be freed; a large DELETE is still capped per transaction by --max-txn-write-bytes.
A table scan reads the table a batch of rows at a time rather than loading it whole, so a full scan of a table larger than memory stays within the cache. A scan still open when its transaction commits or rolls back (a cursor left open) is read to its end at that moment.
B-tree index entries, the primary key's included, live in pages too: each index is a tree of pages ordered by key, plus a map from row to key, both in the page cache and carried by the image like table pages, so a restart does not rebuild them. An entry too large for an index page (a key of roughly 2 KB or more) is kept in memory instead, carried by the image as a record, and counts against the bound. So does a small note per index entry an UPDATE moved to a new key, kept until the background purge removes the old entry; a long-running transaction delays that purge, so heavy key-changing updates under one can grow it. Vector indexes (USING hnsw) are held in memory whatever the bound, and reloaded from their saved graphs at open.
A checkpoint writes only the pages changed since the one before it, into a new segment, and a new image that names the older segments for every other page. Its cost grows with the changes, plus the image's directory of pages (20 bytes per page). Once the segments an image still names would hold more than twice the live pages (plus a fixed slack of 1024 pages), or more than 32 segments, the checkpoint writes every page afresh into one segment instead, so dead pages on disk stay bounded.
Deleting rows frees pages for reuse and lowers the count the next image carries; page memory within a running process is recycled through the cache rather than returned to the operating system.
Row size
A row is stored inline in its 8 KB B-tree leaf while it fits (about 8 KB encoded); a larger row is spread over a chain of overflow pages and the leaf keeps a small stub, so a large text, json, bytea or array value is stored whole. Reading such a row reassembles it from its chain, which costs one page read per 8 KB of the value. A row's encoded size is capped at 32 MiB; a larger one is refused with an error naming both sizes, never truncated:
ERROR XX000: tuple of 40000000 bytes exceeds the maximum row size of 33554432 bytesOverflow pages count toward the resident-memory bound like any other page.
One query, one transaction, one load
The other three limits bound what a single client can do to the server:
| Limit | Flag | Past it |
|---|---|---|
| one executor stage (sort, aggregate, join) | --work-mem | spills to --spill-dir for sorts, DISTINCT, DISTINCT ON, GROUP BY (grouping sets included), window functions, set operations and hash joins; otherwise fails with a message naming the limit and the flag |
| one transaction's uncommitted writes | --max-txn-write-bytes | the transaction fails with XX000 |
one COPY ... FROM STDIN | --copy-max-bytes | the load is aborted; split it or raise the flag |
A spilled sort, DISTINCT or GROUP BY streams its result to the client from the merge of its spill files, so a result larger than --work-mem is fine. Window functions spill per partition; the frames that still have to fit the budget are listed under query memory. A query that fails at the budget leaves the server responsive. A session's SET work_mem moves both the budget and the point where spilling starts.
On Linux all of these derive from --mem-budget, which auto-detects the host or container limit, so a container with a memory limit gets sensible ceilings with no flags. On other systems set --mem-budget (or the individual flags) explicitly; without it the derived limits are unlimited.
CPU compatibility
The executor uses AVX2 where the CPU has it and falls back to a portable path otherwise (older x86 processors, some virtual machines, ARM). Results are the same on both paths; only throughput differs.
Running the container image
The image on Docker Hub, nusadb/nusadb, carries both nusadb-server and nusadb-cli. Use latest or pin a version tag such as 0.1.0-beta.16. The image is published for linux/amd64 and linux/arm64 under the same tag, so Docker pulls the right one for the host. The durable state lives in /var/lib/nusadb; mount a volume there, or the data is lost when the container is removed.
docker run -d --name nusadb \ -p 5678:5678 \ -v nusadb-data:/var/lib/nusadb \ -e NUSADB_USER=app \ -e NUSADB_PASSWORD=change-me \ -e RUST_LOG=info \ nusadb/nusadb:latest
- Server flags go after the image name and replace the default
--listen 0.0.0.0:5678 --data-dir /var/lib/nusadb, so repeat those two when you add others:... nusadb/nusadb:latest --listen 0.0.0.0:5678 --data-dir /var/lib/nusadb --metrics-listen 0.0.0.0:9100. .sqlfiles mounted into/docker-entrypoint-initdb.drun once, in name order, on the first start against an empty data directory: the place forCREATE ROLE,GRANTand schema.- The container honours its memory limit (
--memory=2g) through the auto-detected budget. - Connect from inside:
docker exec -it nusadb nusadb-cli --user app. The password is read fromNUSADB_PASSWORD, which the container already has. - The image exposes
5678and9100; publish9100only on a private interface. - For encryption at rest, mount the key file read-only outside the data volume and point
NUSADB_ENCRYPTION_KEY_FILEat it. The server reads the variable itself, so the first-start initialisation runs encrypted too. The server in the container runs as uid 10001 (group 10001), and the key file it sees must be readable by that user and not readable by others: owned by uid 10001 with mode600, or owned by root with group 10001 and mode640. A bind mount keeps the host file's owner and mode, so set them on the host.
sudo mkdir -p /etc/nusadb sudo nusadb-server --generate-encryption-key /etc/nusadb/master.key # created with mode 600 sudo chown 10001:10001 /etc/nusadb/master.key # the container's server user docker run -d --name nusadb -p 5678:5678 \ -v nusadb-data:/var/lib/nusadb \ -v /etc/nusadb/master.key:/run/secrets/nusadb_master_key:ro \ -e NUSADB_ENCRYPTION_KEY_FILE=/run/secrets/nusadb_master_key \ -e NUSADB_USER=app -e NUSADB_PASSWORD=change-me \ nusadb/nusadb:latest
docker run -d --name nusadb \ -p 5678:5678 \ -v nusadb-data:/var/lib/nusadb \ -v ./init:/docker-entrypoint-initdb.d:ro \ -e NUSADB_USER=nusadb-root \ -e NUSADB_PASSWORD=change-me \ --memory=2g \ nusadb/nusadb:latest
Running on a Linux VM with systemd
1. Get the binary
Build from source on the VM (the toolchain pinned in rust-toolchain.toml is installed by rustup automatically), or download a release tarball for your platform when one is published for the version you want.
cargo build --release --locked -p nusadb-server -p nusadb-cli sudo install -m 0755 target/release/nusadb-server /usr/local/bin/ sudo install -m 0755 target/release/nusadb-cli /usr/local/bin/
2. Create a service user and data directory
sudo useradd --system --no-create-home --shell /usr/sbin/nologin nusadb
sudo mkdir -p /var/lib/nusadb /etc/nusadb
sudo chown -R nusadb:nusadb /var/lib/nusadb
# Place server.crt / server.key under /etc/nusadb (root-owned, readable by nusadb).
sudo chown root:nusadb /etc/nusadb/server.* && sudo chmod 0640 /etc/nusadb/server.*Put the credentials in an environment file readable only by root rather than in the unit:
sudo tee /etc/nusadb/nusadb.env >/dev/null <<'EOF' NUSADB_USER=nusadb-root NUSADB_PASSWORD=STRONG_PASSWORD RUST_LOG=info EOF sudo chmod 0600 /etc/nusadb/nusadb.env
3. systemd unit
Create /etc/systemd/system/nusadb.service:
[Unit] Description=NusaDB server After=network-online.target Wants=network-online.target [Service] Type=simple User=nusadb Group=nusadb EnvironmentFile=/etc/nusadb/nusadb.env ExecStart=/usr/local/bin/nusadb-server \ --listen 0.0.0.0:5678 \ --data-dir /var/lib/nusadb \ --tls-cert /etc/nusadb/server.crt \ --tls-key /etc/nusadb/server.key \ --spill-dir /var/lib/nusadb/spill \ --metrics-listen 127.0.0.1:9100 \ --max-connections 100 Restart=on-failure RestartSec=2 # The server only needs its data directory writable. NoNewPrivileges=true ProtectSystem=strict ProtectHome=true PrivateTmp=true ReadWritePaths=/var/lib/nusadb [Install] WantedBy=multi-user.target
4. Start and verify
sudo systemctl daemon-reload
sudo systemctl enable --now nusadb
sudo systemctl status nusadb
journalctl -u nusadb -f # follow logs
# From a client host, after opening the VM firewall to 5678:
NUSADB_PASSWORD=STRONG_PASSWORD nusadb-cli --host VM_HOST:5678 --user nusadb-root \
--tls --tls-ca /path/to/ca.crt5. Firewall
Expose the wire port to your clients; keep metrics on localhost.
sudo ufw allow 5678/tcp
TLS
TLS runs on the same port: when --tls-cert and --tls-key are set the server offers TLS and a plaintext client is refused. No system trust store is consulted, so a client names the certificate to trust:
nusadb-cli --host db.internal:5678 --user app --tls --tls-ca /etc/nusadb/ca.crt nusadb-cli --host 10.0.0.5:5678 --tls --tls-ca ca.crt --tls-domain db.internal # name to verify
A certificate generated with the common one-line self-signed command is marked as a certificate authority, and is rejected when presented as a server certificate. Create a small private CA and sign a server certificate with it, or generate a leaf certificate that is not marked as a CA. Host-name verification is applied and a mismatch reports which names the certificate covers.
For mutual TLS add --tls-client-ca; every client must then present a certificate signed by that CA, in addition to SCRAM authentication.
Metrics
With --metrics-listen set, the server answers Prometheus scrapes in the text exposition format. The endpoint is unauthenticated, so bind it to a private address.
| Metric | Type | Meaning |
|---|---|---|
nusadb_connections_total | counter | connections accepted since start |
nusadb_connections_active | gauge | connections currently open |
nusadb_queries_total | counter | statements executed |
nusadb_query_errors_total | counter | statements that returned an error |
nusadb_database_stopped{database="..."} | gauge | 1 once that database has stopped after a storage error, 0 while it serves; listed for each database opened since start |
nusadb_backup_last_success_timestamp_seconds | gauge | when the last scheduled backup completed (0 before the first) |
nusadb_backup_last_duration_seconds | gauge | how long the last completed backup took |
nusadb_backup_failures_total | counter | scheduled backups that failed |
nusadb_archive_prune_failures_total | counter | archive prunes that failed |
With scheduled backups on, alert when time() - nusadb_backup_last_success_timestamp_seconds exceeds about twice --backup-interval. Alert on nusadb_database_stopped == 1: a stopped database refuses every statement until the server restarts. The other metrics show whether the server is up and busy. There are no duration histograms, per-database query counters, other storage metrics or serialization-conflict counter yet, so count 40001 retries in the application.
Encryption at rest
Encryption at rest is off unless a key is given. With --encryption-key-file, everything the server writes that holds row values, names or keys is encrypted with AES-256-GCM-SIV: each database's log, checkpoint image and page segments, the scratch file for changed pages under --max-resident-bytes, the spill files of large sorts and joins, and every copy of them (the --wal-archive-dir archive, --backup-dir backups, a standby's copy). Encrypted data is also authenticated: a page or log record that was altered, moved to another place, or written under another key is refused, never read as data.
Keys
The key file holds the master key, 32 random bytes as 64 hex digits. Generate one:
nusadb-server --generate-encryption-key /etc/nusadb/master.key
It is created with mode 600 and its fingerprint is printed. The server refuses a key file that others can read or that group or others can write (640 is accepted, to let a service group read it). Keep a copy of the key somewhere safe and apart from the data: without it the data cannot be read by anyone, and there is no recovery path.
The master key never touches the data directory. Each database gets its own random data key when it is created; that key encrypts the database's files and is stored beside them, sealed under the master key, in base/<db>/btree.wal.key. The archive and every backup carry a copy of it (<archive>/<db>/key, <backup>/base/<db>/btree.wal.key), so they open with the same master key.
Starting an encrypted server
Encryption is a property of the whole data directory and is decided when a database is created:
nusadb-server --data-dir /var/lib/nusadb --encryption-key-file /etc/nusadb/master.key
A fresh data directory starts encrypted, and every database created later is encrypted. At start-up the server checks every database against the key before it reads or writes anything, and refuses to start, naming the database, when
- a database is encrypted and no key was given, or the key is not the one it was encrypted with (the message shows the fingerprint of the key given);
- a key was given and a database holds data that is not encrypted (it would stay readable on disk while the server claims encryption);
- a key file (
btree.wal.key) lies beside data that is not encrypted, for example one copied in from another database: it does not belong there, and the database opens again once it is removed; - a database is an
--encrypt-fromcopy that never finished (it has abtree.wal.incompletefile): run the copy again.
Nothing in the data directory changes on a refused start. A database directory that lost its btree.wal.key cannot be opened at all; restore the file from a backup.
Encrypting an existing data directory
An unencrypted database is never converted in place. Copy it into a new data directory instead, with no server running on the old one:
nusadb-server --data-dir /var/lib/nusadb-encrypted --encryption-key-file /etc/nusadb/master.key \ --encrypt-from /var/lib/nusadb
Every database of the old directory is opened (recovering it), checkpointed, and written into the new directory with its pages and records encrypted; the command then exits. The old directory keeps working unencrypted, so it can be checked against the new one before it is removed. Start the server on the new directory, start a new --wal-archive-dir (the old archive is unencrypted and is refused), take a fresh backup, and then destroy the old directory, its archive and its backups: they hold the data in the clear.
The target must be new: its catalog may name no database the source does not have, and each directory under base/ must be empty (a server started once on a new directory leaves an empty lock file there, which is accepted). Anything else is refused with nothing changed. The command keeps a journal in the target, global/encrypt-copy, naming the source, a check value of the key (never the key itself) and each database it is about to create, and marks each database with a btree.wal.incomplete file until it is written. When the copy completes, the journal is removed and the command exits with success.
A server started on a directory where a copy stopped part way refuses to start and names these files. Run the same command again, with the same source path and the same key: it copies every database again from the start, since the source may have changed in the meantime, and removes from the target a database it created that the source no longer has. It never removes anything it did not create, nor a directory holding files that are not a database's: it stops instead, names them, and keeps its journal, so the command can be run again once they are moved out. A rerun from another source path or under another key is refused, as is a run into a directory holding a finished copy. Do not edit global/encrypt-copy: every database it lists as created is treated as the copy's own, and a rerun may remove it.
Links are refused rather than followed: a database directory under base/ that is a link, a base/ or global/ that is one, and a link at one of a database's file names. Nothing else may change the target while the command runs; a link put there during the run is outside what it guards against. The same command with --encrypt-from-key-file OLD_KEY copies an encrypted directory under new data keys.
Rotating the master key
With the server stopped:
nusadb-server --generate-encryption-key /etc/nusadb/master-2.key nusadb-server --data-dir /var/lib/nusadb --wal-archive-dir /srv/nusadb-archive \ --backup-dir /srv/nusadb-backups \ --encryption-key-file /etc/nusadb/master.key --rotate-encryption-key /etc/nusadb/master-2.key
It seals each data key found in the data directory, the archive and the backups under the new master key, replacing each key file atomically, and reports how many it changed. The data is not rewritten, so it takes milliseconds. If it stops part way, run it again with the same two keys: it finishes the rest. Then start the server with the new key. Copies kept elsewhere (an off-site backup) still need the old key; keep it until they age out. Rotating the master key does not change the data keys; to replace those, copy the data directory with --encrypt-from and --encrypt-from-key-file.
Backups, restore and standby
Copy btree.wal.key together with the image and its segments (see Backup); scheduled backups and the archive include it. --restore-database and --standby-from need the same --encryption-key-file as the primary. An encrypted archive is refused without the key, and an unencrypted archive is refused with one.
Cost
Each page read from disk and each log record is decrypted and checked, and each written is encrypted: a sealed page takes 8,220 bytes on disk instead of 8,192, a log record 28 more bytes. Pages in the cache are held decrypted, so a query over cached data costs the same.
The spill files of large sorts and joins are sealed under a key drawn when the server starts and never written anywhere, so a spill file left by a crash cannot be read by anyone.
Checkpoints, backup and restore
The write-ahead log is the durable copy of the data. A checkpoint folds the state into an image file beside the log and truncates the log, so the data directory holds live data plus the write history since the last checkpoint, and recovery replays only that tail. A checkpoint is taken automatically when a database is opened with a log past a few megabytes.
While the server runs, a background worker per database checks the log every --checkpoint-interval seconds and, once it is longer than --checkpoint-threshold-bytes (64 MiB by default), takes the same checkpoint CHECKPOINT would. That checkpoint needs a moment with no transaction active. With a single writer or a bursty load such moments are frequent and the worker waits for one. Under continuously overlapping transactions from many connections they can be rare, so after three consecutive refusals the worker makes one: it holds new transactions for at most --checkpoint-max-pause seconds (2 by default), lets the running ones end, checkpoints, and resumes. Clients see a short wait on their next BEGIN or autocommit statement, never an error.
A transaction held open longer than the pause budget, such as an idle client inside BEGIN, defeats the pause: the worker logs a warning with the active count, doubles the number of busy checks it waits before pausing again (up to about sixteen minutes between attempts), and the log keeps growing until that transaction ends. The pause is capped at 60 seconds. A prepared transaction (see two-phase commit) does not count as running here: it may wait on its coordinator indefinitely, so the checkpoint carries it into the new image instead of waiting for it, and the log is truncated as usual. Each checkpoint writes the pages changed since the last one and the image's page directory while the engine is paused, and now and then every page (see the page cache section above); on a large database, raise the threshold so the pause is paid less often. Watch the server log at info for runtime checkpoint folded the log and at debug for the busy retries.
Set either flag to 0 to turn the worker off and instead issue CHECKPOINT from a cron job over an otherwise idle connection:
NUSADB_PASSWORD=... nusadb-cli --user nusadb-root -c "CHECKPOINT"
It requires a quiesced engine: it refuses, naming how many transactions are still active, while any transaction is open, including one on the connection issuing it. Run it from a connection in autocommit at a quiet moment; a load with continuously overlapping transactions may need a retry.
When a storage error interrupts a change
If reading or writing a page fails while a row, an index entry, a rollback or the background purge is changing it (a damaged page on disk, an unreadable page of the scratch file), or the log cannot take the records a ROLLBACK TO SAVEPOINT must write (a full disk), the database stops. From then on every statement against it, new transactions included, fails with:
ERROR XX000: i/o error: nusadb-btree: the database stopped after a storage error interrupted a change (<the error>); restart it to recover from its log
The server log holds the same error at ERROR. Memory may then disagree with the log, so the stopped database never checkpoints: its image stays exactly as the last good checkpoint left it. Other databases on the same server keep running. Fix the cause (check the disk, restore the damaged files from a backup), then restart the server: the database is rebuilt from its last image and its log, with every committed transaction and nothing of the interrupted one.
An error while a statement only reads a page fails that statement alone and stops nothing. The background purge, though, walks every table and changes rows as it goes, so a damaged page it meets stops the database within one purge interval even if no statement touches that page.
One server per data directory
A running server holds an exclusive lock on global/cluster.lock, and each open database one on base/<db>/btree.wal.lock (on a data directory of the older single-database layout, nusadb.wal.lock at its root). A second server started on the same directory exits at once with a message naming the lock; a restore or a standby seed into a database that is open is refused, and so is DROP DATABASE of a database another process has open.
The operating system releases the locks when the holder ends, even when it is killed, so there is never a stale lock to remove by hand. The lock files themselves stay; they are empty and harmless. Keep the data directory on a local file system: on some network file systems these locks are not enforced across machines.
Backup
A checkpoint image together with the page segments it names is a complete copy of one database as of its checkpoint. The engine only ever replaces the image by an atomic rename and never rewrites a segment, so a copy of both is a consistent point-in-time backup even while the server keeps writing. Take the image first, then the pages directory.
The segments of an image stay on disk until the checkpoint after the one that replaces it (a restart removes them sooner: at open only the published image's segments are kept), so the safe way is a hard-link snapshot on the same file system, which takes milliseconds, and then a copy of the snapshot wherever it should go. Per database:
NUSADB_PASSWORD=... nusadb-cli --user nusadb-root -d shop -c "CHECKPOINT"
snap=/data/snapshots/shop-$(date +%F) # on the same file system as $DATA_DIR
mkdir -p "$snap/btree.wal.pages"
ln "$DATA_DIR/base/shop/btree.wal.format" "$snap/btree.wal.format"
# an encrypted database: its data key, sealed under the master key
[ -e "$DATA_DIR/base/shop/btree.wal.key" ] && ln "$DATA_DIR/base/shop/btree.wal.key" "$snap/btree.wal.key"
ln "$DATA_DIR/base/shop/btree.wal.ckpt" "$snap/btree.wal.ckpt"
ln "$DATA_DIR/base/shop/btree.wal.pages/"*.seg "$snap/btree.wal.pages/"
cp -r "$snap" /backups/ # then copy it anywhereA copy that misses a segment its image names is refused when opened, naming the segment, never read with pages missing. btree.wal.format records the data format the copy is in (see Upgrades), so a release too old for it refuses it instead of misreading it; the server writes it the first time it opens a database. The backup holds every transaction committed before the CHECKPOINT; what commits afterwards is in the log tail only. The background checkpoint worker refreshes the image on its own as the log grows, so a copy taken without an explicit CHECKPOINT is still consistent, just older.
Restore
The database must be registered in the cluster (it is, if it was created there; in a fresh data directory run CREATE DATABASE shop first), and its directory must hold no log (btree.wal). With the server stopped, remove that database's log if one exists, place the copy, and start the server. It opens the image with an empty log tail.
rm -rf "$DATA_DIR/base/shop/btree.wal" "$DATA_DIR/base/shop/btree.wal.ckpt" \
"$DATA_DIR/base/shop/btree.wal.pages" "$DATA_DIR/base/shop/btree.wal.format" \
"$DATA_DIR/base/shop/btree.wal.key"
cp -r /backups/shop-2026-09-26/btree.wal.pages "$DATA_DIR/base/shop/"
cp /backups/shop-2026-09-26/btree.wal.ckpt "$DATA_DIR/base/shop/btree.wal.ckpt"
cp /backups/shop-2026-09-26/btree.wal.format "$DATA_DIR/base/shop/btree.wal.format"
# an encrypted database: copy its key file too, and start with the same --encryption-key-file
[ -e /backups/shop-2026-09-26/btree.wal.key ] && \
cp /backups/shop-2026-09-26/btree.wal.key "$DATA_DIR/base/shop/btree.wal.key"
nusadb-server --data-dir "$DATA_DIR"A btree.wal left in place would be replayed on top of the image, and the database would not match the backup. For a whole-cluster copy with the server stopped, archive the --data-dir tree and extract it in place. Logical export with COPY table TO STDOUT and reload with COPY table FROM STDIN remains available.
Scheduled backups
With --backup-dir DIR, the server backs up every database every --backup-interval seconds and keeps the newest --backup-keep. Each backup is a directory named for its moment in UTC, laid out like a data directory: a BACKUP manifest (release, moment, and per database its log position and image time), the cluster's global/databases and global/format, and for each database its checkpoint image, the page segments it reads from and its format file under base/<db>/, plus, for an encrypted database, its sealed data key btree.wal.key.
For each database the server first takes a checkpoint, holding new transactions for at most --checkpoint-max-pause seconds so the running ones end, and then copies the image it just published, so the backup holds everything committed up to that moment; if a transaction stays open past the pause, it copies the last image instead and the log says how old it is. Taking a backup does not stop the server or block queries: page segments are hard-linked where DIR is on the same file system as the data directory and copied otherwise, and a checkpoint that runs meanwhile leaves the segments being copied in place. Databases are copied one after another, so each is consistent on its own.
A backup is built under DIR/.partial-<moment>, made durable, and renamed to its final name only once complete, so a directory with a moment name always holds a whole backup; a failed backup leaves nothing behind and is tried again at the next interval. A backup opens every database it copies, and DROP DATABASE of a database being copied reports it is in use if the copy does not finish in time. To restore, stop the server and copy the backup into an empty data directory:
cp -a "$BACKUP_DIR/20261007T020000Z" /data/nusadb-restored rm /data/nusadb-restored/BACKUP nusadb-server --data-dir /data/nusadb-restored
A backup holds what was committed when it was taken; with --wal-archive-dir as well, a point-in-time restore reaches any later moment the archive covers.
Point-in-time recovery
With --wal-archive-dir DIR, every checkpoint keeps two files under DIR/<database>/ before it truncates the log: <lsn>.log, the log segment it folded (every record up to log position <lsn>), and <lsn>.ckpt, the image it published, with the page segments that image names under DIR/<database>/pages/ and their names, one per line, in <lsn>.segments. Files are linked rather than copied where the file system allows. The archive therefore holds a base image plus an unbroken chain of log segments, and every commit record carries the moment it committed.
With --wal-archive-retain SECONDS, the server prunes the archive at start-up and then every hour to what a restore to any moment in that window needs: for each database it keeps the newest image archived before the window and everything after it, and removes the older images, the log segments that image covers, the page segments no segment list names, the superseded-* histories set aside before the window, and the archives of databases dropped before it. A standby following the archive must stay within the window: if it has not applied a segment that is pruned, it stops and has to be seeded again.
Without the flag the archive keeps everything. To prune by hand, remove old images (with their .segments lists) and the log segments before them once you no longer need to restore that far back; keep the newest image and everything after it. Then remove a page segment only when no .segments list left in DIR/<database>/ names it:
set -e cd /archive/shop ls pages/*.seg > /tmp/segments # list the segments first, ls ./*.segments > /dev/null # (stop if there is no list at all) cat ./*.segments | sort -u > /tmp/keep # then read the lists while read -r f; do grep -qxF "$(basename "$f" .seg)" /tmp/keep || rm "$f" done < /tmp/segments
The order matters while the server runs: an image's list is written before any segment it names reaches pages/, so a segment present when the listing was taken is already named by a list read after it.
To restore, stop the server if the target database is live, make sure its directory holds no log or image (a fresh CREATE DATABASE, or remove btree.wal, btree.wal.ckpt and btree.wal.pages from base/<db>/), and run the server in restore mode:
nusadb-server --data-dir "$DATA_DIR" --wal-archive-dir /archive \ --restore-database shop --restore-to-time 2026-09-26T10:30:00Z
The moment is RFC 3339 in UTC or milliseconds since the Unix epoch; --restore-to-lsn N restores to a log position instead. Every commit at or before the target is kept, in commit order: the first commit stamped later ends the replay, and a transaction without its commit inside that prefix never happened. The result is sealed into a fresh image in the database directory; start the server normally to serve it.
The archive ends at the last checkpoint. To restore to a moment after it, pass the database's current log as well (--restore-live-log "$DATA_DIR/base/shop/btree.wal", copied from the source first); the tail of that file is replayed after the archived segments. Issuing CHECKPOINT before taking a copy of the archive gives it the freshest point.
The segments must join up: if one in the middle was pruned or is corrupt, the restore refuses rather than replay across it, and so does a chain that ends before an image that proves the history went on. A target log position the archive never reaches is refused too; a target moment past the end of the archive succeeds with everything the archive holds, and the log says where the history actually ended.
A restore also forks the archive at its target. The segments and images after that point (including the segment that spans it) move into a superseded-<moment>/ directory under the archive, and the sealed image takes their place, so serving the restored database with the same archive continues one consistent history. A later restore into the part that was cut is refused, and so are points between the last image before the cut and the cut itself; issue CHECKPOINT before a restore whose target lies far behind the last checkpoint if you may want the moments just before it later. An interrupted restore leaves nothing that could be served and no half-forked archive; run it again and it lands on the same state. Every fork is recorded in the archive's forks file.
An archive belongs to one history. DROP DATABASE moves the database's archive aside as <name>.dropped-<moment>/ under the archive root. To restore a dropped database, copy that directory under a separate root where it is named after the database again, for example /tmp/archive/shop/, create the database, and restore into its empty directory with --wal-archive-dir /tmp/archive.
Restore from a copy of the archive, or from one no server is writing into: a restore tidies the archive it reads, which would trip a checkpoint running into it at the same moment. The whole chain of segments after the base image is read into memory during a restore, so keep images frequent enough (the checkpoint worker's threshold) that the chain between them stays a few hundred megabytes at most.
Standby (log shipping)
A second server can follow a primary through the primary's checkpoint archive:
# primary nusadb-server --data-dir /var/lib/nusadb --wal-archive-dir /srv/nusadb-archive \ --checkpoint-threshold-bytes 16777216 --checkpoint-interval 5 # standby (a different data directory; the archive root is shared or replicated to it) nusadb-server --data-dir /var/lib/nusadb-standby --standby-from /srv/nusadb-archive --listen 0.0.0.0:5679
On start the standby registers every database the primary archives, seeds each empty database directory from the newest archived image, and from then on applies every log segment the primary's checkpoints archive, in order, once. It serves reads on every database. A write statement is refused with SQLSTATE 25006, sequences do not advance, and CREATE DATABASE and DROP DATABASE are refused. Between polls (--standby-poll, default 5 seconds) new transactions are held for at most --standby-max-pause seconds so the running ones end before a segment is applied; a transaction held open longer defers the segment to the next poll.
The standby lags the primary by the primary's checkpoint cadence: a segment reaches the archive only when the primary checkpoints, so set --checkpoint-threshold-bytes and --checkpoint-interval on the primary to the lag you can accept. The standby keeps what it has applied in its own log, so it survives a restart and continues from where it was. If the primary is restored to an earlier point (which forks its archive) or segments are pruned, the standby logs that the archive has moved past it and stops applying; empty its database directories and start it again to seed afresh.
--standby-from cannot be combined with --wal-archive-dir. When the archive root is replicated to the standby's host rather than shared, each segment must land atomically (copied under a scratch name and renamed into place): a segment whose copy is still in progress is left alone until it is complete.
To promote the standby, stop it and start it again without --standby-from (add a --wal-archive-dir of its own if it should archive): it opens every database writable and continues the primary's history from the last applied position. Point the old primary's clients at it, and do not start the old primary against the same archive root again without moving that archive aside, or the two histories would meet in one archive.
Upgrades
Stop the server, back up the data directory (see Backup), replace the binary (or pull a newer image tag) and start the server again. Recovery replays the log, so a clean restart keeps every committed transaction.
Data format
The files of a data directory are written in a numbered data format, and every directory records which one:
| File | Holds |
|---|---|
global/format | the cluster format: the global/ and base/<db>/ layout and the database catalog |
base/<db>/btree.wal.format | the data format of that database: its log, checkpoint image, page segments, and page and row layouts (format 3 for an encrypted database) |
<archive>/<db>/format | the data format of a --wal-archive-dir archive |
Each file also names the release that last wrote it, for example nusadb data format 2 followed by written by nusadb 0.1.0. On start-up the server checks the cluster format and the data format of every database before it opens any database or records anything, and the engine checks again when a database opens:
- The same format. The directory opens normally.
- An older format. The release upgrades it in place, one format at a time, when the database opens, and records each step as it completes, so an interrupted upgrade resumes where it stopped. Back up first: an upgraded directory cannot be opened by the older release again.
- A newer format (an older binary started on data a newer one wrote). The server refuses to start, names the format and the release that wrote it, and changes nothing. Start it with that release or a newer one. Downgrades are not supported; to go back, restore the backup taken before the upgrade.
A directory written before formats were recorded has no format files; it is format 1 and is stamped the first time a release that records formats opens it.
Format 2 adds the log and checkpoint-image records of prepared transactions (two-phase commit). The first time a release that writes format 2 opens a database, it records format 2 in that database's directory, whether or not two-phase commit is ever used. From then on a release that reads only format 1 refuses the directory: there is no downgrade. Back up the data directory before the first start of such a release if you may need to go back. Nothing else on disk changes in the upgrade.
Format 3 is format 2 with every file of the database encrypted (see Encryption at rest). Only an encrypted database is recorded as format 3, and a database is encrypted only when it is created, so an unencrypted database stays in format 2 and a release that reads format 2 keeps opening it. A release that reads only format 2 refuses an encrypted database by its format number, with nothing changed.
When the format changes
A release that changes how anything on disk is written, in a way an older release cannot read, raises the format number, and its release notes say so. Patch releases (0.1.x, and 1.x.y after 1.0) never change the format. Before 1.0 a minor release (0.2.0) may; after 1.0 only a major release does. A new release reads the formats of the releases before it, upgrading them in place, unless its release notes name a format it no longer reads; such a directory is refused with a message saying so, and is moved by exporting it with a release that reads it (COPY table TO STDOUT) and loading it into a fresh --data-dir.
A database directory written by the removed lsm engine is refused the same way rather than misread; migrate it by exporting from the last release that shipped that engine and reloading into a fresh --data-dir.
Column defaults outside public
Earlier releases stored the default of a column added with ALTER TABLE schema.table ADD COLUMN ... DEFAULT ... under the bare table name, so an insert into schema.table left the column NULL, and a table of the same name in public with a column of that name used the default instead. The first time a newer release opens such a database, it moves each of these defaults to its table, in one transaction, and logs each move at WARN. The stored entry names no schema, so a default left behind by a schema.table that was later dropped and re-created is attached to the new table too, and the log line says how to check and remove it. When public holds a table of that name with that column too, or several schemas do, the entry may be either table's, so it is left in place and logged at WARN with the default and the candidate schemas. Decide which table owns it, then run, for example:
ALTER TABLE app.e ALTER COLUMN flag SET DEFAULT 99; -- on the table that owns it ALTER TABLE public.e ALTER COLUMN flag DROP DEFAULT; -- if public.e should not have it
The repair runs once per database; information_schema.columns shows the defaults each table has. The server prints log lines only for the levels RUST_LOG enables, so start it with, for example, RUST_LOG=info (or RUST_LOG=warn) to see these messages.
Unique indexes from earlier releases
A unique index created by an earlier release allowed only one row with a NULL key. This release treats it as NULLS DISTINCT, like any unique index created without the clause, so it accepts any number of rows with a NULL key. To keep at most one NULL key, recreate the index with NULLS NOT DISTINCT:
DROP INDEX customers_ref; CREATE UNIQUE INDEX customers_ref ON customers (ref) NULLS NOT DISTINCT;
The CREATE fails with 23505 if more than one row with a NULL key was written in the meantime; remove the extra rows and run it again. A unique index on a partitioned table can no longer be created (0A000); declare a UNIQUE constraint on the table instead, which is enforced across its partitions (see keys on partitioned tables).
Indexes over CHAR columns from earlier releases
This release stores the key of an index over a CHAR(n) column without its trailing blanks. An index built by an earlier release may hold the padded value. Such an index stays correct: uniqueness, foreign key and exclusion checks, and queries that read through it, find a key however it was written. It is checked through a slower path until it is rebuilt. When a server opens a database that has such indexes, it logs their number:
WARN nusadb_server::database_manager: 2 index(es) over CHAR columns were built by an earlier release and are checked through a slower path until rebuilt; run REINDEX DATABASE (or REINDEX TABLE / REINDEX INDEX) to rebuild them db="nusadb" indexes=2
Rebuild them with REINDEX:
REINDEX INDEX codes_pkey; -- one index REINDEX TABLE codes; -- every index of a table, and of its partitions REINDEX SCHEMA public; -- every table of a schema REINDEX DATABASE nusadb; -- every table of the current database
Only indexes an earlier release built over CHAR columns are rebuilt; other indexes are left alone. A rebuild keeps the index definition, the constraint it backs, the foreign keys that reference it, and its comment. REINDEX INDEX and REINDEX TABLE need the table's owner or a superuser (42501) and may run inside a transaction block. REINDEX SCHEMA and REINDEX DATABASE rebuild the tables the role owns, commit each table on its own, and are refused inside a transaction block (25001). REINDEX DATABASE must name the current database, and REINDEX SYSTEM is the same as REINDEX DATABASE. While another transaction is writing the table, the rebuild fails with 40001; retry when the table is quiet.
An earlier release could store two rows whose keys are equal once trailing blanks are ignored ('a ' and 'a'). REINDEX then fails and leaves the index as it was, still enforced:
ERROR 23505: could not rebuild unique index "old_d_code": duplicate key violates unique index old_d_code (its rows hold one key twice once trailing blanks of a CHAR value are ignored; remove the duplicate first)
Remove one of the two rows and run REINDEX again.