Realtime collaboration series · Part 2 of 5
Edits get lost, doubled or out of order
- Overview
- 1. Changes take seconds to show up
- 2. Edits get lost, doubled or out of order
- 3. Two people change the same thing
- 4. You can’t tell who else is here
- 5. Cursors lag behind while you pan
The Wi-Fi blips for two seconds. When it comes back, the card you moved is in the wrong place on your teammate’s screen, the comment you typed appears twice, and the shape you deleted is still there. Nothing crashed, and nobody got an error.
1The problem: an open line is not a reliable line
Part 1 opened a live connection. On a perfect network, every message would arrive once and in order. Real networks are not perfect, and an edit can go wrong in four ways:
- Lost: the connection died while the edit was on its way. The sender thinks it was sent.
- Doubled: the sender was not sure, sent it again, and both copies arrived.
- Out of order: two edits to the same thing arrive in the wrong order, so the older one wins.
- Stuck offline: the laptop is on a train. Edits made now have nowhere to go, and a closed tab would lose them.
A single WebSocket keeps its own messages in order while it is open. The trouble starts when it closes: whatever was in flight is gone, a new connection starts from scratch, and edits that are resent can now arrive after newer ones, or twice.
2The solution: number, confirm, resend
The fix is old and simple, and it is the same idea TCP uses inside a single connection, lifted up to the level of edits so it survives reconnects:
- Number every edit. The receiver applies edit n only after n − 1.
- Keep it until it is confirmed. The sender holds each edit until the receiver says “I have everything up to n”.
- Refill gaps. If the receiver sees a number it was not expecting, it asks to resend from the missing one.
- Ignore repeats. An edit with a number already applied is dropped, so resending is always safe.
Noticing a dead connection
A dropped connection often looks exactly like a quiet one. The browser may not get a close event for minutes. So both sides send a tiny heartbeat every few seconds; if no reply comes back in time, the connection is treated as dead and the app reconnects. Retries wait longer each time (1 s, 2 s, 4 s…, plus a little randomness), so a thousand browsers coming back after an outage do not all hit the server at the same instant.
On reconnect, the browser says what it already has. The server replays what it missed. If it was gone too long, for example after a laptop slept overnight, replaying hours of edits is slower than just reloading the document, so the server says “reload” instead.
Working offline: save first, send second
If edits only live in memory until they are confirmed, closing the tab while offline loses them. An outbox stored on the device (IndexedDB in a browser) fixes this: every edit is written there first and removed only when the server confirms it. On the next load, anything left in the outbox is sent again, or the user is asked whether to restore it.
New things need a name before the server answers
One more gap: you create a card and immediately color it. The color edit needs the card’s id, but the database has not created one yet. Waiting would make the app feel slow. Instead, the browser invents a temporary id, uses it straight away, and the server keeps a small map from temporary to real ids, translating every edit that still uses the old name.
3Example code
A browser-side channel that numbers, keeps, resends and reconnects, and the server check that goes with it. Persistence to IndexedDB and the reload-if-too-old rule are left as comments.
reliable-channel.tstype Edit = { seq: number; op: object }
class ReliableChannel {
private socket!: WebSocket
private nextSeq = 1
private outbox: Edit[] = [] // sent, but not confirmed yet
private lastSeen = 0 // last change from others we applied
private retries = 0
private heartbeat?: number
constructor(private url: string, private onRemote: (op: object) => void) {
this.connect()
}
send(op: object) {
const edit = { seq: this.nextSeq++, op }
this.outbox.push(edit) // a real app writes this to IndexedDB first
if (this.socket.readyState === WebSocket.OPEN) this.socket.send(JSON.stringify(edit))
}
private connect() {
this.socket = new WebSocket(this.url)
this.socket.onopen = () => {
this.retries = 0
// Tell the server where we are; it replays what we missed.
this.socket.send(JSON.stringify({ type: 'hello', lastSeen: this.lastSeen }))
for (const e of this.outbox) this.socket.send(JSON.stringify(e)) // resend
this.heartbeat = setInterval(() => this.socket.send('{"type":"ping"}'), 20_000)
}
this.socket.onmessage = (ev) => {
const msg = JSON.parse(ev.data)
if (msg.type === 'ack') {
// Confirmed up to msg.upTo: now it is safe to forget them.
this.outbox = this.outbox.filter((e) => e.seq > msg.upTo)
} else if (msg.type === 'resend') {
for (const e of this.outbox) if (e.seq >= msg.from) this.socket.send(JSON.stringify(e))
} else if (msg.type === 'remote' && msg.n === this.lastSeen + 1) {
this.lastSeen = msg.n // anything else is a duplicate or early
this.onRemote(msg.op)
}
}
this.socket.onclose = () => {
clearInterval(this.heartbeat)
const wait = Math.min(30_000, 1000 * 2 ** this.retries++) // 1s, 2s, 4s…
setTimeout(() => this.connect(), wait + Math.random() * 500)
}
}
}
server.ts
// Per connected browser: the last edit number we applied.
function onEdit(client: { applied: number; socket: WebSocket }, edit: Edit) {
if (edit.seq <= client.applied) return // duplicate: ignore it
if (edit.seq > client.applied + 1) { // gap: ask for the rest
return client.socket.send(JSON.stringify({ type: 'resend', from: client.applied + 1 }))
}
applyAndBroadcast(edit.op) // save, then fan out
client.applied = edit.seq
client.socket.send(JSON.stringify({ type: 'ack', upTo: edit.seq }))
}
Two details carry most of the weight. The outbox is cleared only by an ack, never by a successful send(). And the server acknowledges only after the edit is saved, so a confirmed edit can never be lost by a server crash.
4In practice: a design tool
- Acknowledge after the work, not on arrival. An edit that fans out to several stores is confirmed only when all of them are done.
- Treat “offline too long” as a different case. The browser reports when it went offline. If that is long ago and the board has changed since, a fresh load beats replaying a pile of old edits.
- Show the state honestly. A small “Reconnecting…” and “All changes saved” indicator stops people from closing the tab at the wrong moment.
- Ask before restoring. If the outbox still has edits when the page opens, ask “Restore unsaved changes?” rather than silently replaying edits made against an old version.
5Pros and cons
Pros
- Edits are applied exactly once and in order, even across reconnects
- People can keep working offline without losing anything
- Resending is always safe, which keeps the retry logic simple
- Edits feel instant thanks to temporary ids
Cons
- Both sides keep state: numbers, outboxes, id maps
- One stuck edit blocks every edit behind it until it is resent
- Replaying after a long time offline can be slower than a reload
- Offline edits can conflict with what others did meanwhile (part 3)
6Alternatives
| Option | How it works | Good for |
|---|---|---|
| Fire and forget | Send once, do not track it | Cursors and other data where the next message replaces the last one (part 4) |
| One HTTP request per edit, with an idempotency key | Retry the request; the server ignores keys it has seen | Forms and lower-frequency edits; no ordering across edits |
| Message broker with delivery guarantees | MQTT QoS levels, or a queue such as Kafka, handle acks and redelivery | Server-to-server pipelines, IoT devices |
| Sync by state, not by message | Each side says what it has (a version or state vector) and receives the difference, as CRDT libraries do | Long offline periods and peer-to-peer apps |
7Conclusion
Next: every edit now arrives, once, in order. But what if two people edited the same card at the same moment? Part 3 is about deciding whose change wins.