Under the hood
Protocol and spec
The language-neutral contract between the server and every client: wire protocol v2, sessions, load keys, server queries, replica semantics, the schema IR and conformance vectors.
Under the hood
You don't need this page to use clientdb. It's the contract for anyone writing another client, or debugging what goes over the wire.
Everything a client implementation needs lives in the repo's spec/ folder. The TypeScript client (@clientdb/core), the Swift client and the server's write checks are all tested against it. This page summarizes it; spec/protocol.md is the full text.
| File | What |
|---|---|
spec/protocol.md, spec/protocol.schema.json | Wire protocol v2: endpoints, NDJSON messages, encodings, sessions, rejections |
spec/replica.md | Replica semantics: rows, replaying pending changes, expand (cascades, setNull, restrict), drafts, undo, server input, change sets |
spec/schema-ir.schema.json, spec/schemas/*.json | The schema IR (clientdb.schema.json) |
spec/vector.schema.json, spec/vectors/*.json | Conformance vectors: steps plus the exact observation after each |
Wire protocol v2
JSON everywhere; streams are NDJSON (one JSON value per line). PROTOCOL_VERSION = 2 is sent in meta, the client's hello and pull requests. A server answers a mismatched version with an error (code: "ProtocolMismatch"). A schema hash mismatch makes the client stop with SchemaOutdated and reload.
Encoding
- Rows down (server → client) are arrays in schema field order,
idfirst:upsert.row. Bootstrap rows are wire rows,[...fields, revision, groups], followed byfieldGroupsfor models with restricted fields. - Restricted fields reach only the viewers their field rule allows. Every row of a model with restricted fields carries
fieldGroups: the restricted fields the viewer reads, each with the viewer's groups through which it reads it. A restricted field missing fromfieldGroupsis hidden: its slot in the row is null, and the client stores it as undefined, not as null. - Operations up (client → server) are keyed by field name. The server checks every name, so a client built against another schema version can't silently write the wrong column.
- Timestamps are epoch milliseconds; decimals are strings (
"49.00"); JSON fields carry any JSON value. - Generated fields are filled in by the database. A client's
createcarries them as null and itsupdatenever names them; the server refuses either otherwise (Validation). The upsert of the created row carries the generated values.
Endpoints
All under the base URL (…/sync, /api/sync by default).
| Request | Response |
|---|---|
GET /bootstrap | NDJSON: meta; per eager model, rows* and done; then the eager-relation cascade under those rows (rows* per model) and one covered with its load keys; then end. ?models=a,b sends only those models (a client refetching models whose hash changed), without a cascade. ?load=lazy sends only meta and end |
POST /pull, PullRequest | NDJSON: meta; actions* (group changes, rows of newly granted groups with their cascade, the log since since compacted to the latest action per row; the first actions line carries the cascade's covered); end with syncId, confirmed and rejected. Or a single reset (see Starting over). Pushed transactions apply first |
POST /push, { clientId, transactions } | { results: [{ clientTransactionId, ok, duplicate?, rejection? }] } |
GET /partial?model=&field=&key= | LoadResult, { actions, covered }: upserts for the visible rows of (model, field = key) (or the whole model without field) and their eager-relation cascade; covered lists the load keys the response delivered completely. field must be a load key of the model |
POST /partial, { loads: [{ model, field, key }] } | the same for up to 1,000 loads at once (a client's reads in one tick), rows deduplicated |
POST /query, QueryRequest | QueryResult, { actions, covered, ids, cursor }: one page of a server query. Outside the model's query rules: 403 with code: "Forbidden"; malformed or over maxLimit: 400 with code: "Validation" |
WS /live | the client sends hello, then transactions, token (a renewed sync token) and sync barriers; the server sends hello (the verified session) first, then packet, session, synced and error; or reset after its hello, and closes the socket |
GET /token | { token, expiresAt }: a short-lived sync token carrying the verified session (servers with tokens) |
With inline sequencing (the default for HTTP servers), bootstraps, pulls, loads and queries first order pending changes, so a server without a background process still answers from current data.
Sync barriers
A client that must see everything the server committed before some moment ($sync(), the sync after $action) sends a request that starts after that moment: a pull over HTTP, or on a live socket a barrier, { t: "sync", id }. The server answers { t: "synced", id } once the transactions the socket sent before the barrier are applied (their confirmations or rejections are sent first), pending changes are ordered, and every log entry up to the head at that point is delivered on this socket. When the socket closes before synced, the client pulls over HTTP instead.
Starting over
A syncId is an opaque log position (the entry's number and a random nonce, such as "42-k3J9xq0a", or "0" before the first entry); clients send it back unchanged. The server catches a client up from its since through the log. It can't when since is ahead of the log's head, when the log no longer holds that entry with the same nonce (the database was restored from a backup and wrote other entries since), or when since is older than the oldest entry it keeps (retention.log pruned the entries in between). It then answers a pull with a single reset line, and a socket's hello with reset before closing the socket. The client bootstraps again, replaces the server state of the models it bootstrapped, reloads the loaded parts of the others (taking the server's rows whatever their revisions), then pulls or reconnects from the new syncId. The server applies none of the transactions a refused pull or socket carried. The client's unsent and unconfirmed transactions stay in the outbox and are sent again from the new position.
Resent transactions
A client sends each transaction until it is confirmed or rejected, so the server may receive one it already applied (its answer was lost). It keeps the id of each applied transaction, (clientId, clientTransactionId), for retention.transactions, and confirms a resend without applying it again. Each transaction also carries a base: the syncId the client had when it first tried to send it (stored before it goes out, and forgotten again when the server answers that request with reset). The server applies a transaction at or after its base; when it prunes ids, it moves a horizon past the highest head at which a pruned id was applied. A transaction whose id is gone and whose base is below the horizon may have been applied, so the server refuses it with Stale instead of applying it twice. In practice that is a write the client kept trying to send, unconfirmed, for longer than retention.transactions (attempts while offline count): it is rejected and reported like any other, never applied twice and never dropped silently.
Sessions
Auth: HTTP requests send Authorization: Bearer <token>. Browsers send ?token= on the WebSocket, because they can't set WebSocket headers; native clients send the header there too. The server reads ?token= on WebSocket upgrades only. POST bodies are Content-Type: application/json (415 otherwise). Cookies work for same-origin HTTP and same-origin WebSockets; a WebSocket from another origin needs a sync token or an origin that cors allows (403 otherwise). The server derives the session from these credentials only, and reports it in every meta and in the WebSocket hello:
viewer:{ model, id }for a row of the viewer model, ornullfor anonymous sessions;claims: the names of the claims granted to the session, sorted;readOnly: the server refuses the session's writes. Anonymous sessions are always read-only.
Clients never send their viewer. Stored local data belongs to the viewer it was stored for, and a client that sees another viewer deletes it. A client refuses writes locally while its session is read-only.
A claim grants the session a global group, claim:<name>|*; a session's groups are the groups its rules give it plus those of its claims, computed again on every request. A sync token (GET /token) is an HS256 JWT with audience clientdb-sync carrying the whole session: sub (absent for anonymous sessions), tenant, claims, readOnly, iat and exp.
A live WebSocket checks its session again while open. Opened with a sync token, the client sends { t: "token", token } with a new token before the current one expires, and the server takes its session; a token that expires without renewal closes the socket. Opened otherwise, the server asks the app for the session again with the upgrade request, once per token lifetime (default 5 minutes). When the claims or the read-only flag changed, the server sends { t: "session", viewer, claims, readOnly }, then a packet with the group changes and the rows of granted groups. When the session ended, belongs to another viewer or its token expired, the server sends { t: "error", code: "Unauthorized" } and closes the socket with code 4401.
Rejections
A rejected transaction comes back in rejected as { clientTransactionId, code, message }, and its changes are undone on the client.
| Code | Meaning |
|---|---|
Forbidden | a rule refused a write. The message names the branches that failed; for an update, also the fields it refused (todo.update isPrivate (author: no, admin: no), or (not in any update group)) |
ReadOnly | the session is read-only (a readOnly route, a read-only session, or anonymous): its transactions are refused before anything is read or written, on /push, /pull and the WebSocket alike |
AccessLost | the client lost a row the transaction wrote before sending it (issued on the client; the whole transaction is refused) |
Conflict | a created row already exists, or rows still reference a row being deleted through a restrict relation |
Validation | malformed operations, unknown fields, values of the wrong type, generated fields |
SchemaOutdated | the transaction was written against another schema version |
NotFound | the row the operation names doesn't exist, or the viewer can't read it (refused alike, so rejections never reveal hidden rows) |
Stale | the server may have applied the transaction already and no longer keeps its id (see Resent transactions); it is not applied again |
Messages
// What a client sends, inside { clientId, clientTransactionId, operations }
type Operation =
| { type: "create"; model: string; id: string; data: RowData }
| { type: "update"; model: string; id: string; data: RowData }
| { type: "delete"; model: string; id: string }
| { type: "archive"; model: string; id: string; archivedAt: number; archivedBy: string | null }
| { type: "unarchive"; model: string; id: string }
| { type: "restore"; rows: { model: string; data: RowData }[] }; // undo of a delete
// What the server sends
type SyncAction =
| { type: "upsert"; model: string; id: string; revision: number; row: unknown[]; groups?: string[]; fieldGroups?: FieldGroups }
| { type: "delete"; model: string; id: string; revision: number; moved?: boolean }
| { type: "invalidate"; model: string }
| { type: "groups"; add: string[]; remove: string[] };
type FieldGroups = Record<string, string[]>; // restricted field → the viewer's groups that read it
interface SyncPacket {
syncId: string | null;
actions: SyncAction[];
covered?: LoadKey[]; // load keys the packet delivers completely
confirmed?: string[];
rejected?: { clientTransactionId: string; code: RejectionCode; message: string }[];
}
interface LoadKey {
model: string;
field: string | null; // null: the whole model
key: unknown;
}
// Resume point: the WebSocket hello, and the base of a pull request
interface Hello {
protocol: number;
clientId: string;
since: string | null; // last applied sync id; null needs a bootstrap
knownGroups: string[];
clientIds?: string[]; // other tabs' client ids this connection carries
}
interface PullRequest extends Hello {
since: string;
transactions?: WireTransaction[]; // pushed before pulling
pending?: string[]; // transaction ids the client awaits; applied ones are confirmed
}What clients rely on
syncIdvalues increase in commit order, and log entries are gap-free.- At most once: each transaction applies at most once per
(clientId, clientTransactionId); resends are confirmed without effect while the server keeps the id, and refused asStaleonce it pruned an id they may have used (see Resent transactions). - A client's own transactions come back in
confirmedorrejected, in the packet that contains (or follows) their effects. - Upserts always carry the full row as the viewer may read it.
groupslists the viewer-visible groups of the row;fieldGroupsthe restricted fields the viewer reads, with their groups. - Restricted fields follow access. A row may arrive again with the same revision when a newly granted group reveals a restricted field; the client replaces the row's values and
fieldGroups. When agroupsaction removes every group through which the viewer reads a restricted field, the client hides the field and keeps the row. An update that changes a restricted field the viewer can't read is refused (Forbidden); creates may set them. - Deletes:
moved: truemeans the row left the viewer's groups. Without it, the row was deleted on the server, and the rows that cascade from it with it. groupsactions change the session's groups; the rows of newly granted groups follow in the same response or packet, with their eager-relation cascade. After agroupsaction, the client treats what it learned under the old groups as unverified: lazy loads read as incomplete and load again, and answered server queries are asked again.invalidateasks the client to re-fetch a model through/partialwithoutfield.
Load keys and eager-relation cascades
A load key { model, field, key } names every row of model with field = key the viewer may read; field: null names the whole model. A model's load keys are id, its unique fields and its foreign keys (loadKeys in the schema IR).
Whenever a load delivers a row (a requested load, a whole-model load, or an eager row of a bootstrap), the server also delivers the row's children through eager: true relations, and theirs in turn. The cascade goes down only; the rows a cascaded child points at through other relations come along as single rows; it stops at a model already on its path and at a bootstrap's eager models; and it delivers at most cascadeRowLimit rows per response (default 5,000). covered lists the load keys the response holds completely; parents a cut cascade went through are left out, and the client loads them when read.
A client holds the rows of eager models wholly, and of lazy models only those it loaded. An upsert for a row of a lazy model it doesn't hold is kept only when a complete load matches it; otherwise the client ignores it, so live updates don't pull unrequested rows onto the device. Rows it holds keep updating, and deletes always apply.
Server queries
POST /query answers one page of rows matching a predicate, in order:
{ "model": "todo", "where": [{ "field": "title", "op": "contains", "value": "launch", "mode": "insensitive" }], "orderBy": ["createdAt", "desc"], "limit": 50, "after": null }whereconditions must all hold. Operators:is(null: the field is null),in,gt,gte,lt,lte, and on text fieldscontains,startsWith,endsWith, matched literally.mode: "insensitive"(text operators only) compares lowercased. Booleans takeisandin; JSON fields nothing.orderByis[field, "asc" | "desc"]or null; ties, and queries without it, are ordered byid.limitis at most the model'squery.maxLimit;afteris the previous page'scursor.- The model's
queryrules list the fields and operatorswheremay use. Restricted fields can't be listed. Results are limited to rows the viewer may read.
The answer is a LoadResult plus ids (the page's rows in order) and cursor ({ value, id } while more rows match, else null). The client applies it like any load and cuts the query's result at cursor, so rows the server hasn't sent yet never show between pages.
Replica semantics
The replica is the state machine on the device that every client implements. It is pure: no IO, clocks, randomness or reactivity. Shells feed it local transactions and server packets and apply the change sets it returns.
Each known row has a base (the last server-confirmed row), a revision, its groups, the pending transactions that touch it, and an optional draft. The visible row is the base with pending effects replayed, then the draft:
replay(row, withDraft):
exists = base != null; data = copy(base ?? data)
for tx in row.transactions, for effect of tx on row (in order):
create(d) → exists = true; data = copy(d)
delete → exists = false
set(f→v) → if exists: data[f] = v
if withDraft and draft and exists: apply draft
return (exists, data)Key rules from spec/replica.md:
expandturns each operation into row effects and undo steps. A delete visits cascading children recursively, setssetNullreferences to null, and fails onrestrictreferences.- Server input: an upsert applies only if its
revisionis newer; a real delete records a tombstone and removes cascading children; amoveddelete just drops the base, and keeps older copies of the row (an answer computed before the move) out; removed groups remove rows whose groups no longer overlap, rejecting their unsent transactions withAccessLost. - Undo builds inverse operations from the recorded steps, skipping fields whose current value isn't what the transaction wrote, and reports them.
- Reload re-ingests stored rows, then re-commits each outbox transaction and expands it again against the loaded rows.
Conformance
- An implementation conforms when it reproduces every vector's observations. The TypeScript runner is
checkVectorin@clientdb/core; Swift runs the same files. - The server is held to the same
expandrules: its test suite replays the vectors' local commits as system writes against Postgres and compares the resulting rows. - CI regenerates the vectors (
yarn spec:generate) and fails if they differ from the committed files, so a change in behavior shows up as a vector diff in review.
Writing another client
- Export the schema IR with
exportSchema(schema). - Implement the replica from
spec/replica.mdand run every vector inspec/vectors/. - Implement the shells: filling in new rows (defaults, generated fields), the sync driver for the endpoints above, storage, and your platform's reactivity.