CamusDB is a SQL distributed database written in C# on .NET. It provides a SQL interface with a Raft-replicated, transactional key-value storage layer. Transactions are serializable and strongly consistent by default. You can branch a database copy-on-write, the way you branch code, and you can recover a dropped table or database. It can auto-scale based on traffic. Development is driven by performance and by Jepsen-style testing with fault injection and degraded cluster states.
CamusDB is used in production, but some of its features are young. Use it with caution. APIs and storage formats may change between versions.
Documentation | Live playground
video_2x.mp4
Transactions are serializable unless you ask for less. Pessimistic two-phase locking with range/predicate locks blocks phantoms. Wait-die scheduling avoids deadlocks, and reads use consistent snapshots. Cross-partition writes are coordinated with two-phase commit on top of Raft consensus, which makes a committed write durable and replicated. For a workload that does not need serializability, read-committed is available per transaction (SET TRANSACTION) or as a process default.
A branch is a writable copy of a database. It is created instantly and copies no row data.
CREATE DATABASE staging BRANCH FROM prod;See Database Branching below.
DROP DATABASE and DROP TABLE don't destroy data immediately unless you add FORCE. You can bring a dropped object back until its retention window ends.
SHOW ORPHAN TABLES; -- list recoverable objects
CREATE TABLE users RELINK TO '<id>'; -- bring one back under a (new) nameSee Recovering Dropped Objects below.
You can read a table as it existed at a point in the past. Use it to see a row as it was before a deploy, or to recover rows that a bad statement deleted or overwrote.
SELECT * FROM leaderboard AS OF SYSTEM TIME '-10s'; -- 10 seconds ago
SELECT * FROM accounts AS OF SYSTEM TIME '2026-07-19 20:00:00+00:00'; -- an exact instantSee Time-Travel Reads below.
An inline hint caches the result of a read in memory on the node. You don't need an external cache tier, and a write on the same node invalidates the cached results that depend on it.
SELECT id, total FROM orders {cache=recent_orders, ttl=30s} WHERE status = 1;See Query Result Cache below.
CamusDB's engine is written in modern C#. It is a single .NET process, from the SQL parser down to the embedded Kahuna storage node, with RocksDB underneath for persistence. Because the engine itself is pure .NET, you extend it with ordinary C#. An extension can use your own NuGet libraries and business logic directly in the database layer. You read and debug the engine with the same .NET tools, and you can use it on any platform that .NET 10 supports. Clients talk to it over a JSON/HTTP API or a gRPC API with a .NET client library.
The same engine also compiles to WebAssembly. The browser playground is an in-memory node in a browser tab, with a SQL editor and a sample data set. One button turns it into a three-node cluster in the same tab, over an in-memory transport. You can stop the leader and watch another node take over, then start the old leader and watch it catch up. Try it at camusdb.github.io/playground. See docs/browser-playground.md to build it and serve it from any static host.
- SQL dialect: PostgreSQL-style SQL with prepared statements and parameter placeholders. Writes support upserts (
INSERT … ON CONFLICT,UPSERT INTO) andRETURNING. See docs/postgresql-differences.md for the differences from PostgreSQL. - ACID transactions: pessimistic locking by default, with optimistic locking per transaction (
SET TRANSACTION LOCKING OPTIMISTIC); serializable isolation is the default (range/predicate locks with wait-die deadlock avoidance and snapshot reads), with read-committed available per transaction (SET TRANSACTIONor the begin-request field) or as a process default; cross-partition writes use two-phase commit (2PC). Transactions can carry a priority (SET TRANSACTION PRIORITY) that orders admission on a saturated node once an operator sets a concurrency ceiling. - Copy-on-write database branching: fork a database instantly with
CREATE DATABASE feature_x BRANCH FROM prod; inspect the tree withSHOW BRANCHES FROM dbandSHOW ANCESTORS FROM db. - Recovering dropped objects: a drop defers physical deletion unless it uses
FORCE.SHOW ORPHAN TABLESandSHOW ORPHAN DATABASESlist the dropped objects, andRELINK TO '<id>'brings one back. A background reclaimer deletes an orphan after its retention window. - Time-travel reads:
SELECT … AS OF SYSTEM TIME '-10s'(or an absolute UTC timestamp or epoch ms) reads a consistent historical snapshot. The read takes no locks and doesn't block writers. You can use it to read back rows that were deleted or overwritten by mistake, while their history is retained. - Query result cache: opt-in per query with a
{cache=…}hint. Writes on the same node invalidate the dependent entries before the writes become visible. For writes on other nodes, a TTL orstrictper-hit validation limits staleness. - Aggregation: COUNT, SUM, AVG, MIN, MAX with GROUP BY and HAVING filters.
- Set operations:
UNION,INTERSECTandEXCEPT, each withALLorDISTINCT. You can chain them, andORDER BYandLIMITapply to the combined result. See docs/set-operations.md. - Window functions: ranking and offset functions such as
rankandlag, and aggregates over a window withOVER (PARTITION BY … ORDER BY …). See docs/window-functions.md. - Row-locking reads:
SELECT … FOR UPDATE [OF t] [NOWAIT | SKIP LOCKED]locks each returned row until the transaction ends, for ORM pessimistic locking and job queues. - Joins and subqueries: inner and outer joins over tables and derived tables, with
INandEXISTSsubqueries. See docs/joins.md. - Filtering and ordering:
WHEREsupports pattern matches such asILIKEand the regex operator~.ORDER BYaccepts projection aliases and ordinal positions, andLIMITandOFFSETpage the result. - Scalar functions: over a dozen families, from string and math functions to JSON helpers. See the function reference.
- Query planning: a cost-based planner chooses access paths and join order from table statistics, such as histograms and distinct-value counts. A background job refreshes the statistics of a table when they go stale. Operators that buffer rows, such as sorts and hash joins, spill to temporary files past a configured threshold. A large statement can then complete when its data doesn't fit in memory. A client cancel stops a running
SELECT. See docs/query-planner.md. - Query introspection:
EXPLAINreturns the plan as result rows, with estimated rows and cost.EXPLAIN (ANALYZE)adds the actual row counts and KV access counters. See docs/explain.md. - Indexes: unique and multi-column indexes, with an ascending or descending order per column. A covering index stores extra columns with
INCLUDE, and a query can read them from the index alone. Ajsonbcolumn can have a GIN index. - Database management: a database must be created explicitly with
CREATE DATABASE. Each database gets an immutable internal id at creation time. The name is a display-only label, andRENAME DATABASE old TO newchanges only the label. - Schema management:
ALTER TABLEchanges columns and names, andSHOW CREATE TABLEreturns a table's definition. A column can have a default, such asgen_uuid_v7(). A table can haveCHECKand namedNOT NULLconstraints. In a cluster, DDL is online. Schema changes replicate through Raft, and because they move through staged states, tables stay readable and writable while an index backfills. - Foreign keys: composite and self-referencing foreign keys, with
NO ACTIONorRESTRICTforON DELETEandON UPDATE.ALTER TABLE ADD CONSTRAINTvalidates the existing rows. The checks apply under both isolation levels and on database branches, in standalone and cluster mode. - Data types:
int64,float64,float32,bool,numeric/decimal,string/string(N),bytes,date,datetime,uuid,oid(ObjectId),array(T), andjsonb. Anintervaltype exists in expressions only (ts + INTERVAL '1 day'); a table column cannot have it. - JSON documents: a
jsonbcolumn (jsonis an alias) stored as canonical binary CBOR, with the PostgreSQL operators (->,->>,#>,@>,?,||,#-, …), functions (jsonb_set,jsonb_build_object,jsonb_each,jsonb_agg, …) and GIN indexes (CREATE INDEX … USING GIN). - Views and materialized views:
CREATE VIEWexpands the view where a query names it, and supportsWITH CHECK OPTION.CREATE MATERIALIZED VIEWstores the rows, andREFRESH MATERIALIZED VIEWrecomputes them. See docs/views.md. - Sequences:
CREATE SEQUENCEand thenextvalfunction, which can be a column default (DEFAULT nextval('order_no')). See docs/sequences.md. - Vector search: embeddings stored in
bytescolumns, ranked with an exact distance function such ascosine_distancein an ordinaryORDER BY … LIMIT. - Row-level TTL: a table names an expiry column (
ALTER TABLE t SET (ttl_expiration_expression = 'expires_at')) and a background sweep deletes expired rows; the parameters follow CockroachDB's row-level TTL. - C# extensions: scalar functions, row triggers (
CREATE TRIGGER … EXTERNAL NAME) and stored procedures (CALL) written in C#, loaded from operator-deployed assemblies at startup and installed per database withCREATE EXTENSION(versioned, withALTER EXTENSION … UPDATEfor rolling upgrades), with a SAFE check for reviewed code. - Inline C# functions and triggers:
CREATE FUNCTION … LANGUAGE csharp AS $$ … $$andCREATE TRIGGER … LANGUAGE csharp AS $$ … $$hold the C# body in the statement, and a superuser is not required to create them. Both are off by default (inline_functions_enabled,inline_triggers_enabled). - Large values: large variable-length cells, such as
stringandbytes, are compressed with LZ4 and moved out of the row, with a storage strategy per column. Query results do not change. - Authentication and authorization: off by default. When it is on, users and
GRANT/REVOKEprivileges control access, and clients authenticate with tokens over both APIs. See docs/sql-authentication.md. - Backups and point-in-time recovery: node-wide full and incremental backups and restore through a server-admin HTTP API, with retention and garbage collection.
- Multi-node cluster: Raft consensus (via Kommander) partitions data across nodes; each partition elects a leader. Nodes join a cluster with
--mode=clusterand a static peer list. Data is placed by hash routing by default; opt-in key-range sharding routes key spaces by key order, and a hot range can split automatically by load. - Distributed queries: with key-range sharding and
distributed_query_executionenabled, eligible scans run as fragments on span leaders. Peers can filter rows and compute partial aggregates before the coordinator gathers the results. They can also probe eligible inner hash joins. - Standalone mode: the default mode, with the engine and its storage in one embedded process.
- APIs: all database operations are accessible over a JSON/HTTP endpoint and over a gRPC endpoint (streaming query results and a duplex batch-execute channel with per-transaction chains).
- Observability:
SHOWstatements such asSHOW SLOW QUERIESandSHOW ENGINE STATSfrom a SQL prompt. Each node serves a read-only operator dashboard on its HTTP port. OpenTelemetry metrics and traces are opt-in. - Runtime cluster settings:
SET CLUSTER SETTINGandRESET CLUSTER SETTINGchange a defined subset of the configuration across the cluster at runtime. - Learned client routing: servers attach advisory routing metadata to SQL responses. A client with several endpoints uses it to send repeated statements straight to the node that leads their data.
- Logical dump and reimport: move data across storage revisions or machines with
camus-dumpandcamus-cli. - Multi-platform: any platform that .NET 10 supports.
CREATE TABLE IF NOT EXISTS app_users (
id STRING PRIMARY KEY NOT NULL,
email STRING UNIQUE NOT NULL,
display_name STRING NOT NULL,
password_hash STRING NOT NULL,
role STRING NOT NULL,
created_at_utc STRING NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS app_users_email_idx ON app_users (email);
SELECT DISTINCT role FROM app_users ORDER BY role;
SELECT role, COUNT(*) AS users
FROM app_users
GROUP BY role
HAVING users > 0
ORDER BY 2 DESC;
SELECT r.id, r.name, ur.amount
FROM robots r
JOIN user_robots ur ON r.id = ur.robots_id;
SELECT r.id, r.name, ur.amount
FROM robots r, user_robots ur
WHERE r.id = ur.robots_id;
SELECT *
FROM robots
WHERE id NOT IN (SELECT robots_id FROM user_robots);
SELECT json_value(payload, "$.name")
FROM robots
WHERE json_valid(payload) = true;
EXPLAIN SELECT * FROM app_users WHERE email = 'a@example.com';
EXPLAIN (ANALYZE) SELECT role, COUNT(*) FROM app_users GROUP BY role;On macOS or Linux, install with Homebrew. The package includes the .NET runtime, and you don't need to install .NET first.
brew install camusdb/tap/camusdb
brew services start camusdb # run a node in the background, and again at loginThe service's configuration is in $(brew --prefix)/var/camusdb/config.yml, and its data is in
$(brew --prefix)/var/camusdb/data. Its log is $(brew --prefix)/var/log/camusdb.log. You can
also run camusdb in a shell, as described below.
CamusDB also ships as a .NET global tool. To install it, you need the .NET 10 runtime or SDK.
dotnet tool install -g CamusDB.Server
camusdbThe node starts on built-in defaults and stores its data under ~/.local/share/camusdb (%LOCALAPPDATA%\camusdb on Windows),
serving the JSON/REST API on port 5095 and gRPC on 5096.
To keep settings of your own, write a starter configuration with camusdb init and edit it.
camusdb init # writes ~/.camusdb/config.ymlThis command starts a single node from the published image. It maps the JSON/REST and gRPC ports and stores the data in a named volume.
docker run --rm \
-p 5095:5095 \
-p 5096:5096 \
-v camus-data:/data \
--name camusdb camusdb/camusdb:latestYou can start a local three-node cluster with Docker Compose.
docker compose -f docker/local.yml up --buildThis starts three nodes on a private bridge network.
| Node | JSON/REST API | gRPC API | Raft port |
|---|---|---|---|
| camus1 | localhost:5095 | localhost:6095 | 7070 |
| camus2 | localhost:5096 | localhost:6096 | 7072 |
| camus3 | localhost:5097 | localhost:6097 | 7074 |
You can also run a node from a source checkout with dotnet run. The Homebrew package and the
.NET global tool don't need a source checkout.
# Standalone (default)
dotnet run --project CamusDB
# Cluster node
dotnet run --project CamusDB -- \
--mode=cluster \
--raft-nodename=camus-1 \
--raft-host=192.168.1.10 \
--raft-port=7070 \
--initial-cluster-partitions=3 \
--initial-cluster 192.168.1.10:7070 192.168.1.11:7072 192.168.1.12:7074A SQL statement enters over the HTTP or gRPC API and is parsed into an AST. The AST is bound against the catalog, and a cost-based query planner turns it into a physical plan. The plan executes as a tree of storage-agnostic operators (scan, filter, join, aggregate, sort, project, limit) that read and write rows through a transactional key-value layer. That KV layer is an embedded Kahuna node. Table rows and index entries are mapped onto Kahuna keys with a prefix layout, and transactions are coordinated through Kahuna's transaction API. Raft (Kommander) provides durability and replication. In a cluster, data is partitioned across nodes, and each partition elects a leader. Statements are routed to the owning partition, and cross-partition writes use two-phase commit. Standalone mode uses the same stack with an embedded node in the server process.
See docs/architecture.md for the full developer reference, including the key layout and how standalone and cluster modes differ.
See docs/query-planner.md for the developer reference on the planner, from the physical plan nodes to the cost model. It also has a checklist for adding new SQL features. For the user-facing EXPLAIN output format, see docs/explain.md.
See docs/distributed-schema-architecture.md for the developer reference on how DDL works across a cluster. The schema is a replicated state machine over an ordered Raft log. An online schema change moves through staged states (DeleteOnly → WriteOnly → Public), with a convergence gate between the steps.
Fork a database the way you branch code. CREATE DATABASE feature_x BRANCH FROM prod mints an instant, copy-on-write point-in-time fork. The branch shares the parent's bytes until it diverges, and creating it copies a small amount of schema metadata and no row data. Reads on the branch see the parent as of the fork instant, and writes on the branch are private to it. The parent can change after the fork, but it doesn't see the branch.
-- Instantly fork production into an isolated, writable clone (no data copied)
CREATE DATABASE staging BRANCH FROM prod;
-- Inspect the branch tree
SHOW BRANCHES FROM prod; -- every database forked (transitively) from prod, with depth
SHOW ANCESTORS FROM staging; -- staging's fork chain, immediate parent up to the root
-- Throw it away when done — the parent is untouched
DROP DATABASE staging;Use a branch as a cheap staging clone of production, or for a schema-migration dry-run. Branches nest to any depth. A Raft-replicated snapshot-floor hold makes the fork's frozen view durable. This means that a long-lived branch reads its parent as of the fork instant, even when the parent has a heavy write load.
See docs/database-branching.md for the developer and operator reference, from the ancestry model to operator guidance.
DROP DATABASE and DROP TABLE defer physical deletion unless you add FORCE. The dropped object is unlinked (orphaned), and you can relink it under a new name until its retention window ends. Note that drops in a database branch are immediate: a dropped branch database, or a table dropped in one, can't be recovered.
DROP TABLE users; -- unlinks; data survives for the retention window
SHOW ORPHAN TABLES; -- list recoverable tables (with ids and drop time)
SHOW ORPHAN DATABASES; -- likewise for databases
CREATE TABLE users RELINK TO '<id>'; -- recover a dropped table under a name
CREATE DATABASE app RELINK TO '<id>'; -- recover a dropped databaseA background reclaimer garbage-collects orphans once their retention window elapses; until then, a drop is reversible.
Append AS OF SYSTEM TIME to a SELECT, and the statement reads one consistent snapshot from a past instant. The snapshot applies to the tables and subqueries in the statement. The storage layer is multi-version. Each key retains its prior revisions, tagged with the HLC (hybrid logical clock) timestamp at which they committed. Historical reads take no locks and don't block writers.
-- Relative offset into the past (units: ms, s, m, h, d)
SELECT * FROM leaderboard AS OF SYSTEM TIME '-10s';
-- Absolute UTC instant (also accepts epoch milliseconds or a bound parameter)
SELECT * FROM accounts AS OF SYSTEM TIME '2026-07-19 20:00:00+00:00' WHERE id = 9910;This is also a fine-grained recovery tool: after an accidental DELETE or a bad UPDATE, query the table as of just before the mistake and re-insert what was lost. You don't need a backup restore, as long as the storage layer retains that history. By default, all persisted revisions are kept, and a tighter revision retention narrows the window.
AS OF SYSTEM TIME is limited to autocommit read-only statements, and the instant must be in the past. In an explicit transaction, a statement with AS OF SYSTEM TIME returns an error, and there is no historical UPDATE or DELETE. See docs/time-travel-reads.md for the full reference, including the accepted value forms and the retention behavior.
Opt a read into an in-memory, per-node result cache with an inline hint: SELECT * FROM orders {cache=recent_orders}. An identical later query, with the same bound values and the same schema, is served from memory. A committed write on the same node evicts the dependent entries before the write becomes visible to a later read. This means that a reader on the same node doesn't see stale data. Staleness from writes on other nodes is bounded by a per-entry TTL, or removed per hit with {cache=…, strict}. Options include ttl=30s (units ms/s/m/h) and strict; entries are dropped manually with EVICT CACHE 'name' or EVICT CACHE ALL. The feature is on by default and applies to autocommit single-table SELECTs. A query is cached only if it has a {cache=…} hint. Set query_result_cache_enabled: false to disable the feature.
-- Cache this result under the "recent_orders" family, expiring after 30 seconds
SELECT id, total FROM orders {cache=recent_orders, ttl=30s} WHERE status = 1;
-- Validate against live storage on every hit (no cross-node staleness window)
SELECT * FROM inventory {cache=stock, strict} WHERE sku = 'ABC-123';
EVICT CACHE 'recent_orders'; -- drop one family for the current database
EVICT CACHE ALL; -- drop every result-cache entry for the current databaseSee docs/query-result-cache.md for the operator and developer reference, including the query_result_cache_* settings and the known limitations.
CamusDB pins its on-disk layout to a storage revision. A release that changes the layout opens a new, empty revision directory. It logs a warning when it finds the previous revision on disk, and it does not read or convert the old data in place. To move the data, use a logical dump and reimport.
- Dump the databases with the previous release and
camus-dump. - Upgrade CamusDB.
- Load the dump with
camus-cli.
See docs/logical-dump-and-reimport.md for the procedure, what a dump does and does not carry, and how to roll back.
At startup, CamusDB reads the first configuration file that it finds in these locations, in order.
- The
--configpath - The path in
CAMUS_CONFIG_PATH ./camusdb.ymlor./Config/config.yml~/.camusdb/config.yml
If there is no file, CamusDB starts on built-in defaults. It merges CLI flags and environment variables into a single resolved configuration (precedence: CLI flag > environment variable > configuration file > built-in default). See docs/configuration.md for the full reference, including the CLI ↔ YAML mapping and the validation errors.
- .NET 10 SDK
- Docker (optional, for cluster setup)
The test suite is split into two assemblies that you run separately.
CamusDB.Testsis the fast unit and integration suite for day-to-day changes.dotnet test CamusDB.Tests/CamusDB.Tests.csprojCamusDB.Cluster.Testsis the heavy in-process multi-node cluster suite (real Raft via Kahuna/Kommander). It is a separate assembly because its in-process load (dozens of sequential clusters) made cluster bring-up flaky when it was part of the fast suite. Run it separately and periodically.dotnet test CamusDB.Cluster.Tests/CamusDB.Cluster.Tests.csproj
This project is licensed under the MIT license.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in CamusDB by you, shall be licensed as MIT, without any additional terms or conditions.
