Two students write at the same spot: who wins?
The answer of a CRDT is "nobody loses": both edits stay, and all the replicas arrive at the same text whatever the order in which they receive the updates. That is why a collaborative editor tolerates a classroom with unstable Wi-Fi. But "nobody loses" holds only if you model the data the right way: the rest of the article shows, with code that was run, where the CRDT does its job and where a wrong choice of structure loses data all the same.
The starting problem is distributed concurrency. If Anna and Luca edit the same paragraph from two machines, the "last write wins" rule erases the work of one of them. The two families of solutions are Operational Transformation (OT), in which operations are transformed before being applied and a server that orders them is normally needed, and CRDTs (Conflict-free Replicated Data Types), data structures designed so that two replicas that have received the same updates are identical. With a CRDT the server does not decide the order: it acts as a relay and an archive. The price is that the structure keeps information about the deleted parts, as you will see shortly.
The listings use Yjs 13.6.33 and y-protocols 1.0.7, run with Node 24 in a temporary folder. There is no network: the "sockets" in the listings are in-memory functions, and the text says so where it happens. The code of the real client is a schema to adapt. The context of the platform is in Scalable LMS Architecture: every document belongs to a tenant and access must be checked before entering the room.
Convergence, idempotence and the cost of deletions
Yjs represents text as a sequence of elements, each with an identifier (client and counter). An insertion says "put this after element X": it does not use numeric positions, so two insertions at the same spot do not overwrite each other. The listing starts from a shared sentence, has two students write after "The" while offline, and then rebuilds three replicas that receive the updates in different ways.
import * as Y from 'yjs';
const testo = (doc) => doc.getText('t').toString();
// Initial state: one student writes it, then everyone receives it
const a = new Y.Doc();
a.clientID = 1; // fixed only to make the example reproducible
a.getText('t').insert(0, 'The sun rises in the east');
const iniziale = Y.encodeStateAsUpdate(a);
const b = new Y.Doc();
b.clientID = 2;
Y.applyUpdate(b, iniziale);
const base = Y.encodeStateVector(a);
// Offline: the two write at the SAME point, after "The"
a.getText('t').insert(3, ' big');
b.getText('t').insert(3, ' small');
const ua = Y.encodeStateAsUpdate(a, base); // only what a did
const ub = Y.encodeStateAsUpdate(b, base);
// Three replicas start from the initial text and receive the updates in different ways
const replica = (...updates) => {
const d = new Y.Doc();
Y.applyUpdate(d, iniziale);
updates.forEach((u) => Y.applyUpdate(d, u));
return d;
};
console.log('a then b :', testo(replica(ua, ub)));
console.log('b then a :', testo(replica(ub, ua)));
console.log('a twice :', testo(replica(ua, ua, ub)));
// Tombstones: 2000 write-delete cycles leave the three-letter text
for (const gc of [true, false]) {
const d = new Y.Doc({ gc });
const t = d.getText('t');
t.insert(0, 'abc');
for (let i = 0; i < 2000; i++) {
t.insert(t.length, 'x');
t.delete(t.length - 1, 1);
}
console.log(`gc=${gc}: text "${t.toString()}", encoded state ${Y.encodeStateAsUpdate(d).length} bytes`);
}
// Output (executed):
// a then b : The big small sun rises in the east
// b then a : The big small sun rises in the east
// a twice : The big small sun rises in the east
// gc=true: text "abc", encoded state 35 bytes
// gc=false: text "abc", encoded state 2035 bytes
The first three lines of the output are identical: receiving ua then ub, or the reverse, or ua twice, produces the same text. They are commutativity and idempotence seen in practice: you do not have to guarantee the delivery order or avoid duplicates
(useful with a network that retransmits). The order between "big" and "small" is decided by the client identifier: I fixed clientID at 1 and 2 to make the example reproducible, whereas in real use they are random and the order between the two can change. What does not change is that all the replicas agree.
The last two lines measure the cost. The loop writes and deletes a character 2000 times and leaves the text "abc". With garbage collection active (gc: true, the default according to the Y.Doc documentation) the encoded state weighs 35 bytes; with gc: false, 2035 bytes, because the deleted elements stay as tombstones.
Garbage collection is not free: the documentation warns that disabling it is for being able to restore old content, so whoever wants the version history of an assignment must pay the weight. It is a product choice, not a parameter to leave to chance.
Annotations and threads: where a CRDT loses data anyway
The educational part (highlighting a sentence, commenting on a passage, replying in a thread) is where naive implementations go wrong, in two ways. The first is anchoring the annotation to a numeric index. If a student writes before the highlighted sentence, the index points to a different spot in the text. The second is storing a thread as a whole value inside a map: two concurrent replies overwrite the same key, and one disappears.
import * as Y from 'yjs';
const sincronizza = (...docs) => { // full exchange between all replicas
for (const da of docs) for (const verso of docs) {
if (da !== verso) Y.applyUpdate(verso, Y.encodeStateAsUpdate(da));
}
};
// --- A. Anchoring an annotation: absolute index versus relative position
const a = new Y.Doc(); a.clientID = 1;
a.getText('t').insert(0, 'The photosynthesis produces oxygen');
const b = new Y.Doc(); b.clientID = 2;
Y.applyUpdate(b, Y.encodeStateAsUpdate(a));
const ta = a.getText('t');
const da = 4, fino = 18; // "photosynthesis"
const indiceAssoluto = { da, fino };
const relativa = {
da: Y.createRelativePositionFromTypeIndex(ta, da),
fino: Y.createRelativePositionFromTypeIndex(ta, fino),
};
b.getText('t').insert(0, 'Note: '); // b writes BEFORE the annotation
sincronizza(a, b);
const risolvi = (rel) => Y.createAbsolutePositionFromRelativePosition(rel, a).index;
console.log('text :', ta.toString());
console.log('fixed index :', JSON.stringify(ta.toString().slice(indiceAssoluto.da, indiceAssoluto.fino)));
console.log('relative :', JSON.stringify(ta.toString().slice(risolvi(relativa.da), risolvi(relativa.fino))));
// --- B. Two concurrent replies in the same thread
const modello = (strutturaThread) => {
const x = new Y.Doc(); x.clientID = 1;
const y = new Y.Doc(); y.clientID = 2;
strutturaThread.init(x);
Y.applyUpdate(y, Y.encodeStateAsUpdate(x));
strutturaThread.reply(x, 'teacher\'s reply');
strutturaThread.reply(y, 'a classmate\'s reply');
sincronizza(x, y);
return strutturaThread.read(x);
};
const comeMappa = { // the thread is a whole value inside a Y.Map
init: (d) => d.getMap('threads').set('q1', ['question']),
reply: (d, t) => { const m = d.getMap('threads'); m.set('q1', [...m.get('q1'), t]); },
read: (d) => d.getMap('threads').get('q1'),
};
const comeArray = { // the thread is a Y.Array: every reply is an insertion
init: (d) => { const arr = new Y.Array(); d.getMap('threads').set('q1', arr); arr.push(['question']); },
reply: (d, t) => d.getMap('threads').get('q1').push([t]),
read: (d) => d.getMap('threads').get('q1').toArray(),
};
console.log('thread in Y.Map :', JSON.stringify(modello(comeMappa)));
console.log('thread in Y.Array:', JSON.stringify(modello(comeArray)));
// Output (executed):
// text : Note: The photosynthesis produces oxygen
// fixed index : ": The photosyn"
// relative : "photosynthesis"
// thread in Y.Map : ["question","a classmate's reply"]
// thread in Y.Array: ["question","teacher's reply","a classmate's reply"]
In part A the annotation covers "photosynthesis" (indices 4-18). Then Luca writes "Note: " at the start. With the fixed index the annotation now highlights ": The photosyn", a meaningless fragment; with the relative position, created with createRelativePositionFromTypeIndex and
resolved after synchronisation with createAbsolutePositionFromRelativePosition, it still highlights "photosynthesis". The Yjs documentation guarantees that relative positions, once synchronisation is complete, point to the same spot in all replicas.
Inside the document, save the two relative positions (they are serialisable), not the indices.
In part B, the teacher and a classmate reply to the same question while disconnected. If the thread is a JavaScript array inside a Y.Map, every reply rewrites the whole value: at the merge only one survives (["question","a classmate's reply"]) and the teacher's reply is lost without any error.
If the thread is a Y.Array and every reply is an insertion, all three entries remain. The rule to take away: inside a CRDT, a value that several people can modify in parallel must be a shared type, not an object replaced as a whole. It holds for comments, for participant lists and for scores.
The server: relay, full state and multiple nodes
The server of a CRDT collaboration does three things: it forwards the updates to the clients in the same room, keeps a copy of them for newcomers and saves it. A widely circulated version of this example saves only the last update received as the "document state": every update is an
increment, not the complete state, and the one saved on its own is not enough to rebuild the text. The solution is to keep one Y.Doc per room, apply every update to it and save Y.encodeStateAsUpdate(doc).
import * as Y from 'yjs';
const testo = (doc) => doc.getText('t').toString();
class Bus { // in-memory stand-in for Redis Pub/Sub
constructor() { this.nodi = []; this.consegne = 0; this.perdi = 0; }
publish(msg) {
for (const n of this.nodi) {
if (this.perdi > 0 && n.nome === 'B') { this.perdi--; continue; } // at-most-once: a message is lost
this.consegne++;
n.dalBus(msg);
}
}
}
class Nodo {
constructor(nome, bus) {
this.nome = nome; this.bus = bus; this.doc = new Y.Doc(); this.client = [];
this.ultimoUpdate = null; // the typical mistake: keeping only the last update
bus.nodi.push(this);
}
dalClient(da, update) {
Y.applyUpdate(this.doc, update, 'client');
this.ultimoUpdate = update;
this.client.filter((c) => c !== da).forEach((c) => c.ricevi(update));
this.bus.publish({ da: this.nome, update });
}
dalBus(msg) {
if (msg.da === this.nome) return; // do not reprocess what I published myself
Y.applyUpdate(this.doc, msg.update, 'bus');
this.client.forEach((c) => c.ricevi(msg.update));
}
statoPerNuovoClient() { return Y.encodeStateAsUpdate(this.doc); }
}
class Client {
constructor(id, nodo) { this.id = id; this.doc = new Y.Doc(); this.nodo = nodo; nodo.client.push(this);
this.doc.on('update', (u, origine) => { if (origine !== 'rete') nodo.dalClient(this, u); }); }
ricevi(update) { Y.applyUpdate(this.doc, update, 'rete'); }
scrivi(pos, s) { this.doc.getText('t').insert(pos, s); }
}
const bus = new Bus();
const A = new Nodo('A', bus), B = new Nodo('B', bus);
const anna = new Client('anna', A), luca = new Client('luca', B);
anna.scrivi(0, 'Notes: ');
anna.scrivi(7, 'derivatives');
luca.scrivi(0, '>> ');
console.log('anna :', JSON.stringify(testo(anna.doc)));
console.log('luca :', JSON.stringify(testo(luca.doc)));
console.log('bus deliveries:', bus.consegne);
// A new client on node A: with the full state it sees everything, with the last update it does not
const nuovo = new Y.Doc(); Y.applyUpdate(nuovo, A.statoPerNuovoClient());
const monco = new Y.Doc(); Y.applyUpdate(monco, A.ultimoUpdate);
console.log('full state :', JSON.stringify(testo(nuovo)));
console.log('last only :', JSON.stringify(testo(monco)));
// Pub/Sub loses a message to B: B stays behind until the nodes exchange states
bus.perdi = 1;
anna.scrivi(0, '[1] ');
console.log('after loss : A =', JSON.stringify(testo(A.doc)), '| B =', JSON.stringify(testo(B.doc)));
const mancante = Y.encodeStateAsUpdate(A.doc, Y.encodeStateVector(B.doc));
Y.applyUpdate(B.doc, mancante, 'bus');
console.log('after resync : B =', JSON.stringify(testo(B.doc)), `(${mancante.length} bytes exchanged)`);
// Output (executed):
// anna : ">> Notes: derivatives"
// luca : ">> Notes: derivatives"
// bus deliveries: 6
// full state : ">> Notes: derivatives"
// last only : ""
// after loss : A = "[1] >> Notes: derivatives" | B = ">> Notes: derivatives"
// after resync : B = "[1] >> Notes: derivatives" (21 bytes exchanged)
The listing simulates two nodes (A and B) and a bus that behaves like Redis Pub/Sub, without a network. Anna writes on node A, Luca on B, and the first two lines show that the clients converge. The bus makes 6 deliveries for 3 publications, because it also delivers to the sender; that is why dalBus ignores the messages bearing its own name and does not republish them, otherwise every node would bounce the updates of the others.
Since applying the same update twice is harmless, the bounce would not break the data but would waste bandwidth, and with the number of nodes the waste grows.
The middle lines of the output compare a new client that receives the full state (complete text) with one that receives only the last update (empty text: it depends on earlier updates that it does not have). The last three show the real trouble: the Redis documentation declares at-most-once delivery for Pub/Sub, so a lost message is not retried.
B stays behind until the two nodes exchange states: Y.encodeStateAsUpdate(A.doc, Y.encodeStateVector(B.doc)) computes only what B is missing (21 bytes in the example) and realigns it. In production do it on reconnection and at intervals. Keep in mind also that the reference server y-websocket, according to its README, has an in-memory backend that does not scale easily: for several nodes you need a backend built for this or a job like the one in the listing.
Presence: cursors and online users do not belong in the document
Who is there and where their cursor is is ephemeral information: it changes with every movement and makes no sense to save, nor to make the document grow. Yjs keeps it in a separate channel, the awareness: every client publishes a state of its own and the others receive it as a binary message.
A client that leaves sets its state to null; one that disappears without warning is considered offline after 30 seconds without updates, and for this reason every client must retransmit its state at regular intervals.
import * as Y from 'yjs';
import * as awarenessProtocol from 'y-protocols/awareness';
const docA = new Y.Doc(); docA.clientID = 11;
const docB = new Y.Doc(); docB.clientID = 22;
const aw1 = new awarenessProtocol.Awareness(docA);
const aw2 = new awarenessProtocol.Awareness(docB);
// Every presence change produces a binary message, separate from the document
const inoltra = (da, verso) => da.on('update', ({ added, updated, removed }) => {
const clients = added.concat(updated, removed);
awarenessProtocol.applyAwarenessUpdate(verso, awarenessProtocol.encodeAwarenessUpdate(da, clients), 'rete');
});
inoltra(aw1, aw2);
inoltra(aw2, aw1);
aw1.setLocalStateField('user', { name: 'Anna', color: '#d97706' });
aw1.setLocalStateField('cursor', 14);
aw2.setLocalStateField('user', { name: 'Luca', color: '#2563eb' });
const vista = (aw, nome) => console.log(nome, JSON.stringify([...aw.getStates().entries()].map(([id, s]) => [id, s.user?.name, s.cursor ?? null])));
vista(aw2, 'Luca\'s view:');
console.log('text of Luca\'s document:', JSON.stringify(docB.getText('t').toString()), '(presence is not in the document)');
aw1.setLocalState(null); // Anna leaves: null state = offline
vista(aw2, 'after leaving :');
console.log('inactivity timeout (ms):', awarenessProtocol.outdatedTimeout);
aw1.destroy(); aw2.destroy();
// Output (executed):
// Luca's view: [[22,"Luca",null],[11,"Anna",14]]
// text of Luca's document: "" (presence is not in the document)
// after leaving : [[22,"Luca",null]]
// inactivity timeout (ms): 30000
In the output, Luca sees himself and Anna (with the cursor at position 14), while the text of his document stays empty: presence is not in the document. After setLocalState(null) Anna disappears from Luca's view. The last line prints outdatedTimeout, 30000 milliseconds, the value described in the documentation.
A frequent mistake is to pass the provider a hand-built "awareness" object, with a getLocalState method: the y-websocket README describes the awareness option as an existing instance of Awareness, not an object with methods of its own. Use provider.awareness and set the fields with setLocalStateField.
The real client and the security of the connection
The client connects three things: the document, the local copy in IndexedDB that allows working offline, and the WebSocket provider. The schema below was not run because it requires a reachable server and a browser.
// Schema to adapt: requires a reachable y-websocket server and a browser. NOT executed.
import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';
import { IndexeddbPersistence } from 'y-indexeddb';
const doc = new Y.Doc();
// Local copy: the editor opens and works even without a network
const locale = new IndexeddbPersistence(`doc-${documentId}`, doc);
const provider = new WebsocketProvider('wss://collab.example/yjs', `doc-${documentId}`, doc, {
connect: true, // default: connects immediately
params: { token: sessionToken } // ends up in the URL (?token=...): keep it short-lived
});
// Presence lives in the provider's awareness, not in the document
provider.awareness.setLocalStateField('user', { name: studente.nome, color: studente.colore });
Every line is a decision. IndexeddbPersistence loads the local state before the network, so a student without a connection opens the document and keeps writing: on reconnection the provider exchanges states and the updates merge as in the relay.mjs listing.
connect is true by default; setting it to false is useful if you want to show the editor first and connect after authentication. The params parameter is the delicate point: the browser's WebSocket constructor accepts a URL and subprotocols, not custom headers,
so the token goes in the URL, and URLs end up in proxy and server logs. Use short-lived tokens, valid only for that document, and verify them in the server before letting the client into the room.
Two further checks. The WebSocket protocol specification (RFC 6455, section 10.2) says that a server that does not want to serve arbitrary pages should verify the Origin header and answer 403 if it is not among those expected: without this check a malicious page opened by the student can connect with their credentials.
And idle traffic: nginx, by default, closes a proxied connection if the server transmits nothing for 60 seconds (proxy_read_timeout), and its documentation suggests raising the timeout or having the server send periodic WebSocket pings. With an editor in which nobody writes for a few minutes silence is normal, so you need the pings.
Where it hurts
I summarise the stumbles that emerged above, with the countermeasure each one had in the listings.
- Whole values in a Y.Map: one concurrent reply deletes another; use shared types (
Y.Array, nestedY.Maps). - Annotations on numeric indices: they shift as soon as someone writes before them; use relative positions.
- Saving only the last update: a new client gets an empty text; save the encoded state of the entire
Y.Doc. - Pub/Sub without resynchronisation: a lost message leaves a node behind; exchange state vectors on reconnection.
- Presence inside the document: it makes it grow and clutters it with useless data; use the awareness.
- WebSocket without origin or token: anyone can join; verify
Originand token before the room.
The common thread is that the CRDT guarantees the convergence of the replicas, not the meaning of the data: if the structure you choose overwrites, the convergence is on a result that has already lost something. Three of the six items are therefore data modelling errors (the map, the indices, the document cluttered by presence), two are server architecture errors (the last update, the bus) and one is about security. If you have to audit an existing system, start from the modelling: it is the category that no load test reveals.
Frequently asked questions
CRDT or OT: which to choose for a collaborative editor?
For a new project, with offline work and without wanting to handle the transformation of operations, a CRDT with a mature library such as Yjs is the simplest choice. An OT system already in production should not be rewritten without a reason: the migration cost outweighs the advantage.
Does the CRDT document always grow?
It grows with the history if you disable garbage collection. With the Yjs default, in the article's measurement, 2000 write-and-delete cycles take 35 bytes against 2035 with gc disabled. The document grows anyway with the real content.
Should cursor presence be saved?
No. It is ephemeral state: it is exchanged between clients through the awareness and expires after 30 seconds without updates, according to the Yjs documentation. Saving it in the document weighs it down without giving value.
Do I need Redis to scale across several servers?
You need a channel that forwards the updates between nodes, and Pub/Sub is a common choice, but it delivers at most once: always add the resynchronisation of states on reconnection.
What you can do now
You can explain why two replicas of a CRDT converge, choose the right shared types for annotations and threads, anchor a comment to a relative position, write a server that saves the full state and realigns the nodes after a lost message, and keep presence out of the document. What remains is the case of someone working without a network for hours, not a few seconds: the next article tackles it, Offline-First Learning Apps: Caching, Write Queues and Sync. The events this editor produces can feed the pipeline in Learning Analytics with xAPI and Kafka.
Sources
- Yjs Docs: Relative Positions - the guarantee that relative positions point to the same spot in all replicas and the conversion functions, consulted on 2026-11-12
- Yjs Docs: Awareness & Presence - ephemeral presence state, the null state as offline and the 30-second timeout, consulted on 2026-11-12
- Yjs Docs: Y.Doc - the gc property and its meaning, consulted on 2026-11-12
- y-websocket (README) - the provider options (connect, params, awareness) and the scalability limit of the in-memory backend, consulted on 2026-11-12
- Redis: Pub/Sub - the at-most-once delivery semantics, consulted on 2026-11-12
- RFC 6455: The WebSocket Protocol - the verification of the Origin header (section 10.2), consulted on 2026-11-12
- MDN: WebSocket constructor - the url and protocols parameters only, with no custom headers, consulted on 2026-11-12
- nginx: WebSocket proxying - the closing after 60 seconds of silence and the remedy with proxy_read_timeout or pings, consulted on 2026-11-12
The JavaScript listings were run with Node 24, Yjs 13.6.33 and y-protocols 1.0.7. No WebSocket server or Redis was started: the relay and the bus in the listings are in-memory simulations, and the client schema was not run. The byte measurements are those of the output, reproducible with the same listings.
Commenti
Caricamento commenti...
Sign in to comment