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:workerOpen 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:workerEdit 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
Every document maps to four Streamsy streams under /v1/stream/yjs/:service/docs/:docPath/:
| Stream | Format & live mode | Role |
|---|---|---|
.updates | Binary lib0, long-poll | Append-only Yjs CRDT document updates; server never resolves conflicts on write. |
.snapshots/<offset>_snapshot | Binary, 1 MiB chunks | Merged Y.encodeStateAsUpdate snapshot published by the compaction fold. |
.awareness/<name> | Binary lib0, SSE | Ephemeral cursors, selections, and names with Stream-TTL: 3600 (recreated idempotently). |
.awareness-index | JSON | Lists 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.updatescommit records a durable pending mark in the same SQLite transaction, waking the Durable Object alarm off the write path. Thecompactionfold tracks only three numbers in checkpoint state (bytes,pending, and the latestsnapshotoffset). OncependingcrossesCOMPACTION_THRESHOLD(1 MiB in production), it loads the prior snapshot into aY.Doc, side-reads.updatesto the tail, writes the merged snapshot in 1 MiB chunks, deletes the prior snapshot, and commits the new snapshot and fold state in oneCommit.transaction. - Zero-work discovery (
Projection.read). When a third window joins and requestsGET ?offset=snapshot, the Worker does no Yjs merging—it readsstate.snapshotstraight from the fold checkpoint and returns a307redirect to<offset>_snapshot(or-1if no snapshot exists yet) withCache-Control: private, max-age=5. The peer downloads the snapshot withstream-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
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:
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:
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:
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):
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 }),
]);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
413and snapshots are chunked into 1 MiB messages. Because compaction loads the fullY.Docinside the object's 128 MB isolate limit,POSTrejects further writes (413 DOCUMENT_TOO_LARGE) once foldedbytespasses 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__dssubscription endpoint and read-only stream mounts returning405). - Room access and offline storage. Room IDs sit in the URL fragment with no auth, room registry, or offline persistence.
Related examples
- 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.byRouteandProjectionWakeup.attach. - Cloudflare Durable Objects guide — placement,
StreamsyObject.make, and alarm wakeups.