# durable-sync > Offline-first sync for Cloudflare Durable Objects. An append-only op log on the server, a durable outbox on the client. Zero dependencies, no Postgres, no long-running container, no WebSocket. TypeScript, MIT. durable-sync is a primitive, not a database. A Durable Object is already a single-threaded ordering point per user — the thing other sync engines need Postgres for — so the remaining work is an outbox, a cursor, and honesty about what has actually been acknowledged. Install: `npm i durable-sync`. Two entry points: `durable-sync/server` and `durable-sync/client`. ## Core model - Ops are opaque immutable facts: `{ opId, kind, payload }`. The log never interprets a payload. - The server assigns `seq`, monotonic within an `epoch`. Pushes are idempotent by `opId`. - The client holds a durable outbox (must be IndexedDB — until a push is acknowledged the outbox may hold the only copy of a write) and a per-device cursor `{ seq, epoch }`. - `apply(op)` is supplied by the caller and MUST be idempotent; an op can arrive more than once. - A pull carrying a new `epoch` makes the client replay from 0. This is how a reset log is survivable. - A push reply names the opIds the log holds (`stored`). The client drains exactly those, so an op the journal refused stays queued rather than vanishing. - Limits (`DEFAULT_LIMITS`, override `protected limits` on the subclass): opId 256 chars, kind 128, payload 256 KiB, 1,000 ops a push, 256 MiB a journal, pull pages of 5,000 ops / 4 MiB. An op over the per-op limits comes back in `rejected`; the client passes it to `onRejected(rows)` and drops it from the outbox. A full journal answers `full: true` and the client keeps what wasn't stored. The client sends at most `pushBatch` ops a push (default 1,000), oldest first, up to 50 pushes a sync, and shrinks to a `tooMany` reply's size. The app's route must cap request body size; the journal only sees the body after it's parsed. - Snapshots are optional and client-captured: the journal cannot fold the log because it never reads a payload, so a client folds and the journal stores the blob opaquely. The log is never pruned, so a snapshot is only ever an accelerator. ## Server API (`durable-sync/server`) - `SyncJournal extends DurableObject` (from `cloudflare:workers`) — extend and export from your Worker. Its methods are Durable Object RPC, called on the stub, reachable only from your own Worker: `push(ops)` → `{ seq, accepted, stored, rejected, full?, tooMany? }` (`tooMany: n` = refused unread, more than 4×`maxPushOps` sent; send at most n); `pull(since, withSnapshot?)` → `{ ops, seq, epoch, snapshot?, more? }` (a page; with `more`, `seq` is the last op sent and the client pulls again); `putSnapshot({ seq, epoch, blob })` → `{ ok, seq }`; `opsByKind(kind)` → `{ ops }`; `eraseJournal({ confirm: "erase" })` → `{ cleared, epoch }` (throws without that exact argument; irreversible; never forward it). A client reaches exactly the methods you forward from an HTTP route. There is no `fetch` router on the DO. - `SqlOpStore`, `MemoryOpStore` — implementations of `OpStore`. - `handlePush`, `handlePull`, `handleErase`, `handleOpsByKind`, `handleSnapshot` — the pure logic, testable without a Workers runtime. - Address one instance per user: `ns.get(ns.idFromName(userKey))`. - `handlePull(store, since, withSnapshot)` only returns a snapshot when `since` is 0 AND the caller asked — otherwise `ops` would be a tail and a client that can't restore would hold a history with a hole at the front. - `handleSnapshot` refuses a fold whose `epoch` isn't current (a client that missed a reset must not undo it), whose `seq` exceeds `maxSeq`, or that is older than the fold already held. ## Client API (`durable-sync/client`) - `createSync(options)` → `{ now, enqueue, start, capture, subscribe, getState, getServerState }`. - Options: `endpoint`, `outbox`, `cursor`, `apply`, `canPull`, `canWrite`, `stateKey`, `minIntervalMs`, `pollMs`, `headers`, `timeoutMs`, `snapshot`. - `snapshot?: SnapshotAdapter` — `{ capture(), restore(blob) }`. `restore` returns false (or throws) to refuse a blob it doesn't recognise, e.g. one an older build wrote; the client then replays the whole log, which is slow and always correct. Version your own blob. - `sync.capture()` folds the log and PUTs it. Nothing calls it for you — only the app knows when its state is settled rather than mid-edit. Behind `canWrite()`. Returns false rather than throwing. - `localStorageCursor(key)`, `memoryCursor()`, `memoryOutbox()` — adapters. - `start()` wires `visibilitychange` / `pageshow` / `focus` / `online` plus a poll, single-flighted and throttled; returns a stop function. Call it from an effect, not module scope. - `getState` / `subscribe` / `getServerState` are shaped for React's `useSyncExternalStore`. Pass `getServerState` as the third argument — an inline `() => ({})` makes React throw. - The transport is deliberately not exported: reaching past `createSync` bypasses `canWrite()`. ## The four failure modes it exists to prevent - `res.ok` is not evidence. An auth proxy with an expired session redirects to a same-origin login page; fetch follows it and reports 200. The reply's shape is validated before the outbox is drained. - A cursor only means something against the log that issued it. Every pull carries an `epoch`; a new one triggers replay from 0, otherwise a reset log leaves clients silently stalled forever. - Pulling is not always safe. `canPull()` defers a pull that could disturb work in progress. Pushing is always safe. - The gate must be the only door. `canWrite()` is checked first and `force` never skips it. ## What it does not do No conflict resolution (last writer wins per record). No live push (converges on next foreground). No auth — pair it with durable-auth (https://isaacrowntree.com/durable-auth/), passkey sign-in in one Durable Object. One `createSync` instance per identity. Nothing runs while the app is closed — Safari has no Background Sync. If you need those, use a real sync engine — Zero, Electric, or PowerSync — and the Postgres that comes with it. If you need merge, use a CRDT: Yjs or Automerge. ## Links - Docs: https://isaacrowntree.com/durable-sync/ - Comparison vs Zero, Electric, PowerSync, partysync: https://isaacrowntree.com/durable-sync/vs.html - Source: https://github.com/isaacrowntree/durable-sync - npm: https://www.npmjs.com/package/durable-sync - Sister library, passkey sign-in in one Durable Object: https://isaacrowntree.com/durable-auth/ - Used in production by Rampset, the offline-first barbell app it was extracted from: https://isaacrowntree.github.io/rampset/ (try it: https://liftlog.zackdesign.biz) - Write-up: https://zackdesign.biz/durable-sync/