DEV Community

Cover image for Two people, one stroke list: how Yjs merges without a referee
Karlo Šeler
Karlo Šeler

Posted on Edited on

Two people, one stroke list: how Yjs merges without a referee

In the last post I followed one stroke from pen down to a friend's screen. I skipped the hard question: what happens when two people change the drawing at the same moment? There's no lock, and the server doesn't pick a winner. Yet every screen ends up with the same picture.

This post shows why, with small experiments in Node (Yjs 13.6), and then the other optimizations that keep the canvas fast.

You'll learn:

  • how Yjs names every change, and why that removes most conflicts
  • who goes first when two people add a stroke at the same moment
  • why an old copy doesn't undo a Clear (with one catch), and why Clear only deletes what you've seen
  • what happened when I restarted the server with a drawing open
  • why Clear makes the document smaller and the eraser makes it bigger

Every change has a name

Every Y.Doc gets a random clientID when it's created, so every tab (and every reload) is a new client. Each item you insert gets an id made of that client id plus a counter, the clock:

const doc = new Y.Doc();
doc.clientID; // 128625047, random per Y.Doc

const strokes = doc.getArray('strokes');
strokes.push([a]); // id { client: 128625047, clock: 0 }
strokes.push([b]); // id { client: 128625047, clock: 1 }
Enter fullscreen mode Exit fullscreen mode

Two strokes can never share an id, even if two people draw the exact same line. So "two people changed the same thing" almost never happens: each person mostly adds new things with their own names.

The second idea: an item doesn't store its position as an index. It stores its neighbours at the moment it was inserted, "I go after item (128625047, 0)". Indexes shift whenever someone else inserts. "After this item" doesn't.

What goes over the WebSocket is just the new items and their neighbours, in a compact binary format. Pushing one small stroke ({ id: 'E' }) produced a 23-byte update.

A detail I found while poking at the internals: consecutive strokes from the same client get stored as one block internally, { client, clock: 0, length: 4 }. Each stroke still has its own (client, clock), so nothing changes for you, but it keeps the document small.

Two strokes at the same moment

The most common conflict in a stroke list: you and a friend lift the pen at the same moment. Both strokes say "I go at the end, after the last stroke". One has to come first, and every copy must pick the same one.

You can test it without a server. Two docs, a push each, then exchange updates both ways:

const A = new Y.Doc(); A.clientID = 100;
const B = new Y.Doc(); B.clientID = 200;
A.getArray('strokes').push([{ id: 'from A' }]);
B.getArray('strokes').push([{ id: 'from B' }]);

// send each side what the other is missing
Y.applyUpdate(B, Y.encodeStateAsUpdate(A, Y.encodeStateVector(B)));
Y.applyUpdate(A, Y.encodeStateAsUpdate(B, Y.encodeStateVector(A)));
Enter fullscreen mode Exit fullscreen mode
Client ids A sees B sees
A = 100, B = 200 from A, from B from A, from B
A = 200, B = 100 from B, from A from B, from A

When two items claim the same spot, the lower client id goes first. Both copies apply the same rule to the same ids, so they agree without talking to each other.

On a canvas, array order is drawing order, so this decides which stroke is on top. Client ids are random, so the winner is effectively a coin flip, but everyone sees the same flip. It's one flip per pair of tabs, not per tie: the lower id goes first every time until one of them reloads. For a drawing that's fine. It would not be fine if order meant "who was first", for example in a queue.

Any order, even twice

The network doesn't promise much: after a reconnect you can get an update late, or twice. So I collected four updates from three docs, delivered every update twice, in 20 random orders, each into a fresh doc. All 20 ended with the same list: [a1, a2, b1, c1].

Two things make that work. An update that depends on an item you haven't seen yet ("I go after X") waits until X arrives. An update you already have is recognised by its id and skipped. So the result depends only on which changes you've received, never on their order.

Deletes leave a marker

Clear calls strokes.delete(0, strokes.length). That doesn't erase the items from the structure. It records "client 128625047, clocks 0–49: deleted", a tombstone.

That marker is what stops a cleared drawing from coming back. Picture a tab that was offline during Clear and still holds all the strokes. When it reconnects and sends what it has, the receiving side looks at the ids, finds them already marked deleted, and keeps them deleted. Without the marker, the offline tab would bring the whole drawing back.

The flip side surprised me. In this test, A clears while B is offline, and B draws one more stroke in the meantime:

// A and B both have s1, s2, s3
A.getArray('strokes').delete(0, 3);          // A clears
B.getArray('strokes').push([{ id: 'drawn offline' }]); // B, offline, draws
// reconnect: exchange updates both ways
Enter fullscreen mode Exit fullscreen mode

Both end with ['drawn offline']. A deleted the three strokes it had seen, by their ids. B's new stroke has an id A never saw, so A's Clear couldn't delete it. Clear means "delete what I've seen", not "empty the array".

For a canvas I think that's the right outcome: nobody's offline work is silently thrown away. But if you expect "Clear means empty", it looks like a bug.

Catching up: state vectors

A tab that reconnects doesn't have to download the whole room again. It sends a state vector: for each client it has heard from, the next clock it expects. "From client 128625047 I have everything up to clock 50." The other side replies with only the items past those clocks, plus its delete markers.

Measured on a room with 51 strokes, where the joining doc already had the first 50:

  • state vector sent (small test client ids; real ones add a few bytes): 3 bytes
  • reply: 1.9 KB, instead of the full 95 KB document

The exchange works the same in both directions, and that matters for the next experiment.

The server-restart experiment

My server keeps drawings in memory only. So what happens to a drawing when it restarts? I expected it to be gone. I ran it with the stock y-websocket server and two Node clients:

  1. Tab A connects and adds a stroke.
  2. I kill the server. A notices the dropped socket and starts retrying, waiting longer each time (about 100, 200, 400, 800 ms).
  3. I start the server again, with empty memory. A reconnects about 0.3 s later.
  4. A new tab B joins the room. B sees A's stroke.

On reconnect, A and the server swap state vectors in both directions. The empty server asks for everything, and A sends its whole copy back up. Then B joins and gets it from the server.

The server isn't the source of truth. It's one more copy, merging by the same rules as every tab. A drawing survives as long as at least one copy exists anywhere.

The second half of the experiment: close every tab, restart the server, open a new tab. Empty canvas. No copy was left. y-websocket can keep rooms on disk (set YPERSISTENCE and it uses LevelDB). My server doesn't turn that on yet.

One catch: delete markers also live only in copies. Take a tab that was offline during a Clear, close the tab that cleared, and restart the server. When the offline tab reconnects, nobody remembers the Clear, and the strokes come back. Saving rooms to disk, markers included, would close that hole.

Clear shrinks the document, the eraser grows it

If deletes leave markers, does Clear make the document grow forever? I tested 10 rounds of "draw 50 strokes, clear":

Garbage collection Document after 10 rounds
on (the default) 30 bytes
off (new Y.Doc({ gc: false })) 933 KB

With garbage collection on, Yjs throws away the content of deleted items and keeps only the compact marker. Ten rounds of drawing leave 30 bytes. The y-websocket server has it on too, unless you set GC=false.

The eraser is the opposite. It's a pixel eraser: just another stroke, drawn with globalCompositeOperation: 'destination-out' so it cuts a hole. It adds data. 50 pen strokes took 91 KB; adding 50 eraser strokes over them made it 182 KB, while the canvas showed less than before.

Other optimizations

Unchanged strokes don't re-render. The canvas component re-renders whenever the stroke list changes, and on every kept point of your own stroke. Each finished stroke is a memo component. That only helps if its props keep the same identity, and they do: after a remote push, strokes.toArray() returned the very same objects for the strokes that didn't change (I checked with ===). Only the new stroke renders.

Each component sees only its slice of awareness. Awareness changes about 20 times a second per active person. Components subscribe through a small hook with a "view" function that picks only the fields they need. If the view is unchanged, the hook returns the same array and React skips the render. A friend's cursor moving no longer re-renders the avatar list.

One shared coordinate space. Everyone draws on a logical 800×600 canvas. Each screen only scales it (scaleX/scaleY on the Konva Stage) and reads the pointer with getRelativePointerPosition(). If the canvas just took the window's width, a wide screen could draw at x = 1100, a spot a narrow screen doesn't have.

Konva layers do real work. Each layer is its own <canvas>. The white paper sits in a layer under the drawing, because destination-out only cuts within its own layer: the eraser can't punch through the paper, and exported images have no transparent holes. Remote cursors get their own layer with listening={false}, so 20 updates a second redraw only that small layer and never catch your clicks.

What to watch for

  1. Clear deletes what you've seen, not everything. A stroke drawn offline during a Clear survives it. Decide whether that's what you want before users find it.
  2. Concurrent order is a coin flip. Two inserts at the same spot are ordered by random client ids. Fine for drawing order, wrong for anything that should mean "first come, first served".
  3. Keep garbage collection on. Turning it off (for example, to keep old versions around) means deleted content stays forever: 933 KB after ten cleared drawings, versus 30 bytes.
  4. Erasing adds data. A pixel eraser is a stroke. If people erase a lot, the document grows with every swipe.
  5. The server is just one copy. Without persistence, a room survives restarts only while some tab still has it open, and a restart can bring cleared strokes back from a tab that was offline.

Wrapping up

The question I started with was "who wins when two people change the drawing at once?" The answer turned out to be: almost nobody has to win.

  • Every change has a unique name, so most changes never collide.
  • Positions are "after this item", so they don't shift under you.
  • The rare tie is broken by the same rule everywhere.
  • Deletes leave markers, so an old copy can't undo them while another copy remembers.
  • Every copy merges the same way, so the server is just another copy.

Next in the series: the other half of the project. When you hit Generate, a vision model reads the sketch and writes a structured brief, and that brief becomes the prompt for an image model. That post is about getting reliable, validated output from a model.

Top comments (0)