The user wants me to design a real-time collaboration system similar to Google Docs. This is a classic system design interview question. I need to approach it methodically, covering requirements, high-level architecture, data model, algorithms, and scaling considerations.
1. Clarify Requirements & Scope
- Core Functionality: Real-time editing of text documents by multiple users.
- Consistency: Everyone sees the same thing eventually (or immediately).
- Latency: Changes should appear instantly (low latency).
- Conflict Resolution: Handling simultaneous edits.
- Persistence: Documents must be saved.
- Concurrency: High number of simultaneous users per document and across the system.
- Offline Support (Optional but good): Users can edit offline and sync later. (I'll focus on online first, but mention Offline/CRDT as an advanced option).
2. Key Challenges
- Concurrency Control: What happens when User A and User B type at the same time?
- Approaches: Locking (too slow), Operational Transformation (OT), Conflict-free Replicated Data Types (CRDTs).
- Network Latency: Real-time requires WebSockets or long-polling.
- State Management: Storing the document state and the history of changes.
3. High-Level Architecture
- Client: The editor (React/Vue/etc.). Handles user input, renders text, sends/receives updates.
- Communication Layer: WebSockets for bidirectional communication.
- Collaboration Service (The "Coordinator"): Receives edits, orders them, broadcasts them. This is where OT or CRDT logic lives on the server side (mostly).
- Storage: Database for documents and history.
- Presence Service: Show who is online and their cursors.
4. Deep Dive: Concurrency Control (The "Secret Sauce")
This is the most important part. I need to explain OT vs. CRDT.
- Operational Transformation (OT): The classic Google Docs approach.
- Operations: Insert(index, char), Delete(index).
- Transform: If Op A inserts a char at index 5, and Op B comes in, Op B's index might need to shift to 6.
- Server acts as the central authority.
- CRDT (Conflict-free Replicated Data Types): The modern approach (Figma, etc.).
- Unique IDs for every character (e.g., Lamport timestamps).
- No central coordination needed for validity, just eventual consistency.
- Decision: I will focus on OT as the "standard" answer for Google Docs style, but acknowledge CRDT as the modern alternative. OT is often easier to explain in an interview context regarding the central server role.
5. Detailed Component Design
- Client:
- Sends keystrokes/batches of operations.
- Maintains local state (optimistic UI) and confirmed state.
- Server (Collaboration Service):
- Connection Manager: Manages WebSocket connections.
- Document Server: Handles the OT logic.
- Receives Op from Client A.
- Transforms against operations received from Clients B, C while A was in transit.
- Commits to DB.
- Broadcasts transformed Op to others.
- Database:
- Schema: Document ID, Content (maybe snapshot), Version number.
- Log: Table of operations for history/undo.
6. Data Model (Simplified)
- Document:
doc_id, title, content_snapshot, version.
- Operation:
op_id, doc_id, version, type (insert/delete), position, content, author_id.
7. Algorithm Walkthrough (OT)
Let's walk through a specific scenario:
- Doc state: "ABC"
- User 1 inserts 'x' at index 1 (after 'A'). Op:
Insert(1, 'x').
- User 2 deletes 'C' (index 2). Op:
Delete(2, 'C').
Simultaneous execution:
- Server receives User 1's
Insert(1, 'x'). Applies it. State: "AxBC". Broadcasts Insert(1, 'x').
- Server receives User 2's
Delete(2, 'C').
- Wait, User 2's view was "ABC". User 2 didn't know about 'x'.
- User 2's delete index 2 referred to 'C'.
- Server needs to transform User 2's op against User 1's op.
- User 1 inserted at 1. User 2 deleted at 2. Since 1 < 2, User 2's index shifts to 3.
- Transformed Op:
Delete(3, 'C').
- Result: "AxBC" -> "AxB". Correct.
8. System Architecture Diagram (Mental Draft)
- Client <-> Load Balancer <-> Collaboration Service (WebSocket) <-> Message Queue (maybe for scaling) <-> Operation Transformer <-> Database.
- Actually, for low latency, the Transformation logic usually happens in memory on the Collaboration Service node handling the document.
9. Scaling
- Sharding: How to handle millions of documents? Partition by
doc_id. All users editing Doc X go to Server Node Y.
- Consensus: If multiple servers handle the same document, we need consensus (Raft/Paxos) or a single leader per document. Simplification: Use a consistent hash ring to map
doc_id to a specific server instance.
- Load Balancing: Sticky sessions or connection routing based on
doc_id.
10. Additional Features
- Cursor Presence: Broadcast
(x,y) coordinates or text index + user info.
- Permissions: Check before allowing connection.
- History/Undo: Replay the operation log.
11. Structuring the Response
- Problem Statement: Define what we are building.
- Functional/Non-Functional Requirements.
- High-Level Architecture (The Diagram).
- The Core Algorithm (OT vs CRDT). This is critical.
- Data Storage & Communication.
- Scalability & Reliability.
- Conclusion.
Self-Correction during drafting:
- Should I store the full document text in a DB? It's slow to parse/rewrite constantly.
- Better approach: Store snapshots periodically (every N ops or T minutes) and keep a log of operations since the last snapshot. To load, fetch snapshot + replay ops.
Refining the Algorithm section: I will use Operational Transformation (OT) as the primary explanation because it aligns historically with "Google Docs," though I will mention CRDTs as the modern alternative.
Let's write it out.
Designing a real-time collaboration system (like Google Docs) requires solving a specific computer science problem: Concurrency Control. Unlike standard CRUD applications, where the last write wins, a document editor must preserve the intent of all users typing simultaneously.
Here is a comprehensive system design for a real-time collaborative editor.
1. Requirements & Constraints
Functional Requirements:
- Real-time: Characters appear on other screens immediately (latency < 100ms).
- Concurrency: Multiple users can edit the same section simultaneously without corruption.
- Persistence: Documents must be saved and recoverable.
- History: Ability to undo changes and view revision history.
- Presence: See other users' cursors and selections.
Non-Functional Requirements:
- High Availability: The service must not go down.
- Low Latency: Global distribution needs to be handled efficiently.
- Scalability: Support millions of concurrent documents.
2. The Core Challenge: Concurrency Control
You cannot use standard database locking. If User A locks paragraph 1, User B will freeze when trying to type there. We need an "Optimistic Concurrency Control" mechanism.
There are two industry-standard approaches:
Option A: Operational Transformation (OT)
- How it works: When a client sends an operation (e.g., "Insert 'X' at index 5"), the server transforms it against concurrent operations received from other clients to ensure consistency.
- Pros: The classic algorithm (used by Google Docs). Mathematically proven.
- Cons: Extremely complex to implement correctly; requires a centralized server to handle transformations.
Option B: Conflict-free Replicated Data Types (CRDTs)
- How it works: Every character is assigned a unique ID and a positional relationship (e.g., "Character A is after Character B"). Commutative operations allow merging without coordination.
- Pros: Can be Peer-to-Peer (P2P); no single point of failure; easier to implement offline mode.
- Cons: Higher memory/CPU usage (metadata overhead).
Decision: For this design, we will base it on OT (Operational Transformation) as it is slightly more bandwidth-efficient for a centralized service like Google Docs.
3. High-Level Architecture
We need a persistent connection service. Standard HTTP is too slow (header overhead) and unidirectional. We will use WebSockets.
![Architecture Diagram Description]
Client (JS Editor) <-> Load Balancer <-> Collaboration Service (WebSocket Server) <-> Message Queue <-> Persistence Service <-> Database
4. Detailed Component Design
A. The Client (The Editor)
The client is not just a display; it is a state machine.
- Local State: Holds the current document in memory.
- Optimistic UI: When a user types, the UI updates instantly. It does not wait for the server.
- Pending Queue: Outgoing operations are queued until the server acknowledges them.
B. The Collaboration Service (WebSocket Server)
This is the "brain." It handles the active editing session.
- Document Cache: Stores the current state of the document in RAM (Redis or local memory) to avoid hitting the DB for every keystroke.
- The OT Engine: Receives operations from Client A, transforms them against operations from Client B, and broadcasts the result.
- Presence: Tracks "Heartbeats" to see who is online and broadcasts cursor coordinates (x, y) to other clients.
C. Data Storage (Persistence)
We do not write to the SQL database on every keystroke (that kills the DB).
- In-Memory (Redis): Stores the "Hot" document state and the last 50 operations.
- NoSQL (MongoDB/Cassandra): Stores document snapshots.
- Write-Behind Log: A background process flushes the memory state to the persistent database every few seconds or when a document becomes inactive.
5. The Algorithm Flow (OT)
Let's trace a scenario where User A and User B start with the document "ABC".
Both try to insert a character at index 1 at the exact same time.
- State: Document is
A B C.
- User A Action: Inserts
x at index 1. Client sends { op: INSERT, char: 'x', index: 1, version: 1 }.
- User B Action: Inserts
y at index 1. Client sends { op: INSERT, char: 'y', index: 1, version: 1 }.
Server Processing (The Transformation):
- Server receives A's request. It applies it.
- State becomes
A x B C.
- Server broadcasts A's op to User B.
- Server receives B's request.
- Problem: B's request says "Insert at 1". But the server state is now
A x B C. If it inserts y at 1, it conflicts with x.
- Transformation: The server sees B's index is 1. The server has already applied A's insertion at 1. Since A came first, the server shifts B's insertion index to 2.
- Result:
A x y B C.
- Server sends the transformed op to User A:
{ op: INSERT, char: 'y', index: 2 }.
Result: Both users see A x y B C.
6. Data Model
We need to represent the document efficiently. We cannot store it as a giant string because inserting a character at the start of a 100-page document would require re-indexing the entire string.
We use a Doubly Linked List or a Piece Table.
Example JSON Data Structure (Conceptual):
{
"doc_id": "abc-123",
"content": [
{ "id": "node1", "val": "H", "format": "bold", "next": "node2" },
{ "id": "node2", "val": "i", "format": null, "next": "node3" },
...
],
"version": 104,
"last_edited": "2023-10-27T10:00:00Z"
}
Note: CRDTs often use a format like (site_id, counter) for IDs to ensure uniqueness across devices.
7. Scalability & Reliability
Sharding
How do we handle 10 million documents?
- Consistent Hashing: Documents are assigned to specific Collaboration Service instances based on
doc_id.
- If User A and User B open Doc X, the Load Balancer must route both WebSocket connections to Server Node 5.
Conflict Resolution (Server Crash)
What happens if the Server Node 5 crashes while holding the state of Doc X?
- Clients detect disconnect.
- Client switches to "Offline Mode" (stores ops in LocalStorage/IndexedDB).
- Client attempts to reconnect.
- Load Balancer routes them to a new Server Node.
- New Node loads the last snapshot from the Database/Redis.
- Clients replay their pending operations against the new state (Conflict resolution handled).
8. Summary of Technologies
- Communication: WebSockets (Socket.io / raw ws library).
- Protocol: Protobuf or MsgPack (Binary serialization is faster/smaller than JSON for high-frequency ops).
- Concurrency Logic: Yjs (A popular CRDT library) or ShareDB (OT library).
- Database: Redis (Pub/Sub & Caching), Cassandra (Revision History), S3 (Snapshot Storage).
9. Edge Cases to Consider
- Network Partitions: What if a user is on a flaky train connection? (Use Vector Clocks to version the document).
- Malicious Input: Sanitize HTML/JS on the server to prevent XSS if the user pastes rich text.
- Massive Documents: If a doc is 500 pages, don't load the whole thing. Implement "Windowing" (load only what is visible).