Skip to Content
Examples

Yjs editor

A collaborative ProseMirror editor on Streamsy and Cloudflare Durable Objects, pairing binary Yjs update logs with expiring awareness streams and alarm-driven snapshot compaction.

This example is a live collaborative ProseMirror editor built on Streamsy and Cloudflare Durable Objects. Browser peers sync text, selections, cursors, and display names in real time over binary Yjs CRDT streams—and as edits accumulate, a background projection merges updates into snapshots so late-joining peers load fast without replaying the entire edit history.

Try the live Yjs editor: click Create room, copy the room link into a second window, and edit in both. Rooms are public (anyone with the link can edit, so avoid private data), and each room links directly to its raw /v1/stream update log for inspection with curl.

The full source lives in examples/yjs-editor (with the provider in packages/y-durable-streams).

Run it locally

Run the Worker locally on Miniflare/workerd from the repository root (no Cloudflare account required):

bun install --frozen-lockfile
bun run build
bun run --cwd examples/yjs-editor dev:worker

Open http://127.0.0.1:1340 (override with PORT and YJS_WORKER_STATE). To trigger a compaction snapshot after just a few keystrokes instead of waiting for 1 MiB of edits, lower COMPACTION_THRESHOLD:

COMPACTION_THRESHOLD=1500 bun run --cwd examples/yjs-editor dev:worker

Edit across two windows until you pass 1,500 bytes, then open the room link in a third window to watch it load the compacted snapshot and tail only the remaining updates. You can also run the workerd integration suite with bun run --cwd examples/yjs-editor test:worker.

Updates, awareness, and snapshot compaction

Concept diagram. Peer A posts each Yjs update to the document's .updates stream, and peer B follows that stream with long-polling. Both peers exchange presence through an awareness stream with a one-hour TTL, followed with server-sent events. A compaction fold follows .updates and merges the document into a snapshot after every mebibyte of new updates. A new peer loads the snapshot, then reads only the tail of .updates after it.

Every document maps to four Streamsy streams under /v1/stream/yjs/:service/docs/:docPath/:

StreamFormat & live modeRole
.updatesBinary lib0, long-pollAppend-only Yjs CRDT document updates; server never resolves conflicts on write.
.snapshots/<offset>_snapshotBinary, 1 MiB chunksMerged Y.encodeStateAsUpdate snapshot published by the compaction fold.
.awareness/<name>Binary lib0, SSEEphemeral cursors, selections, and names with Stream-TTL: 3600 (recreated idempotently).
.awareness-indexJSONLists named awareness streams so deleting a document removes all of its streams together.

Decoupled compaction and discovery

Snapshot creation and snapshot discovery are intentionally separated so write and join requests stay fast:

  • Alarm-driven compaction (Projection.fold + ProjectionWakeup.attach). Every .updates commit records a durable pending mark in the same SQLite transaction, waking the Durable Object alarm off the write path. The compaction fold tracks only three numbers in checkpoint state (bytes, pending, and the latest snapshot offset). Once pending crosses COMPACTION_THRESHOLD (1 MiB in production), it loads the prior snapshot into a Y.Doc, side-reads .updates to the tail, writes the merged snapshot in 1 MiB chunks, deletes the prior snapshot, and commits the new snapshot and fold state in one Commit.transaction.
  • Zero-work discovery (Projection.read). When a third window joins and requests GET ?offset=snapshot, the Worker does no Yjs merging—it reads state.snapshot straight from the fold checkpoint and returns a 307 redirect to <offset>_snapshot (or -1 if no snapshot exists yet) with Cache-Control: private, max-age=5. The peer downloads the snapshot with stream-next-offset, then tails only updates after that offset.

Compaction never prunes .updates, so lagging peers keep reading without interruption; snapshots optimize join latency and transfer size rather than disk usage.

Durable Object topology

Architecture diagram. The browser runs the ProseMirror editor and YjsProvider, and links the raw update stream. A Cloudflare Worker sends /v1/yjs document requests to the DocumentObject named after the document, and /v1/stream reads through router(placement). In the object, the Yjs routes forward to the .updates and .awareness streams and read the compaction fold's state for snapshot discovery and the size budget. Http.routes serves all four streams read-only. The object's alarm runs the compaction fold, which keeps a checkpoint of byte counts and the snapshot offset and publishes a .snapshots stream stored as 1 MiB messages.

All four streams for a document share one DocumentObject via Placement.byRoute, keeping .updates, .snapshots, .awareness*, and the fold checkpoint in one SQLite database so compaction and document deletion stay transactional. See Cloudflare alarms and projections.

Inside the editor and Durable Object

Snippet paths below are relative to examples/yjs-editor. // ... marks omitted lines.

Binding ProseMirror to YjsProvider

Each browser connects a Y.Doc and Awareness instance to ProseMirror via y-prosemirror and YjsProvider, allowing edits only while connected:

src/main.ts
const doc = new Y.Doc();
const awareness = new Awareness(doc);
awareness.setLocalStateField("user", { name: name.value, color });

const provider = new YjsProvider({
  doc,
  awareness,
  baseUrl: `${location.origin}/v1/yjs/editor`,
  docId: roomId,
  connect: false,
});

const view = new EditorView(element("#editor"), {
  state: EditorState.create({
    schema,
    plugins: [
      ySyncPlugin(doc.getXmlFragment("prosemirror")),
      yCursorPlugin(awareness),
      yUndoPlugin(),
      keymap({ "Mod-z": undo, "Mod-y": redo, "Mod-Shift-z": redo }),
      keymap(baseKeymap),
    ],
  }),
  // ...
  editable: () => provider.connected,
  // ...
});
// ...
provider.on("status", renderStatus);
provider.on("error", renderError);
void provider.connect();

Alarm-driven compaction fold

compaction tracks total and pending bytes in FoldState. Updates already covered by state.snapshot still increment bytes without re-triggering merges across a backlog, and retry: { maxAttempts: 5 } handles transient failures while leaving committed updates intact:

worker/compaction.ts
const FoldState = Schema.Struct({
  bytes: Schema.Finite,
  pending: Schema.Finite,
  snapshot: Schema.optionalKey(Schema.String),
});
// ...
export const compaction = Projection.fold({
  id: "yjs-compaction",
  // Generation 2 rebuilds state with the snapshot offset that used to live in an `.index` stream.
  generation: 2,
  params: { document: Schema.String },
  inputs: { updates: Updates },
  state: { schema: FoldState, initial: { bytes: 0, pending: 0 } },
  commit: Commit.transaction,
  retry: { maxAttempts: 5 },
  fold: (state, { item, offset }, unit) =>
    Effect.gen(function* () {
      const bytes = state.bytes + item.length;

      // The last snapshot read to the log's tail, so it already covers this update.
      if (
        state.snapshot !== undefined &&
        offset !== undefined &&
        compare(offset, state.snapshot) <= 0
      )
        return { ...state, bytes };
      const pending = state.pending + item.length;

      if (pending < (yield* CompactionThreshold)) return { ...state, bytes, pending };

      return {
        bytes,
        pending: 0,
        snapshot: yield* publishSnapshot(unit.params.document, state.snapshot),
      };
    }),
});

Request-time snapshot discovery

GET ?offset=snapshot reads compaction's checkpoint with Projection.read and issues the 307 redirect:

worker/document.ts
const snapshotDiscovery = Effect.fn("Yjs.snapshotDiscovery")(function* (url: URL, id: string) {
  yield* requireDocument(id);

  // A pending snapshot is not in the fold state yet, so discovery returns the previous one.
  const { state } = yield* Projection.read(compaction.at({ document: id }));

  url.searchParams.set("offset", state.snapshot ? `${state.snapshot}_snapshot` : "-1");

  return HttpServerResponse.empty({
    status: 307,
    headers: {
      location: `${url.pathname}${url.search}`,
      "cache-control": "private, max-age=5",
    },
  });
});

Placement and DocumentObject wiring

All four document streams map to the same owner name, and DocumentObject mounts them read-only under /v1/stream alongside /v1/yjs/* (stripping headers like Stream-Closed on forwarded appends so a disconnecting peer cannot close the room):

worker/placement.ts
export const placement = Placement.byRoute([
  rule({ stream: Updates, owner: ({ document }) => document }),
  rule({ stream: Snapshots, owner: ({ document }) => document }),
  rule({ stream: Awareness, owner: ({ document }) => document }),
  rule({ stream: AwarenessIndex, owner: ({ document }) => document }),
]);
worker/objects.ts
export class DocumentObject extends StreamsyObject.make({
  app: Layer.merge(Http.routes(streams, { prefix: "/v1/stream", access: "read" }), yjsRoutes),
  wakeups: [ProjectionWakeup.attach(compaction)],
  layer: (state: DurableObjectState, env: Env) =>
    Layer.merge(storage(state), CompactionThreshold.layer).pipe(
      Layer.provideMerge(
        ConfigProvider.layer(
          ConfigProvider.fromUnknown({
            COMPACTION_THRESHOLD: env.COMPACTION_THRESHOLD || undefined,
          }),
        ),
      ),
    ),
}) {}

Going further

Production notes

  • Durable Object SQLite and memory bounds. Durable Object SQLite rejects values over 2 MB, so update appends over 1.5 MiB return 413 and snapshots are chunked into 1 MiB messages. Because compaction loads the full Y.Doc inside the object's 128 MB isolate limit, POST rejects further writes (413 DOCUMENT_TOO_LARGE) once folded bytes passes an approximate 8 MiB budget (checked against the alarm-updated checkpoint, so a burst can land slightly above 8 MiB).
  • Disconnect handling and upstream behavior. To avoid losing edits on reconnect, the editor pauses editing when disconnected and prompts a reload. Against upstream yjs-conformance.test.ts (461b4026), 59/68 tests pass (3 Node-only skipped; 6 fail due to an unimplemented __ds subscription endpoint and read-only stream mounts returning 405).
  • Room access and offline storage. Room IDs sit in the URL fragment with no auth, room registry, or offline persistence.
  • Doom — binary input streams with server-side snapshot projections and native stream forks on Cloudflare Durable Objects.
  • Folder sync — another multi-stream Cloudflare Durable Object app using Placement.byRoute and ProjectionWakeup.attach.
  • Cloudflare Durable Objects guide — placement, StreamsyObject.make, and alarm wakeups.

On this page