Designing a system for real-time collaborative editing is a classic system design interview question. The core challenge here is maintaining consistency across multiple clients who might be editing the same document simultaneously, especially when network latency causes operations to arrive out of order or late.
Operational Transformation (OT) is the algorithmic backbone of such systems (like Google Docs). I need to structure the answer to explain the problem, the core concepts of OT, the architecture, and the data flow.
High-Level Goal: Allow multiple users to edit a document at the same time and see each other's changes instantly, ensuring everyone eventually sees the same final document.
The Core Problem: Concurrency.
Imagine User A and User B both have the string "ABC".
User A inserts "x" at index 0 (result: "xABC"). They send this operation to the server.
User B deletes "C" at index 2 (result: "AB"). They send this operation to the server.
If the server just applies these sequentially, order matters.
If B's delete arrives first, state is "AB". Then A's insert arrives. If applied blindly (insert at 0), result is "xAB".
But on A's screen, the "C" existed when they typed "x". The intent was "xABC" -> then remove "C" -> "xAB".
OT solves this by transforming operations against each other.
Key Concepts:
Operations (Ops): Insert, Delete, Retain (or just Index-based).
Transformation Function: The logic that adjusts an operation based on a concurrent operation.
Example: T(opa,opb). If opa inserts a character before opb's cursor, opb needs to shift its index +1.
Client-Server Architecture: Usually, a central server handles the transformation logic and ordering to ensure convergence (Canonical State). Peer-to-peer is too complex for consistency.
Architecture Components:
Client:
Editor UI (contenteditable or canvas).
Local State (Document revision).
Outgoing Buffer (Ops waiting to be ACK'd).
Incoming Buffer (Ops from server waiting to be transformed and applied).
Server:
Document Store.
Operation Log (History).
Transformation Engine.
Connection Manager (WebSockets).
The Flow (The "Hard" Part):
Scenario: Client A makes a change.
Client A sends Op to Server.
Client A updates local UI immediately (Optimistic UI).
Server receives Op.
Server transforms Op against any Ops that happened since Client A's last sync.
Server applies Transformed Op to Master Doc.
Server broadcasts Transformed Op to other clients (B, C...).
Server sends ACK to Client A.
Client B receives Op. Must transform it against pending local ops.
Data Structures:
String-based is simple for explanation, but list-based or tree-based is more realistic. I'll stick to String/Index for clarity in the "Transformation Logic" section.
Revision numbers are crucial.
Detailed Design Steps:
Step 1: The Data Model. The document is a sequence of characters. An Operation is (type, position, char).
Step 2: The Algorithm (OT). Explain the transformation function xform(op1,op2).
Case 1: Insert vs Insert.
Case 2: Insert vs Delete.
Case 3: Delete vs Delete.
Step 3: Client Side Logic.
Needs to handle "Local Echo" vs "Remote Update".
Needs to handle the buffer of sent operations. If I send Op1 and Op2, and server ACKs Op1, I can discard Op1. If I receive Op_remote while I have Op2 pending, I must transform Op_remote against Op2.
Step 4: Server Side Logic.
The "Jupiter" model (single server transforming against history).
Maintaining a history buffer is essential for transforming late-arriving packets.
Refining the "Transformation" Explanation:
This is usually where diagrams fail in text. I need a concrete example.
State: "AB"
Client 1: Insert "x" at 1 -> "Ax B". Sends Ins(1, 'x').
Client 2: Delete "B" (at 2) -> "A". Sends Del(2).
Server:
Recv Ins(1, 'x'). Apply. Broadcast.
Recv Del(2) from C2. C2 was based on state "AB".
Server state is "Ax B". The "B" is now at index 3? No, "Ax B" -> index 0='A', 1='x', 2=' '?, wait.
Let's use a cleaner example.
State: "AC"
User 1: Insert "B" at 1 -> "ABC". Op: Ins(1, 'B').
User 2: Delete "C" (at 1) -> "A". Op: Del(1).
Transformation on Server:
U1's Ins(1, 'B') makes "ABC". U2's Del(1) intended to delete 'C'.
Because 'B' was inserted before 'C', the index of 'C' moved.
We transform U2's op against U1's op.
Since U1 inserted at 1 (where U2 was acting), U2's target index shifts +1 -> Del(2).
Result: Delete 'C' from "ABC" -> "AB".
Convergence achieved: "AB".
System Architecture Diagram Description:
WebSockets for bidirectional comms.
Redis for pub/sub (if multiple server instances).
Database for persistence (NoSQL doc store or SQL with large text blobs/operation logs).
Persistence: Storing snapshots + op logs (CRDTs vs OT persistence).
Scalability: Sharding by document ID.
Structure of the Response:
Introduction: Definition and Goals.
Core Concept: What is OT? (Transform function).
Architecture: Client & Server components.
Workflow/Algorithm: The step-by-step logic (Optimistic UI + ACK).
Data Structure: How to represent Ops.
Example Walkthrough: The "AC" -> "ABC" vs "A" example.
Scaling & Persistence: Snapshots, WebSockets, etc.
Self-Correction/Refinement:
Correction: Don't confuse OT with CRDTs. Mention CRDTs as an alternative (Conflict-free Replicated Data Types) but focus on OT as requested.
Detail: The "Jupiter" algorithm is the standard reference for OT server implementation. I should mention keeping a history buffer on the server.
Client complexity: The client needs to maintain a "pending" stack. If I type "A", "B", "C" quickly, I send 3 ops. If the server sends back an update from another user while my "A" is in flight, I can't just apply it to my current state "ABC". I have to transform the incoming op against my pending queue.
Final Polish: Use bolding for key terms. Keep explanations concise but precise.
(Self-Correction during drafting the "Algorithm" section): Make sure to distinguish between the Server's role (ordering) and the Client's role (transforming against local buffer).
Server: Linearizes history. Transforms incoming Ops against the history stack that the Client hasn't seen yet.
Client: Transforms incoming Ops against the Ops it has sent but not yet been acknowledged.
Let's proceed with generating the design.
Designing a real-time collaborative editor (like Google Docs) requires solving the problem of Concurrency Control. When two users edit the same character at the exact same time, the system must decide how to merge those changes without breaking the document or losing data.
We will use Operational Transformation (OT). OT is an algorithm that transforms a client’s operation based on the operations previously executed by other clients.
1. High-Level Architecture
The system follows a Client-Server architecture. The server acts as the central authority (The Jupiter model) to ensure consistency.
Components
Client (Editor):
Local State: The current text content.
Operation Queue: Outgoing operations waiting for server acknowledgment.
Document State: A revision number (version) of the document the client is currently looking at.
Server (Collaboration Engine):
Document Service: Stores the canonical document state.
Operation Log: A history of operations (transformations) to handle sync for lagging clients.
Transformation Engine: The logic that modifies incoming operations to fit the current document state.
Communication:
WebSockets: For bidirectional, low-latency communication.
2. Data Structures
We need to represent the document and changes efficiently.
A. The Document
The document is not just a string; it is usually a sequence of characters with metadata. For this design, we treat it as a String, but in production, this would be a Rope or Piece Table data structure to handle large files efficiently.
B. Operations (Ops)
Instead of sending "deltas" or diffs, we send explicit operations.
Insert(pos, text): Insert text at index pos.
Delete(pos, length): Delete length characters starting at pos.
Retain(pos): (Used in composed ops) Keep text at pos.
Every operation sent to the server includes:
Revision Number: The version of the document this operation applies to.
Payload: The specific Insert/Delete instruction.
3. The Core Algorithm: Operational Transformation
OT relies on two functions: Transform and Compose.
The Transform Function (T)
This is the heart of OT. It takes two concurrent operations (Oa and Ob) and produces new versions (O and ) such that the resulting document state is consistent.
Example Scenario:
Initial State: "AC"
User A inserts "B" at index 1 (Intent: "ABC"). Sends Op Oa=Insert(1,"B").
User B deletes "C" at index 1 (Intent: "A"). Sends Op O.
Both ops arrive at the server.
Server applies Oa: "AC" → "ABC".
Now Ob arrives. It says "Delete at index 1". In "ABC", index 1 is now "B".
If we apply blindly, we get "AC" (User B deleted User A's text!). Data Loss.
The Fix:
We transform Ob against Oa.
Ob (Delete 1 char at 1) needs to account for Oa (Insert "B" at 1).
Since O inserted 's cursor, 's index shifts right by 1.
4. Detailed Workflow
Here is how the system handles the lifecycle of a keystroke.
Phase 1: Local Edit (Optimistic UI)
User A types "X".
Client immediately updates the UI (Optimistic UI assumption).
State Check: Server is at rev 12. Client Op is at rev 10.
Transformation:
Server retrieves history of ops between rev 10 and rev 12 (let's say User B inserted "Y" at pos 4).
Server transforms User A's Op against User B's Op.
The position of "X" might shift from 5 to 6.
Apply: Server applies the transformed op to the master document.
Broadcast: Server broadcasts the transformed op to all other connected clients.
Ack: Server sends an ACK to User A confirming the op is committed.
Phase 3: Remote Update (Client Side)
User B receives the broadcast from the Server.
User B checks their current state. If they have no pending ops, they apply the op directly.
If User B also has pending ops (un-acked changes), they must transform the incoming server op against their own pending local ops before applying it to the UI.
5. Algorithm Logic (Pseudo-code)
Server Side Transformation Logic
python
class Server:
def __init__(self):
self.document = ""
self.history = [] # List of all committed ops
self.current_rev = 0
def on_receive_op(self, client_op, client_rev):
# 1. Get operations client has missed
# We need to transform the incoming op so it applies to current state
missed_ops = self.history[client_rev:]
transformed_op = client_op
# 2. Transform against history
for historical_op in missed_ops:
# The function 'transform' returns the modified incoming op
transformed_op = transform(transformed_op, historical_op)
# 3. Apply to document
self.document = apply(self.document, transformed_op)
self.current_rev += 1
self.history.append(transformed_op)
# 4. Broadcast transformed_op to other clients
broadcast(transformed_op)
The transform Function (Simplified)
This logic handles the shifting of indices.
python
def transform(incoming_op, existing_op):
# Case 1: Incoming Insert
if incoming_op.type == 'INSERT':
# If existing op inserted before or at same spot, shift index right
if (existing_op.type == 'INSERT' and existing_op.pos <= incoming_op.pos):
incoming_op.pos += len(existing_op.char)
# If existing op deleted before current pos, shift index left
elif (existing_op.type == 'DELETE' and existing_op.pos < incoming_op.pos):
incoming_op.pos -= existing_op.length
# Case 2: Incoming Delete
elif incoming_op.type == 'DELETE':
if (existing_op.type == 'INSERT'):
if existing_op.pos <= incoming_op.pos:
incoming_op.pos += len(existing_op.char)
# ... complex logic for Delete vs Delete conflicts (overlapping deletes)
return incoming_op
6. Handling Edge Cases & Persistence
Intention Preservation
The most common bug in OT is Intention Violation.
Example: User A bolds the word "Hello". User B types "!" at the end.
If transformation isn't careful, User B's "!" might get bolded too, or the bold tag might close prematurely. OT treats attributes (bold, italic) as operations on the character metadata, not just text indices.
Persistence
We cannot store the document as a single blob for every character typed.
Operation Log: We store the stream of operations. To load a document, we replay the log.
Snapshots: Every N operations (e.g., 1000), we save a snapshot of the document text. Loading becomes: Load Snapshot + Replay remaining Ops.
Scaling (Redis Pub/Sub)
If you have 1 million users, a single Node.js server won't hold all WebSocket connections.
Use Redis Pub/Sub.
Server A handles User 1. Server B handles User 2.
When User 1 types, Server A publishes the Op to Redis channel doc_ID.
Server B subscribes to doc_ID, receives the Op, and pushes it to User 2.
Summary
Designing an OT system involves:
Optimistic UI: Update screen instantly, send op to server.
Server Authority: Server transforms all ops against a linear history to create a single source of truth.
Client Sync: Client transforms incoming remote ops against its own pending local ops.
Persistence: Use operation logs and snapshots for recovery.
a
′
Ob′
b
=
Delete(1,1)
a
before
Ob
Ob
New Ob′: Delete(2,1).
Result: "AB" (User B's intent to remove 'C' is preserved, and User A's text is preserved).