Skip to content
clientdb

Search the docs

Find a page or section

Under the hood

The sync model

How clientdb keeps every device's copy correct: one ordered log of changes, access groups, versions per row, and pending local changes.

Under the hood

You don't need this page to use clientdb. It explains how things work inside, for when you're curious or debugging. The short version is How it works, in 5 pictures.

The architecture in one picture

Text
 browser tab(s)                          server (Node / Next.js route handlers)       Postgres
┌───────────────────────────┐  pull/push  ┌─────────────────────────────────────┐  ┌──────────────────────────┐
│ db.issue.where(…)  (live) │ ──────────▶ │ permissions → compiled access plan  │  │ app tables (yours/Prisma)│
│ optimistic tx, undo       │  or WS live │ write: check rules, route rows to   │─▶│ routing metadata         │
│ IndexedDB, multi-tab      │ ◀────────── │   groups, append to outbox          │  │ clientdb_outbox → _log   │
└───────────────────────────┘  per-viewer │ sequencer: outbox → ordered log     │  │ clientdb_viewer_groups … │
                                 deltas    │ fanout: project log onto viewers    │  └──────────────────────────┘
                                           └─────────────────────────────────────┘

A write travels like this:

  1. A client applies a transaction optimistically and sends it.
  2. The server checks the write rules, writes the rows, computes their routing groups and any viewer membership changes, and appends the resulting actions to the outbox, all in one Postgres transaction.
  3. The sequencer moves committed outbox entries into the ordered sync log.
  4. Each connected or pulling client receives the log entries projected for its viewer. Its own transaction comes back as confirmed, or as rejected with a reason.

Sync log and sync ids

Every change becomes part of one append-only, gap-free log (clientdb_log). Entries are numbered by a monotonically increasing sync id, one entry per write transaction. Sync ids follow commit order, so "everything after sync id N" is always well defined. A client stores the last sync id it applied (db.$lastSyncId), and resuming means asking for everything after it.

Groups and routing

Read rules compile into group kinds, such as team.member(teamId) or team.admin(teamId). A group is a kind applied to one id, written as a key like team.member|<teamId>.

  • Every synced row is tagged with the groups whose members may read it: its routing groups.
  • Every viewer has a set of groups they belong to.
  • A row reaches a viewer exactly when the two intersect.

Membership comes from rows: a teamMember row with userId = viewer puts the viewer in team.member|<teamId>. So the server knows which viewers a write affects without evaluating rules per viewer. A claim is a group too (claim:staff): the session callback grants it to a session, with no rows involved. Details in Groups and routing.

A restricted field has its own read rule, so the server also records which groups may read it. A viewer in the row's groups but in none of the field's receives the row with that field left out (undefined on the client).

Move-in and move-out

Access changes in two ways, and both produce precise deltas:

  • A membership change (promotion, removal, new member) sends the viewer a groups action. For added groups the viewer receives their rows; for removed groups the client evicts every row that no longer intersects its groups. A claim the session callback stops granting works the same way.
  • A row move (a hidden issue, a changed team) re-tags the row. Viewers who gain it receive the full row; viewers who lose it receive an id-only delete marked moved.

See Move-in and move-out.

Bootstrap, catch-up and lazy loads

  • Bootstrap is a streamed NDJSON response: meta (sync id, groups, schema hash, and the session: viewer, claims, read-only), then the rows of every eager model, then the end marker. db.$ready() resolves once they are usable.
  • Catch-up happens on reconnect or pull. It sends the group delta, a snapshot of newly granted groups, then the log range compacted to the latest action per row, so clients never see superseded intermediate states.
  • Lazy loads fetch rows of a lazy model by a load key the first time a read needs them: an id (get(id)), a foreign key (issue.comments), a unique field (where({ email })), or the whole model (db.comment.all). Reads in the same tick share one request (POST …/partial). preload() starts a fetch early, as an optimisation. The client remembers which load keys it holds completely, and deltas keep them current.
  • Eager-relation cascades: when a load brings a parent row, the children of its eager: true relations come in the same response, and the load keys they complete (issue.comments of each issue) are marked as held. A cascade stops at 5,000 rows; what it didn't deliver loads when it's read.
  • Server queries (db.issue.query({ where, orderBy, limit })) ask POST …/query for one page of matching rows the viewer may read. The rows become ordinary rows on the device; the query keeps the page boundaries.
  • Eviction: with eviction: { maxRows }, the client drops the loads used longest ago as units once it holds more rows, and forgets that it held their load keys. Loads holding anything observed (a collection on screen, a row whose fields a component reads), eager models and rows with unsent writes stay.
  • Invalidation: after a bulk server-side change above a threshold, the server sends invalidate and the client re-fetches that model.
  • Retention: with retention.log, the server deletes old log entries. A client that last synced before the oldest kept entry gets a reset and loads afresh, keeping its unsent writes. Applied transaction ids are kept for retention.transactions (90 days by default): a write is applied at most once, and one resent after its id is gone that the server may have applied is rejected with Stale.

Revisions and tombstones

Every row has a revision drawn from one database sequence, bumped on each write and each routing change. The client applies a server row only if its revision is newer than the one it holds, so a row that arrives through two groups, or twice, is never applied twice or out of order. Hard deletes leave a client-side tombstone, so a stale upsert can't resurrect the row. Evictions caused by access changes are not tombstones: if access comes back, the row is delivered again.

Optimistic writes and rebase

The client keeps, per row, the server base and the stack of pending transactions that touch it. The visible row is the base with pending operations replayed on top. When a newer base arrives, pending writes are rebased onto it, so your local edit stays visible on top of other people's concurrent changes. See Conflicts and rejections.

Schema hashes

The schema has a stable hash (also per model and per field) over fields, relations including onDelete and eager, and load modes. A client whose hash differs from the server's gets SchemaOutdatedError and must reload: by design there is no support for old clients. See Migrations.

The layers of the client

  • Replica (@clientdb/core): pure and deterministic. It takes local transactions and server packets and returns change sets. No IO, no reactivity. Specified in the protocol and spec.
  • ClientView (@clientdb/client): entities, live queries and reactive atoms, updated from change sets.
  • Drivers: the sync client (HTTP and WebSocket), IndexedDB storage and multi-tab coordination.

The Swift client follows the same split.