If one person opens a document, writes, and saves when done, the document being edited and the saved file can be the same thing. They need to be separate once several people edit at the same time, each person’s input reaches the others right away, and anyone who opens the document later reads what was saved.

Our team build this with a CRDT (a data structure that merges without conflicts; here, Yjs). While a document is open, its source of truth is the CRDT document in the server’s memory. The save is a snapshot: the encoded CRDT state, optionally with plain text, written out separately. This post covers why the two are kept apart and the rules that follow.

The problem

If the saved snapshot is the source of truth and everyone writes their full text back, the later write overwrites the earlier edit.

Before sync finishes, the client’s document is empty. With a CRDT, merging an empty document does not erase anything. Two things are dangerous. One is saving that empty state over the snapshot, which erases the saved content. The other is a client that thinks the document is empty, rebuilds it from plain text, and then merges, which duplicates the text. In my Yjs test, merging a document holding "abc" with a separately re-seeded "abc" gave "abcabc".

If updates are distributed through the save, nobody sees others’ input until the save finishes. A slow save looks like slow editing, and a failed save looks like a failed edit. If you do not save at all, a crash loses the merged result.

Permissions matter too. Disconnect people who cannot write and they stop seeing updates. Let them connect and accept their updates, and you have a hole in write permissions.

What I did not do

ApproachProblem
Use the snapshot as the source of truth and write full text backLater writes erase earlier edits; others’ input is invisible until reread
Show an empty editor before syncReaders think it is empty; typing or autosave creates blanks or duplicates
Use one write for both saving and deliveryA slow or failed save becomes a slow or failed edit
Lock so only one person writesPrevents overwrites but gives up simultaneous editing, the actual goal
Disconnect people who cannot writeThey stop seeing live updates
Rebuild from plain text after a crashStructure plain text cannot hold, and merges newer than it, are lost

The design

Do not show empty until sync finishes

The client keeps synced false until the first state arrives from the server. Meanwhile it does not show an empty editor; it shows the snapshot’s plain text if there is one. If it already has an encoded state locally, it applies it before connecting.

Every client-side save, including on close and on leaving the page, checks this flag. Hiding the empty editor and not writing empty are separate guards. Hiding alone does not help if a background save still runs.

The CRDT state is built from plain text only once, for a document whose snapshot has no state yet. Rebuilding every time causes duplicates like the "abcabc" above.

Updates go to open connections right away

The server applies each update to the in-memory document and sends it to the other connections on the same document immediately, without waiting for the save.

Read-only connections still join and receive updates. Updates from them are dropped before they are applied. Authentication happens before the document is touched; whether the connection may write is decided after that.

The save is written separately as a snapshot

There are two save triggers: 2 seconds after the last change, and when a connection closes. The delay keeps every keystroke from causing a write. Delivery never waits for it.

The cost is that if the server process dies inside that window, those edits are lost. In the example below, killing the process before the save lost the edit after restart. If you cannot accept that, shorten the delay or keep a separate append-only log of updates.

If a save fails, the in-memory document and connections stay as they are; the failure is logged and the next save writes again.

A minimal example

Tested with Yjs 13.6.33, ws 8.22.0 and Node.js 22. The server keeps one Y.Doc per name, delivers updates immediately, and writes a snapshot after a 2-second delay and on disconnect.

// server.mjs
import * as Y from "yjs";
import { WebSocketServer } from "ws";
import { readFileSync, writeFileSync, existsSync } from "node:fs";

const docs = new Map(); // name -> { doc, conns, timer }

function open(name) {
  if (docs.has(name)) return docs.get(name);
  const doc = new Y.Doc();
  const file = `${name}.snapshot`;
  if (existsSync(file)) Y.applyUpdate(doc, readFileSync(file));
  const room = { doc, conns: new Set(), timer: null };
  const save = () => writeFileSync(file, Y.encodeStateAsUpdate(doc));
  room.save = save;
  doc.on("update", (update, origin) => {
    for (const c of room.conns) if (c !== origin) c.send(update); // deliver now
    clearTimeout(room.timer);
    room.timer = setTimeout(save, 2000); // snapshot 2 s after the last change
  });
  docs.set(name, room);
  return room;
}

new WebSocketServer({ port: 1234 }).on("connection", (ws, req) => {
  const url = new URL(req.url, "http://x");
  const room = open(url.pathname.slice(1));
  const canWrite = url.searchParams.get("role") !== "viewer";
  room.conns.add(ws);
  ws.send(Y.encodeStateAsUpdate(room.doc)); // first message = full state
  ws.on("message", (msg) => {
    if (!canWrite) return; // drop updates from read-only connections
    Y.applyUpdate(room.doc, new Uint8Array(msg), ws);
  });
  ws.on("close", () => {
    room.conns.delete(ws);
    clearTimeout(room.timer);
    room.save(); // save now on disconnect
  });
});
// client.mjs
import * as Y from "yjs";
import WebSocket from "ws";

export function connect(name, role = "editor") {
  const doc = new Y.Doc();
  const ws = new WebSocket(`ws://localhost:1234/${name}?role=${role}`);
  let synced = false; // no saves or edits before the first state arrives
  ws.on("message", (msg) => {
    Y.applyUpdate(doc, new Uint8Array(msg), ws);
    synced = true;
  });
  doc.on("update", (update, origin) => {
    if (origin !== ws && ws.readyState === 1) ws.send(update);
  });
  return { doc, ws, isSynced: () => synced };
}
// demo.mjs
import { connect } from "./client.mjs";
import { readFileSync } from "node:fs";
import * as Y from "yjs";
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
const text = (c) => c.doc.getText("t").toString();

const a = connect("note"), b = connect("note"), v = connect("note", "viewer");
await wait(300);
a.doc.getText("t").insert(0, "hello ");
b.doc.getText("t").insert(0, "world ");
v.doc.getText("t").insert(0, "VIEWER ");          // dropped by the server
await wait(300);
console.log("a:", text(a), "| b:", text(b), "| viewer:", text(v));
await wait(2500);                                   // debounce passes
const snap = new Y.Doc();
Y.applyUpdate(snap, readFileSync("note.snapshot"));
console.log("snapshot:", snap.getText("t").toString());
for (const c of [a, b, v]) c.ws.close();
process.exit(0);
npm init -y > /dev/null && npm pkg set type=module && npm i yjs@13.6.33 ws@8.22.0
node server.mjs &
node demo.mjs
kill %1

Output:

a: world hello  | b: world hello  | viewer: world hello VIEWER 
snapshot: world hello 

The order of the two concurrent words can differ between runs. VIEWER stays only in the viewer’s local copy. The server dropped it, so it reached neither the others nor the snapshot. A real client makes the viewer’s editor read-only.

This example shows the mechanism only. It leaves out authentication, reconnects, showing plain text, and the Yjs sync protocol (sending only diffs). In production, an existing implementation such as y-websocket is simpler.

When to use it

Use this shape when several people edit at once and every person’s input must survive. For documents edited by one person at a time, or settings where the last save may win, a normal save is enough.

Common mistakes

  • Saving the pre-sync empty state over the snapshot. The saved content is lost.
  • A client that sees an empty document rebuilds it from plain text and merges. The text is duplicated.
  • Hiding the empty editor but forgetting the save guard.
  • Applying read-only users’ updates on the server instead of dropping them.
  • Having only the delayed save and not saving on disconnect.