Examining the Core Problem
I've just begun unpacking the central challenge: real-time collaborative editing. Operational Transformation will be the key. My focus is on breaking down the primary elements before getting bogged down in complexities. The goal is to highlight the fundamental building blocks of the system.
Mapping Out System Elements
I'm now diving into the system architecture. Clients need a rich text editor to manage user input and changes. The server, the central hub, must order and transform operations, and the database stores the content. A WebSocket connection will be used for communication between the clients and the server.
Architecting System Components
Now I'm designing the frontend and backend components. The client will need a rich text editor with an OT engine, managing states and handling socket communication. The server, the core, has to implement the OT transformation logic and needs to manage user connections and the database. It is essential to ensure eventual consistency.
Formulating Data Handling
I'm presently focusing on how to persist data and the operation lifecycle. A key concern is handling concurrent operations, ensuring that the database correctly manages versions and operation transformations. I need to make decisions on data flow, including optimistic updates, and how to use the server to manage consistency between different client versions.
Structuring the Final Report
I'm now outlining the final report format. I'll start with a concise introduction to Operational Transformation, followed by a high-level architectural diagram. The report needs to include data models for operations and snapshots. Then I'll explain the Jupiter OT algorithm, and I'll include explicit client-side pending change management.
Deep Diving Into OT Mechanics
I'm now fully immersed in the core OT concepts. I understand the Diamond Problem and the need for transformation functions. Convergence, causality, and intention preservation are crucial. Exploring the Jupiter algorithm's state machine, and the importance of revision numbers, is essential to understand the system.
Designing a real-time collaborative editing system based on Operational Transformation (OT) is a classic distributed systems problem. The standard solution (used by Google Docs, Etherpad) relies on a central server to act as the source of truth and to sequencer operations.
Below is a detailed system design, broken down by architecture, algorithms, data models, and edge case handling.
1. High-Level Architecture
The system relies on a Client-Server architecture using WebSockets for full-duplex communication. While Peer-to-Peer (P2P) is possible with CRDTs, OT generally requires a central server to resolve total ordering of operations.
Core Components:
- Client (Frontend): Rich Text Editor (e.g., Quill, Monaco), OT Client Engine, WebSocket Handler.
- Load Balancer: Manages incoming connections.
- OT Application Server: The "brain" that performs transformations and sequences operations.
- History Cache (Redis): Stores the recent window of operations for fast transformation.
- Persistent DB (Postgres/Mongo): Stores document snapshots and the full ledger of operations.
2. The Algorithm: OT Logic (Jupiter Protocol)
The core concept is distinguishing between the Local State (what the user sees) and the Server State (the truth).
The Basic Operations
We define text changes as atomic units:
Retain(n): Keep n characters.
Insert(s): Insert string s.
Delete(n): Delete n characters.
The Transformation Function T
If two operations A and B occur concurrently on the same document state, we need a function T(A,B) that produces a pair (A.
- A′ is the version of A transformed to apply after B.
- B′ is the version of transformed to apply .
Revision Numbers
Every document has a version number (V).
- Client is at V=10. It sends an operation with
baseVersion=10.
- Server is at V=12.
- Server sees the client is outdated. It retrieves operations 11 and 12 from history.
- Server transforms the incoming operation against and .
3. Client-Side Architecture
The trickiest part of OT is the client UI. You cannot lock the UI while waiting for the server; the user must be able to keep typing (Optimistic UI).
The Client OT Engine acts as a state machine with three states:
- Synchronized: Client is up to date with server. No pending changes.
- Awaiting: User typed something. Op sent to server. Waiting for Acknowledgment (ACK).
- Buffering: User typed something (in Awaiting), and kept typing before the ACK came back.
Client Processing Loop:
- Input: User types character 'X'.
- Action: Apply 'X' to local view immediately.
- Logic:
- If Synchronized: Send Op to server. Switch to Awaiting.
- If Awaiting: Store Op in a buffer. Switch to Buffering.
- If Buffering: Merge new Op into the existing buffer.
- On Receive ACK:
- If Awaiting: Switch to Synchronized.
- If Buffering: Send the buffered Op. Switch to Awaiting.
- On Receive Remote Op (from Server):
- Transform remote Op acts against pending/buffered Ops.
- Apply transformed remote Op to the view.
4. Server-Side Architecture
The server acts as the serializer.
Sticky Sessions / Document Routing
Because OT relies on an in-memory application of a specific sequence of history, it is best if all users editing Document A connect to the same server node.
- Routing: Use a Hash Ring (Consistent Hashing) on
docID at the Load Balancer level to route WebSocket connections to the specific node managing that document.
- Pub/Sub Fallback: If using sticky sessions is not possible, you must use a Redis Pub/Sub to distribute operations, but this adds latency and race condition complexity. Stick to sharding by Document ID.
Request Lifecycle
- Receive Op: Server receives
Op(insert 'a', index 0) from User A with baseRev=5.
- Lock: Acquire a lightweight lock on Document A (mutex within the Node process).
- Wait-Check:
- Server current
Rev is 5? No transformation needed.
- Server current
Rev is 7?
- Fetch Ops
6 and 7 from Redis.
- Run
Transform(IncomingOp, [Op6, Op7]).
- Apply & Save:
- Update Document text in memory.
- Increment
Rev to 8.
- Log Op to Database (
doc_id, rev: 8, timestamp, op_data).
- (Optional) Every 100 ops, save a Snapshot of the whole text to DB.
- Broadcast: Send the transformed Op to all other connected clients (B, C, D) with
Rev=8.
- ACK: Send ACK to User A with
Rev=8.
5. Data Models (Database)
We need two primary collections/tables.
1. Documents (Snapshot)
{
"_id": "doc_123",
"title": "Design Doc",
"content": "Hello World...", // Snapshot of text
"latest_revision": 150,
"last_snapshot_revision": 100
}
2. Operations (The Ledger)
{
"_id": "op_xyz",
"doc_id": "doc_123",
"user_id": "user_bob",
"revision": 151, // The revision this op CREATED
"op": [{"i": "Hello"}], // The actual change
"timestamp": 1678889000
}
6. Handling Corner Cases
The "Diamond" Problem
User A inserts "X" at index 0. User B inserts "Y" at index 0 concurrently.
- Without OT: Result A might be "XY", Result B might be "YX".
- With OT: The server decides order. If Server picks A first, it transforms B to insert at index 1. Both clients converge on "XY".
Network Disconnects
- If a client goes offline, they stack up operations in the buffer.
- Upon reconnection, the client tries to send a massive composite operation with an old
baseRev.
- The server performs transform loops. If the history required (e.g., Client is at rev 5, Server is at 5000) is too large, the server may reject the edit and force the client to reload with the latest snapshot (Hard Re-sync).
Undo/Redo
Global undo in collaborative editing is notoriously difficult.
- Strategy: Maintain a local undo stack only. If User A hits Undo, the client generates the inverse operation (Delete for Insert) and sends it to the server as a new operation. Do not try to "rollback" the server version.
7. Scalability Strategy
How to handle 10 million active users?
- Service Sharding: Split the OT Logic Servers. Since operations are atomic per document, Sharding Key =
doc_id.
- Server 1 handles Docs 1-1000.
- Server 2 handles Docs 1001-2000.
- Hot Storage (Redis): Don't hit Postgres for every operation transformation. Keep the last 100 operations of active documents in Redis lists.
- Snapshotting: Don't reconstruct a document from Op #1 every time a user opens it. Load the latest Snapshot (Rev 500) and apply subsequent ops (501-505) from the Ledger.
- History Pruning: Once a snapshot is saved and verified, operations older than the snapshot can be moved to cold storage (S3/Data Lake) for audit trails, keeping the active DB light.
8. Technology Stack Proposal
- Frontend: React + OT.js (or ShareDB client).
- Backend: Node.js or Go (Go is excellent for concurrent WebSocket handling).
- Transportation: Socket.io or raw WebSockets.
- Memory Store: Redis (for Op history buffer).
- Persistence: MongoDB (good for storing JSON ops) or PostgreSQL (JSONB).
Summary of Flow
User Types "A" → Client Buffer → WebSocket → Load Balancer → Node.js Server → Fetch History (Redis) → Transform Op .