Skip to content
clientdb

Search the docs

Find a page or section

Reference

The engine

createEngine ties your permissions and your database together: its options, hooks and retention, its lifecycle from install to prune, and writing from your server.

The engine is clientdb's server side. It checks every write from a device against your rules and applies it, keeps the sync log, sends each device the rows it may read, and works out what to add or remove when someone's access changes. You create it once and hand it to a route handler or a Node server.

The examples use the todo app from the quick start.

src/sync/engine.ts
import { createEngine } from "@clientdb/server";
import { hooks } from "./hooks";
import { permissions } from "./permissions";

export const engine = createEngine({
  permissions,
  hooks,
  retention: { log: "30d", archived: "90d" },
});
  • The schema comes from permissions: it's the one you passed to definePermissions(schema, …).
  • Creating the engine costs nothing: it opens its connection pool on first use (5 connections on serverless hosts such as Vercel), so a module-level engine is fine during next build.
  • Without database, it connects to DATABASE_URL and logs once that it did.
  • In development, one engine per database survives hot reloads of the route module, so edits don't leak connections. When the schema or rules change, the old engine is closed and replaced.
  • Rules are compiled when the engine is created; a rule the engine can't route to devices throws AccessCompileError right there. See Groups and routing.

Where rows live

  • Prisma's tables, when the schema comes from fromPrisma: the schema carries the table and column mapping, and the engine reads and writes your tables. Its own bookkeeping lives in clientdb_* tables that you add to schema.prisma; your tables are never altered.
  • Engine-owned tables otherwise: one m_<model> table per model, created by engine.migrate(). Schema changes then go through migrations.

Options

OptionMeaning
permissionsrequired: the rules from definePermissions
databasea Postgres URL, or a pg.Pool you manage yourself (default: DATABASE_URL)
directUrlthe direct, non-pooled connection migrate() needs for its lock (default: DIRECT_URL)
hooksonWriteRejected and onAccessRemoved, for logs and metrics (below)
retentionhow long the sync log and archived rows are kept (below)
bootstrapRowWarningwarn when one first load sends more rows than this (default 20,000; false turns it off)
cascadeRowLimitthe most rows one load brings through eager relations (default 5,000)
resyncInvalidateThresholdabove this many rows, engine.resync(model) tells clients to reload the model instead of sending each row (default 10,000)
migrationsversioned migrations for engine-owned tables, applied by migrate()
snapshotStorea cache for first loads, shared by everyone who reads the same rows: MemorySnapshotStore, FsSnapshotStore or your own
rowLevelSecurityadds Postgres row-level security per tenant on engine-owned tables, as defense in depth

Hooks

Hooks receive who did what and the outcome, never row data, so they are safe to log:

src/sync/hooks.ts
import type { EngineHooks } from "@clientdb/server";
import { logger } from "@/lib/logger";

export const hooks: EngineHooks = {
  onWriteRejected: ({ session, code, model, operation, failedBranches }) => {
    logger.warn("write rejected", { viewer: session.viewer, code, model, operation, failedBranches });
  },
  onAccessRemoved: ({ session, groups, reason }) => {
    logger.info("access removed", { viewer: session.viewer, groups, reason });
  },
};
  • onWriteRejected runs when the server refuses a transaction. code is the rejection code (Forbidden, Validation, ReadOnly, …), and failedBranches lists the labels of the rule's $.anyOf branches, none of which held.
  • onAccessRemoved runs when a session loses groups, so rows leave its devices. reason is "claim" when your session callback stopped granting a claim, and "rules" when a write changed what the rules give the viewer.

A hook that throws is logged and never breaks sync.

Retention

Without retention, the sync log, the ids of applied transactions and archived rows are kept forever. With it:

  • log: "30d" deletes sync-log entries older than 30 days (at least "1h"). A device last synced before the oldest kept entry loads afresh, and keeps its unsent changes.
  • transactions: "180d" deletes the ids of applied device transactions older than that (at least log; default the longer of log and "90d"). While an id is kept, a resend of its transaction is confirmed without applying it again. After that, a resend the server may have applied is refused with Stale instead.
  • archived: "90d" deletes rows of archivable models archived more than 90 days ago, with the rows that cascade from them, and the deletes reach every device. A row that a restrict relation still points at stays.

Periods are days ("30d") or hours ("12h"). Pruning runs on every clientdb migrate, hourly in a process that called engine.start(), and whenever you call engine.prune(), for example from a cron job on a serverless deployment:

src/app/api/cron/prune/route.ts
import { engine } from "@/sync/engine";

export async function GET() {
  const pruned = await engine.prune(); // { logEntries, transactions, archived: { project: 2 }, archivedKept: {} }
  return Response.json(pruned);
}

Lifecycle

CallWhat it does
npx clientdb migrate src/sync/engine.tsthe deploy step: runs engine.migrate(), then engine.prune() when the engine sets retention, prints what they did and closes the pool
npx clientdb migrate src/sync/engine.ts --dry-runprints what that would do, and changes nothing
engine.migrate()creates or checks clientdb's tables, applies pending migrations, adopts and reconciles rows written outside clientdb (Prisma), and re-routes models whose rules changed. It needs a direct connection: a pooler URL is refused
engine.migrationPlan()what migrate() and prune() would do, read without writing (what --dry-run prints)
engine.prune()applies retention now
engine.start() / engine.stop()the background sequencer, which live connections need (createSyncServer starts it for you)
engine.idle()resolves when every committed write has reached every connection (useful in tests)
engine.close()stops the engine and closes the pool it opened; await using engine = createEngine(…) does it for you

Until migrate() has run for the current schema and rules, the routes answer 503 NotMigrated and log why. With the HTTP and Next.js handlers you don't call start(): each request does the sequencing it needs. See Outbox and sequencer.

Writing from the server

clientdb doesn't run your business logic. Logic that must run on the server (charging a card, sending an email, checks across many rows) stays in your own server actions, tRPC procedures and API routes, which write to the database as they do today. The browser calls them through db.$action, which waits until the rows they wrote are on the device.

With Prisma, write with Prisma Client. The triggers bring every write to the devices that may see it, with no clientdb calls:

src/app/projects/actions.ts
"use server";
import { prisma } from "@/lib/prisma";

export async function clearDoneTodos(projectId: string) {
  await prisma.todo.deleteMany({ where: { projectId, done: true } }); // reaches every member's devices
}

Without Prisma, or for jobs that should go through clientdb, use systemWrite. It applies operations without permission checks, in one transaction:

scripts/seed.ts
import { engine } from "@/sync/engine";

const projectId = crypto.randomUUID();
await engine.systemWrite([
  { type: "create", model: "project", id: projectId, data: { name: "Launch" } },
  { type: "create", model: "todo", id: crypto.randomUUID(), data: { projectId, authorId: "user_1", title: "Write the announcement" } },
]);

Operations are create, update, delete, archive and unarchive. On engine-owned tables with several tenants, pass { tenant } as the second argument.

Three more calls cover writes clientdb didn't see:

CallWhen
engine.reconcile()compares Prisma's tables with what clientdb last sent and syncs every difference. migrate() runs it; you can also run it from a cron job
engine.changed({ todo: [todoId] })apps that can't install the triggers: say which rows you wrote, inside your transaction for atomicity
engine.resync("todo")after a bulk change in SQL: sends the whole model again (engine.resync() for every model)

See Writes from your server.

Inspecting the compiled rules

scripts/explain-rules.ts
import { compileAccess } from "@clientdb/server";
import { permissions } from "@/sync/permissions";

console.log(compileAccess(permissions).explain());

This prints every group kind, how each model's rows are routed, and which rows decide who belongs to which group. See Groups and routing.

Serving it