Skip to main content

Welcome to a Grasp lesson

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

Lesson 57

Real-time Collaborative Editing: OT vs. CRDTs

This lesson is built with resources from youtube.com, tiny.cloud and 1 more site.

Hello! Welcome to your next lesson on system design.

In our last session, we designed a rental booking system like Airbnb. We focused on the challenges of managing a large, bookable inventory, diving deep into search optimization and, crucially, handling transactional concurrency to prevent double-bookings.

Today, we're tackling a system where concurrency isn't just an edge case to manage, but the central feature: a real-time collaborative editor like Google Docs. Our learning outcome is to design a real-time collaborative editing system, with a focus on Google Docs, and discuss the trade-offs between Operational Transformation (OT) and Conflict-free Replicated Data Types (CRDTs).

This problem forces us to think about consistency and concurrency at a much more granular level—character by character, keystroke by keystroke—and serves as a masterclass in the trade-offs at the heart of distributed systems.

1. The Core Challenge: Concurrent, Non-Commutative Edits

Imagine two users, A and B, start with the text "hello".

  • User A inserts 'w' at the beginning. Their view is "whello".
  • User B deletes the 'o' at the end. Their view is "hell".

If they both send their operations—insert('w', 0) and delete(4)—to each other and apply them naively, they will end up with different documents. User A will have "whell" and User B will have "whelo". The document state has diverged. This is because text editing operations (inserting and deleting at specific indices) are not commutative; the order in which they are applied matters.

Any robust solution must guarantee eventual consistency: all users must eventually converge to the identical document state. Simple solutions, like sending the entire document on every keystroke or using a global lock, are too slow and defeat the purpose of "real-time" collaboration. This brings us to the two main algorithmic approaches.


2. Approach 1: Operational Transformation (OT)

Operational Transformation was pioneered by Google Docs and has been the workhorse of collaborative editing for years. The core idea is to use a central server to establish a canonical, total order of operations. When a client sends an operation to the server, the server transforms it to account for any other operations that have already been applied, ensuring all clients apply operations in a consistent, logical sequence.

Google SWE teaches systems design | EP47: Collaborative Text Editing (operational transform v. CRDT)

To understand the mechanics of OT, please watch this short, clear explanation. It visualizes how operations are modified to maintain consistency.

Watch the segment from 02:09 to 03:43. Focus on how the insert(d, 2) operation is 'transformed' into insert(d, 3) after a preceding insertion operation is taken into account.

Comparison of OT and CRDT Approaches for Collaborative Editing
This diagram compares different approaches to collaborative editing. Panel (b) specifically illustrates the core of OT: User A and User B send operations to a central component, which uses transformation functions (Tid and Tdi) to adjust the operations before broadcasting them, ensuring both users converge to the same final state.

Staff-Level Analysis: Why Google Docs Stuck with OT

For a system like Google Docs, OT makes a lot of practical sense. Let's explore the reasoning behind this choice by reading a short but insightful analysis.

CRDTs vs. Operational Transformation

This article provides excellent insights into the real-world trade-offs between OT and CRDTs. We'll start with the section explaining the rationale behind OT's use in Google Docs.

Read the sections 'Two Philosophies for One Problem' and 'Common Knowledge: Why Google Stuck With OT'. The key takeaway is that since a central server is already needed for features like access control, comments, and saving, the additional overhead of transforming operations is minimal. It allows for a much simpler data model on the client and keeps the document itself lightweight.

Key Trade-offs of OT:

  • Pro: The data representation is simple (just text), keeping document size small.
  • Pro: Logic is centralized, which can simplify client implementation.
  • Con: Requires a central server, which can be a performance bottleneck and a single point of failure.
  • Con: Does not work offline. Clients need a constant connection to the server.
  • Con: The transformation functions are notoriously complex to implement correctly, with hundreds of subtle edge cases.

3. Approach 2: Conflict-free Replicated Data Types (CRDTs)

CRDTs represent a fundamentally different philosophy. Instead of centralizing the conflict resolution logic on a server, CRDTs embed the resolution logic into the data structure itself. This allows operations to be applied in any order and still mathematically guarantee convergence.

For text editing, a common CRDT approach is to abandon integer-based character indices and instead model the document as an ordered sequence of characters, each with a unique, immutable identifier.

12: Design Google Docs/Real Time Text Editor | Systems Design Interview Questions With Ex-Google SWE

This is the core technical part of our lesson. This detailed video explains how a text-editing CRDT can be implemented. It covers the core concepts of data modeling, handling concurrent insertions, and ensuring idempotency.

Please watch the segment from 10:27 to 28:32. This is a dense but crucial section. Focus on understanding these concepts: The Core Idea (from 10:27): How CRDTs allow for multiple write servers, removing the OT bottleneck. State-based vs. Op-based CRDTs (from 13:08): Why sending operations (op-based) is better than sending the whole state for large documents. The Text CRDT Model (from 16:35): The key technique of using fractional indexing (assigning each character a floating-point position between its neighbors) to create a conflict-free ordering. Idempotency and Ordering (from 20:43): How to use unique operation IDs (e.g., a server ID + sequence number, similar to a Lamport clock) and version vectors on the client to handle duplicate or out-of-order messages.

Staff-Level Analysis: The CRDT Trade-offs

CRDTs seem like a silver bullet—they're decentralized and scalable. However, this power comes with significant costs.

CRDTs vs. Operational Transformation

Now, let's read the counter-arguments from the same article. This will give you a balanced view, which is exactly what's expected in a Staff-level interview.

Read the sections 'Rare Knowledge: The CRDT Metadata Explosion', 'Advanced Insight: The Interleaving Problem', 'Strategic Impact: Why Figma Switched from OT to CRDTs', and 'The Undo Problem'. These sections highlight the major drawbacks: Metadata Overhead: The cost of storing unique IDs for every character. Interleaving: How CRDTs can produce text that is technically convergent but violates user intent (e.g., cat + dog -> cdaotg). Undo Complexity: The challenge of 'tombstones' (markers for deleted items) that bloat the data structure.

Undo in Collaborative Editing Systems
This diagram illustrates the complexity of implementing 'Undo'. In a distributed system, an undo is not a simple reversal. It's a new operation that compensates for a previous one. In CRDTs, this often means creating a 'tombstone' to mark an element as deleted, which adds to the metadata overhead.

Key Trade-offs of CRDTs:

  • Pro: Highly scalable and resilient; no central server bottleneck.
  • Pro: Natively supports offline editing and peer-to-peer collaboration.
  • Pro: The merge logic is mathematically proven to converge, reducing bugs in that area.
  • Con: Metadata explosion. Document size can be 10-30x larger than the raw text.
  • Con: Can violate user intent (the interleaving problem).
  • Con: More complex client-side logic and data structures are required.

The choice between OT and CRDT is a classic engineering trade-off. As the article points out, Figma switched to CRDTs because their data model (shapes, layers) was more complex than linear text, making CRDTs a better fit. This shows that the "right" choice depends entirely on the specific product requirements.


4. System Architecture for a CRDT-based Editor

Let's synthesize this into a high-level architecture. We'll use the CRDT approach as it allows for a more distributed and scalable design, presenting more interesting components for a Staff-level discussion.

12: Design Google Docs/Real Time Text Editor | Systems Design Interview Questions With Ex-Google SWE

Let's conclude by looking at a full architecture diagram that incorporates the CRDT concepts we've discussed, along with essential components for persistence, fast loading, and reliability.

Please watch from 28:28 to 36:27 and the final architecture review from 41:56 to 47:10. This covers two critical, advanced topics: Loading Documents: You can't just replay every operation since the beginning of time for a new client. The video explains a clever optimization: using a Change Data Capture (CDC) pipeline to create pre-materialized Document Snapshots for fast initial loads. Full Architecture: The final diagram ties everything together: clients connecting to a Write Cluster via WebSockets, a Rights Database for durability, the CDC pipeline, and the Document Snapshot store for reads.

Key Architectural Components:

  • Clients: Connect to servers via WebSockets for persistent, bidirectional communication.
  • Write Cluster: A group of servers that can accept write operations. Since we're using CRDTs, any server can process a write, which is great for scalability.
  • Rights Database: A durable log of all operations (e.g., using a partitioned database like Cassandra or ScyllaDB). This is the source of truth and allows clients to "catch up" on operations they may have missed due to network issues.
  • CDC and Snapshot Service: An asynchronous process that consumes the stream of operations from the Rights Database and constructs full document snapshots. This is a form of derived data.
  • Document Snapshot Store: A database (perhaps a key-value or document store) optimized for fast reads of the full document content. New clients load from here, then subscribe to the real-time stream for subsequent changes.
  • Version Vector Store: A separate table, updated atomically with the snapshot (e.g., via a two-phase commit in the CDC pipeline), that stores the version vector corresponding to a given snapshot. This tells a newly connected client which operations are already included in the snapshot it loaded.

This architecture is robust, scalable, and demonstrates a deep understanding of the practical challenges beyond the core OT/CRDT algorithm itself.


Conclusion

Designing a real-time collaborative editor is a fascinating problem that exposes fundamental trade-offs in distributed systems. There is no single "best" solution, only the most appropriate one for a given set of product requirements.

Key Takeaways:

  • The Core Conflict: Real-time collaboration is hard because text operations are not commutative.
  • Operational Transformation (OT): Centralizes conflict resolution on a server. It keeps data models simple but requires a central server and has notoriously complex transformation logic. It's a good fit when a server is already in the critical path (e.g., Google Docs).
  • Conflict-free Replicated Data Types (CRDTs): Distributes conflict resolution into the data structure itself. This enables decentralization, scalability, and offline support but comes at the cost of significant metadata overhead and potential violations of user intent. It's a good fit for complex, non-linear data and offline-first applications (e.g., Figma).
  • Staff-Level Insights: A deep discussion should cover not just how OT and CRDTs work, but their real-world consequences: data size, implementation complexity (the "undo problem," "interleaving"), and how they fit into a larger system architecture with components for persistence, caching, and fast document loads.

Preview of the Next Lesson:
Now that we've designed another complex, distributed system, the question of "how do we know it's working correctly and performing well?" becomes paramount. In our next lesson, we will officially move into the "Staff-Level System Design Depth" module and learn how to articulate an observability strategy for a distributed system, covering metrics, logging, and tracing. We'll use the systems we've designed as practical examples.