Video in progress
How do you build a document system where several people edit at the same time, like Google Docs: OT or CRDT?
Both bring simultaneous edits to the same result on every client. OT relies on a central server's ordering and is well studied for text; CRDT merges even without servers and suits offline work, but carries more metadata. The choice depends on the offline requirement and the architecture.
📖 Answer
The problem: Ali typed "x" at position 5, and at the same time Vali deleted the character at position 3. Each change is correct relative to its own state, but if you simply apply them on top of each other, the documents end up different.
Operational Transformation. The server gives the operations a single order. A client "transforms" an operation that came from the server against its own not-yet-acknowledged operations (shifting the position). Google Docs went this way. Because the server is central, access control, history and versions are easy. The painful part is that the transformation functions are very hard to get right, and each document is tied to one server process.
CRDT (for example, Yjs, Automerge). Every character gets a globally unique ID, and an insert is expressed as "after character X". Even if operations arrive in any order, everyone reaches the same state. It works naturally with offline editing, peer-to-peer and several regions. The cost is metadata next to every character, deleted characters stay as "tombstones", and the document grows over time and has to be compacted now and then.
Architecture (either way):
- a "session owner" for each open document: WebSocket connections for one document are routed to one process (consistent hashing by document ID);
- the operation log is stored sequentially, with a snapshot taken periodically; a new client gets the snapshot plus the operations after it;
- cursors and "who is online" are temporary and aren't persisted.
In a new product today I'd often pick an off-the-shelf CRDT library, since offline mode and a battle-tested algorithm come for free. But for rich text (tables, formatting) and big documents, you have to measure memory and performance up front.
Sign up to mark studied questions and save your progress.