Blogs

Realtime collaboration series · Part 2 of 5

Edits get lost, doubled or out of order

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.
Screens · animated
Alice’s screenBob’s screen123123CardCardends on 2, should be 3network#1 move to 2#2 move to 3Alice drags a card to slot 2, then slot 3Her “move to 2” gets stuck on a slow routeIt arrives last, and Bob’s card ends in the wrong place
Order matters for edits to the same thing. “Move to 2” then “move to 3” is not the same as “move to 3” then “move to 2”.

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:

  1. Number every edit. The receiver applies edit n only after n − 1.
  2. Keep it until it is confirmed. The sender holds each edit until the receiver says “I have everything up to n”.
  3. Refill gaps. If the receiver sees a number it was not expecting, it asks to resend from the missing one.
  4. Ignore repeats. An edit with a number already applied is dropped, so resending is always safe.
Sequence · animated
Browserkept until confirmedServerapplied#1#2#3#1#2#3#1#2✕lost#3#3? I need #2 firstresend from #2#2#3ok up to #3Every edit gets a numberA gap is noticed and refilledThe browser forgets an edit only once it is confirmed
Numbers turn “lost”, “doubled” and “out of order” into one problem the receiver can detect: a gap.
Key ideaResending is only safe if repeats are harmless. Numbers make every edit idempotent: the second copy of #3 is recognised and ignored.

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.

Screens · animated
Bob’s screenLiveReconnecting…Livecaught up on 3 changesServerlatest: #44Wi-Fi dropspingpongpingpongpingno pong in time → connection is deadretry 1 ✕retry 2 ✕waits 1 s, then 2 s, then 4 s…hello, I have up to #41#42#43#44Small pings prove the line is aliveSilence means it is dead: reconnect, waiting longer each timeBack online, say what you have; the server sends what you missed
Heartbeat, backoff and replay together turn a dropped connection into a short “Reconnecting…” and a quiet catch-up.

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.

Screens · animated
Alice’s screenOffline: changes are saved on this deviceBack online: sending saved changes…All changes saved ✓✎ rename title✎ add a card✎ move a cardOutboxon disk (IndexedDB)rename titlerename titleadd a cardadd a cardmove a cardmove a cardServerunreachableEvery edit is saved locally firstOffline, the outbox simply growsOnline again, it drains in order
The outbox is the numbered list from above, kept on disk instead of in memory.

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.

Sequence · animated
Alice’s screentmp-7tmp-7card-901Servertmp-7 → card-901remembered at oncecolor card-901 ✓create tmp-7color tmp-7 orangetmp-7 is card-901The browser names a new card itself, instantlyLater edits use that name before the server has answeredThe server maps it; the browser swaps in the real id
The server records the mapping as soon as the create arrives, before the database write finishes, so edits right behind it are not lost.

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.ts
type 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

OptionHow it worksGood for
Fire and forgetSend once, do not track itCursors and other data where the next message replaces the last one (part 4)
One HTTP request per edit, with an idempotency keyRetry the request; the server ignores keys it has seenForms and lower-frequency edits; no ordering across edits
Message broker with delivery guaranteesMQTT QoS levels, or a queue such as Kafka, handle acks and redeliveryServer-to-server pipelines, IoT devices
Sync by state, not by messageEach side says what it has (a version or state vector) and receives the difference, as CRDT libraries doLong offline periods and peer-to-peer apps

7Conclusion

Key ideaNumber every edit, keep it until it is confirmed, and make repeats harmless. Heartbeats and backoff find dead connections, an on-disk outbox survives closed tabs, and temporary ids keep new objects instant.

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.