●  Sync engine v0.1 · local-first · edge-native

Shared state for people and their agents.

syncbase is a database that runs inside your app and at the edge. Reads come from local memory. Writes apply instantly. Every change reaches every collaborator — browser tab, phone or agent — in one hop.

Read the docs → $bun add @syncbase/client
Rust core · WASM + OPFS Durable Objects + R2 docs.md for agents
0ms

Reads and optimistic writes resolve against the local replica. No spinner, no loading state.

1hop

From one client's write to every subscriber: edge fan-out, sequencer, push. No polling.

<1MB

Memory to answer a lookup from immutable segments with HTTP range reads.

0DBs

Durable Objects and R2 are the whole backend. Nothing to provision, replicate or vacuum.

01 — The problemWhy a sync engine

Your app no longer has one user per screen.

A person opens a task. Three agents start working on it. A teammate leaves a comment while the person rewrites the plan the agents are executing. Everyone is a writer, and the agents write fast, in parallel, for minutes at a time.

Request–response apps were built for one writer who waits. Bolt agents onto them and four things break.

01.1

Stale views

The agent finished two minutes ago. The tab still says running, until someone refreshes.

GET /runs/8f2c status: running agent status → done GET /runs/8f2c (cached)
01.2

Lost writes

The agent saves the row with its new status. The person saves the same row with a new title. The last request wins the whole row.

alice PUT {title, status:running} agent PUT {title:old, status:done} alice's title is gone
01.3

Waiting

Every click is a round trip. Every agent step triggers a refetch of everything that might have changed.

click ─── 240 ms ───▶ render step ─── refetch ×6 ──▶ render
01.4

Glue

Cache keys, polling, sockets, retry queues and an offline mode: five systems, each slightly wrong about the current state.

cache ∪ poll ∪ ws ∪ retry ∪ offline ≠ truth
The fix

A sync engine replaces all of it with one primitive: a replicated database with a single order of events. Every client holds the data it may see, writes locally, and converges on the same sequence — people and agents alike.

02 — ArchitectureClient · Edge · Sequencer · Storage

The database lives where the user is.

The same Rust engine runs in the browser, in Workers and on mobile. One sequencer per workspace orders writes; fan-out servers at the edge push them out; immutable segments in R2 hold everything else.

Client

Replica

  • Rust → WASM in a Worker
  • Segments + WAL on OPFS
  • Optimistic overlay
  • Reactive models
SBW1 / ws
Edge · Durable Object

Fan-out

  • Hibernated sockets
  • Sync-group filtering
  • Presence · CRDT relay
  • Write coalescing
batch
Durable Object

Sequencer

  • One per workspace
  • Validate · run commands
  • Assign seq · hot WAL
  • Flush L0 segments
range read
R2 · edge cache

Segments

  • Immutable SBSEG001
  • Posting-list indexes
  • Compacted out of band
  • Bootstrap by range read
1

Write locally

The mutation lands in the optimistic overlay and the UI renders it in the same frame.

issue.save()
2

Sequence

The sequencer checks sync groups and policies, runs commands authoritatively and assigns the next seq.

validate · apply · seq++
3

Fan out

Fan-out pushes the batch only to clients whose sync groups and loaded slices match.

groups ∩ row.groups
4

Rebase

Each client drops its overlay, applies the batch in order and replays what is still pending. Intent survives.

drop · apply · replay
5

Compact

Hot rows flush to immutable segments in R2. New clients bootstrap from the edge cache, never from a database.

L0 → L1 · CAS manifest
03 — Built for agentsSix primitives

Agents are clients, not cron jobs.

An agent holds a scoped replica, writes through the same API as the UI, and shows up live in front of the person who started it. syncbase gives it the primitives to do that without stepping on anyone.

03.1 · Same SDK

One client, every runtime

Browser, Bun, Node or a Worker. The agent's writes render in the user's tab the moment they are sequenced.

new SyncedStore({ userId: "agent:reviewer" })
03.2 · Overlays

Propose, then promote

Agents draft into a named overlay on top of live data. A person reviews the diff; promote or discard it in O(1).

createOverlay("triage") → promoteOverlay()
03.3 · Commands

Intent, not values

Named commands run optimistically on the client and authoritatively on the server. Ten agents incrementing a counter get the right sum.

runCommand(recordUsage, run, { tokens: 1840 })
03.4 · CRDT fields

Stream while they edit

Token streams go into a CRDT field while a person edits the same text. Deltas merge commutatively and relay peer-to-peer.

@crdtField(yjs) accessor plan
03.5 · Presence

See what it is doing

Ephemeral awareness frames — cursors, "running tests", "reading auth.ts" — travel through the edge and never touch storage.

setAwareness("run:8f2c", bytes)
03.6 · Sync groups

Least privilege by routing

Every row carries sync groups. An agent's token lists the groups it may touch; it never receives anything else.

syncGroups: ["proj:42"]
04 — The APITypeScript · Stage 3 decorators

Models in, live objects out.

Declare classes. Mutate fields. Call save(). The rest — persistence, ordering, conflict resolution, fan-out — is the engine's job.

models.ts
import { Model, model, field, hasMany, crdtField, createYjsCodec } from "@syncbase/client";
import * as Y from "yjs";

@model({ name: "Run", loadStrategy: "partial", syncGroups: (r) => [`proj:${r.projectId}`] })
export class Run extends Model {
  @field({ indexed: true }) accessor projectId = "";
  @field() accessor status: "queued" | "running" | "done" = "queued";
  @field({ type: "number" }) accessor tokensUsed = 0;
  @hasMany(() => Step, { foreignKey: "runId" }) accessor steps!: ReactiveCollection<Step>;

  // Streamed by the agent, edited by the human — merged, never overwritten.
  @crdtField(createYjsCodec(Y)) accessor plan!: CrdtFieldController<Y.Doc>;
}
RunView.tsx
import { observer, useCollection, useAwareness } from "@syncbase/react";

export const RunView = observer(({ run }: { run: Run }) => {
  const steps = useCollection(run.steps);          // suspends until hydrated
  const { peers } = useAwareness(`run:${run.id}`); // who is here, human or agent

  return (
    <section>
      <header>{run.status} · {run.tokensUsed} tokens · {peers.length} watching</header>
      {steps.map((s) => <StepRow key={s.id} step={s} />)}
      <button onClick={() => { run.status = "done"; run.save(); }}>
        Mark done {/* renders in 0 ms, syncs in one hop */}
      </button>
    </section>
  );
});
agent.ts
// An agent is just another client. Bun, Node or a Worker.
const store = new SyncedStore({
  models: [Run, Step],
  commands: [recordUsage],
  userId: "agent:reviewer",
  syncGroups: ["proj:42"],                       // sees only what its token grants
  transport: new WebSocketSyncTransport({ baseUrl, token }),
});
await store.connect();

store.createOverlay("review");                   // propose, don't overwrite
await store.applyLocalToOverlay("review", {
  op: "patch", model: "Run", id: run.id, fields: { status: "done" },
});
await store.runCommand(recordUsage, run, { tokens: 1840 }); // intent, not a value

const plan = run.plan.doc.getText("plan");
for await (const t of llm.stream(prompt)) plan.insert(plan.length, t);
worker.ts
// One Worker, two Durable Objects, one R2 bucket. No database.
export class WorkspaceSequencerDO { /* new WorkspaceSequencer({ sql, r2, wasm, … }) */ }
export class WorkspaceFanoutDO   { /* new WorkspaceFanout({ … }) */ }

export default {
  fetch: (req: Request, env: Env) =>
    createSyncbaseWorker<Env>({
      schema: buildSchemaDescriptor([Run, Step]),
      segmentCodec: createWasmSegmentCodec(wasm),
      authenticate: createJwtAuthenticator({ getSecret: (e) => e.JWT_SECRET }),
      getR2: (e) => e.SYNCBASE_R2,
      getSequencer: (e, ws) => sequencerClient(e.SEQUENCER, ws),
      getFanout: (e, ws, shard) => fanoutClient(e.FANOUT, ws, shard),
      upgradeToFanout: (req, e, auth, shard) => forwardSocket(e.FANOUT, req, auth, shard),
    }).fetch(req, env),

  scheduled: (_e: ScheduledEvent, env: Env) => compactAll(env), // L0 → L1 in R2
};
05 — Why syncbaseDifferences that matter

Linear's architecture, in the open.

Linear showed that a sync engine with partial loading, sync groups and a purpose-built segment store makes software feel instant. Nobody shipped that design as a library. syncbase does — and builds it on the edge instead of a database.

05.1

One format, edge to disk

The same immutable segments live in R2 and in the browser's OPFS. A cold start is a cacheable range read, not a query.

05.2

No database to run

Durable Objects hold the order of events; R2 holds the data. No Postgres, no logical replication, no connection pool.

05.3

Three merge rules, one model

Per-field last-writer-wins for records, semantic commands for intent, CRDT fields for text. Chosen per field, not per product.

05.4

Partial by design

Sync groups decide what a client may see; index subscriptions decide what it has loaded. Large workspaces stay light.

05.5

Drafts are a primitive

Named overlays share the confirmed base without copying it. Agent proposals and previews cost nothing until promoted.

05.6

One Rust core, verified

The engine runs as WASM in browsers and Workers, and through UniFFI on iOS and Android. Checked with state-machine property tests, crash-consistency tests and Quint specs.

syncbase Postgres syncZero · Electric Document CRDTsJazz · Automerge · Liveblocks Event-sourced SQLiteLiveStore
Source of truthIts own engine on Durable Objects + R2Your PostgresDocuments merged on every peerAn event log per store
WritesOptimistic and offline, rebased by seqThrough server mutators or your APILocal, merged commutativelyLocal events, rebased
ConflictsPer-field LWW · commands · CRDT fieldsServer decidesA CRDT for every valueEvent reducers
Partial syncSync groups + index subscriptionsQueries or shapesPer documentPer store
Cold startRange reads of immutable segments from edge cacheReplicate query resultsLoad documentsReplay or snapshot
To operateA Worker and a bucketPostgres + sync serviceSync server or hostedSync backend
06 — SpecificationDatenblatt

Every part has a name and a number.

No magic, no hidden service. Each layer is a documented format or a class you can read.

Core
Rust · syncbase-core
Client runtime
WASM in a dedicated Worker · OPFS · SharedWorker leader across tabs
Server runtime
Cloudflare Workers · SQLite Durable Objects · R2 — or Bun/Node + S3
Segment format
SBSEG001 · block-based · posting lists · CRC32 trailer
Wire format
SBW1 binary frames · JSON fallback
Merge
Per-field LWW by seq · commands · Yjs/yrs, fractional order, PN-counter, LWW-set
Authorization
Sync groups in HS256 JWTs · per-model write policies
Subscriptions
FNV-1a slice hashes per (model, index, key)
Platforms
Web · React · React Native · Swift · Kotlin
Verification
proptest state machines · crash consistency · network simulation · Quint
07 — Honest limitsv0.1
Not yet

No SQL engine

Queries compose over indexed slices in memory. No joins planner, no incremental view maintenance.

Not yet

No Postgres ingest

syncbase is the database of record. There is no CDC bridge from an existing database.

By design

One sequencer per workspace

About 1,000 requests/s per Durable Object, batched by fan-out. Shard hot workspaces with partitioned sequencers.

Not yet

Policies are code

Write rules are TypeScript hooks. A declarative permission language is not part of 0.1.

Hand the docs to your agent.

$curl -s https://syncbase.submodule.nl/docs.md
$curl -sH "Accept: text/markdown" https://syncbase.submodule.nl/docs
# every page has a Markdown twin: append .md or send Accept: text/markdown