Skip to content

    Frontend System Design

    CRDTs and Operational Transformation

    Compare operational transformation and CRDTs for shared state in the browser: how each merges concurrent edits, what the client carries and costs, with a lab.

    By Published 16 min read

    • frontend-system-design
    • crdt
    • operational-transformation
    • collaboration
    Share

    Flagship lessonadvancedTypeScript labFrontend System Design

    Before this: Reconnection and Message Ordering

    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

    1. 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).
    2. 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.
    3. 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

    sequenceDiagram accTitle: Applying concurrent edits as written accDescr: Users a and b both start from the text cat. User a inserts X at index 1 and user b deletes the character at index 2. Each sends its operation to the other and applies it unchanged. User a ends with cXt and user b ends with cXa, so the replicas have diverged. participant A as User a participant B as User b Note over A,B: both start from "cat" A->>A: insert "X" at 1, screen "cXat" B->>B: delete at 2, screen "ca" A->>B: insert "X" at 1 B->>A: delete at 2 Note over A: applies delete at 2 to "cXat", screen "cXt" Note over B: applies insert at 1 to "ca", screen "cXa" Note over A,B: the replicas have diverged

    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

    Operational transformation: clients keep their own edits visible, and one server orders and transformsClient a to OT server (operation, base revision); Client b to OT server (operation, base revision); OT server to Document (apply in order)Client a: pending editsClient apending editsClient b: pending editsClient bpending editsOT server: history, transformOT serverhistory,transformDocument: server copyDocumentserver copyoperation, base revisionoperation, base revisionapply in order

    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

    sequenceDiagram accTitle: Two concurrent edits ordered by an OT server accDescr: Clients a and b start from cat. Client a sends insert X at 1 and client b sends delete at 2, both with base revision 0. The server stores insert X at 1 as revision 1, then rewrites b's delete at 2 to delete at 3 because b had not seen revision 1, and stores it as revision 2. Both clients and the server end on cXa. participant A as Client a participant S as Server participant B as Client b A->>S: insert "X" at 1 (base revision 0) B->>S: delete at 2 (base revision 0) Note over S: revision 1: insert "X" at 1 Note over S: revision 2: delete at 3 (b had not seen revision 1) S-->>A: ack revision 1, then delete at 3 S-->>B: insert "X" at 1, then ack revision 2 Note over A,B: all three show "cXa"

    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

    CRDT replicas edit locally and exchange updates through a relay that does not decide the resultReplica a to Sync relay (updates); Replica b to Sync relay (updates); Sync relay to Saved copy (persist)Replica a: local documentReplica alocal documentReplica b: local documentReplica blocal documentSync relay: forwards updatesSync relayforwards updatesSaved copy: optionalSaved copyoptionalupdatesupdatespersist

    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

    flowchart TD accTitle: Choosing a merge approach per field accDescr: For each field, ask whether concurrent edits must keep both users' text. If not, and a lost write is acceptable, use last writer wins with a version check. If both writes must be kept and it is a set, use an add-wins set. If it is long text, use a text CRDT library or OT with a server. If a wrong merge breaks a rule such as stock not below zero, one server decides. F["A field edited by two users"] --> R{"Does a wrong merge break a rule
    (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.

    1. Run the tests, then the demo, and compare it with the output below.
    2. In the LWW-Register section, find the line where the tablet's write is lost: the type converged, and one write disappeared.
    3. 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

    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

    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

    Starting architecture: each staff member loads the product, edits a local copy and saves the whole thingStaff 1 to Product API (PUT product); Staff 2 to Product API (PUT product); Product API to Database (overwrite)Staff 1: edits a copyStaff 1edits a copyStaff 2: edits a copyStaff 2edits a copyProduct API: replace on saveProduct APIreplace on saveDatabase: one rowDatabaseone rowPUT productPUT productoverwrite

    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

    1. Ship the per-field versions first. They fix the silent overwrite for most fields with no new service.
    2. Add the text editing behind a flag for a few staff, and compare the merged text with each person's local copy.
    3. 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.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments