Blogs

Realtime collaboration series · Part 3 of 5

Two people change the same thing

You and a teammate both pick a color for the same button in the same second. A moment later, you see their color and they see yours. Nobody notices, and the file stays different on two screens until someone reloads.

1The problem: edits nobody saw coming

Parts 1 and 2 made sure every edit arrives, once, in order. That is not enough when two edits are concurrent: each was made without knowing about the other. If every screen simply applies what it receives, the order depends on the network, and screens can end up different.

Screens · animated
Alice’s screenBob’s screenAlice: “blue”Bob: “orange”make it bluemake it orangescreens disagreeAlice and Bob recolor the same card at the same momentEach applies the other’s change when it arrivesNow their screens disagree, and nothing will fix it
Each screen is “right” by its own order of events. The goal is not to pick the best color, but to make every screen agree on one.

Any fix has to guarantee one thing: everyone converges on the same state. After that, the questions are how much each person can lose, and how much complexity you are willing to carry.

2The solution: choose how to prevent, decide or merge

There is no single answer. There is a spectrum, from not letting conflicts happen at all, to letting everyone edit anything and combining the results.

Map
one editor at a timeeveryone edits everythingPreventLockOnly one person can edit;others waitfiles, records, legal docsDetectVersion checkSave fails if someonesaved first; retryforms, admin panelsDecideLast writer winsOne server orders edits;the later one wins, perpropertydesign canvases, boards,spreadsheetsMergeOT / CRDTBoth edits are combined;one value still needs a single winnertext documents, code,offline-first apps
Moving right lets more people edit at once, and costs more to build. Most products use more than one: a lock on a whole file, last-writer-wins on shapes, merge on text.

Decide: one server puts edits in order

For a canvas, a board or a spreadsheet, the simplest strategy that still lets everyone edit is server-ordered last writer wins. Every edit for a document goes through one place (the room owner from part 1), which applies them one at a time. The later edit wins. The server then sends each edit, with its order, to everyone.

Sequence · animated
Alice’s screenBob’s screenServerapplies in arrival order1. Alice: blue2. Bob: orangecard = orangeblueorange#2 orange#1 blue“#1 is older than myown pending edit: skip”same everywhere ✓Both edits go to one serverIt puts them in one order: the later one winsEveryone converges on the same answer
One order, applied everywhere, means every screen ends the same. The “skip” on Bob’s side stops Alice’s older blue from flashing over his orange.
Key ideaConvergence comes from a single order, not from clever merging. If every screen applies the same edits in the same order, they end the same.

Make the winner as small as possible

“Last writer wins” on a whole object throws away more than it needs to. Deciding per property keeps changes that did not really collide.

Compare
Alice changes the color, Bob changes the text, at onceBeforeButtonAliceButtoncolor → blueBobLogintext → “Login”Whole card winsLoginBob saved the whole card last: Alice’s blue is goneEach property winsLoginthey touched different properties: both survive
A real conflict is two people changing the same property of the same object. Everything else should simply combine.

Merge: when nothing may be lost

Text is different. Two people typing in one paragraph are editing the same property all the time, and dropping either person’s words is not acceptable. Here you need a merge:

  • Operational transformation (OT) rewrites an incoming edit against the edits it did not know about, for example shifting a position. A central server keeps the order. Google Docs works this way.
  • CRDTs give every character a unique, ordered id, so edits can be applied in any order and still produce the same text. Yjs and Automerge are popular libraries, and they work peer-to-peer and offline.
Example · animated
startHelloAliceHello!insert “!” at position 5BobOh, Helloinsert “Oh, ” at position 0whole text winsOh, HelloAlice’s “!” is lostmergeOh, HelloBob’s insert applied first…Oh, Hello!…so Alice’s position 5 becomes 9: “Oh, Hello!”
Both approaches reach “Oh, Hello!”. OT does it by adjusting positions; a CRDT by never using raw positions at all.
Key ideaMerge whenever you can; pick a winner when you cannot. Two people typing in one paragraph can both keep their words. Two people setting the same single value cannot: a red button and a blue button do not merge into a purple one, so one color has to win. Last writer wins is the usual rule, and CRDT libraries do the same for a value set twice: Yjs and Automerge keep one of the two. The only other option is to stop and ask a person.

3Example code

Server-ordered, per-property last writer wins, with the small client rule that keeps your own edits from flickering. Deleting, undo and text merging are left out.

server.ts
type Props = Record<string, unknown>
type Edit = { id: string; prop: string; value: unknown; from: string }

const doc = new Map<string, Props>()   // element id → its properties
let order = 0                          // one counter per document

// Every edit for this document passes through here, one at a time.
function applyEdit(edit: Edit) {
  const el = doc.get(edit.id)
  if (!el) return                      // element was deleted: drop the edit
  el[edit.prop] = edit.value           // last writer wins, per property
  broadcast({ ...edit, order: ++order })
}
client.ts
// Local edits we sent but the server has not confirmed yet.
const pending = new Map<string, number>()   // "id.prop" → how many in flight

function editLocally(id: string, prop: string, value: unknown) {
  setProp(id, prop, value)                  // show it immediately
  const key = `${id}.${prop}`
  pending.set(key, (pending.get(key) ?? 0) + 1)
  send({ id, prop, value })
}

function onServerEdit(e: Edit & { order: number }, mine: boolean) {
  const key = `${e.id}.${e.prop}`
  if (mine) {
    const left = (pending.get(key) ?? 1) - 1
    left ? pending.set(key, left) : pending.delete(key)
    return                                  // we already show our own value
  }
  // Someone else's older value must not flash over our newer one.
  if (pending.has(key)) return
  setProp(e.id, e.prop, e.value)
}

The server code is almost boring, and that is the point: because a single place applies edits one at a time, there is never a question of which came first. All the subtlety is in the client, which must not let an older value from someone else overwrite a newer one it is still waiting to confirm.

4In practice: a design tool

  • Per element, per property. Position, size, color and text of a shape are decided separately, so a move and a recolor never clash.
  • Deletes beat edits. An edit to an element that no longer exists is dropped rather than bringing it back.
  • Check structure, not just values. Two people moving groups into each other could create a loop (A inside B inside A). The server rejects the edit that would close the loop.
  • Undo is per person. Undo reverts your own last edit, even if others have edited since, otherwise one person’s undo erases a teammate’s work.
  • Text boxes can stay simple. Most shapes hold short labels edited by one person at a time; last writer wins on the whole label is usually fine. Long shared text is where a CRDT earns its cost.

5Pros and cons

For server-ordered, per-property last writer wins:

Pros

  • Everyone always converges on the same state
  • Simple to build and to reason about
  • Most real edits touch different properties, so few are lost
  • The server can validate every edit before it applies

Cons

  • On a true conflict, one person’s change silently disappears
  • Needs a server online; no peer-to-peer or long offline editing
  • Not suitable for shared text, where every keystroke conflicts
  • Long offline edits may overwrite newer work from others

6Alternatives

OptionConflicts are…Good for
Lock (check-out)impossible: others waitFiles, contracts, anything edited rarely by one person at a time
Version check (optimistic locking)detected; the later save fails and must retryForms and records with a save button
Last writer wins, server-ordereddecided; the later edit wins per propertyCanvases, boards, spreadsheets
Operational transformationmerged by adjusting positions on a central serverShared text documents
CRDTmerged by design, in any order, even peer-to-peerOffline-first apps, text, local-first software

7Conclusion

Key ideaFirst make every screen agree, then decide how much a conflict may lose. For most structured data, one server ordering per-property edits is enough. Merge wherever edits can be combined, like text; when two people set the same single value, one of them has to win.

Next: edits are reliable and conflicts are rare and fair. But you still cannot see who is about to touch what. Part 4 is about showing who else is here.