The Problem#
Google Docs lets several people type into the same document at the same time and see each other's changes within a fraction of a second. Each person sees the others' cursors moving, coloured by name. Nobody presses "save", nobody gets a "this file was changed by someone else" dialog, and when everyone stops typing, every screen shows exactly the same text.
That last sentence is the hard part. Two people typing at the same moment send edits that cross on the network. Alice inserts "Hello " at the start of the line while Bob deletes the word at position 10. By the time Bob's delete reaches Alice's browser, position 10 no longer holds the same word, because Alice's insert shifted everything right by six characters. Applying Bob's operation as written would delete the wrong text. Multiply this by dozens of editors, flaky mobile networks, a laptop that was offline on a plane for three hours, and a document that has been edited for ten years, and you have one of the classic problems in distributed systems: keeping replicas of a shared, ordered sequence consistent under concurrent edits, with zero perceived latency.
Analogy. Imagine a group of writers each with a photocopy of the same manuscript, sitting in different rooms. They mark changes on their own copies and send runners to the others with notes like "insert 'very' before word 12". Runners cross paths, so notes arrive in different orders in different rooms. A naive rule ("apply notes in the order they arrive") leaves every room with a different manuscript. The system needs either a referee in the middle who orders the notes and rewrites each note to fit the version it lands on (operational transformation), or a way of writing notes that does not depend on positions at all, so they can be applied in any order and still agree (CRDTs). It also needs the runners to keep working when a writer leaves the building and comes back hours later with a pile of changes.
What makes this a staff-level interview question is that it touches almost everything:
- Algorithms: OT and CRDTs, with real correctness subtleties.
- Stateful servers: unlike most web services, the best design keeps each live document in the memory of one specific server.
- Realtime networking: millions of long-lived WebSocket connections.
- Event sourcing: the document is a log of operations plus periodic snapshots.
- Offline and mobile: long disconnections that still have to merge cleanly.
- Scale and failure handling: routing, failover and moving hot documents between servers without losing an edit.
Clarifying Questions#
| Question | Why it matters | Assumed answer |
|---|---|---|
| Plain text or rich text (bold, headings, tables, images)? | Rich text needs a tree or annotated sequence model, not just characters | Rich text in scope at the model level; start with plain text in the core design |
| How many simultaneous editors per document? | Decides whether one server per document is enough | Typically 1 to 5; support up to about 100 active editors, many more viewers |
| What latency do users expect? | Drives local-first editing and the network protocol | Own keystrokes appear instantly; others' edits within about 100 to 300 ms |
| Must edits work offline? | Forces merge of long-diverged histories | Yes, for hours or days, then merge on reconnect |
| Cursors and presence? | A separate, high-rate, ephemeral channel | Yes: who is here, where their cursor and selection are |
| Version history? | Shapes how long the operation log is kept | Yes, named and automatic versions, restore to any version |
| Comments and suggestions? | Anchors that must move with text | Yes, as an extension of the core model |
| Permissions? | Every operation must be authorised | Owner, editor, commenter, viewer; link sharing |
| Scale? | Capacity planning | Hundreds of millions of users, billions of documents, millions concurrently open |
| Peer-to-peer or server-based? | Central authority simplifies everything | Server-based, browser and mobile clients |
Requirements#
Functional Requirements#
- Create documents and open existing ones by id.
- Concurrent editing: many users edit the same document at the same time, and all replicas converge to the same content.
- Realtime view: each user sees others' changes within a few hundred milliseconds.
- Presence and cursors: see who is in the document and where their cursors and selections are.
- Offline editing: continue editing without a connection, then merge on reconnect.
- Version history: list past versions and restore one.
- Sharing and permissions: grant edit, comment or view access; enforce on every operation.
Below the line, mentioned but not designed in depth: full-text search across documents, export to PDF or Word, spelling and grammar suggestions, AI assistance, templates.
Non-Functional Requirements#
- Convergence (strong eventual consistency): once all edits have been delivered, every replica shows exactly the same document. This is non-negotiable; a document that silently differs between two people is the worst bug the product can have.
- Intention preservation: an edit should have the effect the user intended even when applied after concurrent edits, for example an insertion stays between the same two words.
- Zero-latency local editing: typing never waits for the network.
- Low remote latency: other users' edits visible within about 100 ms p50 and 300 ms p99 in the same region.
- Durability: an edit acknowledged by the server is never lost, even if that server crashes immediately afterwards.
- High availability: a server failure interrupts a document for at most a few seconds, and clients recover automatically.
- Scalability: millions of concurrently open documents and connections; billions of stored documents.
- Bounded storage growth: the history of a document must not grow unbounded with every keystroke.
Capacity Estimation#
These are design-sizing numbers for a Google Docs-scale product, not Google's actual figures, which are not public. The method matters more than the exact inputs; see Back-of-the-Envelope Estimation.
Users and sessions.
- 100 million daily active users; at peak, 10 million are connected with a document open.
- Documents are mostly single-user at any moment. Assume an average of 2 connected users per open document, so about 5 million open documents at peak.
- About 20 percent of connected users are actively typing at any instant: 2 million active typists.
Operation rate.
- A fast typist produces 5 to 8 keystrokes per second; the average active user far fewer. Clients batch keystrokes into one message every 50 to 100 ms while typing, and the average active user sends about 2 operation messages per second.
- Peak inbound edit rate: 2 million x 2 = 4 million operations per second.
- Each operation is fanned out to the other connected users of the document (on average 1 more), plus an acknowledgement to the sender: about 8 million outbound edit messages per second.
Presence and cursors.
- Cursor and selection updates are throttled to at most about 10 per second per user, and only sent when the cursor moves. Assume 2 per second on average for active users, 0 for idle ones.
- About 4 million cursor updates per second in, a similar number out. These are ephemeral: never stored, droppable under load.
Connections.
- 10 million WebSocket connections at peak. A tuned connection server holds 100,000 or more idle connections, but with TLS, buffers and per-session state, plan for about 50,000 connections per server: 200 servers, about 300 with headroom for a zone failure and reconnect storms.
- Memory per connection: 20 to 50 KB with TLS state and buffers, so 50,000 connections use 1 to 2.5 GB. CPU, not memory, is usually the limit: TLS, framing and message fan-out.
Document session servers.
- Each open document is held in memory by one session server: the current text and its structure, recent operations (for transforming late-arriving edits), and the list of connected sessions.
- A typical document is 10 to 100 KB of text; the in-memory structure with formatting, metadata and an operation buffer is maybe 3 to 5 times that. Assume an average of 200 KB per open document: 5 million x 200 KB = 1 TB of RAM in total. With servers using 32 GB for document state each, about 30 servers by memory; CPU is again the limit.
- Processing an operation (validate, transform against concurrent operations, apply, append to the log, fan out) costs perhaps 20 to 100 microseconds of CPU. At 4 million operations per second and 50 microseconds each, that is 200 CPU-seconds per second, about 200 cores. Spread with headroom and hot-document isolation: about 100 servers of 16 cores.
Storage.
- An operation record (document id, revision number, author, timestamp, compact operation encoding) is about 100 bytes after batching.
- 4 million per second at peak is about 400 MB/s; averaged over a day at maybe a quarter of peak, roughly 8 to 10 TB of new operation log per day, about 3 PB per year if kept raw.
- That is why the log must be compacted (deep dive 6): keep raw operations for a recent window, then fold older operations into snapshots and coarser revisions. After compaction, history might cost 2 to 5 times the size of the document itself.
- 10 billion documents x 50 KB average current snapshot = 500 TB of snapshots, plus compacted history of perhaps 1 to 2 PB. Large, but modest by modern standards; images and embedded objects go to object storage (see Object Storage and Blob Storage).
Bandwidth.
- Edit messages are small: 8 million per second x about 200 bytes with framing = 1.6 GB/s, about 13 Gbps of egress, plus a similar amount for cursors. Document loads dominate: if 2,000 documents open per second at 100 KB each, that is another 200 MB/s. Bandwidth is not the bottleneck; connection count, per-document ordering and tail latency are.
Latency budget for a remote edit (same region).
| Step | Typical time |
|---|---|
| Client batches keystrokes | 0 to 50 ms |
| Client to connection server (WebSocket) | 10 to 40 ms |
| Connection server to session server | 1 ms |
| Transform, apply, append to durable log | 2 to 10 ms |
| Fan-out back through connection servers | 1 ms |
| Connection server to other client | 10 to 40 ms |
| Client applies and renders | 1 to 5 ms |
| Total | about 25 to 150 ms |
The local user sees their own keystroke in under 16 ms (one frame), because it is applied locally before anything is sent. Look up typical values in Numbers Every Engineer Should Know.
Core Entities#
- Document: id, title, owner, created and updated times, current revision number, pointer to the latest snapshot.
- Operation (op): one change to a document, such as "insert 'abc' at position 42" or "delete 3 characters at position 7" or "set bold on range 10 to 20". Each accepted op gets a revision number, assigned by the server in strict order per document. An op also records its author, the client's session id, and the revision it was based on.
- Snapshot: the full document content at a particular revision, stored so that loading does not require replaying the whole history.
- Session: one open instance of the editor (a browser tab or app) connected to a document, with a client id and the revision it has acknowledged.
- Presence: ephemeral per-session state: user, colour, cursor position, selection range, and last-active time. Never stored durably.
- Permission: who may do what (owner, editor, commenter, viewer), on a document or folder, or for anyone with the link.
- Version: a named or automatic point in history (a revision number plus metadata) that users can view and restore.
- Comment and suggestion: annotations anchored to ranges of text, which must move as the text around them changes.
API Design#
Two kinds of interface: ordinary request-response HTTP for document lifecycle, and a persistent WebSocket for live editing. See API Design Best Practices and Polling, Long Polling, SSE, WebSockets and Webhooks.
HTTP endpoints.
POST /v1/documents -> { docId }
GET /v1/documents/{docId} -> { title, revision, snapshot, permissions }
PATCH /v1/documents/{docId} { title } (metadata only)
DELETE /v1/documents/{docId} (moves to trash)
GET /v1/documents/{docId}/versions -> [{ revision, name, author, time }]
POST /v1/documents/{docId}/versions/{rev}/restore
POST /v1/documents/{docId}/permissions { principal, role }
GET /v1/documents/{docId}/session -> { wsUrl, token } (where to connect)
The client authenticates with a normal session cookie or OAuth token; the session endpoint returns a short-lived token bound to this user and document, plus the address of the WebSocket endpoint.
WebSocket messages. After connecting, the client says which document and which revision it already has; the server sends whatever the client is missing, then both sides exchange messages:
// Client -> server
type Join = { t: "join"; docId: string; token: string; haveRevision: number };
type Submit = { t: "op"; clientId: string; seq: number; // seq: per-client counter
baseRevision: number; ops: Op[] }; // ops relative to baseRevision
type Cursor = { t: "cursor"; pos: number; anchor: number }; // throttled, droppable
// Server -> client
type Snapshot = { t: "snapshot"; revision: number; content: Doc };
type Ack = { t: "ack"; seq: number; revision: number }; // your op became this revision
type Remote = { t: "remote"; revision: number; author: string; ops: Op[] };
type Presence = { t: "presence"; sessions: { id: string; user: string; pos: number }[] };
type Error = { t: "error"; code: "forbidden" | "stale" | "too_large"; detail: string };
// A text operation as a list of retain / insert / delete components
type Op = { retain: number } | { insert: string; attrs?: Record<string, unknown> }
| { delete: number };Key points:
baseRevisiontells the server which version of the document the client's op was written against, so the server knows which concurrent ops it must transform it against.clientIdplusseqmakes submission idempotent: if the client resends after a reconnect, the server recognises the duplicate and returns the existing ack instead of applying the op twice. See Idempotency and Safe Retries.- Acks carry the assigned revision, so the client knows where its op landed in the global order.
- Cursors are a separate message type: they can be throttled, coalesced and dropped without affecting the document.
- The op format (retain, insert, delete components covering the whole document) is the style used by several real editors, for example the Delta format of the Quill editor and the changesets of Etherpad. It is compact for typing ("retain 4,203, insert 'a'") and makes transformation straightforward.
High-Level Design#
We build the design one requirement at a time, then put it together.
1. Create and open documents#
Creating a document is ordinary CRUD. The client calls POST /v1/documents; the document service writes a metadata row (id, owner, title, revision 0) to the metadata database, creates an empty snapshot, and grants the creator the owner role. Opening a document calls GET /v1/documents/{id}, which checks permissions and returns metadata plus the latest snapshot, then the client asks where to open its WebSocket.
The metadata database holds a few billion rows of a few hundred bytes each: a sharded relational database or a scalable key-value store both work, sharded by document id. Permissions are read on every open and cached. Snapshots can live in the same database for small documents or in object storage with a pointer for large ones.
2. Multiple users edit concurrently#
This is the heart of the problem. Consider three approaches.
Bad: lock the document or send the whole document
Option A, pessimistic locking: only one person may edit at a time; others wait for the lock. Correct, but it is not collaboration, and a user who leaves a tab open holds the lock forever.
Option B, last writer wins on the whole document: each client sends its whole document every few seconds; the server keeps the latest. Two people typing at once overwrite each other's work. Even with paragraph-level granularity, concurrent edits to the same paragraph lose data.
Option C, send raw operations and apply them in arrival order: each client sends "insert 'x' at position 5", and everyone applies ops as they arrive. Because ops arrive in different orders at different replicas and positions shift, replicas diverge. A worked example:
- Document:
abc. Alice insertsXat position 0 (intendingXabc). Concurrently Bob deletes the character at position 2, thec(intendingab). - At Alice: apply her insert, giving
Xabc; then Bob's "delete position 2" deletesb, givingXac. - At Bob: apply his delete, giving
ab; then Alice's "insert X at 0" givesXab. - Alice sees
Xac, Bob seesXab. They have diverged, and Alice's copy lost the wrong character.
Good: operational transformation with a central server
Operational transformation (OT), introduced by Clarence Ellis and Simon Gibbs ("Concurrency Control in Groupware Systems", SIGMOD 1989), fixes this by transforming an incoming op against the concurrent ops that were applied before it, adjusting its positions so that it has the intended effect on the current document.
In the example, when Bob's "delete position 2" reaches Alice, her replica knows it was concurrent with her own "insert at 0". Since her insert was before position 2, it shifts Bob's delete to position 3, which deletes c: both end with Xab. Formally, a transform function T(a, b) returns a version of op a adjusted to apply after op b.
Peer-to-peer OT, where every client transforms against every other, is notoriously hard to get right (deep dive 1). The practical variant, used by Google Docs and descended from the Jupiter system (Nichols and colleagues, UIST 1995), puts one server in charge of ordering each document:
- The client applies its edit locally at once and sends it with the revision it was based on.
- The server transforms it against any ops accepted since that revision, assigns the next revision number, appends it to the document's log, and broadcasts it.
- Other clients transform the incoming op against their own pending (unacknowledged) ops, then apply it.
There is now a single total order of ops per document, and each client only has to reconcile its own pending ops with the server's stream: a two-party problem, which is much easier than the general case.
Great: a dedicated session server per document, plus a durable log
The Good design leaves open which server does the ordering. If any of 100 API servers could accept an op for a document, they would have to coordinate (through a database lock or compare-and-set on the revision) for every keystroke. The great design makes one document session server the owner of each open document:
- All connections for a document route to the session server that owns it (deep dive 4).
- That server holds the document in memory, transforms and orders ops, and fans them out to all sessions directly. No cross-server coordination per op.
- Each accepted op is appended to a durable operation log before it is acknowledged, so a crash loses nothing acknowledged.
- Periodically, the server writes a snapshot, so loading and recovery replay only a short tail of the log (deep dive 6).
The same structure works with CRDTs instead of OT; the session server then acts as a relay and durable store rather than as the transformer. Deep dive 1 compares the choice.
3. Users see each other's changes in real time#
When the document is loaded
- The client fetches the latest snapshot and its revision (say revision 5,000) over HTTP, possibly from a cache or CDN-like edge for large public documents.
- It opens a WebSocket to a connection server, which forwards a
joinwithhaveRevision = 5000to the document's session server. - The session server sends any ops after revision 5,000 (the snapshot may be a little older than the live state) and adds the session to the document's subscriber list.
- From now on the client is live: it receives every new op in revision order.
If the document is not currently open anywhere, the session server first activates it: loads the latest snapshot and replays the log tail, which takes tens of milliseconds for a typical document.
When updates happen
Each edit flows client, connection server, session server, log, then fans out to every subscriber's connection server and on to their clients. Two properties matter:
- Ordering: every client receives ops in revision order. The session server is the single sequencer, and each connection is a single ordered TCP stream, so order is preserved end to end. If a client sees a gap (revision 5,010 then 5,012), it asks for the missing op instead of applying out of order.
- Push, not poll: polling every 100 ms per client would mean 100 million requests per second for 10 million clients with almost nothing to say; persistent WebSockets carry only real changes. See Pattern: Pushing Realtime Updates.
4. Users see cursors and presence#
Presence (who is here) and cursors (where they are) use the same WebSocket but a different path:
- Clients send cursor updates at most every 50 to 100 ms, only when the cursor or selection changes.
- The session server keeps the latest cursor per session in memory only, and broadcasts updates to the document's other sessions, coalescing if a newer one arrives before the older one was sent.
- Cursor positions are expressed relative to a revision and transformed through concurrent ops just like edits, so a remote cursor stays next to the same character while text is inserted before it.
- When a session disconnects, the server broadcasts its departure; if a client vanishes without closing, a heartbeat timeout of 10 to 30 seconds removes it.
Nothing about presence is written to disk. If a session server crashes, presence is simply rebuilt as clients reconnect and resend their cursors. Deep dive 7 covers the details.
The full high-level design#
Components:
- Clients keep a full local model of the document, apply edits immediately, track pending ops, and transform incoming ops. Mobile and desktop clients persist the document and pending ops locally for offline use.
- API gateway and document service handle authentication, document CRUD, permission changes, version listing and restore, and return the WebSocket address. See API Gateway and Backend-for-Frontend.
- L4 load balancer and connection servers terminate TLS and WebSockets, authenticate the session token, and forward messages to the right session server. They hold no document state, so they scale horizontally.
- Routing service maps each active document to the session server that owns it, using consistent hashing plus leases in a coordination service (deep dive 4).
- Document session servers own active documents in memory: validate permissions, order and transform ops, append to the log, fan out edits and presence, and write snapshots.
- Operation log: an append-only, replicated store keyed by (document id, revision). Durable before ack.
- Snapshot store: full document states at chosen revisions, in a database or object storage.
- Metadata and permissions DB: documents, ACLs, versions, comments.
- Change stream consumers: search indexing, history compaction and named versions, notifications ("Alice mentioned you"), all asynchronous and off the editing path.
Key Flows#
Flow 1: opening a document and joining the live session#
Two details: the snapshot over HTTP can be served from a cache, because the WebSocket catch-up fixes any staleness; and the routing answer carries a lease epoch, which lets the system reject a server that has lost ownership (deep dive 4).
Flow 2: two concurrent edits, transformed by the server#
Document at revision 41 is abc. Alice inserts X at 0; Bob, at the same moment, deletes position 2.
Both end at Xab. Note what each side does:
- The server transforms Bob's op because it was based on revision 41 but arrives after revision 42 was accepted.
- Bob receives revision 42 while his own delete is still pending. He transforms the incoming insert against his pending delete (the insert is at position 0, before the delete, so it is unchanged), applies it, and transforms his pending delete forward to position 3 so that it matches what the server will produce. When the ack for revision 43 arrives, it confirms his op is now part of history.
- Alice has nothing pending when revision 43 arrives, so she applies it as sent.
Flow 3: reconnecting after working offline#
With OT, the client rebases its pending ops onto the server's history before resubmitting; with a CRDT, it sends its ops as they are and the merge is automatic. Either way, long offline periods need care: see deep dive 8 for permissions that changed meanwhile, huge divergences and the user experience of a large merge.
Flow 4: a session server crashes#
No acknowledged op is lost, because acknowledgement happens only after the log append. Unacknowledged ops are still in each client's pending queue, and are resent with the same (clientId, seq) so duplicates are recognised. The fencing epoch guarantees that if the old server was only slow, not dead, its late writes to the log are rejected. Users see a pause of a few seconds and a brief "reconnecting" banner.
Data Model#
The data splits into three groups with very different access patterns: metadata (documents, permissions, versions, comments), the operation log (append-heavy, read in revision ranges), and snapshots (large, write-occasionally, read on every open).
| Store | Contents | Access pattern | Good fits |
|---|---|---|---|
| Metadata DB | Documents, permissions, versions, comments | Point reads by doc id, listing by owner or folder | Sharded PostgreSQL or MySQL, Spanner, DynamoDB |
| Operation log | One row per accepted op batch, keyed by (doc_id, revision) | Append at the head, range-read the tail on load | Bigtable, Cassandra, DynamoDB with conditional puts, a replicated log |
| Snapshot store | Serialised document at a revision | Read the latest on open, write every N ops | Object storage for large docs, the metadata DB for small ones |
| History blocks | Compacted diffs for version history | Read only when browsing history | Object storage or a wide-column store |
| Presence | Cursor, selection, last seen | In memory only, on the session server | Never persisted |
Key decisions:
- The op log's primary key is (doc_id, revision), so all ops of a document are stored together and in order, and a load is one range scan. Revision numbers are dense and assigned by the single owner, so "append revision 6,831" can be a conditional put (insert only if absent). If two servers ever both believe they own the document, the second put of revision 6,831 fails, which is a second line of defence after fencing.
- (client_id, client_seq) is stored with each op so that duplicate resubmissions after a reconnect are recognised and acknowledged with the original revision.
- owner_epoch on the document row is the fencing token: the log store rejects appends from a stale epoch (deep dive 4).
- Snapshots are immutable and named by revision, so they can be cached and written without coordination.
- Comments are anchored, not positioned. An anchor refers to stable character identities (CRDT ids) or to a range that the server transforms with every op, so a comment stays attached to its text as the document changes.
For choosing the stores, see Choosing a Database: A Decision Guide and Data Modeling.
Deep Dives#
1. OT versus CRDT: choosing the concurrency algorithm#
Both families solve the same problem: replicas apply concurrent edits in different orders and must still converge to the same document while preserving each user's intent. They take opposite routes.
- Operational transformation keeps positional operations ("insert at 42") and rewrites them when they cross concurrent ops. The intelligence is in the transform functions, and usually in a server that fixes the order.
- Conflict-free replicated data types (CRDTs) give every character a unique, permanent identity and express ops against identities ("insert after character (alice, 17)"), designed so that applying the same set of ops in any order gives the same result. The intelligence is in the data structure. The formal framework is from Marc Shapiro, Nuno Preguiça, Carlos Baquero and Marek Zawirski ("Conflict-free Replicated Data Types", SSS 2011).
Basic: OT with a central server
Every op goes through the document's session server, which assigns a total order. Clients and server need only a transform for each pair of op types (insert/insert, insert/delete, delete/delete, plus formatting) satisfying one property, described in deep dive 2. This is how Google Docs is widely understood to work: Google described its use of operational transformation when it launched the rewritten Docs editor in 2010, and the architecture descends from Jupiter and Google Wave.
Strengths:
- Compact documents: the stored document is just the text and formatting; deleted characters leave no trace, and there are no per-character ids.
- Simple server-side features: since the server sees every op in order, it can enforce permissions per op, validate schema (no broken tables), and compute derived state (word counts, search indexing) on a single canonical history.
- Mature and proven at very large scale.
Weaknesses:
- Requires a central server (or a carefully designed ordering service) for each document. Peer-to-peer use and long offline periods are awkward.
- Transform functions get complicated for rich structures (tables, nested lists, moves). Every pair of op types needs a correct transform, and the number of pairs grows quadratically with op types.
- Offline rebase is expensive: transforming 500 local ops against 5,000 remote ops is up to 2.5 million transform steps, with costs that grow with divergence.
Better: a sequence CRDT with a relay server
Each inserted character gets an id such as (replica id, counter). An insert says "put this character after the character with id X"; a delete marks the character with id Y as deleted (a tombstone), because other replicas may still be inserting relative to it. Ties between concurrent inserts at the same spot are broken deterministically, for example by replica id, so every replica orders them the same way. Algorithms in this family include WOOT (Oster and colleagues, CSCW 2006), Logoot (Weiss, Urso and Molli, ICDCS 2009), Treedoc (Preguiça and colleagues, ICDCS 2009), RGA (Roh and colleagues, Journal of Parallel and Distributed Computing, 2011), YATA as used by the Yjs library (Nicolaescu and colleagues, GROUP 2016), and Fugue (Weidner and Kleppmann, 2023).
The server's role shrinks to relay and durable store: it forwards ops, persists them, and serves the merged state to newly joining clients. It does not need to transform anything.
Strengths:
- Order-independent merge: ops can arrive in any order, from any path, after any delay. This is ideal for offline editing and for peer-to-peer or local-first apps (Martin Kleppmann, Adam Wiggins, Peter van Hardenberg and Mark McGranaghan, "Local-First Software", Onward! 2019).
- No central sequencer required, which simplifies failover and multi-region designs.
- Mathematically clean correctness: convergence follows from the data type's properties (commutative, associative, idempotent merges), and has been formally verified for some algorithms.
Weaknesses:
- Metadata overhead: every character carries an id and tombstones stay until it is safe to remove them. Naive implementations used tens of bytes per character. Modern libraries (Yjs, Automerge 2, Diamond Types) compress runs of consecutive characters typed by one user into a single item, bringing overhead down to a small multiple of the text size in typical documents.
- Interleaving anomalies: some algorithms can interleave two users' concurrently typed words character by character ("HWeolrllod" from "Hello" and "World"). Kleppmann and colleagues analysed this ("Interleaving anomalies in collaborative text editors", PaPoC 2019); Fugue was designed to minimise it.
- Semantic conflicts are still possible: a CRDT guarantees that replicas agree, not that the result makes sense. Two users concurrently fixing the same typo can produce a doubled correction.
- Server-side validation is harder: since ops are designed to apply anywhere, rejecting one (because of permissions or schema) breaks the "every replica applies every op" assumption; the server must filter ops before relaying, which reintroduces a central authority.
Best: decide by the product's constraints, and mix where it helps
| Constraint | Leans OT (central server) | Leans CRDT |
|---|---|---|
| Always-online web editor, server must validate every op | Yes | Possible, with server filtering |
| Long offline periods, mobile and desktop apps | Possible with rebase | Yes |
| Peer-to-peer or end-to-end encrypted collaboration | Hard | Yes, the server can relay ciphertext |
| Very large documents, memory-sensitive clients | Yes, no per-character metadata | Acceptable with run-length compression |
| Rich structure: tables, nested blocks, moves | Hard transforms for each pair | Hard too, but per-type CRDTs compose |
| Team experience and existing libraries | ShareDB, ProseMirror collab, Etherpad | Yjs, Automerge, Diamond Types |
Real systems often blend the two:
- Server-ordered CRDTs: keep a session server that assigns revision numbers anyway, for durability, simple catch-up ("send me everything after revision 5,000") and permission checks, while using a CRDT for the merge itself. Many Yjs deployments work this way with a central sync server.
- Last-writer-wins per property: for objects that are not text sequences (a shape's colour, a table cell's width), a simple LWW register per property is often enough. Figma's multiplayer system, described by Evan Wallace in 2019, uses a central server per document with last-writer-wins on individual properties, and borrows ideas from CRDTs rather than implementing a text CRDT for the whole canvas.
- Rebase-style central authority: ProseMirror's collaboration module accepts a client's steps only if they are based on the latest server version; otherwise the client rebases its steps locally and retries. This moves transformation entirely to the client and keeps the server trivially simple.
- Event-graph approaches: Eg-walker (Joseph Gentle and Martin Kleppmann, EuroSys 2025) stores the raw op history like OT, but merges like a CRDT by temporarily building CRDT state only for the concurrent part of the history, aiming for OT-like memory use with CRDT-like offline merging.
Recommendation for this design: an OT core with a session server per document, because the product is server-centric, needs per-op permission checks and must keep documents compact; plus offline support through client-side rebase (deep dive 8). If the brief emphasised offline-first, peer-to-peer or end-to-end encryption, a CRDT core with a server relay would be the better answer. In an interview, state the trade-off and pick one; both are defensible. See Conflict Resolution, OT and CRDTs.
2. Inside operational transformation#
The transform function
For two concurrent ops a and b applied to the same document state, the transform T(a, b) produces a', a version of a that applies after b. For single-character text ops at positions p and q:
- insert vs insert: if q is before p, or q equals p and b wins the tie-break, shift a right by the length of b's insert. Otherwise leave it.
- insert vs delete: if b deleted a character before p, shift a left by one.
- delete vs insert: if b inserted before or at p, shift a right.
- delete vs delete: if b deleted the same character, a becomes a no-op; if before, shift left.
The tie-break for two inserts at the same position must be deterministic and the same on all replicas, for example by comparing client ids, or "the op already accepted by the server goes first".
The correctness properties
TP1 (convergence for two ops): applying a then T(b, a) must give the same document as applying b then T(a, b). In symbols, a then b' equals b then a'. Every correct OT system needs TP1.
TP2 (convergence for three or more ops): transforming an op along two different but equivalent paths of concurrent ops must give the same result. TP2 is needed only when ops can be transformed along different paths, which happens in fully distributed OT without a central order. These properties were formalised by Matthias Ressel, Doris Nitsche-Ruhland and Rul Gunzenhäuser (CSCW 1996), and later work showed that several published OT algorithms violated TP2 in edge cases, a famous source of subtle divergence bugs.
The central server sidesteps TP2. With a server that defines one total order and clients that only ever transform their pending ops against the server's stream, every transformation happens along a single path. Only TP1 is needed, and TP1 is easy to test exhaustively for small op types. This is the main reason production OT systems are server-centric.
The client state machine
Each client is in one of three states (from the Jupiter design, popularised by the ot.js library and others):
- Synchronized: no pending ops. A local edit is sent immediately; move to awaiting ack.
- Awaiting ack: one op in flight. New local edits are composed into a buffer instead of being sent. Incoming remote ops are transformed against both the in-flight op and the buffer.
- Awaiting ack with buffer: when the ack arrives, send the buffer as the next in-flight op.
In the buffered state, further local edits are composed into the same buffer, and in either waiting state remote ops are transformed and applied without changing state. Only one op is in flight per client at a time, which keeps the server's transform simple (each client op needs transforming only against server ops it has not seen) and naturally batches fast typing: while waiting 50 ms for an ack, a fast typist's next several keystrokes are composed into one op.
Composition and the op format
Compose merges two sequential ops into one: "insert 'a' at 10" then "insert 'b' at 11" becomes "insert 'ab' at 10". Composition is what keeps the protocol efficient: buffers, catch-up batches and history compaction all compose many small ops into few large ones.
The retain / insert / delete format (seen in Quill's Delta and Etherpad's changesets) describes an op as a walk over the whole document: "retain 42, insert 'X', retain 158". Transform and compose then become merges of two such walks, linear in the number of components, and adding formatting is natural: "retain 10 with bold, retain 5".
Undo
Undo in a collaborative editor must undo my last change, not whoever typed last. The client keeps the inverse of each of its own ops and transforms those inverses forward through every later op (local and remote), so that "undo" still removes the text you typed even after others edited around it. If someone else has since deleted the same text, the transformed inverse may become a no-op, which matches user expectations.
3. Inside a sequence CRDT#
Even if the core design uses OT, a staff-level answer should be able to explain how a text CRDT works, because it is the natural alternative for offline and peer-to-peer requirements.
Identities instead of positions
Every inserted character gets a globally unique id, typically (replicaId, counter) where counter increases with every op from that replica. The document is a sequence of items, each holding an id, the character, the id of the item it was inserted after (its origin), and a deleted flag.
- Insert "put character c with id (alice, 7) after item (bob, 3)".
- Delete "mark item (alice, 5) as deleted". The item stays in the structure as a tombstone, invisible to the user.
Because ops refer to ids, not positions, they mean the same thing on every replica no matter what else has happened. The only remaining question is how to order concurrent inserts after the same origin.
Ordering concurrent inserts, RGA style
In RGA (Replicated Growable Array), each insert also carries a logical timestamp. When inserting after an origin, a replica skips over any items already following that origin that have a greater timestamp, then inserts. Concurrent inserts at the same spot therefore end up ordered by descending timestamp (ties broken by replica id) on every replica, regardless of arrival order.
Worked example, starting from ab with item ids a = (s, 1), b = (s, 2):
- Alice inserts
Xafter a, with timestamp 10. Bob concurrently insertsYafter a, with timestamp 11. - At a replica that receives Alice's op first:
aXb. Then Bob's op: after a, the next item is X with timestamp 10, which is smaller than 11, so Y goes immediately after a:aYXb. - At a replica that receives Bob's first:
aYb. Then Alice's: after a, the next item is Y with timestamp 11, greater than 10, so skip it; next is b, whose timestamp (2) is smaller than 10, so stop and insert:aYXb. - Both converge to
aYXb.
Because the effect of an op depends only on its id, its origin and the timestamps of items it might skip, applying ops in any causally consistent order (each op after the ops it depends on, which is easy to ensure by buffering ops whose origin has not arrived yet) gives the same result everywhere. See Time, Clocks and Ordering for the logical clocks behind the timestamps.
Keeping metadata small
The naive costs are large: a 16-byte id, a 16-byte origin, a timestamp and a flag for every character of a 1 MB document is tens of megabytes. Production libraries reduce this dramatically:
- Run-length encoding of items: a user typing "hello world" produces ids (alice, 100) to (alice, 110), each inserted after the previous. Store it as one item covering 11 characters; split it only if someone later inserts in the middle.
- Columnar binary encodings for storage and transfer, as in Automerge 2 and the Yjs update format, where long runs of similar values compress to a few bytes.
- Tombstone garbage collection: a tombstone can be removed once every replica has seen the delete and no future op can refer to it. In a server-based system, the server knows which revision every connected client has seen and can compact tombstones older than all of them; offline clients that return with ops referring to collected items need a fallback (for example, resolve their origin to the nearest surviving neighbour, or reload).
With these, CRDT documents in typical editing workloads take a small multiple of the plain text size in memory, and less on disk.
Rich text and structure
Formatting is harder than characters. If Alice bolds a range while Bob types in the middle of it, should Bob's text be bold? Peritext (Geoffrey Litt, Sarah Lim, Martin Kleppmann and Peter van Hardenberg, CSCW 2022) treats formatting marks as anchored to character ids at their start and end, with explicit rules on whether a mark expands to include text inserted at its edges (bold usually expands at the end; a link usually does not). Block structure (paragraphs, list items, table cells) is usually modelled as a tree of CRDTs: a sequence CRDT for the children of each node, maps (with LWW registers per key) for attributes. Moving a subtree safely is a known hard problem; Kleppmann and colleagues proposed a move operation for replicated trees ("A highly-available move operation for replicated trees", IEEE TPDS 2022) that avoids cycles.
4. The document session server#
The defining architectural choice is one owner per active document: all edits to a document pass through one process, which holds the document in memory. This is unusual for web systems, which are normally stateless, so it needs justification and careful mechanics.
Why a single owner
- Total order for free: a single process can assign revision numbers with a counter, no distributed consensus per keystroke.
- Speed: the document, its recent ops and its subscriber list are in memory; applying an op is microseconds, and fan-out is a loop over local sessions.
- Simplicity of OT: the server-centric OT protocol of deep dive 2 needs exactly one transformer per document.
The price: a document's throughput is limited to what one machine (often one thread) can handle, and the server is a failure point for that document. Both are acceptable because documents are small units. Even a heavily edited document with 100 active editors at 5 ops per second is 500 ops per second, trivially within one core's budget of tens of thousands.
Bad: any server handles any document, coordinate through the database
Each op does "read head revision, transform against ops since base, conditional-write revision + 1". With several servers handling the same document, they race on the conditional write, retry, and re-read. It works at low concurrency but costs a database round trip per keystroke and collapses under contention on busy documents.
Good: consistent hashing of documents to session servers
Hash the document id onto a ring of session servers (see Consistent Hashing). Connection servers compute the owner locally. Adding or removing a server moves only about 1/N of documents. The weakness: during membership changes, different connection servers can briefly disagree about the ring, and two servers may both think they own a document. Without protection, both accept ops and assign the same revision numbers to different ops: a split brain that corrupts the document.
Great: explicit ownership with leases and fencing
- A routing service backed by a coordination store (etcd or ZooKeeper; see ZooKeeper and etcd) records, for each active document, its owner and an epoch number. Consistent hashing can still be used to choose the default owner, but the record is the authority.
- To own a document, a server acquires a lease (a lock that expires unless renewed, for example every 3 seconds with a 10-second timeout), and the epoch increments each time ownership changes.
- Every log append carries the epoch. The log store accepts an append only if the epoch matches the current owner record (or is at least the highest epoch seen for that document). This fencing token means a server that was paused (a long garbage-collection pause, a network partition) and still believes it is the owner cannot corrupt the log after ownership has moved. See Leader Election and Coordination Services.
- Connection servers cache the routing record. If a session server receives a message for a document it no longer owns, it answers "moved, epoch 13 is at S2", and the connection server updates its cache.
Leases per document can be many: 5 million active documents with 3-second renewals would be 1.7 million writes per second to the coordination store, far beyond etcd's comfort zone. In practice, leases are taken per shard (a range of hash space containing thousands of documents) and the epoch is per shard, or session servers hold one lease for their whole membership and the routing table assigns shards to members. Per-shard leases cut coordination load by three or more orders of magnitude.
Activation and passivation
A document is active only while someone has it open. On the first join, the owner loads the snapshot and log tail (tens of milliseconds); when the last session leaves, it writes a fresh snapshot, waits a short idle period (in case of a quick reopen), and evicts the document from memory. Of 10 billion documents, only millions are active at once, so memory scales with concurrent use, not with the corpus. This is the virtual-actor pattern popularised by Microsoft Orleans (Bykov and colleagues, "Orleans: Cloud Computing for Everyone", SoCC 2011): an entity exists in memory on exactly one node while it is in use, and is reactivated transparently on demand.
5. WebSocket sessions at millions of connections#
A realtime system has two "hops": from the server to the client (the connection), and from where an update originates to the server holding the recipient's connection (the backend routing). Both must scale.
Why WebSockets
- Polling every second wastes requests and adds up to a second of latency; at 10 million clients it is 10 million requests per second carrying almost nothing.
- Long polling cuts the waste but needs a new request after each message, and fast typing produces many messages.
- Server-Sent Events are one-way (server to client); edits must still go up by separate HTTP requests, which do not share ordering with the downstream stream.
- WebSockets give a single, ordered, full-duplex stream per session over one TCP connection, with a few bytes of framing per message. Edits up, edits and acks down, cursors both ways. This is the natural fit. A long-polling fallback is still worth keeping for networks with proxies that break WebSockets.
See Polling, Long Polling, SSE, WebSockets and Webhooks and TCP vs UDP (and QUIC).
Bad: clients connect directly to session servers
Point the client's WebSocket straight at the document's owner. It looks efficient (one hop fewer), but:
- The client must know the owner, and when ownership moves every client must reconnect.
- TLS termination and connection handling consume the session servers' CPU and memory, which should be spent on documents.
- A user with three documents open needs three connections to three servers.
- A session server deploy or crash drops every connection on it at once.
Good: a stateless connection tier, routing to session servers
Clients connect through an L4 load balancer (TCP-level, so it does not need to understand WebSocket frames) to any connection server. The connection server authenticates the session token once at connect time, then multiplexes: one client connection can carry several documents, and messages for a document are forwarded over a small number of persistent internal connections (gRPC streams or similar) to the owning session server. Session servers push outbound messages back to the connection servers that hold the subscribers.
- Connection servers are cheap and stateless (apart from the sockets themselves), and scale by count: 10 million connections at 50,000 each is 200 servers.
- Ownership changes are invisible to clients: the connection server reroutes.
- Session servers handle only internal streams, a few thousand at most, not millions of sockets.
Great: the good design plus the operational details that make it survive
- Heartbeats: WebSocket ping frames every 20 to 30 seconds keep NAT mappings and proxies alive and detect dead clients. Without them, a laptop that closes its lid leaves a zombie session for minutes.
- Reconnect with exponential backoff and jitter: if a connection server fails, 50,000 clients reconnect at once. With jittered backoff (first retry within 0 to 1 s, then 0 to 2 s, and so on) the load spreads out; without it, the reconnect storm can take down the servers that remain. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.
- Resumable sessions: on reconnect, the client sends the last revision it saw and its unacked ops, so recovery is incremental, never a full reload.
- Graceful drain on deploy: a connection server being replaced stops accepting new connections and sends clients a "reconnect elsewhere" message spread over a few minutes, instead of dropping them all at once.
- Backpressure: if a client cannot keep up (a slow phone on a bad network), the connection server's send buffer for that socket grows. Cap it: coalesce cursor messages, and if edit messages back up beyond a limit, drop the connection and let the client resync from its last revision. One slow client must never slow down the session server for everyone else.
- Token expiry and revocation: a session token is short-lived (minutes to an hour); the client refreshes it over the open socket. If a user's access is revoked, the session server closes their sessions for that document.
Routing the second hop: direct versus pub/sub
How do updates get from the session server to the connection servers holding a document's subscribers?
- Direct routing (our choice): each session server knows which connection servers have subscribers for each of its documents (they registered on join) and sends to them directly. Ordering is preserved because each session-to-connection-server stream is ordered and the session server is the sole source.
- Pub/sub (for example Redis Pub/Sub, or a broker topic per document): the session server publishes, connection servers subscribe to the documents their clients have open. Simpler to wire up, and useful when many independent publishers write to one topic, but it adds a hop and its delivery guarantees (Redis Pub/Sub is fire-and-forget) mean gaps must be detected and repaired by revision numbers anyway. See Redis in Practice.
Either way, revision numbers are what make ordering robust: a client applies revision N + 1 only after N. If anything is lost or reordered across distributed servers, the client sees a gap, buffers what came early, and fetches the missing revisions from the session server or the log. Ordering never relies on the network alone.
6. The operation log and snapshots: durability and bounded storage#
The document as an event log
The authoritative record of a document is its operation log: every accepted op, in revision order. The current content is just the result of applying all of them to an empty document. This is event sourcing (see Database Replication for logs as the basis of replication). It gives version history, audit ("who wrote this sentence?"), and precise recovery for free, at the cost of unbounded growth and slow replay.
Durability before acknowledgement
An op is acknowledged only after it is durably appended. Options:
- Append to a replicated database (Bigtable, Spanner, DynamoDB, Cassandra with quorum writes): a few milliseconds per write, replicated across zones. One write per op batch.
- Append to a replicated log (Kafka with
acks=all, or an internal consensus log): similar latency, sequential writes, and other consumers (search indexing, history compaction) can read the same log. See Apache Kafka in Practice. - Group commit: the session server batches ops from all documents it owns into one write every 2 to 5 ms. This turns 40,000 ops per second per server into a few hundred writes, at the cost of a few ms of latency.
Writing to local disk alone is not enough: if the server dies, its disk may be gone too, and the next owner needs the log.
Snapshots bound replay time
Loading a ten-year-old document by replaying 5 million ops is far too slow. The session server writes a snapshot (the full serialised document) every N ops or T minutes, for example every 1,000 ops or 10 minutes of activity, and on passivation. Loading is then "latest snapshot plus the tail since it". With N = 1,000, the tail is at most 1,000 ops, which applies in well under 10 ms.
The cost trade-off: a 100 KB document snapshotted every 1,000 ops at 100 bytes per op means a snapshot costs as much as the ops it covers. Snapshot more often and storage and write bandwidth go up; less often and loads and failovers get slower. Keep only the latest few snapshots for loading; older snapshots are needed only as anchors for history.
Snapshot format and cadence in practice
A few refinements make snapshots cheaper and safer:
- Adaptive cadence. Snapshot by work done, not by clock: a document receiving 50 ops per second needs a snapshot every 20 seconds of activity to keep the tail at 1,000 ops, while a document edited once an hour needs one only on passivation. Size also matters: a large document is cheaper to replay a few hundred ops on than to re-serialise, so its threshold can be higher.
- Self-describing, versioned format. A snapshot records its revision, the schema version of the document model and a checksum. When the model changes (a new block type), old snapshots must still load, so loaders handle every past version, or a background job migrates snapshots forward.
- Verify before trusting. After writing a snapshot, the server can reload it in the background and compare the checksum with the in-memory state. A buggy serialiser that silently drops a table is then caught immediately, not months later when a document is loaded from that snapshot.
- Snapshots for clients, too. Clients that open a document receive the latest snapshot; for very large documents, a client can receive a snapshot of only the first sections plus an index, and fetch the rest as the user scrolls, so time to first paint stays low.
- Keep the log as the source of truth. A snapshot is a cache of the log, never the other way around. If a snapshot is found to be corrupt, the document is rebuilt from an earlier snapshot plus the raw log, which is one more reason to keep raw ops for a recent window.
Compaction keeps history useful and cheap
Users want "see what changed since yesterday" and "restore Tuesday's version", not every keystroke from 2017. A background history compactor (reading the change stream, off the editing path):
- Keeps raw ops for a recent window (for example 30 days), so fine-grained history and precise undo of recent work are available.
- Groups older ops into history blocks: consecutive ops by the same authors within a time window (say 30 minutes of an editing session) are composed into one diff, stored compressed with the list of authors.
- Keeps named versions (user-created) and periodic checkpoints (daily, then weekly) as full snapshots or as anchors that blocks refer to.
- Deletes raw ops older than the window once they are safely compacted.
With compaction, history shrinks by one to two orders of magnitude: thousands of tiny keystroke ops become one diff per editing session. That is what keeps the capacity section's 3 PB per year of raw ops down to a manageable size. Retention policies (and legal holds) decide how far back history goes; see Data Lifecycle, Tiering and Retention.
Restoring a version
Restoring revision 4,000 of a document at revision 9,000 does not rewrite history. The server computes the diff from the current state to the state at 4,000 and applies it as a new op, revision 9,001. Collaborators see the restore as a big edit, history stays linear, and the restore itself can be undone.
7. Presence and cursors#
Presence answers "who else is here?"; cursors answer "where are they working?". Both make collaboration feel alive, and both have requirements opposite to document edits: high frequency, low value per message, no durability, and freshness matters more than completeness.
Bad: treat cursor moves like edits
Send every cursor move as an op through the log. Cursor traffic is as large as edit traffic or larger (moving with arrow keys, selecting with the mouse), so this doubles log writes for data that is worthless a second later, and makes recovery replay meaningless cursor history.
Good: an ephemeral channel through the session server
- Clients send
{pos, anchor}(cursor and selection end) only when they change, throttled to at most one message every 50 to 100 ms. - The session server keeps the latest cursor per session in memory, and broadcasts to other sessions of the document. If a newer update for the same session arrives before the older one was sent, it replaces it (coalescing).
- Under load, cursor messages are the first to be dropped. Nobody notices a cursor that jumps a little.
Great: cursors that stay attached to text
A cursor position "offset 120" becomes wrong the moment someone inserts text before it. Two ways to keep it right:
- With OT: each cursor update carries the revision it refers to. Receivers transform the position through any ops after that revision (an insert before it shifts it right, a delete before it shifts it left), and keep transforming stored remote cursors through every new op. The same transform functions as for edits apply; a cursor is just a zero-width op.
- With a CRDT: express the cursor as "after item (alice, 107)". Since item ids never change, the cursor stays attached to the same character with no transforms. If that character is deleted, the cursor moves to the nearest visible neighbour (tombstones still give it a place to anchor).
Presence lifecycle
- Join: when a session joins, the server sends the current presence list, and announces the new session to others (name, avatar, assigned colour).
- Activity: "last active" timestamps distinguish active editors from idle tabs (shown faded).
- Leave: an explicit close on tab exit; otherwise a heartbeat timeout of 10 to 30 seconds. Unreliable mobile networks need some hysteresis, so users do not flicker in and out.
- Same user, many tabs: show the user once with several cursors, or once with the most recent cursor; decide in product, but keep presence keyed by session, not by user.
Scale
For a document with n active sessions each sending c cursor updates per second, outbound cursor traffic is n x (n - 1) x c. With 5 editors at 10 per second that is 200 messages per second, trivial. With 100 editors it is about 99,000 per second for one document, which one server can still push, but clients cannot usefully render 99 moving cursors. Large sessions degrade gracefully: lower the per-client rate as n grows (for example cap total cursor messages per document at 1,000 per second), show only cursors near the viewer's viewport, and for very large audiences (a company all-hands document with 2,000 viewers) show a viewer count instead of individual cursors. Google's help pages describe a limit of about 100 people who can edit or comment at the same time, beyond which additional people can only view; the exact behaviour may change, but the design lesson is to cap the fully interactive set.
8. Offline edits#
Offline editing turns a millisecond-scale concurrency problem into an hours- or days-scale one. A user edits on a plane for six hours; meanwhile, colleagues rewrite half the document.
What the client stores
- The document state at the last known server revision, plus the revision number.
- The queue of pending ops made since then, each with its
(clientId, seq). - Both persisted in local storage (IndexedDB in browsers, SQLite or files on mobile and desktop) and written before the edit is shown, so a crash or closed tab loses nothing.
Reconnecting with OT: rebase
The client receives all remote ops since its base revision, transforms its pending ops past them (in the same way as during normal editing, just in bulk), and submits the transformed ops based on the latest revision. To make this tractable:
- Compose before transforming: 2,000 pending keystrokes compose to perhaps 50 ops; 20,000 remote ops compose to a few hundred. Composition first reduces transform work by orders of magnitude.
- Submit in batches, with idempotent
(clientId, seq), so a disconnect mid-upload resumes safely. - Bound the divergence: if the gap is enormous (the document was restructured, or the client was away for weeks and history was compacted past its base revision), fall back: save the offline copy as a separate version or a suggestion, and let the user merge, rather than attempting an automatic transform that may produce nonsense.
Reconnecting with a CRDT: exchange missing ops
The client and server exchange state vectors (for each replica id, the highest counter seen) and each sends the other the ops it is missing. Merge is automatic and order-independent, which is the main reason offline-first apps prefer CRDTs.
Problems that remain with either algorithm
- Permissions changed while offline. If the user's edit access was revoked, the server must reject their pending ops. Tell the user clearly, and offer to save their changes as a copy. With a CRDT, the server must filter the rejected ops before relaying them to others.
- The document was deleted or moved to trash. Same treatment: reject, offer a copy.
- Semantic conflicts. Both algorithms guarantee convergence, not meaning. If two people rewrote the same paragraph, the merged paragraph may contain both rewrites interleaved at word level. Many products highlight heavily merged regions after a long offline session, or show the offline changes as suggestions for review.
- Clock and identity issues. Never trust client wall-clock times for ordering. Revision numbers (OT) or logical clocks (CRDT) decide order; client timestamps are only for display.
- Storage limits. Offline caches are bounded; the client chooses which documents to keep available (recently opened, starred) and must handle eviction.
Telling the user what is going on
Offline is mostly a UX problem. A good editor shows "working offline, changes saved on this device", then "syncing 240 changes", then "all changes saved". If a merge needed manual help, it says which parts. Users forgive delay; they do not forgive silently lost work.
9. Scaling documents across servers#
Ownership by document gives natural horizontal scaling: more documents, more session servers. The interesting problems are uneven load, moving documents without dropping edits, and very hot documents.
Sharding the document space
Hash each document id into one of, say, 16,384 shards; assign shards to session servers through the routing table. With 100 servers, each holds about 164 shards. Shards, not individual documents, are the unit of lease, assignment and movement, which keeps the coordination store small (deep dive 4). This is the same pattern as virtual nodes in consistent hashing; see Partitioning and Sharding.
Balancing load
Document load is skewed: most open documents get an edit a minute; a few have 30 people typing. A placement controller watches per-shard metrics (ops per second, active sessions, memory) and moves shards from hot servers to cold ones. It moves gradually (a few shards at a time) and only when imbalance persists, to avoid thrashing.
Moving a document without losing an edit
A shard move is a controlled ownership transfer:
- The controller chooses a new owner S2 for shard 812 and tells the old owner S1 to hand it over.
- S1 stops accepting new ops for documents in the shard (clients' ops wait in their pending queues; to them it looks like a brief latency spike), finishes appending in-flight ops to the log, and writes a snapshot of each active document.
- The routing record for shard 812 is updated to S2 with epoch + 1.
- S2 acquires the lease, loads each active document from the fresh snapshot (no tail to replay) and starts accepting ops.
- Connection servers get "moved" responses from S1 (or a push from the routing service), reroute, and resubmit pending ops to S2. Duplicates are filtered by
(clientId, seq).
The pause is typically a few hundred milliseconds. Because ownership is fenced by epoch, even a buggy handover cannot produce two owners appending to the same log.
Hot documents
A single document is bounded by one owner, so what if one gets very hot?
- Many viewers, few editors (a status page, a launch document viewed by 50,000 people): the editing path is light; the problem is fan-out. Serve viewers from a read-only broadcast tier: the owner publishes ops once per region to relay servers, which fan them out to viewers' connection servers. Viewers who join get a recent snapshot from a cache plus a short catch-up. Edits are still ordered by one owner.
- Many editors: hundreds of people typing at once (a live workshop) is a few thousand ops per second, still within one core if the transform path is efficient, but presence becomes the problem (deep dive 7). Cap interactive participants, degrade cursors, and isolate the document on a dedicated server so it cannot slow neighbours.
- Huge documents: a 1-million-character document with 200 pages costs more memory and longer snapshots. Split large documents into sections (chapters, tabs, or blocks) internally, each with its own op stream and snapshot, while presenting one document; ops that cross sections are rare. Google documents its own size limit for Docs as about 1.02 million characters, a sign that bounding document size is a legitimate design tool.
Capacity headroom
Plan for losing a zone: if session servers are spread over three zones, each zone's servers must be able to absorb a third more load during failover. A failed zone's shards are reassigned (leases expire after about 10 seconds), and their documents reactivate from snapshots and logs across the remaining servers. Activation rate during such an event is the number to test: a third of 5 million active documents reactivating within a minute is about 28,000 activations per second, each reading a snapshot and a log tail. The snapshot store and log must be provisioned for that burst, not just for steady state. See Capacity Planning and Load Testing.
10. Multi-region collaboration#
Users in Tokyo, London and San Francisco edit the same document. Where does it live?
Bad: one global region
All documents live in one region. Users far from it see 150 to 250 ms of round-trip latency on every ack and every remote edit. Thanks to local-first editing, their own typing still feels instant, but collaboration feels sluggish and a regional outage takes down everyone.
Good: a home region per document
Each document has a home region, initially the creator's, where its session server and authoritative log live. Users near it get low latency; distant collaborators connect to their nearest connection servers, which forward over the provider's backbone to the home region. Remote latency for distant users is then roughly the inter-region round trip plus local overhead: 100 to 200 ms, acceptable for seeing others' edits because their own edits are applied locally.
Moving the home: if a document's active editors are mostly in another region (a team in London working on a document created in San Francisco), migrate it, the same handover as a shard move, but with log and snapshot copied or replicated first.
Great: home region plus cross-region replication for reads and disaster recovery
- The log and snapshots are replicated asynchronously to one or two other regions, so that if the home region fails, the document can be reactivated elsewhere with at most a few seconds of acknowledged edits at risk, or none if the log is replicated synchronously across regions at the cost of higher ack latency.
- Read-only viewers in other regions are served from the local replica and the broadcast tier.
- For true multi-master editing across regions, a CRDT core makes regions peers: each region's server accepts ops locally and exchanges ops with the others, and convergence is guaranteed. This is one of the strongest arguments for CRDTs in a global product, but it requires per-op permission checks in every region and careful tombstone collection.
The trade-off is the usual one between latency, consistency and simplicity; see Multi-Region and Global Data and Disaster Recovery and Backups.
11. Rich text, comments and suggestions#
The core design treats a document as a string. Real documents have structure, and the hard parts of a real editor are there.
The document model
Common models:
- Annotated sequence: a flat sequence of characters, each with formatting attributes (bold, italic, link), plus special characters for paragraph breaks and embedded objects. Quill's Delta uses this; it keeps OT transforms simple because everything is still a sequence.
- Tree of blocks: a document is a tree (paragraphs, headings, lists, tables, cells), each block containing an inline sequence. ProseMirror and Notion-like block editors work this way. Transforms or CRDTs then operate on trees, which is more expressive but harder (concurrent moves, splits and joins of blocks).
Schema validation matters with structure: two concurrent edits might each be valid but together produce an invalid document (for example a table row with the wrong number of cells). With a server-ordered design, the server can validate each transformed op against the schema and repair or reject it. This is a real advantage of OT with a central server for rich documents.
Formatting ops
Formatting is an op too: "retain 10, retain 5 with bold=true, retain rest". Transforming formatting against inserts raises intent questions: if Alice bolds "quick brown" while Bob inserts "very " between them, Bob's text should almost certainly become bold. If Bob inserts right at the end of the bold range, it depends on the mark type: bold usually extends, a link usually does not. These rules must be explicit and consistent on all replicas.
Comments
A comment is anchored to a range. The anchor must move with the text: stored as a pair of positions transformed with every op (OT), or as a pair of stable character ids (CRDT). Comment bodies and threads live in the metadata store, not the op log, because they have their own lifecycle (replies, resolve, notifications). If the anchored text is deleted entirely, the comment is shown as detached rather than silently lost.
Suggestions (track changes)
A suggestion is an op that is visible but not yet accepted. One implementation: suggested inserts are inserted with a "suggestion by Bob" attribute and shown in colour; suggested deletes mark text with a "deleted by Bob" attribute instead of removing it. Accepting a suggestion is a new op that removes the attribute (insert) or really deletes the text (delete); rejecting is the reverse. Because suggestions are just attributed ranges, all the existing transform and history machinery applies.
12. Permissions, security and the change stream#
Enforcing permissions on every op
Opening a document checks permissions once, but permissions can change while the document is open. The session server holds the current ACL for each active document, and the document service notifies it on every change. On revocation, the server rejects further ops from that user and closes their sessions; on downgrade from editor to commenter, it rejects edit ops but keeps comments. Clients are never trusted to enforce permissions themselves. See Authentication and Authorization.
Validating ops: the server checks that each op is well formed (positions within the document, lengths sane), that its size is bounded (no 50 MB paste in one op; large content goes through a separate upload path), and that the client is not exceeding rate limits (a script hammering 10,000 ops per second is cut off). See Rate Limiting and Throttling.
Link sharing ("anyone with the link can view") uses an unguessable document id or token; viewers through a link get read-only sessions, possibly through the broadcast tier.
Encryption: TLS on every hop; at rest, the log and snapshots are encrypted, typically with per-customer or per-document keys for enterprise customers who manage their own keys. End-to-end encryption, where the server cannot read the document, is possible only if the server does not need to understand ops, which points to a CRDT design with the server relaying ciphertext. See Security Fundamentals for System Design.
The change stream: everything that is not editing
The operation log doubles as a change stream for asynchronous features, all off the editing path:
- Search indexing: an indexer consumes ops (or, more efficiently, periodic snapshots of changed documents) and updates a full-text index, so "search my Drive" finds documents within seconds to minutes of an edit. Indexing per keystroke is wasteful; debounce per document (for example, reindex at most once a minute).
- Notifications: "@Alice" in a comment or a document triggers an email or push notification; an "edited since you last viewed" badge updates.
- Thumbnails and previews: regenerate the first-page preview after editing pauses.
- Analytics and audit: enterprise audit logs record who viewed, edited, shared or downloaded.
Each consumer reads at its own pace and can be rebuilt by replaying the stream, the usual benefit of an event-sourced design.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Session server crash | Documents it owned pause for a few seconds | Lease expiry and reassignment, reactivation from snapshot plus log tail, clients resend unacked ops idempotently |
| Split brain after a network partition | Two owners assign the same revisions, document corrupted | Per-shard leases, fencing epoch on every log append, conditional put on (doc_id, revision) |
| Connection server crash | Tens of thousands of clients disconnect at once | Stateless tier, jittered reconnect backoff, resumable sessions from last revision |
| Reconnect storm after a zone outage | Login and activation spikes overload remaining servers | Backoff with jitter, admission control, activation rate limits, headroom per zone |
| Hot document with many viewers | Fan-out overloads the owner | Regional broadcast relays, cached snapshots for joiners, viewer counts instead of cursors |
| Many simultaneous editors | Cursor traffic grows as n squared | Throttle and coalesce cursors, cap interactive participants, viewport filtering |
| Slow client on a bad network | Send buffers grow, memory pressure | Per-socket caps, coalescing, disconnect and resync from revision |
| Op log write latency spike | Acks slow, pending queues grow, typing still local | Group commit, replicated log with low tail latency, alert on ack latency |
| Huge or ancient document | Slow loads and long replays | Frequent snapshots, section-based internal splitting, document size limits |
| Long offline divergence | Expensive or meaningless automatic merge | Compose then transform, bound divergence, fall back to saving a copy or suggestions |
| Transform or CRDT bug | Replicas silently diverge | Server is authoritative, periodic checksum of document state sent with ops, client reloads on mismatch, fuzz testing |
| Permission revoked mid-session | Unauthorised edits | ACL pushed to session server, per-op checks, sessions closed on revocation |
What Interviewers Expect#
Mid-level#
- Explains why polling is wrong and uses WebSockets for realtime edits.
- Recognises that applying positional ops in arrival order makes replicas diverge, and names OT or CRDTs as the fix.
- Proposes storing documents with a log of changes and periodic snapshots.
- Sketches create and open document APIs and the message types on the socket.
- Handles cursors as separate, non-persistent messages.
Senior#
- Designs server-centric OT: base revision, server transform, revision numbers, client pending queue, acks.
- Routes all edits for a document to a single session server and explains why (total order, in-memory speed), with consistent hashing for assignment.
- Separates a stateless connection tier from stateful session servers.
- Explains durability before ack, snapshots for fast load, and log compaction for bounded storage.
- Handles reconnection, offline queues, and idempotent resubmission with client sequence numbers.
Staff+#
- Compares OT and CRDTs with concrete trade-offs (TP1 vs TP2, metadata overhead, interleaving, server validation, offline and peer-to-peer) and picks one for the stated product.
- Prevents split brain with leases and fencing tokens, and sizes the coordination load (per-shard leases).
- Covers hot documents, document migration without losing edits, zone failover and activation storms with numbers.
- Discusses multi-region placement (home region, migration, CRDT multi-master) and rich-text intent issues (formatting expansion, schema validation, comments as anchors).
- Talks about correctness assurance: fuzzing transforms for convergence, checksums to detect divergence, and staged rollouts of algorithm changes.
Deep Dive: OT transforms in code, and how to prove they convergeShow
A minimal transform for single-character insert and delete ops. Real systems use multi-component ops (retain, insert, delete runs), but the logic is the same.
type Op = { kind: "ins"; pos: number; ch: string; site: number }
| { kind: "del"; pos: number }
| { kind: "noop" };
// Return a version of a that applies after b (both written against the same state).
// aFirst breaks ties between two inserts at the same position, identically everywhere.
function transform(a: Op, b: Op, aFirst: boolean): Op {
if (a.kind === "noop" || b.kind === "noop") return a;
if (a.kind === "ins" && b.kind === "ins") {
if (b.pos < a.pos || (b.pos === a.pos && !aFirst)) return { ...a, pos: a.pos + 1 };
return a;
}
if (a.kind === "ins" && b.kind === "del") {
return b.pos < a.pos ? { ...a, pos: a.pos - 1 } : a;
}
if (a.kind === "del" && b.kind === "ins") {
return b.pos <= a.pos ? { ...a, pos: a.pos + 1 } : a;
}
// both deletes
if (a.kind === "del" && b.kind === "del") {
if (b.pos === a.pos) return { kind: "noop" }; // same character already gone
return b.pos < a.pos ? { ...a, pos: a.pos - 1 } : a;
}
return a;
}
// TP1 check: apply(apply(s, a), transform(b, a, false)) must equal
// apply(apply(s, b), transform(a, b, true))Testing convergence. Because transform bugs cause silent divergence, the transform must be tested far beyond hand-written cases:
- Property-based fuzzing of TP1: generate a random document, two random concurrent ops, and check that both application orders give the same result. Millions of cases run in seconds and find off-by-one errors at document boundaries, empty ranges and equal positions.
- Simulated sessions: run three to ten simulated clients against a simulated server with random delays, disconnects and offline periods, then check that every replica ends identical to the server's state. This tests the whole protocol (state machine, buffering, acks, rebase), not just the transform.
- Production checksums: periodically, the server includes a hash of the document at revision N in a message; clients compare it with their own state at revision N. A mismatch triggers a silent reload from the server and an error report. Rare bugs that escape testing are then detected and self-healed rather than leaving two users looking at different documents.
Composition must be tested too: apply(apply(s, a), b) must equal apply(s, compose(a, b)), and transform must distribute over compose. Bugs in compose show up only when buffering or history compaction kick in, which is exactly when they are hardest to notice.
Deep Dive: numbers worked throughShow
OT versus CRDT memory for one document. A 200-page report has about 500,000 characters.
- OT: the in-memory model is the text plus formatting runs and structure, say 1 to 2 MB in a browser.
- Naive CRDT: 500,000 items, each with a 16-byte id, a 16-byte origin, flags and pointers, perhaps 60 to 100 bytes per character: 30 to 50 MB, plus tombstones for everything ever deleted (often as much again over a document's life).
- Run-length-compressed CRDT: most text is typed in runs of tens of characters by one user, so 500,000 characters might be 20,000 items, perhaps 2 to 4 MB including tombstones. This is why modern CRDT libraries are practical for documents of this size, and why naive implementations were not.
Rebase cost after offline editing. A client has 3,000 pending keystrokes; the server has 30,000 remote ops since its base.
- Without composition: transforming each pending op against each remote op is 90 million transform steps; at 50 ns each that is 4.5 seconds of CPU on a phone, too long for the main thread.
- With composition: the pending ops compose to about 60 multi-component ops; the remote ops compose into one large op of a few thousand components. Transform is now linear in the number of components: tens of thousands of steps, a few milliseconds. Composition is what makes offline OT practical.
Session server sizing. Each server owns 50,000 active documents (5 million across 100 servers), 10 GB of document state at 200 KB each, and handles 40,000 ops per second.
- CPU: 40,000 x 50 microseconds = 2 cores for op processing; fan-out, serialisation and log writes perhaps triple that. A 16-core server runs at about 40 percent, leaving room for a zone failover (each surviving server takes 50 percent more load).
- Log writes: with group commit every 5 ms, 200 writes per second per server, each carrying about 200 ops (20 KB).
- Snapshots: if each active document snapshots every 1,000 ops or on passivation, the server writes roughly 40 snapshots per second plus passivations, a few MB/s to the snapshot store.
Failover time budget. A session server dies.
| Step | Time |
|---|---|
| Lease expires (10 s timeout, renewed every 3 s) | up to 10 s |
| Routing update and connection servers learn the new owner | under 1 s |
| New owner loads snapshot and log tail per document (in parallel) | 20 to 100 ms each |
| Clients resend unacked ops | under 1 s |
| Total for most documents | about 5 to 12 s |
Shorter leases cut the outage but risk false failovers during brief network blips or GC pauses; 5 to 10 seconds is a common compromise. Users keep typing locally throughout, so the visible effect is a delay in seeing others' edits and a "reconnecting" indicator.
Storage after compaction. Raw ops at 8 to 10 TB a day (capacity section) are kept for 30 days: about 300 TB. Older history compacted to one diff per editing session: if an average active document gets 3 sessions a day of 20 KB diffs each, and 100 million documents are edited per day, that is 6 TB a day, or about 2 PB per year. Retention policies and coarser compaction for old years (daily diffs after one year, monthly after five) keep growth sub-linear.
Deep Dive: how real collaborative editors are builtShow
Public descriptions of real systems, with internals that were never published left out.
- Google Docs uses operational transformation with a central server per document. Google described this in 2010 when it launched the rewritten editor, explaining that each change is sent to the server as an operation and transformed against concurrent changes so that all collaborators converge. Its design lineage goes back to Jupiter (Xerox PARC, UIST 1995), whose two-party client-server OT avoided the general multi-party problem, and to Google Wave (2009), which used Jupiter-style OT and whose protocol and code were later open-sourced (Apache Wave).
- Etherpad (created at AppJet in 2008, acquired by Google in 2009 and then open-sourced) uses "Easysync" changesets: each change is a compact description of retains, inserts and deletes over the whole document, transformed and composed on a central server. Etherpad is a good open-source codebase to study the server-centric OT pattern.
- Figma runs one multiplayer process per open document that holds the document in memory and is the authority. Evan Wallace's 2019 article explains that Figma chose not to use OT; instead, document objects are trees of properties, and concurrent changes to the same property are resolved by last-writer-wins at the server, borrowing CRDT ideas without implementing a full text CRDT. Figma has also written about rewriting performance-critical parts of the multiplayer server in Rust.
- Microsoft Fluid Framework (open-sourced in 2020) uses a lightweight central ordering service that assigns a sequence number to every op and broadcasts it, while the merge logic runs in clients as distributed data structures. It is an example of "server orders, clients merge".
- Yjs (Kevin Jahns) implements the YATA CRDT with heavy optimisation and is widely used with editors such as ProseMirror, Quill, CodeMirror and Monaco, typically with a central WebSocket sync server that relays and persists updates.
- Automerge (Martin Kleppmann and colleagues) is a JSON-like CRDT library for local-first apps; version 2 introduced a compact binary format and a Rust core. The underlying model is described in "A Conflict-Free Replicated JSON Datatype" (Kleppmann and Beresford, IEEE TPDS 2017).
- ProseMirror (Marijn Haverbeke) ships a collaboration module using a central authority that accepts steps only against its latest version; clients rebase and retry, which keeps the server trivial.
- Differential synchronization (Neil Fraser, DocEng 2009) is a third approach, described in the next deep dive, used in Fraser's MobWrite project.
Common lessons from these systems: every production editor at scale has some central authority per document (for ordering, durability or validation) even when it uses CRDTs; documents are held in memory by a stateful process; and the hard engineering is in the protocol around the algorithm (reconnection, offline, permissions, rich structure), not in the transform or merge function itself.
Deep Dive: differential synchronization, a third approachShow
Neil Fraser's differential synchronization ("Differential Synchronization", DocEng 2009) avoids transforming operations altogether. Instead of sending ops, each side periodically sends a diff of its text against a shared "shadow" copy.
How it works for one client and one server:
- Both sides hold the document text and a shadow: their last agreed copy of the other side's text.
- Periodically (or after edits), the client diffs its current text against its shadow, sends the diff, and copies its text into the shadow.
- The server applies the diff to its shadow exactly (they were identical) and to its own text with a fuzzy patch, which applies each hunk by matching surrounding context rather than exact positions, so it still lands correctly if the server text has changed nearby.
- The server then does the same in the other direction: diff its text against its shadow, send, update the shadow.
Each cycle converges both sides a little more; when editing stops, a few cycles make them identical.
Strengths: simple to implement for plain text with a good diff and fuzzy-patch library (Fraser's diff-match-patch); tolerant of lost messages and of editors that cannot emit ops (any text box can be diffed); no op history needed. Weaknesses: diffs are computed on whole documents (cost grows with size); fuzzy patching can fail or misplace text when both sides edited the same spot, so intent is preserved only approximately; rich text and structure are awkward; and the server keeps a shadow per client. Versions with backup shadows and version numbers handle lost packets more robustly.
It is a useful idea for an interview answer as "the simple option": for a plain-text notes app with a few collaborators, differential sync is far less work than OT or a CRDT, and its weaknesses only bite under heavy concurrent editing of the same region.
Deep Dive: failure walkthroughsShow
1. A session server freezes for 15 seconds (a long garbage-collection pause or a hung disk).
- Its shard leases expire after 10 seconds; the routing service gives the shards to other servers with new epochs, and they reactivate the documents from snapshots and logs.
- Clients reconnect through their connection servers to the new owners and resend unacked ops.
- At 15 seconds the frozen server wakes up and tries to append a buffered op to the log with its old epoch. The log store rejects it. The server sees its lease is gone, drops its in-memory state for those shards, and answers "moved" to any message it receives.
- The op it failed to append was never acked, so its author still has it pending and has already resent it to the new owner. Nothing is lost or duplicated.
2. The op log store has a latency spike (p99 write latency jumps from 5 ms to 800 ms).
- Acks slow down; clients keep typing locally, with ops buffered and composed in their pending queues. Users notice that others' edits arrive late.
- Session servers keep accepting ops into memory but do not ack or broadcast them until they are durable, preserving the "acked means durable" rule. Memory for unpersisted ops is bounded; past the bound, the server applies backpressure (stops reading from client streams).
- Alerting on ack latency fires; if the spike is localised to some log partitions, the affected shards can be moved to servers in a healthier zone.
3. A transform bug ships. A new release mishandles formatting inserted at the end of a bold range.
- Checksums sent with periodic server messages start mismatching for a small fraction of documents. Affected clients reload silently from the server state, which is authoritative, and report the mismatch.
- The error rate is visible on dashboards within minutes of the staged rollout reaching its first few percent, and the release is rolled back.
- Because the server's own state and log were computed by the server's transform (which may also have the bug), the post-mortem checks whether server-side documents are corrupted. If so, the log allows replay from the last good snapshot with the fixed code. This is a strong reason to keep raw ops for a recent window.
4. A whole zone is lost. A third of session servers and connection servers vanish.
- Three million clients reconnect with jittered backoff over about a minute; connection servers in the surviving zones absorb them (sized for this).
- Shards owned by the lost servers are reassigned after lease expiry; about 1.7 million documents need reactivation, of which most are activated on demand when their clients reconnect. Activation is rate-limited so the snapshot store and log are not overwhelmed; clients that wait longer see a "reconnecting" state while still editing locally.
- No acked op is lost, because the log is replicated across zones.
5. A client's local state is corrupt (a browser extension modified the DOM-backed model, or a storage bug truncated the offline cache).
- The next checksum comparison fails, or the server rejects an op as invalid for the document. The client discards its local model, reloads from the server, and re-applies any pending ops that are still valid against the fresh state; if that fails, it saves them as a recoverable draft rather than discarding them.
Deep Dive: a 45-minute interview plan and common variantsShow
Plan.
- Minutes 0 to 5: requirements. Concurrent editing with convergence, realtime visibility, cursors and presence, offline, history. Clarify text versus rich text and maximum editors per document.
- Minutes 5 to 10: estimates. Concurrent connections, open documents, ops per second, log size per day; conclude that connections and per-document ordering matter more than bandwidth.
- Minutes 10 to 20: high-level design. Document service and metadata DB; connection tier; session server per document; op log plus snapshots. Show the divergence example and how OT fixes it.
- Minutes 20 to 35: deep dives. OT versus CRDT choice; session server ownership with consistent hashing, leases and fencing; scaling WebSockets; snapshots and compaction.
- Minutes 35 to 45: offline, presence, failure handling, hot documents, multi-region; wrap up with trade-offs.
Variants and how the design changes.
- Collaborative whiteboard or design tool (Figma, Miro): objects with properties, not a text sequence; last-writer-wins per property with a server per document is often enough. Rendering performance and large documents (thousands of objects) dominate.
- Collaborative spreadsheet (Google Sheets): cell-level ops are easy to merge, but formulas create dependencies: a change in one cell recomputes others, so the server (or clients) must run a recalculation engine and order its results with the edits. Inserting rows and columns shifts references, which is OT again.
- Collaborative code editor (VS Code Live Share, Zed): plain text with high edit rates, plus language-server features that must see a consistent state. Zed has written about using CRDTs for its buffers.
- Block-based notes (Notion-style): a tree of blocks with per-block text; moves and nesting changes are the hard ops; most concurrent edits touch different blocks, so per-block granularity avoids many conflicts.
- Local-first or end-to-end encrypted notes: CRDT core, server as an encrypted relay and backup, merges in clients.
- Online chess or turn-based games: also realtime and stateful per game, but with strict turn order there is no concurrent edit to merge; a single authoritative game server per match is enough.
Deep Dive: ordering guarantees end to endShow
"How do you keep messages in order across distributed servers?" is the question behind every realtime design. For a collaborative editor the answer is precise.
What order is needed. Ops on one document need a single total order (OT) or at least causal order (CRDT): an op must never be applied before an op it depends on. Ops on different documents need no order relative to each other at all. This is what makes the system scalable: there is no global sequence, only one sequence per document, owned by one server.
Where order is created. The session server assigns revision numbers with a counter. It is the only writer for the document (enforced by leases and fencing), so revisions are dense (no gaps) and unique.
Where order could be lost, and how it is restored.
- Between the session server and connection servers: each is a single ordered stream, but a connection server could reconnect to a new owner mid-stream after a failover. The new owner's first message states its current revision; anything the client is missing is fetched explicitly.
- Through a pub/sub layer: brokers may drop or duplicate messages. Clients detect gaps by revision and fetch missing ones; duplicates (a revision already applied) are ignored.
- Between client and server: the client's own ops are in flight while remote ops arrive. The client state machine (deep dive 2) handles exactly this interleaving by transforming against pending ops.
- After reconnect: the join message carries the client's last revision, and catch-up fills the gap from the log.
Exactly-once effect from at-least-once delivery. Neither direction relies on exactly-once delivery. Upstream, ops may be resent after a reconnect; (clientId, seq) deduplicates them at the server. Downstream, revisions may arrive twice; the revision number deduplicates them at the client. The combination gives each op exactly one effect on every replica. See Idempotency and Safe Retries and Time, Clocks and Ordering.
Causal order for CRDTs. A CRDT does not need a total order, but it does need each op's dependencies to be present (an insert after item X needs X). Clients buffer ops whose dependencies have not arrived. Version vectors (the highest counter seen per replica) summarise what each replica has, so missing ops can be requested precisely.
Order across documents, when it matters. Rarely, a feature crosses documents: moving a section from one document to another. Do not try to order the two documents' streams together. Treat it as two independent edits (delete in one, insert in the other) coordinated by the client, or as a small workflow that tolerates a brief window where the text is in both or neither; see Distributed Transactions: 2PC, Sagas and Outbox for the general pattern.
Deep Dive: the client editor, where most of the complexity livesShow
Users judge the product by what happens under their fingers, and much of the engineering of a real editor is in the client.
- A model separate from the screen. The browser's built-in editable regions (contenteditable) produce inconsistent DOM changes across browsers. Serious editors keep their own document model (a sequence or tree, as in deep dive 11), translate keystrokes and input events into model ops, and render the model to the screen. Google described moving Docs rendering to canvas in 2021 for more consistent layout and performance; other editors such as ProseMirror keep the DOM but strictly control it from the model.
- Input method editors. Typing Chinese, Japanese or Korean uses composition: several keystrokes build one character, with intermediate states visible. The editor must not send or transform half-composed text as if it were final, and remote ops arriving mid-composition must not break the composition. This is a common source of bugs.
- Selection mapping. The user's own cursor and selection must be transformed through incoming remote ops exactly like remote cursors, otherwise the cursor jumps when a colleague types above it.
- Rendering cost. Applying one remote op must update only the affected part of the screen. A 300-page document cannot be re-laid out on every keystroke; editors paginate or virtualise, laying out only what is visible plus a margin.
- Undo stack. Each client keeps its own undo history of its own ops (deep dive 2), transformed through all later ops.
- Local persistence. Writes to IndexedDB are batched (every few hundred milliseconds) to avoid blocking typing, but always before an op is considered "saved".
- Main thread budget. At 60 frames per second, the browser has about 16 ms per frame. Transforms, rendering and network handling must fit within it during typing; heavy work (large catch-ups, offline rebase) goes to a background worker.
Deep Dive: observability for a collaborative editorShow
What to measure and alert on (see Observability: Logs, Metrics and Traces):
- Edit latency: time from a client sending an op to the ack (p50, p99), and time from an op being accepted to its arrival at other clients. These are the user-visible "lag" numbers.
- Convergence health: rate of checksum mismatches and forced reloads per million sessions. This should be near zero; any rise after a release is a stop-the-rollout signal.
- Connection health: concurrent connections per server, connect and reconnect rates, time to reconnect, fallback-to-long-polling rate.
- Ownership health: lease renewals and expirations, shard moves per minute, rejected appends due to stale epochs (each one means fencing just prevented corruption), activation latency and rate.
- Backlog signals: pending-op queue sizes reported by clients, server memory for unpersisted ops, per-socket send buffer sizes.
- Storage: log write latency, snapshot write and read latency, compaction lag, history size per document.
- Offline merges: number and size of offline rebases, failures that fell back to saving a copy.
Client-side telemetry matters as much as server metrics: most of the latency and many of the bugs are only visible from the browser or app.
Key Takeaways#
- Positional edits applied in arrival order diverge. Concurrent editing needs either operational transformation (rewrite ops against concurrent ones) or a CRDT (identity-based ops that commute). See Conflict Resolution, OT and CRDTs.
- Server-centric OT is the pragmatic default for an online editor: one ordering authority per document turns a multi-party problem into a two-party one, needs only TP1, keeps documents compact, and allows per-op validation. Choose a CRDT core when offline-first, peer-to-peer, multi-master regions or end-to-end encryption dominate.
- Give every active document one owner. A session server holds it in memory, orders and fans out ops, and appends to a durable log before acking. Assign ownership by shard with consistent hashing, leases and fencing epochs to rule out split brain. See Consistent Hashing and Leader Election and Coordination Services.
- Split connections from state. A stateless WebSocket tier terminates millions of sockets and routes by document; revision numbers make ordering and gap repair robust across servers. See Pattern: Pushing Realtime Updates.
- The document is an event log plus snapshots. Snapshots bound load and failover time; compaction folds keystrokes into per-session diffs so history stays useful and storage stays bounded.
- Presence is ephemeral. Throttle, coalesce and drop cursor updates; anchor cursors and comments to text through transforms or stable ids; cap the interactive set for large audiences.
- Offline is a protocol and UX problem. Persist pending ops locally, compose before rebasing, resubmit idempotently with client sequence numbers, re-check permissions, and fall back to saving a copy when divergence is too large.
- Assume bugs and failures. Fuzz transforms for convergence, checksum document state in production, stage rollouts, and size for zone failover and activation storms.