Skip to main content

Storage Engines

Each Kahuna node stores its data with an embedded storage engine on the node itself. You don't run a separate database server. The engine that you choose affects write throughput and how easily you can inspect data. It also affects how much there is to operate. The distributed guarantees come from Kahuna and Kommander, and they don't depend on the engine: commands are replicated through Raft, then committed state is written to the configured local backend.

A Kahuna server has two independent storage choices.

  • --wal-storage controls the Raft write-ahead log (WAL) used by Kommander.
  • --storage controls the materialized Kahuna state for persistent objects, for example locks and key/value entries.

Both options take rocksdb, sqlite, or memory as values. RocksDB is Kahuna's default backend for both Raft WAL storage and materialized persistent state.

If you are unsure, keep the default: RocksDB for both. Choose SQLite for small deployments, or when you want to inspect data with standard SQLite tools. Choose memory only for tests and embedded nodes where losing persistent state on restart is acceptable. See Choosing an Adapter for a full comparison.

What the Storage Backend Stores​

The IPersistenceBackend contract stores the latest state and historical revisions of Kahuna's persistent objects.

  • locks, with fields such as the owner and the fencing token
  • key/value entries, with fields such as the value and the revision
  • revision records used by compare-revision reads and revision-aware commands
  • prefix and bucket reads over persistent key/value data

Kahuna's actors keep hot state in memory while the background writer batches dirty persistent objects to disk. Reads that miss memory, or that need a specific persistent revision, go through the configured backend.

RocksDB in Kahuna​

RocksDB is an embedded key/value database from Meta, built on an LSM tree (log-structured merge tree), that favors high write throughput and efficient scans over sorted keys. When you select it, the engine executes as native C++ code in the Kahuna process.

How an LSM Tree Works​

An LSM tree turns many small writes into larger sequential disk writes. New writes land in a sorted in-memory memtable, protected by a separate RocksDB WAL. A full memtable is flushed to disk as an immutable sorted file (an SST file). A read checks memory before it searches SST files across levels. The block cache stores recently read blocks in memory. Bloom filters skip SST files that can't contain the key. Background compaction merges SST files, drops overwritten values and tombstones when safe, and moves data through levels to keep reads efficient.

This fits Kahuna's persistent path: Kahuna batches committed actor output, RocksDB absorbs those writes efficiently, and compaction later reorganizes the data for long-running read and scan performance.

Kahuna's RocksDB adapter opens one RocksDB database under the configured storage path and revision. It uses separate column families for key/value data and lock data.

  • kv stores persistent key/value entries and their revision records.
  • locks stores persistent distributed lock state.

Each write is serialized as a protobuf message and appended through a RocksDB WriteBatch with synchronous write options enabled. The adapter opens RocksDB with absolute WAL recovery. For a normal persistent key/value write, the adapter stores two records.

  • key~CURRENT, the latest visible state of the key
  • key~revision, the immutable revision record for revision-aware reads

When a write uses SET ... NOREV or KeyValueFlags.SetNoRevision, Kahuna updates key~CURRENT but skips the key~revision record for that write. The current revision number advances as usual, but historical reads can't get the skipped revision. This reduces memory and disk write amplification for cache-style workloads that only need the latest value.

Locks follow the same pattern, with resource~CURRENT and resource~fencingToken records in the lock column family. Prefix scans use RocksDB's sorted keyspace directly: the adapter seeks to the requested prefix, iterates until the prefix range ends, and returns only records ending in ~CURRENT.

RocksDB scans skip long sequences of historical key~revision records after the visible current row or the requested snapshot row is known. This means that the cost of a scan over a revision-heavy store depends more on the number of logical keys than on the number of archived revisions. Kahuna also tracks keys that contain ~. This makes sure that the optimization is correct for escaped or unusual key names. Older stores that don't have that registry are read correctly, with the slower step-over path where necessary.

Storage Failure Recovery​

If RocksDB latches a storage error after a failed append, for example after a temporary full-disk condition, the failed background-write batch is retained. It isn't dropped. After repeated failed flush cycles, the background writer asks the backend to recover. RocksDB recovery closes and reopens the native engine behind a swap fence, then retries the retained batch when the backend is writable again.

This path is for transient storage failures. Operators must fix the underlying disk or filesystem problem. While the backend remains unavailable, unflushed writes of the affected partitions remain in memory, and checkpoints cannot advance for those writes.

Storage Damage and Node Identity​

RocksDB verifies block checksums on reads. When its materialized store returns Corruption, Kahuna latches a fail-stop for the rest of the process. Later backend operations fail, and data from the damaged store isn't served. Point reads and scans surface StorageCorrupt; a scan does not silently treat a corrupt block as the end of the range. Corruption found while opening the store, or an undecodable durability-floor row, prevents startup.

StorageCorrupt is a terminal response for that node, distinct from retryable MustRetry. The node withholds candidacy for its hosted partitions and tries to step down where it leads. Healthy replicas can then take over. Containment is asynchronous and reasserted by the writer; it does not guarantee an immediate handoff. A single-replica partition remains unavailable until repaired. Health returns HTTP 503 with storageFault; kahuna.persistence.store_fail_stops_total counts the fail-stop once per process. The background writer does not repeatedly reopen a corrupt store through the transient disk-full recovery path.

Repair requires operator action: preserve the damaged files, then restore a valid backup or move the damaged materialized-store directory aside and restart with its WAL intact to rebuild from peers. Inspect partition storage health; peer rebuild requires a healthy source. A single-replica partition can recover missing compacted history only from a backup. This checksum and fail-stop contract applies to the RocksDB materialized store. In Kahuna, SQLite doesn't have an equivalent page-checksum protection.

A RocksDB store is also stamped with the identity of its node: the Raft endpoint, a creation ID, and the creation time. Startup checks the stamp before it trusts durability floors.

Store found at startupBehavior
Matching endpointOpen normally.
Different endpointRefuse startup with StoreIdentityMismatchException; use this node's own store. Do not copy another node's live directory into place.
No stamp, but existing rows or floorsAdopt the older store by stamping it.
Empty store, and the WAL doesn't have historyStamp it as a fresh store.
Empty store under a WAL with historyReport replacement at Critical and through storageFault, then rebuild from the log or a peer snapshot.

An empty floor-tracking store shows a data-partition durability floor of 0. If the WAL contains the full prefix, the node can replay it. If the required prefix was compacted, Kahuna requires a full partition snapshot. It doesn't apply a surviving suffix to incomplete data. After the replacement notice, readiness is false for that process, even after catch-up; inspect recovery and restart after repair. kahuna.persistence.store_replaced_at_start_total records the startup finding.

Backup images don't include the identity stamp. This means that restore and bootstrap can stamp the identity of the receiving node. See Backups for supported restore workflows.

Shared RocksDB Memory​

When Kahuna uses RocksDB for both --storage and --wal-storage, one node opens two separate RocksDB databases.

  • the materialized key/value and lock backend
  • the Kommander Raft WAL

They are separate on disk. This means that the consensus log and the data path have independent files and recovery. Shared RocksDB memory only shares in-process memory objects: one block cache and one write-buffer manager.

These options enable it.

kahuna-server \
--storage rocksdb --wal-storage rocksdb \
--rocksdb-shared-memory \
--storage-shared-cache-mb 512 \
--storage-shared-memtable-budget-mb 128

The total budget controls the shared block cache. The memtable budget is part of that same total. This means that cached SST blocks and in-memory write buffers use one budget across both RocksDB databases.

SettingDefaultMeaning
--rocksdb-shared-memorydisabledEnables one shared block cache and write-buffer manager.
--storage-shared-cache-mb0Total shared cache budget in MiB; must be positive for shared RocksDB memory.
--storage-shared-memtable-budget-mb0Memtable sub-budget in MiB, charged into the shared cache; must be positive and no larger than the cache.

The shared budgets are engine-neutral settings that a custom storage provider can also use. RocksDB applies them when both storage layers use RocksDB and --rocksdb-shared-memory is set. That mode now requires both budgets explicitly; the former 320 MiB and 128 MiB defaults no longer apply. The old --rocksdb-shared-memory-budget-mb and --rocksdb-shared-memtable-budget-mb names remain accepted as aliases.

Use this feature when process memory is constrained and RocksDB is used for both durable state and WAL. Measure before and after you enable it, under representative load. Watch these values.

  • Process RSS
  • RocksDB block-cache usage
  • Memtable usage of the write-buffer manager
  • Raft commit or WAL append latency

The feature has these operational caveats.

  • The feature is opt-in and reversible. It doesn't change the on-disk format or the WAL semantics, and it doesn't change recovery or wire behavior.
  • A write burst in one RocksDB database can cause more frequent flushing that affects the shared memory budget for the other database.
  • Kahuna uses a soft cache and a non-stalling write-buffer manager for this mode. You should use conservative sizes. Don't rely on RocksDB stalls for back-pressure.

Limit Compaction Work​

On a busy RocksDB store, flushes and compactions can compete with synchronized writes for disk throughput. Two optional settings limit that background work on the materialized store. They don't apply to the Raft WAL.

SettingDefaultEffect
--storage-compaction-rate-mbps0 (unlimited)Limits store flush and compaction writes in MB/s.
--storage-max-background-compactions0 (RocksDB default)Caps concurrent store compactions.

Set these only after measuring disk contention. A rate below the incoming write load can let RocksDB level-0 files accumulate and eventually slow writes. SQLite and memory ignore these settings; a custom engine may choose to honor them.

Reclaiming Deleted-Key History​

Deleting a persistent key does not immediately free its revision archive. Persistent revision retention is disabled by default. With --persistent-revision-retention-age configured (in seconds), RocksDB removes a deleted key's archived rows once the deletion is older than that age and no registered snapshot hold needs history from before the deletion. Count-based retention alone does not release the complete deleted-key archive.

The current deletion record remains: it preserves the revision number, and recreating the key continues from that revision. There is no operation to forget the key's revision identity. SQLite also prunes old revisions by age, but retains the deletion's history row; its database file does not automatically shrink.

RocksDB batches cleanup and flushes the memtable at the end of a sweep cycle so background compaction can reclaim files. Disk usage can decrease later than logical deletion. Snapshot holds and compaction pacing, for example, can delay reclamation. kahuna.persistence.revision_prune.delete_records_released_total counts deleted-key archives released, and kahuna.persistence.revision_prune.sweep_catch_up_passes_total counts immediate follow-up passes on an idle writer after a productive, budget-limited pass. See revision pruning and snapshot holds.

Direct Reads and Statistics​

Kahuna enables RocksDB direct reads by default for the materialized state backend. Direct reads bypass the operating-system page cache for SST reads. This means that RocksDB's block cache becomes the main read cache. This avoids double-caching the same data in both RocksDB and the OS page cache and makes the process memory budget easier to reason about, especially when shared RocksDB memory is enabled.

Disable direct reads when the operating-system page cache is intentionally part of the deployment's read strategy, or when a small local installation benefits more from buffered filesystem reads than from a cache that only RocksDB manages.

kahuna-server \
--storage rocksdb \
--disable-rocksdb-direct-reads

RocksDB statistics are disabled by default because they add accounting overhead to each operation. You can enable them when you tune or diagnose storage behavior.

kahuna-server \
--storage rocksdb \
--rocksdb-statistics

When statistics are enabled, RocksDB records internal counters, for example block-cache activity and write stalls. It writes them each 60 seconds to the RocksDB LOG file under the configured storage path.

SettingDefaultUse whenTrade-off
--disable-rocksdb-direct-readsdisabledYou want buffered reads through the OS page cache, and not direct I/O.Can reintroduce double caching and less predictable read-memory accounting.
--rocksdb-statisticsdisabledYou investigate storage behavior, for example block-cache efficiency or write stalls.Adds per-operation overhead and more LOG output.

RocksDB WAL Tuning​

When --wal-storage rocksdb is used, Kahuna exposes Kommander's RocksDB WAL shard tuning knobs. These affect the Raft log layout. They don't affect the materialized key/value backend. Leave them at 0 unless you measure WAL compaction behavior under production-like load, for example write amplification.

SettingDefaultMeaning
--raft-wal-shard-write-buffer-size-mb0Keep Kommander's default memtable size, currently 64 MiB.
--raft-wal-shard-min-write-buffer-number-to-merge0Keep Kommander's default immutable memtables merged per flush, currently 2.
--raft-wal-shard-max-write-buffer-number0Keep Kommander's default maximum memtables per shard, currently 4.
--raft-wal-shard-level0-file-num-compaction-trigger0Keep Kommander's default level-0 compaction trigger, currently 8 files.
--raft-wal-shard-level0-slowdown-writes-trigger0Keep Kommander's default level-0 slowdown trigger, currently 28 files.
--raft-wal-shard-level0-stop-writes-trigger0Keep Kommander's default level-0 stop trigger, currently 44 files.
--raft-wal-shard-max-bytes-for-level-base-mb0Keep RocksDB's level-base sizing, currently 256 MiB unless overridden by Kommander.
--raft-wal-shard-universal-compactiondisabledUse universal compaction for WAL shard column families. The default is leveled compaction.

Larger flush units can let a log row and the range tombstone that later removes it meet earlier, reducing WAL rewrite work. The trade-off is memory use and restart replay size. Universal compaction can reduce leveled compaction churn for log-shaped data, but it should be enabled only after benchmarking your workload.

SQLite in Kahuna​

SQLite is a serverless, self-contained relational database that stores tables and indexes in B-trees and supports ACID transactions through rollback journals or write-ahead logging.

Kahuna's SQLite adapter stores materialized state across eight shard files under the configured storage path and revision.

kahuna0_<revision>.db
kahuna1_<revision>.db
...
kahuna7_<revision>.db

Keys are routed to a shard by hash. Each shard has a separate SQLite connection and reader/writer lock. Eight files give Kahuna more concurrency than a single database file, and the implementation is simple. The adapter creates three tables.

  • locks, keyed by lock resource
  • keys, keyed by key name and storing the latest visible key/value state
  • keys_revisions, keyed by (key, revision) and storing historical key/value revisions

SQLite is opened in WAL mode with synchronous=NORMAL and temp_store=MEMORY. synchronous=NORMAL is a performance-oriented durability setting: it is appropriate for many WAL-mode deployments, but it is not SQLite's strictest durability mode. Key/value batches are grouped per shard and committed in a SQLite transaction. Lock writes are upserted by resource.

Prefix reads are implemented with SQL over the keys table using LIKE '<prefix>%'. Because Kahuna routes bucket-style keys by prefix, the adapter opens the shard for the prefix and scans that shard's current-key table.

Memory Backend​

The memory backend is useful for embedded nodes and tests. It stores state in process memory and doesn't do disk I/O. However, it isn't restart-safe and should not be used for durable production state. Persistent revision reads also require an on-disk backend.

Choosing an Adapter​

RocksDBSQLite
Storage modelEmbedded C++ key/value store based on an LSM treeEmbedded relational database based on B-tree tables and indexes
Kahuna layoutOne database under the storage revision, with kv and locks column familiesEight hash-sharded database files named kahunaN_<revision>.db
Latest stateStored as key~CURRENT or resource~CURRENT recordsStored in keys and locks tables
Historical revisionsStored as revision-suffixed records in the same column family; handles the append-heavy pattern of a latest-state plus a revision record per persistent update wellStored in the keys_revisions table with (key, revision) as the primary key; works for many retained revisions with disk maintenance
Write pathBatched protobuf records written through WriteBatch with sync writes; the background writer's batches of dirty locks and key/value entries map cleanly to itSQL upserts; key/value writes are grouped per shard and committed in transactions
Write concurrencyStrong fit for sustained write-heavy workloads. Memtables and background compaction suit high insert and update rates better than page-oriented storageWrites are serialized for each shard, and high write concurrency can become a bottleneck. Suitable for low to moderate write volume
Prefix scansNative ordered-key iterator over sorted SST files, which makes prefix and bucket scans over large keyspaces naturalSQL LIKE '<prefix>%' query on the prefix shard. Native ordered-key iteration isn't used
Operational footprintLarger: native library dependencies and platform-specific packaging. It has more to tune and monitor, and it gives the most tuning controlSmall: a server process isn't needed. Ordinary database files are easy to package and back up
Inspection and debuggingData files are not convenient to inspect manually; needs RocksDB tooling or application-level inspectionStandard SQLite tools can inspect the tables directly, for example values and lock rows
Disk behaviorCompaction behavior and file counts matter under load and need monitoring. Revision-heavy workloads store current and historical records. Plan disk growth and compactionLarge values and revision-heavy workloads can grow database and WAL files quickly; long-running deployments may need WAL checkpointing and occasional vacuuming
Best fitProduction clusters with sustained persistent traffic, for example high write rates or large keyspaces with retained revisionsLocal development and tests, and small persistent clusters. Also embedded deployments in constrained environments, where its file model is easy to reason about
Weak fitVery small deployments and simple embedded usage, where it can be more machinery than necessaryThe highest-throughput or write-heavy production workloads, and very large revision-heavy keyspaces

For most production clusters, start with RocksDB for both --wal-storage and --storage. Use SQLite when a small footprint and easy inspection matter more to the deployment than maximum write throughput.

Operational Notes​

  • Keep --wal-path and --storage-path on reliable local disks. Network filesystems can add latency and failure modes that hurt Raft and embedded database behavior.
  • Use a stable --storage-revision and --wal-revision for an existing data directory. Changing revisions points Kahuna at a different set of local files.
  • Monitor disk growth when using persistent key/value revisions. Kahuna stores both latest records and revision records.
  • Ephemeral objects live in memory, and they don't use the storage backend; use them for data that does not need restart persistence (see Durability Levels).