The Brixus Blog

YjsHocuspocusReal-time collaboration

Why Our Collaborative Editor Doubled Pages on Reconnect

Rebuilding a Yjs document from JSON mints new item ids, so a reconnecting tab merged two histories and doubled the page. Persisting the Yjs state fixed it.

Brixus authors edit course pages together in real time. The editor is Tiptap in an Angular app, synced through Yjs by a Hocuspocus server, with the page stored as ProseMirror JSON in our .NET backend.

For a while we had a bug that sounds impossible: occasionally an author reconnected and every paragraph, every question and every image on the page appeared twice. Nobody had pasted anything. The page had simply doubled.

Here is why it happened, and the small change that made it impossible.

How the pieces fit together

When an author opens a page, the collab server loads it:

  1. Fetch the page's ProseMirror JSON from the backend.
  2. Build a Yjs document from it with prosemirrorJSONToYDoc from y-prosemirror.
  3. Sync that document to every connected browser.

While people edit, the server converts the Yjs document back to JSON with yDocToProsemirrorJSON and stores it. When the last author leaves, the document is unloaded from memory. The next person to open the page starts again at step 1.

This all looks reasonable, and it is fine almost all the time.

Why the page doubled

Yjs is a CRDT. Every piece of content in a Yjs document is an item with an identity: the id of the client that created it plus a counter. Merging two copies of a document means taking the union of their items, and items with the same id are the same item. That's what makes merging safe and repeatable.

The problem is step 2. Building a Yjs document from JSON creates every item fresh, under a new random client id. The content is identical, but as far as Yjs is concerned it is all new content that has never been seen before.

Now picture this sequence:

  1. An author has a page open. Their browser holds the Yjs document, with item ids from the server's last build.
  2. The server unloads that document. This happens on a deploy, a restart, or simply because the connection dropped long enough that the server saw nobody connected.
  3. The author's tab is still open. It reconnects.
  4. The server rebuilds the document from JSON, which means new ids for the same content.
  5. The browser and the server sync. Yjs sees two independent histories, each containing a full copy of the page, and merges them the only way it can: it keeps both.

The page doubles, and the doubled version is then stored as if someone had written it.

The fix: persist the Yjs state, not just the JSON

The cure is to make the server rebuild the same document, with the same ids, after an unload. Yjs can serialise a document's complete state as a binary update with Y.encodeStateAsUpdate. So every time the server stores a page, it now sends both:

  • the ProseMirror JSON, which the rest of the backend reads, and
  • the encoded Yjs state, stored next to it.

On load, the server prefers the state:

export function resolveInitialUpdate(docJson: unknown, state: Uint8Array | null) {
  if (state && state.byteLength > 0 && stateMatchesJSON(state, docJson)) {
    return { update: state, source: 'state' };
  }
  return { update: jsonToUpdate(docJson), source: 'json' };
}

Restoring from the state brings back the original item ids. When the author's tab reconnects, Yjs recognises every item it already has, and the merge changes nothing. Merging is idempotent again.

The guard: only trust state that still matches the JSON

There is one catch. Not every write to a page goes through the collab server. Our AI pipeline generates pages, and maintenance scripts that copy or regenerate books write content directly. After any of those, the stored Yjs state describes an older version of the page than the JSON does. Restoring it would silently roll back the newer content.

So the state is trusted only if it still describes the stored JSON:

function stateMatchesJSON(state: Uint8Array, docJson: unknown): boolean {
  const restored = new Y.Doc();
  try {
    Y.applyUpdate(restored, state);
    return JSON.stringify(documentToJSON(restored)) === JSON.stringify(normalizeDocumentJSON(docJson));
  } catch {
    return false;
  } finally {
    restored.destroy();
  }
}

Both sides are normalised through the same schema first, so attribute defaults and mark order can't cause false mismatches. On top of that, the backend clears the stored state whenever it writes page content outside the collab server, so a stale state is usually gone before the check even runs. If the server ever has to fall back to JSON, it logs a warning, because that is exactly the situation that used to double pages.

What we took away

  • In Yjs, content identity is the item id, not the text. Two documents with identical content but different ids are different documents, and merging them duplicates everything.
  • Rebuilding a CRDT document from a plain snapshot is a fork. It's safe only if no client still holds the old history. With browser tabs that stay open for hours, some client always does.
  • Persist the CRDT state alongside the readable format. The JSON stays the source of truth for everything else; the state exists so the collab server can come back as the same document.
  • Guard against stale state. Any write that bypasses the CRDT must invalidate its persisted state, and the loader should verify the state before trusting it.

The whole fix is a few dozen lines on the server and one extra column in the database. Most of the work was understanding why a merge that is supposed to be safe could duplicate a page at all.

Kubilay TarhanFounder of Brixus. Writes and reviews its certification courses and builds the platform they run on.

Free to try

See it running

Every Brixus course is built in this editor, with exam questions inside the lessons. The first lesson of each course is free to read, no account needed.