Sync / Replicated state
Choosing document boundaries
A document (documentId) defines a single consistency boundary: one contract, one journal key, one outbox, and one commit order.
Enforce a rule inside Sync whenever one document's snapshot holds everything needed to judge it.
Inside each commit, the journal runs validate, authorize, reduce, and laws against that single document's authoritative snapshot under the document write lock (or via optimistic compare-and-set on D1). No external document or table is read inside that lock, and sequences advance independently per document.
| Rule concern | Hook | Client rejection |
|---|---|---|
| Document invariant (cap, order, total) | laws | Invalid with law ID and message |
| Caller permission | authorize | Forbidden with reason |
| Operation format | validate | Invalid ("Not a valid operation") |
A rule that fits: at most 100 todos
Because todos lives inside one document, capping its length is a document laws entry:
const CappedTodoSync = forApplication(App)
.withPrincipal<Principal>()
.make({
documentId: DocumentId.make('todos-capped'),
shared: Projection.pick(App.model.todos),
durable: MessageSet.make(App, [Message.CreatedTodo, Message.RenamedTodo]),
laws: {
atMost100Todos: {
holds: ({ after }) => after.todos.length <= 100,
message: 'A list holds 100 todos',
path: ['todos'],
},
},
})Laws evaluate the snapshot produced by any durable Message, so adding a DuplicatedTodo variant later enforces the 100-item cap automatically. If two devices add the 100th todo offline simultaneously, the server commits the first and rejects the second (Sync.isInvalidBy(refusal, CappedTodoSync.laws.atMost100Todos)). Devices also check laws locally at submit (LawBrokenError) as an early hint.
If existing live documents already exceed a newly added cap, use a monotone law that allows shrinking toward the limit, and audit existing snapshots beforehand with CappedTodoSync.judge(snapshot, snapshot):
const ShrinkingTodoSync = forApplication(App)
.withPrincipal<Principal>()
.make({
documentId: DocumentId.make('todos-shrinking'),
shared: Projection.pick(App.model.todos),
durable: MessageSet.make(App, [Message.CreatedTodo, Message.RenamedTodo]),
laws: {
atMost100Todos: {
holds: ({ before, after }) => after.todos.length <= Math.max(100, before.todos.length),
message: 'A list holds 100 todos',
path: ['todos'],
},
},
})A rule that crosses documents: unique usernames
If each user is a separate document (user-ada, user-grace), neither journal can inspect the other to enforce globally unique usernames. Choose an owner that sees every username:
| Strategy | Owner | When to use |
|---|---|---|
| Single shared username index doc | Sync authorize | Small index; single commit queue is acceptable |
| Server SQL unique constraint | foldkit-remote | Server-owned records; online claims |
| Per-name reservation document | Sync claim doc + confirmation | Claims work offline; confirm via mounted.committed |
For the reservation pattern, first commit Claim({ owner: ada }) to username-ada (whose authorize checks the snapshot has no owner yet), wait until mounted.committed confirms ada owns the claim, and then commit ChoseUsername('ada') in user-ada. Because the two documents commit independently, design cleanup or expiration for abandoned reservations.
Guidelines for splitting documents
- Keep co-constrained facts together: Any two fields governed by one invariant belong in one document.
- Separate independent workloads: Put each user's or workspace's independent data in its own document so snapshots stay small and cursors scale independently.
- Move cross-document uniqueness to Remote: Enforce cross-record uniqueness or balances in a server database via Remote mutations or a reservation document.