Sync / Replicated state

3. The server: an exchange over the journal

A replica and server communicate through an exchange request/response cycle:

  • Request: The replica sends its cursor, its pending operations, and the epoch it last observed.
  • Response: The server returns newly committed operations after cursor, acknowledged and rejected IDs (with typed refusals for rejected operations), an optional checkpoint { cursor, model } if history was compacted below the replica's cursor, a more flag for paginated catch-up, and the server's epoch.

serveJournal from foldkit-sync/journal implements this exchange over Journal:

ts
import { Effect } from 'effect'
import { ActorId, Journal, OpId } from 'foldkit-durable'
import type { SocketLike } from 'foldkit-sync'
import { serveJournal } from 'foldkit-sync/journal'

const server = Effect.gen(function* () {
  const journal = yield* Journal.make({
    ...TodoSync.journalContract(),
    file: 'todos.sqlite',
    opId: operation => OpId.make(operation.opId),
    actorId: (principal: Principal) => ActorId.make(principal.actorId),
    validate: ({ operation, cursor }) => {
      if (operation.baseCursor > cursor) throw new Error('Operation is ahead of the server')
    },
  })
  return (socket: SocketLike, principal: Principal) =>
    serveJournal(socket, {
      sync: TodoSync,
      journal,
      principal,
      admit: () => principal.canWrite,
    })
}).pipe(Effect.scoped)

For an in-process transport, use journalExchange; call journal.recover (settle) after exchanges when updating downstream stores. The server preserves six invariants:

  • Verify cursors first: If a replica's cursor exceeds the journal's cursor, fail before appending so acknowledgements are never lost.
  • Reject deterministic failures, retry storage failures: Policy denials, decode errors, and ID collisions return in rejected so replicas drop them; transient JournalError storage faults fail the exchange so replicas retry safely.
  • Deduplicate retransmissions: append acknowledges previously committed opIds (Committed or compacted AlreadyCommitted) without re-applying them.
  • Paginate and checkpoint: Long-offline devices catch up via more: true pages, or adopt a load checkpoint when their cursor falls below compaction.
  • Track history epochs: Sending a mismatched epoch resets the replica cleanly from 0 after a server reset.
  • Authenticate on the connection: principal comes from the authenticated socket rather than client payloads, Durable pins each replica ID to its first committing actor, and serverOnly Messages are rejected if sent from any client replica.

The server's own writes, and work after a commit

Use serverJournal (appendAsServer(message, { key })) for server-originated facts such as webhooks so redelivery commits at most once. For side effects triggered by commits (receipts, provider calls, follow-up server Messages), register a reaction that advances a stored cursor from commit N after recording the external effect in the ledger:

  • At-least-once external calls: Because SQLite/D1 and external APIs share no distributed transaction, crashes between an API call and recording its completion re-run the call with the same stable idempotency key.
  • Once-committed follow-ups: Appends emitted by a reaction derive deterministic IDs from the reaction and trigger ID so duplicates acknowledge cleanly.

Failed reactions wait on a stored backoff without blocking other reactions, and permanently rejected runs (or runs failing eight times over at least an hour) are parked for inspection so compaction continues. Long-lived servers fork follow, Durable Objects schedule alarms, and stateless Workers run waitUntil plus cron triggers. See Work after a commit: reactions and examples/sync.