What you'll learn: By the end of this lesson you will be able to explain why concurrent edits cannot simply be applied as written, show how operational transformation (OT) rewrites an operation and why it relies on a server that picks one order, show how a CRDT avoids the problem by naming things, state what each costs a browser client (metadata, history, a server, a library), pick a merge policy per field instead of per system, and run a lab that shows both approaches converging.
Two editors hold the same printed draft of a letter. One writes "insert a paragraph after line 1". The other writes "delete line 3". Each posts the note to the other. When the notes arrive, "line 3" means something different, because the new paragraph pushed everything down. There are two ways out. A referee can rewrite each note against the one that went first, so "delete line 3" becomes "delete line 4": that is operational transformation. Or every line can have a permanent name, "delete the line called L7", so position stops mattering: that is the idea behind a CRDT for sequences.
This lesson is the front-end treatment: what the browser holds, what it sends, and what that costs. The theory of replicated data types, the two delivery styles and a replicated-list lab are in CRDTs and Conflict Resolution: Merging Edits Without a Coordinator, and ordering with logical clocks is in Logical and Vector Clocks; here they are the working definitions only. The messaging layer (WebSocket framing, reconnection and message ordering) and the product side of collaborative editing have their own lessons in this course.
The running example is an admin tool where two staff edit a product description, a price and a tag list at the same time. The lab's documents are tiny and made up for the lesson.
The core idea
- Concurrent edits cannot be applied as written. An edit is made against one version of the document. If another edit was made against the same version, applying them one after the other in each replica's own order gives different documents. Something has to change: the operation (OT), or what the operation refers to (CRDT).
- OT repairs the operation; a CRDT designs the data. OT takes two operations made concurrently and rewrites one so it means the same thing after the other, and in practice relies on a server to choose a single order. A CRDT (conflict-free replicated data type) is a data type whose merge gives the same result in any order, so replicas converge without one authority.
- The choice is architectural, and it is per kind of data. It decides who orders edits, how much metadata the client carries, how big the state grows, and which libraries you can use. Most fields of a real page need neither: a price is not text.
Three illustrations run through the lesson: a minimal example (insert and delete in the three-letter document "cat"), a realistic example (two staff editing a product description with a server in between) and a failure example (history that grows without bound, and text that interleaves).
The problem: positions shift
Take the document cat. User a inserts X at index 1, giving cXat. User b, at the same time, deletes the character at index 2, which is t, giving ca. Each then receives the other's operation.
Figure 1. Two concurrent edits applied as written
How to read this: each operation was correct for the text its author saw. Applied to a different text, "delete at 2" removes a instead of t.
The lab prints exactly this, and then the repaired version. The first block is the problem:
a: insert "X" at 1; b: delete at 2
a's screen: "cXt" b's screen: "cXa" (different)
Two users, two screens, no error. Nothing crashed and nothing is wrong locally, which is why this class of bug is dangerous.
Operational transformation: rewrite the operation
Operational transformation is described in the Wave OT paper as a theoretical framework of concurrency control; its transformer takes two operations as input and outputs two operations. The lab's transform(op, against) does this for one-character inserts and deletes: it returns op rewritten so that it means the same after against has been applied.
| Concurrent pair | Rule in the lab | Example on cat |
|---|---|---|
| insert, then something inserted before it | shift right | delete at 2 against insert at 1 becomes delete at 3 |
| operation, then something deleted before it | shift left | insert at 2 against delete at 0 becomes insert at 1 |
| two inserts at the same index | the smaller site id goes first | A from site a, B from site b: both screens show cABat |
| two deletes of the same character | the second becomes a no-op | already gone |
The rules are small, but they must agree on both sides: both replicas must produce the same document from the two orders. The same-index insert shows why. Without a tie-break rule both sides would keep their own insert first and diverge; the lab's tests include that broken variant and check 3,000 seeded random pairs of operations for convergence.
Each of those four cases is easy. Making a full set of rules correct for rich text, lists and nested structures, for any number of concurrent operations, is the hard part. The Fugue paper traces OT to Ellis and Gibbs and says CRDTs for text arose after bugs were found in several OT algorithms.
The server in the middle
A pairwise transform is not enough on a network where operations from three or more people cross. Practical OT systems add a server that decides a single order, as in the Wave design (which builds on the Jupiter design). Per the Wave OT paper, the client waits for an acknowledgement before sending more operations, and in the meantime caches what it produces locally. The server then needs only a single state space: it transforms each incoming operation against its own history, applies it and broadcasts it. The cost the paper names is that clients see others' changes in chunks, roughly one round trip apart.
Figure 2. The OT architecture
How to read this: the server is the one place that knows the order. Each client sends an operation with the revision it was made against, and the server rewrites it past everything the client had not yet seen.
The lab's OtServer and OtClient follow this shape. A client applies its own edit at once, keeps unconfirmed edits in a pending list, and sends one at a time with the number of server operations it had processed (baseRev). A remote operation is transformed past every pending edit, and each pending edit is transformed past it, before it is applied.
Figure 3. Two edits ordered by the server
How to read this: the same two operations as Figure 1, but ordered. The delete moved from index 2 to index 3, so it still removes t.
CRDTs: give every element a name
A CRDT is described on crdt.tech as a data structure that simplifies distributed data storage systems and multi-user applications, whose copies on different replicas merge without coordination. A sequence CRDT removes the problem of Figure 1 at the root: each character gets a unique id and an operation says "insert after the element with this id" instead of "insert at index 1". A delete marks the element as deleted. The Fugue paper explains why it is a mark and not a removal: deleted nodes may be ancestors of live or concurrently inserted nodes, so a deleted element's node cannot simply be removed. These marked elements are called tombstones. The backend lesson linked above builds such a list in the replicated-list lab; this lesson does not repeat it.
Most shared state in a front end is not text, and for that the small types in the lab are enough. Two fields of the admin tool show the two policies:
- the product's name, edited by two staff: a last-writer-wins register keeps the write with the greater timestamp, then the greater replica id, and silently drops the other;
- the product's tag list: an observed-remove set keeps an element added concurrently with its removal (add wins), because a remove only cancels the adds it has seen.
Figure 4. The CRDT architecture
How to read this: each replica applies its own edits immediately and merges whatever arrives. The relay moves bytes and may store them, but the merge result does not depend on it or on arrival order.
In a front end: libraries, not hand-rolled merges
In practice a team uses a library. Yjs describes itself as a high-performance CRDT for building collaborative applications that sync automatically, exposes its data as shared types similar to Map and Array (and Y.Text for text and rich text), makes no assumptions about the network, and needs no central source of truth. Its document updates are commutative, associative and idempotent, and per its documentation all clients sync up once they have received all updates. The text API still looks like indexes: insert(index, content) and delete(index, length); the unique ids are the library's job. Automerge is described as a data structure library for collaborative applications that merges concurrent changes automatically, works offline and syncs when a connection exists, with a JavaScript implementation for Node.js, Electron and browsers and a Rust one compiled to WebAssembly. Both leave the network to separate providers.
For OT, ShareDB describes itself as a full-stack library for realtime JSON document collaboration with a Node.js server that coordinates and commits edits from multiple clients, and a client that runs in Node.js or a browser. Presence (who is here, where their cursor is) is a separate feature in each. In Yjs it is the awareness protocol, defined in y-protocols: it spreads cursor location and a username, is described as a simple network-agnostic CRDT, lives in memory, and marks a remote client offline if nothing is heard for 30 seconds, so clients must rebroadcast. Presence is deliberately not part of the saved document.
| Question | Operational transformation | CRDT |
|---|---|---|
| Who decides the order | A server | No one: merge is order-independent |
| What the client sends | An operation and the base revision it was made against | An update the receiver can merge in any order |
| Offline editing | Edits wait in pending; the server transforms them on return |
Replicas edit freely and merge on return |
| Extra data kept | Little on the client; the server keeps history | Ids and tombstones in the document |
| Hardest part | Correct transformation rules for every pair of operations | Metadata growth and choosing a merge meaning |
| Examples named in this lesson | ShareDB | Yjs, Automerge |
What it costs: history, memory and surprises
History. The Ink & Switch local-first essay warns that CRDTs store all history, including character-by-character text edits, which causes storage and performance problems, and that old history is hard to discard because a collaborator may come back after months. Yjs exposes a gc flag on the document: set doc.gc = false to disable garbage collection and be able to restore old content, which shows the trade: a document that forgets deleted content cannot restore it. The Fugue paper reports numbers for its own saved document: the CRDT metadata is 60% of the text's size and the memory is about 23 bytes per character, which the authors argue refutes a common criticism of CRDTs. Those figures come from that paper's implementation and benchmark, not from every library.
Interleaving. Two people typing different words at the same place can get a merge that mixes the letters. The Fugue paper defines interleaving this way, says almost all the text collaboration algorithms it surveyed, both CRDT and OT, suffer from it in some case, and notes that RGA and Yjs are non-interleaving for forward insertion but can interleave backward insertions with multiple replicas. Convergence only promises that every replica agrees, not that the result is what either author meant.
Same-property conflicts. The Ink & Switch essay says a CRDT cannot automatically resolve a change to the same property of the same object by two users at once; the application or the user must choose. This is why the name field above needs a policy and not just a type.
Figure 5. Choosing per field
(stock, balance, uniqueness)?"} R -->|"yes"| SRV["One authority decides:
validate on the server"] R -->|"no"| T{"Must both users' edits be kept?"} T -->|"no, a lost write is fine"| LWW["Last writer wins
plus a version check"] T -->|"yes, it is a set"| SET["Add-wins set"] T -->|"yes, it is text"| TEXT["Text CRDT library
or OT with a server"]
How to read this: apply it field by field. A product page usually ends up with three or four of these branches.
The other side of this topic. On the back end the same ideas appear as ordering and causality: logical and vector clocks decide which of two events could have influenced the other, which is exactly the "was this edit made before or after seeing that one?" question OT answers with a revision number and a CRDT answers with ids. See Logical and Vector Clocks.
Build it: converge two ways
Goal. Run the lab's CRDT types and its OT model on small documents and see replicas converge, then see where a policy loses a write.
Setup. The lab is examples/frontend/labs/crdt-basics in the course's example workspace (Node 26.13.1, pnpm). It was extended for this lesson with an OT model (src/ot.ts, src/otSession.ts): operations, transform, a central server and a client that keeps pending edits. It is pure logic: no React, no DOM, no network.
cd examples/frontend
pnpm install
cd labs/crdt-basics
pnpm test # 55 tests, including 200 seeded OT sessions
node src/demo.ts
Steps.
- Run the tests, then the demo, and compare it with the output below.
- In the LWW-Register section, find the line where the tablet's write is lost: the type converged, and one write disappeared.
- In the OT sections, find the delete that moved from index 2 to index 3 at the server, and the last line: 200 random sessions with three clients and shuffled delivery all end on the server's document.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01; the LWW-Register, OR-Set and OT sections of the demo, the G-Counter and PN-Counter sections above them are left out):
=== LWW-Register: two devices rename a document concurrently
phone : {"replica":"phone","timestamp":1700,"value":"Q3 plan"}
laptop : {"replica":"laptop","timestamp":1700,"value":"Q3 roadmap"}
tablet : {"replica":"tablet","timestamp":1650,"value":"Q3 roadmap v2"}
merge(phone, laptop) = {"replica":"phone","timestamp":1700,"value":"Q3 plan"} (same timestamp: greater replica id "phone" > "laptop" wins)
merge(laptop, phone) = {"replica":"phone","timestamp":1700,"value":"Q3 plan"}
merge(tablet, laptop, phone) = {"replica":"phone","timestamp":1700,"value":"Q3 plan"} (the tablet write is lost: that is LWW)
=== OR-Set: add wins over a concurrent remove
A after remove : ["eggs"] state {"adds":{"eggs":["A:2"],"milk":["A:1"]},"removed":["A:1"]}
B after add : ["eggs","milk"] state {"adds":{"eggs":["A:2"],"milk":["A:1","B:1"]},"removed":[]}
merge(A,B) : ["eggs","milk"]
merge(B,A) : ["eggs","milk"]
same state: true
after a later remove that has seen both tags: ["eggs"]
and it can be added back: ["eggs","milk"]
=== OT: two users edit "cat" at the same time, applying each other's operation as written
a: insert "X" at 1; b: delete at 2
a's screen: "cXt" b's screen: "cXa" (different)
=== OT: the same operations, each rewritten past the other with transform
b's operation after a's: delete at 3; a's operation after b's: insert "X" at 1
a's screen: "cXa" b's screen: "cXa" (same)
two inserts at index 1: a's screen "cABat", b's screen "cABat" (smaller site id goes first)
two deletes of index 1: b's second operation becomes no-op
=== OT with a server: two edits made at the same time, put in one order by the server
a edits locally: screen "cXat", sends base revision 0
b edits locally: screen "ca", sends base revision 0
server stores revision 1: insert "X" at 1
server stores revision 2: delete at 3 (b had not seen revision 1, so the index moved from 2 to 3)
server "cXa"; a "cXa"; b "cXa"; revisions seen: a 2, b 2
=== OT: 200 random sessions (seeds 1 to 200): 3 clients, 60 steps, random delivery order
operations issued: 7997; rewritten by the server because they were concurrent: 2428
sessions where every client ended on the server's document: 200 of 200
What the lab does not show. No browser, no network and no real clocks: the LWW "timestamp" is a number the demo sets, and message delivery is a seeded shuffle that keeps each client's own queue in order, as one connection would. The OT model handles only one-character inserts and deletes, has no undo and no cursors, and relies on a central server; it does not attempt transformation between peers without one. The merge rules (site id as the tie-break, base revisions, one operation in flight) are this lab's own simplified design and are not how any library behaves. It has no sequence CRDT: the replicated-list lab of the linked backend lesson covers that.
Break it. In src/ot.ts, change const moves = against.pos < op.pos || (against.pos === op.pos && against.site < op.site); to const moves = against.pos < op.pos;. Four tests fail: the tie test, the 3,000-pair convergence check and both random-session tests. Restore it.
In practice: two staff editing one product description
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
An admin tool lets staff edit a product's description, price and tags. Two people sometimes edit the same product during a campaign. The tool sends the whole product on save, so the second save silently replaces the first person's change, including a paragraph they spent an hour writing.
Starting architecture
Figure 6. Starting point: the last save wins for the whole product
How to read this: nothing tells the second save that the product changed after it was loaded.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Lock the product while someone edits | No conflicts | A person waits, a lock can be left behind | Locks that never release |
| Per-field versions: reject a stale save and show the difference | Price and tags stop overwriting each other | A merge screen to build | Users see conflict dialogs |
| A text CRDT or OT library for the description, per-field policies for the rest | Both people's paragraphs survive | A library, a sync service, state that grows | Operating a new service |
The decision
| Field | Decision record |
|---|---|
| Context | The description is long text edited together; price and tags are small values. |
| Decision | Use a text CRDT library for the description. Keep a last-writer-wins register with a version check for the name and price, an add-wins set for tags, and validate stock and price rules on the server. |
| Consequences, good | Concurrent paragraphs both survive; price rules cannot be bypassed by a merge. |
| Consequences, bad | The description's history grows; a sync service must be run and monitored. |
| Revisit when | Two people rarely edit the same product (per-field versions may be enough), or documents grow large enough that load time suffers. |
Rollout and verification
- Ship the per-field versions first. They fix the silent overwrite for most fields with no new service.
- Add the text editing behind a flag for a few staff, and compare the merged text with each person's local copy.
- Watch document size, load time and the share of sessions that reconnect with unsent edits.
The 2 a.m. failure
Weeks later, opening the description of a long-running campaign product takes noticeably longer and the saved state is much larger than the visible text, because every deleted word is still in the document as history (illustrative). A staff member also reports that two people typing the same words at the same place produced a jumble.
First three checks: (1) compare the saved document size with the visible text length; (2) check whether garbage collection is enabled and whether anything needs the old content; (3) reproduce the jumble with two clients typing at once. Mitigation: snapshot the visible text into a fresh document for old products, and tell staff to work in different paragraphs. Follow-up: set a size budget with an alert, document the interleaving behaviour as a known limit, and keep the plain-text field as a fallback.
Architect's notes
- Decide per field, not per system. A price, a tag list and a paragraph need three different answers.
- Use a library for the hard part. Neither OT's transformation rules nor a text CRDT's ids are something to write in application code.
- Plan for state that only grows. Set a size budget and a snapshot or compaction path before launch.
- Keep rules that must hold on the server. A merge converges; it does not enforce a limit.
- Separate presence from the document. Cursors and "who is here" should not be saved.
Common mistakes
- Applying an operation written for an old version without transforming it.
- Assuming convergence means correctness. Every replica can agree on a result neither author wanted.
- Using last-writer-wins for text, which drops one person's work.
- Putting limits (stock, balance) in a CRDT.
- Saving presence data in the document.
Key takeaways
- Concurrent edits are made against one version, so they cannot be applied as written.
- OT rewrites the operation and in practice relies on a server that picks one order and transforms against its history.
- A CRDT names things (ids, tombstones, merge rules) so replicas merge in any order without one authority.
- Both converge; neither guarantees the merged result is what the users meant.
- Costs: OT needs a server and correct transformation rules; CRDTs keep history that grows.
- Choose per field: validate rules on the server, last-writer-wins for small values, add-wins sets for sets, a library for text.
Practice exercises
Exercise 1 — Starter (45 min): In the lab, write a test where a deletes at 0 and b inserts at 0 on cat, work out by hand what each side must send, and check it against transform.
Exercise 2 — Intermediate (2 hours): Add an operation that deletes a range of two characters to the OT model. List the cases of transforming it against an insert inside the range, and explain why the single-character version was simpler.
Exercise 3 — Advanced (half day): For a form with a title, a long description, a tag list and a stock count, choose a merge policy for each field using Figure 5, and write down which field would still lose a user's change and how you would show that to the user.
Related reading
In this course:
- CRDTs and Conflict Resolution: Merging Edits Without a Coordinator, delivery styles, conflict policy and the replicated-list lab.
- Logical and Vector Clocks, ordering events without a shared clock.
- Offline-First Sync and Conflict Resolution, where a conflict policy meets an outbox and a server.
- State Persistence and Synchronization, why ordering is not merging.
- WebSockets, Server-Sent Events and Long Polling, the transport a sync layer runs on.
Official documentation
- CRDT.tech: About CRDTs, the definition and reading list.
- Yjs documentation, Y.Text, Document Updates and About Awareness.
- Automerge documentation, what it is and its languages.
- ShareDB, a realtime collaboration library built on operational transformation.
- Google Wave Operational Transformation, the client and server protocol with acknowledgements.
- Weidner and Kleppmann: The Art of the Fugue, tombstones, metadata size and interleaving across OT and CRDT algorithms, and Ink & Switch: Local-first software, the ideals and the limits of CRDTs.