Skip to content

Every peer holds its own copy of whatever the room shares: a set of fields, a list, a document. A broadcast is best effort, so a copy can miss a change, and a peer that joins later has seen none of the earlier ones. Three techniques, usually used together, keep the copies the same. Who decides, and who gives a late joiner the state, depends on the kind of state: choosing a state model compares a chat, a game and a drawing. Whenever the state must be authoritative (fair, secret, or recorded), keep it on your own server and let jsflow carry the high-rate traffic.

For a shared document that many peers edit at once, you do not have to write these yourself: Collaborative documents with Yjs uses a library that merges the edits, with a provider for jsflow. A shared whiteboard builds on it.

Give every change from a sender a sequence number. A receiver that sees a gap asks the sender for the missing changes with sendReliable, which is retransmitted until acknowledged.

app.ts
import { join, text } from 'jsflow-sdk';
const room = await join({ app: 'pk_…', room: 'team-7' });
const enc = (o: unknown) => JSON.stringify(o);
let seq = 0;
// Recent changes, so we can resend them.
const sent: { seq: number; change: unknown }[] = [];
// Per sender: the sequence number we expect next.
const next = new Map<number, number>();
function publish(change: unknown) {
const m = { seq: ++seq, change };
sent.push(m);
if (sent.length > 200) sent.shift();
room.broadcast(enc({ t: 'change', ...m }));
}
room.on('message', (from, data) => {
const m = JSON.parse(text(data));
if (m.t === 'change') {
// The first change from a peer sets the start.
const want = next.get(from) ?? m.seq;
if (m.seq > want) {
const ask = { t: 'resend', from: want, to: m.seq - 1 };
room.sendReliable(from, enc(ask));
}
if (m.seq >= want) {
apply(from, m.change);
next.set(from, m.seq + 1);
}
} else if (m.t === 'resend') {
const missed = sent.filter((s) => s.seq >= m.from && s.seq <= m.to);
for (const old of missed) {
room.sendReliable(from, enc({ t: 'change', ...old }));
}
}
});
declare function apply(from: number, change: unknown): void;
export { publish };

Two details matter. Keep a bounded window of recent changes, and fall back to a snapshot (technique 2) when a gap reaches further back than the window. And remember that a peer’s id changes when it reloads: a new id starts a new sequence.

A peer that joins late has seen none of the earlier changes, and a broadcast sent at that moment may be lost, so it has nothing to repair itself from: it needs the state from someone, with sendReliable. Who sends it depends on the shape of the state. Choosing wrongly is the usual cause of a history that shows up twice, or in a different order on every peer.

the state is example who sends it to a late joiner what the joiner does
set-like: the order of the parts does not matter, and applying a part twice changes nothing presence, shared fields, a set of reactions every peer sends its own part or snapshot merges each one (a union, or last writer wins per key)
ordered history: the order is part of the state a chat log, a list of events, a move list one designated source answers; the others stay silent removes repeats by id and puts the entries in one agreed order

Set-like state: every peer sends, the joiner merges

Section titled “Set-like state: every peer sends, the joiner merges”
app.ts
import { join } from 'jsflow-sdk';
const room = await join({ app: 'pk_…', room: 'team-7' });
declare function snapshot(): unknown;
room.on('peer', (id, up) => {
if (up) {
const hello = { t: 'snapshot', state: snapshot() };
room.sendReliable(id, JSON.stringify(hello));
}
});

Both sides do this, so two peers that meet each end up with the union of what they knew. Merging is order-free and a repeat changes nothing, so a joiner that gets the same facts from several peers is fine.

Ordered history: one source, ids, one order

Section titled “Ordered history: one source, ids, one order”

If every peer sends its own copy of an ordered list, the joiner receives several copies, each in its sender’s arrival order. Appended as they come, they interleave: with three peers in a room, a fourth sees a history that no one else has. Merging cannot repair that, because the order is the state. Do three things instead:

  1. Ask one source. The joiner picks one peer and asks it for the history: the host if your app has one, otherwise the lowest peer id the joiner sees. If that peer is silent for a few seconds, it asks the next. The others do not answer.
  2. Give every entry a unique id: a random tag chosen when you join, and a counter. Do not build it from the peer id: ids are drawn at random and can be reused by a later joiner, and a repeated id would make the joiner drop that person’s messages as repeats. The joiner ignores an id it already has, which also covers an entry that arrives both live and in the history.
  3. Agree one order. Each entry carries a clock that is higher than every clock its author has seen (a Lamport clock), and ties break by author id. Every peer sorts by it, so everyone shows the same list.
chat.ts
import { join, text } from 'jsflow-sdk';
type Entry = { id: string; clock: number; from: number; body: string };
const room = await join({ app: 'pk_…', room: 'team-7' });
const enc = (o: unknown) => JSON.stringify(o);
declare function render(log: Entry[]): void;
// The conversation, by id: an entry seen twice counts once.
const byId = new Map<string, Entry>();
let clock = 0;
let counter = 0;
const tag = crypto.randomUUID().slice(0, 8); // one per join
const add = (e: Entry) => {
if (byId.has(e.id)) return false;
byId.set(e.id, e);
clock = Math.max(clock, e.clock);
return true;
};
// One order everywhere: by clock, ties by author.
const log = () =>
[...byId.values()]
.sort((a, b) => a.clock - b.clock || a.from - b.from);
export function say(body: string) {
const id = `${tag}-${++counter}`;
const e: Entry = { id, clock: ++clock, from: room.id, body };
add(e);
render(log());
for (const p of room.peers()) {
void room.sendReliable(p, enc({ t: 'entry', e }));
}
}
// A joiner asks ONE peer for the history, the lowest id first,
// and the next one if that peer is silent or has none yet.
const asked = new Set<number>();
let haveHistory = false;
let asking = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const notReady = new Set<number>();
// join() resolves before any link is up, so peers() is empty at
// first. Still nobody there after a few seconds: nothing to ask.
setTimeout(() => {
if (room.peers().length === 0) haveHistory = true;
}, 3000);
function askForHistory() {
clearTimeout(timer);
if (haveHistory) return;
const source = room.peers()
.filter((p) => !asked.has(p))
.sort((a, b) => a - b)[0];
if (source === undefined) { asking = false; return; }
asking = true;
asked.add(source);
void room.sendReliable(source, enc({ t: 'history?' }));
timer = setTimeout(askForHistory, 3000);
}
room.on('peer', (_id, up) => {
if (up && !asking) askForHistory();
});
room.on('message', (from, data) => {
const m = JSON.parse(text(data));
if (m.t === 'entry') {
if (add(m.e)) render(log());
} else if (m.t === 'history?') {
// Only the peer that was asked answers, and only with a
// history it has: a peer that is itself new says so.
const last = log().slice(-100);
const ready = haveHistory;
const reply = { t: 'history', ready, log: last };
void room.sendReliable(from, enc(reply));
} else if (m.t === 'history') {
// Merging is safe: the order comes from the sort, not from
// the order things arrived in, and repeats are dropped by id.
for (const e of m.log) add(e);
render(log());
clearTimeout(timer);
if (m.ready) {
haveHistory = true;
} else {
notReady.add(from); // that peer is new too
const all = room.peers().every((p) => notReady.has(p));
if (all) haveHistory = true; // nothing older exists
else askForHistory(); // the next one
}
}
});

A peer that is itself new has no history to give: it answers ready: false, and the joiner asks the next peer at once. The joiner is done when a ready: true history arrives, when every reachable peer has said it is new too (then nothing older exists, and what they sent is merged), or when nobody is reachable a few seconds after joining. Note that join() resolves when the service admits you, usually before any link is up, so room.peers() is empty at that moment even in a busy room: never decide “I am alone” from it right away.

Why one source, if merging is safe? Because the order comes from the clock, the author and the id, and not from the order things arrived in, so a joiner that merges several histories ends up right. One source is about cost: every other peer would send the same 100 entries. The original bug was ordering by arrival. Entries that arrive live while the history is on its way are merged by the same rules. If your app has a server, the server can be the one source.

3. Compare digests, and fetch on a mismatch

Section titled “3. Compare digests, and fetch on a mismatch”

Even with both of the above, a copy can drift (a long network break, a bug). Every few seconds each peer broadcasts a small digest of its state, such as the number of entries and a hash over them that does not depend on order. A peer that sees a different digest asks the sender for its full state, reliably, and merges it. The digest is a few bytes, so the cost is small, and it makes the room converge without anyone having to notice the problem.

When two peers change the same thing at the same time, every peer must pick the same winner without asking anyone. The simplest rule is last writer wins, with an order that is the same everywhere: each change carries a counter that is higher than every counter its author has seen (a Lamport clock), and ties break by the author’s id. Applying the same set of changes in any order then gives the same result, and applying one twice changes nothing. Merging a snapshot is just applying each of its entries.

For lists and text, where “last writer wins” loses data, use a structure designed for concurrent editing (a CRDT) and put its operations through the same three techniques.

The shared-state example (in the examples/ folder of the jsflow-community repository) is a working page that combines all of this: three shared fields, last-writer-wins registers, a snapshot to late joiners, and digests. Its logic is a few dozen lines and is tested for convergence in every order.