Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 38

OT vs. CRDTs: A Conceptual Divide

Recommended resources

Welcome back. In our previous lesson, we established the communication channels—like WebSockets—needed for real-time features. We saw that for something as complex as a collaborative editor, just having a low-latency, bidirectional channel isn't enough. The critical challenge lies in what you send over that channel. When multiple users edit the same document concurrently, especially with intermittent connectivity, how do you merge their changes without corrupting the document or losing work?

This is a classic distributed systems problem, and it requires a formal, algorithmic approach. This lesson moves up the stack from the network transport to the data model itself. We will explore the two dominant philosophies for achieving consistency in collaborative applications: Operational Transformation (OT) and Conflict-free Replicated Data Types (CRDTs). By the end of this lesson, you will be able to explain the conceptual difference between them, their core mechanisms, and the architectural trade-offs that guide when to use one over the other—a key discussion point in senior frontend system design interviews.

1. The Challenge of Concurrent Editing

Before we dive into the solutions, it's crucial to understand why this problem is so difficult. Naive approaches that might seem intuitive often fail spectacularly.

Imagine two users, Alice and Bob, start with the text cat.

  • Alice concurrently inserts s at the end (cats).
  • Bob concurrently inserts r at the beginning (rcat).

If we simply represent these as operations based on character indices—insert('s', 3) and insert('r', 0)—and send them to each other, the final state depends entirely on the order they are applied. If Bob's operation is applied to Alice's document, the r is inserted at index 0, resulting in rcats. If Alice's operation is applied to Bob's document, the s is inserted at index 3, resulting in rcats. This seems to work.

But what if both edit the same position?
Start with: hello

  • Alice inserts X at index 2: heXllo
  • Bob deletes the character at index 2 (l): helo

If we just apply the raw operations, we get chaos. If Alice's insert arrives at Bob's client, it inserts X at index 2 of helo, giving heXlo. If Bob's delete arrives at Alice's client, it deletes the character at index 2 of heXllo (X), giving hello. The clients have diverged, and user intent has been lost.

This demonstrates the core problem: an operation's meaning is tied to the state of the document at the moment it was created. When that state changes due to concurrent edits, the operation itself must be adapted.

Operational Transformation (OT) and CRDTs - Real-Time Collaboration Systems - DEV Community

This article from the DEV Community provides an excellent foundation by first explaining why simple approaches to merging are doomed to fail. This context is essential for appreciating why OT and CRDTs were invented.

Start by reading Chapter 1, which frames concurrent editing as a distributed systems challenge and defines concepts like "intention preservation." Then, read Chapter 2, which walks through why naive merging strategies like "last write wins" or server-ordered streams are insufficient.

A crucial insight, especially given your interest in distributed systems, is that this problem is fundamentally different from consensus (like in a blockchain). A consensus algorithm forces all nodes to agree on one value out of many conflicting proposals, discarding the rest. In collaborative editing, we want the opposite: to preserve all contributions and merge them together intelligently.


2. The Two Philosophies: OT vs. CRDT

The diagram below illustrates the high-level architectural difference between the two main approaches to solving this problem. We will spend the rest of the lesson unpacking this.

This diagram shows the centralized, transform-based flow of Operational Transformation versus the decentralized, merge-based flow of a Conflict-free Replicated Data Type.

As the "Operation Flow and Convergence" diagram shows, OT and CRDTs represent two fundamentally different philosophies for achieving a consistent state.

  • Operational Transformation (OT): Assumes conflicts will happen and provides a mechanism to resolve them by changing the operations. It's a system of conflict resolution.
  • Conflict-free Replicated Data Types (CRDTs): Designs the data structures and operations in such a way that conflicts are mathematically impossible. It's a system of conflict avoidance.

3. Operational Transformation (OT): The Centralized Arbiter

OT is the older of the two approaches and is famously used in Google Docs. Its core idea is to preserve user intent by transforming incoming operations to account for changes that have already occurred.

How It Works

In an OT system, when a client generates an operation (e.g., insert('a', 5)), it sends it to a central server. This server is the single source of truth for the document's state and, most importantly, for the total order of all operations.

  1. Centralized Ordering: The server receives operations from all clients and establishes a definitive sequence. For example, it might process OpA from Alice, then OpB from Bob, then OpC from Alice.
  2. Transformation: When the server receives a new operation, say OpB, it first transforms OpB against any concurrent operations it has already accepted (like OpA). This transformation modifies OpB into OpB' so that it can be correctly applied to the document state after OpA.
  3. Broadcast: The server then broadcasts the transformed operation (OpB') to all other clients.
  4. Convergence: Because every client receives and applies the same sequence of transformed operations from the server, all clients are guaranteed to converge to the same final state.

Conflict-Free Replicated Data Types (CRDT) for Distributed JavaScript Apps.

This video provides a very clear, visual explanation of the OT mechanism and its reliance on a central server.

First, watch the walkthrough of a simple text editing example to see how transformations work to preserve user intention. Then, pay close attention to the explanation of the "Google Docs cheat" (multi-peer editing limitations), which clarifies why a central server is a mandatory part of most practical OT implementations.

The key takeaway is that OT's complexity lives in the transformation logic. You need a function for every possible pair of concurrent operations (Transform(Insert, Insert), Transform(Insert, Delete), etc.). Getting this "algebra" of operations correct is notoriously difficult; for years, many published OT algorithms were later found to have subtle bugs.


4. Conflict-free Replicated Data Types (CRDTs): The Decentralized Merge

CRDTs are a newer approach, born from the world of distributed databases and peer-to-peer systems. They are used by modern collaborative tools like Figma and Notion. The philosophy is to make the data structure itself so smart that the order of operations doesn't matter.

How It Works

A CRDT achieves this by ensuring its merge function has three mathematical properties:

  • Commutative: merge(A, B) is the same as merge(B, A).
  • Associative: merge(A, merge(B, C)) is the same as merge(merge(A, B), C).
  • Idempotent: merge(A, A) is the same as A.

Together, these properties guarantee that as long as all replicas receive the same set of updates, they will converge to the same state, regardless of the order or number of times they receive them.

How does this work for text editing?

  1. Abandon Indices: CRDTs discard unstable numeric indices (0, 1, 2...). Instead, every character (or element) is assigned a globally unique and immutable ID.
  2. Positional IDs: An insertion is not "insert 'X' at index 5." It's "insert 'X' with new ID id_X between the elements with id_A and id_B."
  3. Deterministic Ordering: When two users concurrently insert between the same two elements, they each generate a new unique ID for their character. The final order is resolved simply by sorting the IDs. Because the ID generation and sorting rules are deterministic, all clients arrive at the same order without any central coordination.
  4. Tombstones for Deletes: When an element is deleted, it isn't removed from the data structure. It's marked with a "tombstone." This prevents errors if another client tries to reference that element in a later operation (e.g., inserting a character next to it). The element is kept for historical reference but is hidden from the user's view.

CRDTs and the Quest for Distributed Consistency

This talk by Martin Kleppmann, a leading researcher in this field, provides an authoritative overview of CRDTs.

First, watch the section explaining the history and challenges of Operational Transformation, which provides context for why CRDTs were developed. Next, understand the basic idea of CRDTs by seeing how they apply to different data types like sets and counters. Finally, watch the detailed explanation of how a text CRDT works using unique identifiers to handle concurrent insertions and resolve conflicts deterministically.

The complexity in CRDTs moves from the transformation logic into the data structure itself. The trade-off is often a higher memory and network footprint due to the metadata (unique IDs, tombstones) that must be stored and transmitted.


5. Head-to-Head: The Brutal Comparison

Now that we have a conceptual understanding of both, we can make a direct comparison. No algorithm is universally superior; the choice is a significant architectural decision that depends entirely on product requirements.

Operational Transformation (OT) and CRDTs - Real-Time Collaboration Systems - DEV Community

The same DEV Community article we started with provides a clear, detailed breakdown of both OT and CRDTs, culminating in a direct comparison table.

First, read Chapter 4 for a recap of OT's mechanics and its reliance on a central server. Next, dive into Chapter 5 to understand the internal mechanics of CRDTs, including how they use IDs and tombstones. Finally, study the excellent comparison table in Chapter 6, which summarizes the key differences.

Let's synthesize this information into a comprehensive trade-off table, incorporating performance aspects.

Dimension Operational Transformation (OT) Conflict-free Replicated Data Types (CRDTs)
Core Idea Transform operations to fit the current state (conflict resolution). Design data structures so that merge order doesn't matter (conflict avoidance).
Architecture Centralized. Requires a server to establish a total order of operations. Decentralized. Natively supports peer-to-peer and offline editing.
Complexity In the transformation logic. Hard to implement correctly (many edge cases). In the data structure. Metadata management (IDs, tombstones) is complex.
Offline Support Difficult and fragile. Long offline periods can lead to complex and slow merges. A primary strength. Replicas can diverge and merge seamlessly when reconnected.
Payload Size Small. Operations are typically compact (e.g., insert(char, pos)). Larger. Operations or state deltas must include rich metadata (unique IDs).
Memory Usage Low. The document state is compact. High. The structure grows with every edit due to IDs and tombstones.
Garbage Collection Simple. Once an operation is in the server's log, its job is done. Hard. Removing tombstones requires coordination to ensure no replica ever needs them again.
Text Editing Intent Generally better at preserving user intent for linear text edits. Can result in "interleaving" of concurrently typed words (e.g., "helllpo" instead of "hello world").
Real-World Examples Google Docs, Microsoft Office Online, Etherpad Figma, Notion, Apple Notes, Automerge, Yjs
This table compares the performance characteristics of CRDTs and OT across latency, operation cost, and network bandwidth.

Conclusion

You now have a solid conceptual framework for the two primary strategies for building collaborative applications. In a senior-level interview, being able to articulate these trade-offs clearly is far more important than knowing the implementation details of a specific algorithm.

Key Takeaways:

  • OT is for Centralized Control: It optimizes for efficiency and fidelity in text editing by using a central server as an arbiter. This makes it a good fit for applications where a reliable connection is expected and offline work is a secondary concern.
  • CRDTs are for Decentralized Resilience: They optimize for availability and offline-first capabilities by designing data to merge mathematically. This makes them ideal for P2P applications, local-first software, and scenarios with unreliable networks.
  • It's a Trade-off: The choice between them is a classic system design trade-off. OT trades availability for the efficiency of a central server. CRDTs trade memory and CPU efficiency for the simplicity and robustness of a decentralized model.

In our next lesson, we will continue exploring real-time systems by tackling another common feature: designing a presence system. We'll look at how to architect features like online indicators ("green dots"), live cursors, and typing indicators, which are often built alongside collaborative editors.