What you'll learn: By the end of this lesson you will be able to explain why "put this at position 5" breaks when two people edit at once, describe a server-ordered design (operations, revisions, a central history), transform one operation across another, run the client state machine (synchronized, awaiting acknowledgement, awaiting with a buffer), keep a caret in place when someone else types, and say what convergence does not promise.
Picture two people editing a shared shopping list over the phone. One says "add eggs after line 2", the other says "delete line 3" at the same moment. Each does what they heard, then they read out the result and the lists differ. Each instruction was true when spoken and false once the other change landed. A collaborative editor is the set of rules that makes both phones end on the same list.
The running example is a shared note on an order in the grocery marketplace front end used in this course: a picker and a support agent both type substitution notes into one text box.
The core idea
- An edit is data, not a new copy of the text. Sending whole texts makes the last writer win and silently drops the other person's work. Sending small operations lets both survive.
- Positions are only true for the text they were made against. An insert "at 0" is the same operation after someone else typed, but "delete at 2" may now point at the wrong character. Something must rewrite it.
- One order, then rewrite. In the design this lesson teaches, a server decides the order of all operations; every operation that was made against an older text is rewritten across the ones accepted since. That rewriting is called operational transformation (OT).
The alternative that avoids rewriting by giving each character an identity is the CRDT approach, compared with OT in the CRDTs and Operational Transformation lesson of this module, and covered from the back end in CRDTs and Conflict Resolution. This lesson builds what both families share: an operation model, a local copy that responds at once, and a way to reconcile.
Why positions break
Wikipedia's article on operational transformation uses a three-letter text: with the text "abc", one site applies Insert[0, "x"], giving "xabc", while another site concurrently applies Delete[2, "c"]. Run the delete at its original position on "xabc" and it removes "b" instead of "c"; the fix is to shift it to Delete[3, "c"], so both sites end with "xab". The idea is to adjust an operation's parameters so it keeps its intended effect after concurrent edits.
Illustration 1: the minimal example
The lab runs exactly that case through two clients and a server, first with rewriting off and then on.
Expected output, captured from a real run (first scenario of the lab demo):
1. Insert and delete at the same time, on "abc" (a inserts "x" at 0, b deletes the "c")
without transformation server="xac" a="xac" b="xab"
server history 1: insert(0, "x"); 2: delete(2)
with transformation server="xab" a="xab" b="xab"
server history 1: insert(0, "x"); 2: delete(3)
Without rewriting, the server deleted the wrong character ("xac"), client a agrees with it, and client b, which applied the edits in the other order, holds "xab". With rewriting, the server stored the delete as delete(3) and every copy agrees on "xab".
The design: a central authority
CodeMirror's collaboration example describes the same architecture: "a central system (authority) that builds up a history of changes". Each update pairs a change with a client id, and the length of the history array is the current version. ProseMirror's guide says its collaborative editing "employs a central authority which determines in which order changes are applied", with the authority's version being the length of its step list; editors send the last version they received so the authority can tell whether their changes are current.
Figure 1. Clients, an authority and one history
How to read this: each editor sends an operation together with the revision of the text it was made against. The authority compares that revision with its own, rewrites the operation across anything newer, appends it and tells everyone, the sender included.
The server's rule is short. An operation made against revision base is carried across every operation accepted since, in order, then applied and appended. In the lab (src/server.ts):
for (const accepted of this.#history.slice(msg.baseRevision)) op = transform(op, accepted, true);
this.#doc = apply(this.#doc, op);
this.#history.push(op);
CodeMirror's example says the server can instead reject an out-of-date push, but warns that this can starve a high-latency client whose peers keep submitting, so it recommends rebasing when practical. ProseMirror's guide says a rejected editor rebases its local changes on top of the others' and resubmits.
Figure 2. The abc example over time
How to read this: A's edit is ordered first, so B's delete is the one rewritten, from position 2 to position 3. Each client applies its own edit at once; the arrows show what the server later says about it.
The transform rules
transform(op, other, otherFirst) returns op as it must be applied after other. There are only a few cases for insert and single-character delete:
op |
other |
Result |
|---|---|---|
| insert | insert before it | shifted right by the length of the other text |
| insert | insert at the same position | shifted right only if other was ordered first |
| insert | delete before it | shifted left by one |
| delete | insert at or before it | shifted right by the other text's length |
| delete | delete before it | shifted left by one |
| delete | delete of the same character | becomes a no-op |
The same-position insert is the one case with no right answer, only a rule every replica shares. The lab breaks the tie by server order, so no client names are involved, and scenario 2 of the demo has a first: aXYb on every copy. Wikipedia states the property a transform must have (called TP1 or CP1): applying one operation and then the other, transformed, must give the same result as the reverse order. The lab's test checks it on 2,000 seeded random pairs.
The client: three states
A client cannot wait for the server before showing a keystroke. CodeMirror's example keeps unacknowledged local edits queued on the peer and sends them with the version the peer has synchronised to; if a push is in flight, it waits. The lab's client sends one operation at a time and has three states.
Figure 3. The client state machine
How to read this: the text on screen always holds the user's own edits. A remote operation is transformed across everything pending before it is applied, and the pending operations are transformed across it, so what is sent next is still correct.
The client's visible text is the server's text plus the pending operations, which is why the user's typing never waits. This is the same shape as an optimistic update (Optimistic Updates and Rollback), with the difference that a rejected change is rewritten, not rolled back.
Carets
A caret is a position, so it needs the same treatment. A text area's selectionStart is, per MDN, a zero-based index of the first selected character, or the caret position if nothing is selected. The lab maps a caret across an operation: an insert strictly before it, or a delete strictly before it, moves it; an insert exactly at it leaves it before the new text.
Expected output, captured from a real run (the caret scenario of the lab demo):
5. Where a caret goes (text "hello world", caret at 5, after the word hello)
insert(0, "Oh, ") caret 5 -> 9
insert(5, "!") caret 5 -> 5
insert(8, "big ") caret 5 -> 5
delete(1) caret 5 -> 4
delete(7) caret 5 -> 5
Showing other people's carets is a separate feature (presence, covered in its own lesson of this module); it reuses the same position mapping.
Offline and reconnecting
A client that cannot reach the server keeps editing and its operations queue. When it reconnects, the server transforms them across everything accepted meanwhile.
Illustration 2: the realistic example
On the order note, the picker is in a cold store with no signal. The picker prepends "buy " and appends "!" while the agent, online, adds a comma and appends " bread".
Expected output, captured from a real run (lines 16 to 21 of the demo output):
3. One client offline (text "milk eggs"; b edits twice while offline, a edits twice and its edits go through first)
b has 2 unacknowledged changes; only the first is in flight
edits made server="milk eggs" a="milk, eggs bread" b="buy milk eggs!"
a's edits delivered, b offline server="milk, eggs bread" a="milk, eggs bread" b="buy milk eggs!"
b reconnects, all delivered server="buy milk, eggs bread!" a="buy milk, eggs bread!" b="buy milk, eggs bread!"
server history 1: insert(4, ","); 2: insert(10, " bread"); 3: insert(0, "buy "); 4: insert(20, "!")
Both people's edits are in the final text. The picker's ! was typed at position 13 and landed at 20 because 7 characters were added before it. Storage and conflict policies are in Offline-First Apps: Sync and Conflict Resolution; how this looks to the user is the subject of Offline UX Patterns in this module.
Convergence is not intent
All copies agreeing is the guarantee; whether the result is what each author meant is not.
Illustration 3: a failure and an edge
Two people type into an empty text, one character per message: a types "ABC", b types "123".
Expected output, captured from a real run (first two lines of the scenario):
4. Two people type at the same place, one character per message (a types ABC, b types 123 into an empty text)
after delivery server="A1B2C3" a="A1B2C3" b="A1B2C3"
Every copy holds "A1B2C3". The words are interleaved, because each character is ordered separately and the delivery schedule here alternated. A different schedule would give a different but equally convergent result. Production editors batch operations and handle rich text and undo; this model does none of that. An edge case: if both people delete the same character, the second delete becomes a no-op (scenario 2b in the demo). How much the rewriting matters shows in 200 seeded random sessions of three clients with random delivery order.
Expected output, captured from a real run (the last section of the demo):
6. 200 seeded random sessions (3 clients, 40 steps, random delivery order)
with transformation 200 of 200 converged, 0 threw while applying, 3225 edits in total
without transformation 0 of 200 converged, 81 threw while applying, 2858 edits in total
Without rewriting, no session converged, and 81 of them applied an operation at a position that no longer existed.
OT and CRDTs, briefly
Wikipedia lists a CRDT sequence type as another alternative to OT, and notes that "post-OT" designs avoid transforming operations by using unique identifiers, vector timestamps and tombstones. Yjs, whose documentation calls it a high-performance CRDT, says documents sync as long as all changes eventually arrive and the order of updates does not matter, and lists bindings for editors including ProseMirror, Monaco and CodeMirror. ShareDB, in contrast, names OT as its conflict management for JSON documents. The CRDT-and-OT lesson in this module compares them; the question that matters here is where the order comes from: a server in the design above, the data itself in a CRDT. Why wall-clock time cannot supply an order is in Logical and Vector Clocks.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Server-ordered OT | Simple order; small state; works with a plain server | The server is a bottleneck and a single point of failure; the transform rules multiply with each operation type |
| One operation in flight | Easy to reason about | Slow acknowledgement slows the pipeline unless operations are batched |
| Rebase on the server | A late client is never starved | History back to the client's revision |
| CRDT sequence | No central order needed | Per-character metadata and tombstones |
Build it
The lab is examples/frontend/labs/collab-editing-basics: a pure model of server-ordered OT for plain text, with a thin React component on top. The core (src/ops.ts, src/server.ts, src/client.ts, src/session.ts) has no DOM and no timers; the Session class stands for a network whose messages you deliver by hand. src/EditorPanel.tsx is a text area and a status line that read a client through useSyncExternalStore. It is a model: it is not a production editor, uses no real socket, and has no composition (IME) handling, which MDN's compositionstart page describes as a session in which a text composition system builds text before it is committed.
cd examples/frontend/labs/collab-editing-basics
../../node_modules/.bin/vitest run # 29 tests: operations, the server, the client, 200 + 100 random sessions, the React panel in jsdom
node src/demo.ts # the output shown above
Verified. The tests passed and the demo output above is a verbatim excerpt of examples/frontend/golden/collab-editing-basics.txt. The React tests ran in jsdom, a JavaScript model of the DOM: no typing in a real browser, layout, caret drawing or screen reader was observed.
In practice: the shared order note
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A picker and a support agent both edit the free-text note on an order. Today a save sends the whole note, and the last save wins. Agents report that the picker's substitutions "disappear".
Starting architecture
Figure 4. Starting point: whole-note saves
How to read this: the warning box overwrites the whole value, so the later save erases whatever the earlier one added since the other person last loaded.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Lock the note while one person edits | No lost edits | Waiting, stuck locks | Locks held by closed tabs |
| Server-ordered operations (this lesson) | Both edits kept | Operation history, transform code | Transform bugs; a busy single server |
| A CRDT library | No central order | A dependency and larger state | Library maturity and format lock-in |
The decision
| Field | Decision record |
|---|---|
| Context | Two people edit one short text; the server is already in the loop. |
| Decision | Server-ordered operations over the existing real-time connection, with a revision on every message and a snapshot to resync from. |
| Consequences, good | Both people's edits survive; the model is small enough to test exhaustively. |
| Consequences, bad | History must be kept; retries must not apply an operation twice. |
| Revisit when | Offline-first editing of long documents or rich text is needed. |
Rollout and verification
- Test the transform with the rules table and a seeded random convergence test.
- Test the client against a controlled network, delivering messages in the order each scenario needs.
- Dark-launch by recording operations while the old save still runs, and compare the final texts.
- Watch for divergence: compare a hash of each client's text with the server's.
The 2 a.m. failure
Users on a flaky connection see doubled characters. A reconnect resends an operation whose acknowledgement was lost, and the server applies it twice. The lab's server does not guard against this: its messages carry no operation id.
First three checks: (1) does each operation carry a unique id, and does the server remember recent ones; (2) compare the server history with a client's pending list around the reconnect; (3) check whether the client resyncs from a snapshot after a gap. Mitigation: drop the duplicate by id and force a resync. Follow-up: a test that replays an unacknowledged operation.
Architect's notes
- Keep the operation set small. Each new operation type multiplies the transform cases.
- Send a revision with every operation. The server cannot rewrite what it cannot place.
- Hash and compare. Convergence bugs are silent; detect them by comparing state.
Common mistakes
- Sending whole texts and calling it collaboration.
- Applying a remote operation without transforming it across pending local ones.
- Forgetting the tie rule for inserts at the same position.
- Assuming a retry is safe without an operation id.
Key takeaways
- Edits are operations; positions are only valid for the text they were made against.
- A central authority gives one order; late operations are rewritten across newer ones.
- The client applies its own edits at once, keeps them pending, and transforms every remote operation across them.
- Carets move with the same rules as text.
- Convergence means every copy agrees, not that the result is what each author meant.
Practice exercises
Exercise 1: Starter (30 min). By hand, transform insert(2, "Q") across delete(1) and across insert(2, "ab") with each tie rule, then check with the lab.
Exercise 2: Intermediate (2 hours). Add an operation id to each message and make the server ignore a repeat; add a test that replays an unacknowledged operation.
Exercise 3: Advanced (half day). Let a client send its whole buffer as one batch. What must the server transform?
Related reading
In this course:
- CRDTs and Conflict Resolution: the back-end treatment of CRDTs.
- Logical and Vector Clocks: ordering events without wall-clock time.
- Offline-First Apps: Sync and Conflict Resolution: local copies and merge policies.
- Optimistic Updates and Rollback: applying a change before it is confirmed.
- WebSockets, SSE and Long Polling: the transports under real-time editing.
Official documentation
- CodeMirror: Collaborative Editing example: a central authority, versions, unconfirmed changes and rebasing.
- ProseMirror guide: Collaborative editing: the authority, step versions and rebasing local changes.
- Wikipedia: Operational transformation: the insert and delete example and the convergence property.
- CRDT.tech: what a CRDT is.
- Yjs documentation: a CRDT library for collaborative applications.
- ShareDB: a server and client using operational transformation for JSON documents.
- MDN: HTMLTextAreaElement.selectionStart: the caret position in a text area.