The user wants a design for a real-time collaboration system similar to Google Docs. This is a classic system design interview question.
1. Understand the Goal:
The goal is to allow multiple users to edit the same document simultaneously, seeing each other's changes in real-time, with low latency and high consistency. The system needs to handle conflicts (two people typing in the same place at the same time) and ensure everyone ends up with the same document state.
2. Key Requirements:
- Functional:
- Create, Read, Update, Delete (CRUD) documents.
- Real-time editing and viewing.
- User presence (seeing who else is online/cursors).
- History/Versioning (undo/redo).
- Permissions (view only, edit).
- Non-Functional:
- Low Latency: Changes must appear instantly (< 100ms).
- High Consistency: All clients must see the same document eventually (ideally immediately). No data loss.
- High Availability: The system should be up even if some nodes fail.
- Scalability: Support millions of users and documents.
- Offline Support: Users should be able to edit offline and sync later.
3. Core Challenge: Concurrency Control
This is the heart of the problem. If User A types "Hello" and User B types "World" at the same position, how do we resolve it?
- Approach 1: Locking. (Pessimistic). User A locks the file. User B waits. Bad UX. Not Google Docs style.
- Approach 2: Operational Transformation (OT). The classic algorithm used by Google Docs. It transforms operations based on history.
- Approach 3: Conflict-free Replicated Data Types (CRDTs). The newer, trendy approach (used by Figma, Notion, etc.).
Decision: I should discuss OT vs. CRDT. I will probably focus on OT as the "traditional" Google Docs approach but mention CRDTs as the modern alternative because it's often preferred for decentralized or p2p architectures.
4. High-Level Architecture:
- Client: The web browser. Needs to maintain a local state, capture keystrokes, send operations, receive operations.
- Load Balancer: Distributes traffic.
- API Gateway / Web Socket Manager: Handles the persistent connections.
- Collaboration Server (The "Coordinator"): This is where the OT/CRDT logic lives. It sequences operations.
- Database: Stores the document state and operation history.
- Presence Service: Tracks who is online and cursor positions.
5. Deep Dive: Operational Transformation (OT)
- Concept: If Client A sends Op A and Client B sends Op B at the same time, the server transforms them.
- Server state:
S
- Op A: Insert "X" at index 0.
- Op B: Insert "Y" at index 0.
- Server applies A ->
S'. It needs to apply B.
- It transforms B to B' such that B' incorporates A's intent. If A went first, B' might be "Insert Y at index 1".
- Why Centralized Server is needed for OT: OT is complex to implement correctly in P2P. A central server usually acts as the source of truth for the sequence of operations.
6. Deep Dive: Storage (Data Model)
How do we store the doc?
- Option A: Snapshot only. Easy, but history is lost.
- Option B: Log of Operations. We can replay the log. Good for history, bad for loading a large doc (replaying 1 million ops takes too long).
- Option C: Hybrid (Snapshots + Delta Log). Every N operations or M minutes, save a snapshot. To load, fetch the latest snapshot and apply recent deltas. This is the standard approach.
7. Communication Protocol
- HTTP is too chatty for typing.
- WebSockets are the standard for bidirectional, low-latency communication.
8. Detailed Component Design Steps:
- Step 1: Connection. Client connects via WebSocket to a specific document channel.
- Step 2: Loading. Client requests document. Server sends latest snapshot + pending ops.
- Step 3: Editing.
- Client generates Op (e.g.,
Insert("A", pos: 5)).
- Client optimistically updates UI (makes it feel fast).
- Client sends Op to Server.
- Step 4: Broadcasting.
- Server validates/authenticates.
- Server applies OT logic.
- Server persists Op (Database).
- Server broadcasts Op to other connected clients.
- Step 5: Receiving.
- Other clients receive Op.
- They transform it against their pending local ops (OT client-side) and apply it.
9. Refinements & Edge Cases:
- Offline: Client stores ops in LocalStorage/IndexedDB. On reconnect, sends batch of ops. Server transforms/rebases them.
- Cursor Position: Separate from text content. Needs to be updated as text shifts.
- Scaling: Documents are independent. We can shard by Document ID. "Sticky sessions" or a Pub/Sub layer (Redis/Kafka) is needed if different users are connected to different servers but editing the same doc.
10. Structuring the Answer:
- Clarify Requirements: Functional/Non-functional.
- Capacity Estimation: (Briefly).
- API Design: Websocket message formats.
- High-Level Architecture: Diagram description.
- Deep Dive: Concurrency Control (OT vs CRDT). Crucial section.
- Deep Dive: Storage & Data Model.
- Scalability & Performance.
- Failure Handling.
Self-Correction/Review during thought process:
-
Initial thought: Should I recommend CRDTs? They are order-independent.
-
Correction: Google Docs famously uses OT. The prompt asks for a system similar to Google Docs. I should explain OT in detail as the primary mechanism but mention CRDTs as an alternative architecture that simplifies the server logic but increases client complexity/storage size. I will stick to OT for the main design to align with the specific "Google Docs" reference, but acknowledge CRDTs.
-
Storage: Don't just say "SQL". Document text can be huge. Storing just the text in a BLOB is okay, but storing the history needs a time-series approach or a specialized log storage. I'll propose a Hybrid approach.
-
Communication: Ensure I mention "Optimistic UI". If you wait for the server to acknowledge keystrokes, it feels laggy.
Let's write it out.
Drafting the Content:
- Title: Real-time Collaborative Document Editor.
- Core Problem: State Synchronization.
- Algorithm: Operational Transformation (OT).
- T(Oa,Ob) transforms O such that it includes the intent of .
This looks solid. I will structure the response clearly with headings and diagrams (in text format).
(Self-Correction on Storage): Storing every character change as a row in MySQL is bad for performance after millions of edits. Google Docs uses a specialized backend (Megstore/Colossus/Spanner). For this design, I will suggest a generic NoSQL or Object Store (S3) for snapshots and a fast write-heavy DB (Cassandra/DynamoDB) or a log-based store for operations. Or just a simplified SQL approach with an "Operations" table, acknowledging the scaling need for compaction.
Let's finalize the design structure.
- Introduction: Requirements & Constraints.
- Solution Strategy: The Algorithm (OT vs CRDT).
- System Architecture: The Diagram.
- Component Details: Client, Gateway, Collaboration Logic, Storage.
- Handling Conflicts: The OT flow.
- Data Storage: Snapshots vs Logs.
- Scalability: Sharding & Pub/Sub.
Ready to generate output.
Designing a real-time collaboration system like Google Docs is a complex distributed systems challenge. The core difficulty lies in Concurrency Control: ensuring that when two users edit the same line of text at the exact same time, their changes don't overwrite each other or corrupt the document.
Here is a comprehensive system design for a real-time collaborative editor.
1. Requirements & Constraints
Functional Requirements:
- Real-time: Edits should appear to other users almost instantly (< 100ms latency).
- Concurrent Editing: Multiple users must be able to edit the document simultaneously.
- Consistency: All users must eventually see the exact same document state (Eventual Consistency).
- Offline Support: Users should be able to edit offline, and changes should be synced when they reconnect.
Non-Functional Requirements:
- Low Latency: Must handle high throughput of small messages (keystrokes).
- High Availability: The service should survive network partitions.
- Scalability: Support millions of documents and concurrent users.
2. The Core Algorithm: Conflict Resolution
You cannot simply send the text "Hello World" every time a user types a letter. We need to send Operations (e.g., "Insert 'A' at index 5"). However, if User A inserts a character at index 5 while User B deletes index 5, the indices drift, causing data corruption.
There are two main algorithms to solve this:
- Operational Transformation (OT): Used by Google Docs. Operations are transformed based on other concurrent operations before being applied.
- Conflict-free Replicated Data Types (CRDTs): Used by Figma, Notion, and Redis. Data types are mathematically designed to always converge to the same state regardless of the order of operations.
Decision: For this design, we will choose CRDTs (specifically a RGA - Replicated Growable Array) or a modern OT implementation. CRDTs are preferred today because they allow for Peer-to-Peer syncing and easier offline logic (order of applying ops doesn't strictly matter for convergence), whereas OT usually requires a centralized server to serialize history.
3. High-Level Architecture
The system is composed of three main planes: the Client, the Coordination Server, and the Storage Layer.
Architecture Diagram
[User A] [User B] [User C]
| | |
+-------+-----+-------------+
| (WebSocket / wss)
v
[ Load Balancer ]
|
+-------+-------+
| |
[Collab Server] [Collab Server] <-- Stateless Node.js/Go/Rust
| (Pub/Sub Group)
v
[ Redis Cluster ] [ MySQL/Postgres ]
(Memory/Session) (Permanent Storage)
4. Component Design
A. Client (The Editor)
The client is not just a display; it holds a local copy of the document state.
- Local State: Stores the document in a data structure optimized for the UI (e.g., a Piece Table or Gap Buffer).
- Optimistic UI: When a user types, the UI updates immediately without waiting for the server.
- Outgoing Queue: Stacks operations (Ops) to send to the server.
- Incoming Handler: Receives remote Ops from other users, transforms them against local pending Ops, and applies them to the UI.
B. Communication Protocol: WebSockets
HTTP is too slow (handshake overhead) for keystrokes. We use WebSockets for a persistent, bidirectional communication channel.
- Message Format (JSON/Protobuf):
{
"type": "OP",
"doc_id": "abc-123",
"version": 42,
"payload": { "insert": "H", "position_id": "uuid-xyz", "clock": 5 }
}
C. Collaboration Server (The Coordinator)
This is a stateless layer (Node.js or Go) that handles the real-time traffic.
- Connection Manager: Manages active WebSocket connections.
- Pub/Sub (Redis): The server itself doesn't know who is in which document. It uses Redis Pub/Sub. When a user joins Document X, the server
SUBSCRIBES to channel doc:X.
- Broadcasting: When Server A receives an Op from User 1, it publishes it to Redis. All servers subscribed to
doc:X (hosting other users in that doc) receive the Op and push it down the WebSocket to their connected clients.
D. Persistence Layer
We do not hit the database for every keystroke (too much load).
- Redis (Hot Storage): Stores the current state of the document and the last ~100 operations in a stream. This allows re-syncing a disconnected user quickly.
- Database (Cold Storage): Periodically (e.g., every 30 seconds or on document close), a background worker "snapshots" the Redis state to the persistent SQL/NoSQL database.
5. Workflow Walkthrough
Scenario: User A types "H"
- Input: User A types "H".
- Client A: Generates a unique ID for this character (UUID). Creates an Op:
Insert "H" at position P. Updates local UI immediately.
- Transmission: Sends Op via WebSocket to Collaboration Server.
- Server:
- Validates Op.
- Pushes Op to Redis Stream (for durability).
- Publishes Op to Redis Pub/Sub channel
doc:123.
- Broadcast: Server receives the pub/sub message and forwards the Op to all connected clients (User B and C).
- Client B & C: Receive the Op.
- If they have no pending outgoing Ops, they simply insert "H" into their local document.
- If they do have pending Ops (concurrent editing), the CRDT logic merges the changes automatically.
6. Handling Offline & Conflict (CRDT Details)
If User A goes offline, they keep editing locally. The "Client Clock" (Lamport Timestamp) increments locally.
When User A reconnects:
- Sync: Client sends its current "Version Vector" (a map of
{user_id -> last_known_clock}).
- Diffing: Server compares User A's vector with the server's global history.
- Catchup: Server sends User A all the Ops it missed.
- Merge: User A uploads its offline Ops. Because we used CRDTs:
- The Ops contain unique IDs and logical clocks.
- Even if User B deleted the text User A was editing offline, the algorithm mathematically resolves the conflict (usually prioritizing the "later" logical timestamp or preserving both) without data corruption.
7. Scalability Strategy
- Sharding: Documents are independent. We can shard the system by
doc_id. All users editing Doc X should ideally connect to the same Collaboration Server to avoid unnecessary Redis Pub/Sub hops.
- Connection Pooling: Use high-performance WebSocket servers (e.g., written in Go or Rust) to handle 100k+ concurrent connections per node.
- Snapshotting: To prevent the Op log from growing infinitely (e.g., a document edited 1 million times), the system periodically takes a Snapshot. When a new user joins, they download the Snapshot + recent Ops, rather than replaying the entire history.
8. Database Schema (Simplified)
Table: Documents
id (UUID)
title (String)
owner_id (UUID)
snapshot (Blob - Binary representation of the document)
version (Integer)
Table: Permissions
doc_id
user_id
role (Viewer, Editor, Owner)
Summary
This design relies on a WebSocket infrastructure for transport, Redis Pub/Sub for routing messages between server instances, and CRDTs (or OT) to guarantee mathematical consistency of the text even during network failures or concurrent edits.