Skip to content
mstdokumaciPublic

About

Realtime database using Zig + SQLite + uWebSockets

Resources

Contributing

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

ZyncBase

One binary. One SQLite file. Every realtime primitive your app needs.

ZyncBase replaces the patchwork of managed services — a database, a WebSocket relay, a presence service, a CRDT server — with a single self-hosted process. Define your schema in JSON, declare your authorization rules, and get live queries, presence, server actions, and Yjs collaboration over one connection.

Status: pre-release — single-node, no automatic failover. The core primitives are tested (unit, E2E, stress, crash recovery, sanitizers) and the API is stabilizing. Validate against your workload before production use.

At a glance

  • 50,000 concurrent clients on ~3 cores and ~1.3 GB RAM (benchmark details)
  • Filtered fanout — live queries run on the server; a write only reaches subscribers whose filter matches
  • Store + Presence + Actions + Yjs in one SDK, one connection, one schema
  • SQLite WAL persistence — your data is a file you can backup, restore, replicate with Litestream, and inspect with any SQLite tool
  • Declarative security — JSON authorization rules with $session, $doc, and $namespace variables; no custom code in the database
  • TypeScript-first — generated types from schema, React 19 hooks, optimistic writes with pending markers

How it works

┌──────────────────────────────────────────────────────────┐
│  TypeScript SDK          React Hooks       Yjs Provider  │
│  store · presence · actions · subscribe · listen         │
└──────────────────────────┬───────────────────────────────┘
                           │ MessagePack over WebSocket
┌──────────────────────────▼───────────────────────────────┐
│  ZyncBase Server (Zig)                                   │
│  ┌────────────┐ ┌──────────────┐ ┌────────────────────┐  │
│  │ uWebSockets│ │ Subscription │ │ Auth / Authz       │  │
│  │ reactors   │ │ engine       │ │ (JWT + JSON rules) │  │
│  └────────────┘ └──────────────┘ └────────────────────┘  │
│  ┌────────────────────────────────────────────────────┐  │
│  │ SQLite WAL — single-writer, concurrent readers     │  │
│  └────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────┘

Quick start

Create zyncbase-config.json. Anonymous access is off by default; this local-dev config enables it and declares the tasks collection used by the examples below:

{
	"authentication": { "anonymous": { "enabled": true } },
	"schema": {
		"version": "0.1.0",
		"store": {
			"tasks": {
				"fields": {
					"status": { "type": "string" }
				}
			}
		}
	}
}

Install the server launcher and the client together; add the backend package when you run action workers or mint JWTs. All packages are released at the same version, so update them together and keep their versions equal:

bun add --exact zyncbase @zyncbase/client
bun add --exact @zyncbase/backend   # worker/backends only

Start a development server. bunx uses the installed launcher, which downloads the matching native binary for your platform on first run:

bunx zyncbase dev --config zyncbase-config.json

zyncbase dev runs the config as written, plus a short list of development overrides that it prints at startup, such as allowing localhost origins and generating secrets. --ephemeral gives you a throwaway data directory, and --run "<command>" starts your app or worker once the server is ready. In production, run the same file directly:

bunx zyncbase --config zyncbase-config.json

See configuration for the full config and schema reference, the launcher for every zyncbase dev flag, and BUILD.md to build from source.

Subscribe to live data

import { createClient } from "@zyncbase/client";

const client = createClient({
	url: "ws://localhost:3000",
	auth: { anonymous: true },
});

await client.connect();

// Live subscription — callback fires on every matching change
await client.store.subscribe("tasks", {
	where: { status: { eq: "active" } },
	orderBy: [{ created_at: "desc" }],
	limit: 50,
}, (tasks, { pending }) => {
	renderTaskList(tasks, pending);
});

// Atomic write — subscribers see it immediately (optimistic), then on commit
await client.store.set("tasks.t1.status", "done");

Track who's online

Without a presence section in the schema, each user has one status string. Declare more fields, such as cursors, in the schema.

await client.presence.set({ status: "active" });

await client.presence.subscribe((users) => {
	users.forEach((u) => renderStatus(u.userId, u.data.status));
});

Call server actions

Actions are declared in the schema. Add this to the quick-start schema:

"actions": {
	"complete_task": {
		"params": { "task_id": { "type": "string" } },
		"required": ["task_id"],
		"returns": { "status": { "type": "string" } }
	}
}

The worker is a backend client connected with serviceAuth from @zyncbase/backend. Add a service secret and the authorization file to the config:

"authentication": {
	"anonymous": { "enabled": true },
	"service": { "secret": "${ZYNCBASE_SERVICE_SECRET}" }
},
"authorization": "./authorization.json"

zyncbase dev generates ZYNCBASE_SERVICE_SECRET when it is unset; in production, set it to at least 32 random bytes. Registering the action is not enough: the worker also needs store permission for the client's task. This authorization.json keeps the anonymous client's own-task writes and adds service writes:

{
	"namespaces": [
		{
			"pattern": "public",
			"storeFilter": true,
			"presenceRead": true,
			"presenceWrite": true
		}
	],
	"store": [
		{
			"collection": "tasks",
			"read": true,
			"write": {
				"or": [
					{ "$doc.owner_id": { "eq": "$session.userId" } },
					{ "$session.isService": { "eq": true } }
				]
			}
		}
	],
	"actions": [
		{
			"action": "complete_task",
			"invoke": true,
			"register": { "$session.isService": { "eq": true } }
		}
	]
}

Restart the server after editing the schema or config; connected clients reconnect automatically and load the new action list.

The worker runs in a separate process. Let the launcher start it, so it gets the server URL and the generated secret through its environment:

bunx zyncbase dev --config zyncbase-config.json --run "bun worker.ts"
// worker.ts
import { serviceAuth } from "@zyncbase/backend";
import { createClient } from "@zyncbase/client";

const worker = createClient({
	url: process.env.ZYNCBASE_URL ?? "ws://localhost:3000",
	auth: serviceAuth({
		secret: process.env.ZYNCBASE_SERVICE_SECRET ?? "",
		sub: "service:worker",
	}),
});
await worker.connect();

await worker.actions.handle("complete_task", async (ctx, params) => {
	const taskId = String(params.task_id);
	await worker.store.set(["tasks", taskId, "status"], "done", {
		if: {
			status: { eq: "active" },
			owner_id: { eq: ctx.userId },
		},
	});
	return { status: "done" };
});

The client creates the task and calls the action:

await client.store.set("tasks.t1", { status: "active" });
const { status } = (await client.actions.call("complete_task", {
	task_id: "t1",
})) as { status: string };

Use React hooks

import { createClient } from "@zyncbase/client";
import {
	ZyncBaseProvider,
	useListen,
	usePresence,
	useQuery,
} from "@zyncbase/client/react";

const client = createClient({
	url: "ws://localhost:3000",
	auth: { anonymous: true },
});
await client.connect(); // the provider does not connect

function Tasks() {
	const { data, isLoading } = useQuery("tasks", {
		where: { status: { eq: "active" } },
	});
	const { value: status } = useListen("tasks.t1.status");
	const { peers, publish } = usePresence();
	// ...
}

root.render(
	<ZyncBaseProvider client={client}>
		<Tasks />
	</ZyncBaseProvider>,
);

See sdk/typescript/client/README.md for typed schemas, Yjs integration, and the full API.

Examples

Each example is a complete app. Running them requires a source build — see BUILD.md for the commands.

  • Cordon Off — a multiplayer territory game: browser actions, a Bun simulation, and two independently sized chunk-table subscriptions.
  • Quorum — a live decision room with presence, private vote budgets, and an atomic reveal, built with the React bindings.
  • Verso — a Notion-like workspace with Yjs editing, page history, and presence carets.

Features

Store Path-based documents, filtered live subscriptions, conditional writes, atomic increments, batches of up to 500 ops
Presence Per-user and shared namespace state, schema-validated, ~60fps throttled, auto-cleanup on disconnect
Actions Sync RPC and async streams to backend workers, schema-typed params and results, round-robin routing
Yjs CRDT provider with chunked persistence, snapshots, compaction, and awareness ↔ presence mirroring
Auth JWT validation (HMAC, RSA, ECDSA, JWKS), short-lived tickets, session claim projection, anonymous access
Authorization Declarative JSON rules — namespace, collection, and action scoping with $session, $doc, $value, $namespace
Schema Strict validation, references with cascade/restrict/set_null, unique constraints, generated TypeScript types, startup migrations
Transport MessagePack over uWebSockets; binary WebSocket; integer-routed fields for compact payloads
Ops Online backup, verify, restore with safety copy; Litestream WAL replication; /health and /stats endpoints

Performance

Reference run on a 12-logical-CPU host:

Scenario CPU Memory Throughput Store p99
50k clients, 5 namespaces ~2.9–3.0 cores ~1.16–1.31 GB ~4.9–5.5M fanout msg/s 0.75–1.13 s
100k clients, 10 namespaces ~3.2–3.3 cores ~2.31–2.39 GB ~4.0–4.8M fanout msg/s 2.23–2.71 s

CPU, memory, and store throughput come from runs without latency probes; latency comes from separate runs with BENCH_LATENCY=1.

Caveat: these are synchronized-burst numbers, not sustained throughput or steady-state p99. The 100k result is ten namespaces of 10k clients, not one 100k-subscriber namespace.

Methodology and isolation checks: benchmark/README.md.

Production

Single-node operation is documented in OPERATIONS.md:

  • Consistent online snapshots, verify, and restore with a safety copy.
  • Cron/systemd scheduling, retention, offsite copies, and Litestream for second-level RPO.
  • Startup migrations with dry-run, pre-migration snapshots, and rollback.
  • storage.synchronous durability modes and WAL/checkpoint monitoring.

Boundary: backups and restores are covered; automatic failover and multi-node replication are not. Plan for manual recovery or add external automation.

When to use ZyncBase

Good fit

  • Internal tools, multiplayer games, live decision rooms, collaborative editors, and presence-heavy apps.
  • Self-hosted SaaS, community apps, and on-prem deployments where you need data ownership and predictable cost.
  • Workloads up to roughly 50k concurrent clients per node.

Use a managed service instead when you need

  • Global multi-region or automatic failover.
  • Zero-ops with no server to maintain.
  • Offline-first synchronization.

Managed realtime services (Firebase, Supabase, Convex, Liveblocks) are the better default when you need zero-ops or global edge. ZyncBase targets the other case: you want the realtime layer to be a file on a server you control, with predictable cost and no per-operation billing.

Documentation

I want to… Read
Build from source BUILD.md
Deploy, back up, restore, migrate OPERATIONS.md
See benchmark results and caveats benchmark/README.md
Use the TypeScript SDK sdk/typescript/client/README.md
Try a complete app examples/
Understand the internals specs/README.md
Contribute CONTRIBUTING.md
Use the logo or the name assets/brand/README.md
Cut a release RELEASING.md

License

ZyncBase is licensed under the Functional Source License, Version 1.1, ALv2 Future License (FSL-1.1-ALv2).

  • Use, modify, and self-host it for any purpose except a Competing Use — offering ZyncBase to others in a commercial product or service that substitutes for it or provides substantially similar functionality, such as a hosted ZyncBase service.
  • Every release becomes Apache 2.0 two years after it is published.
  • The zyncbase npm launcher and the release binaries ship under the same terms.
  • TypeScript SDKs (sdk/typescript/client/ and sdk/typescript/backend/): Apache License 2.0 — see sdk/typescript/client/LICENSE.

For full terms, see LICENSE.

About

Realtime database using Zig + SQLite + uWebSockets

Resources

Contributing

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages