System design practice

Collaborative Docs

hard websocket pub-sub presence consistency durability

Google Docs-style editing, one sequencer per document, a log written before the ack, pub/sub fan-out.

Solve it in your browser Read the lesson first

Design the editing service behind a Google Docs-style editor. Several people have the same document open; each keystroke shows up on everyone else's screen within a fraction of a second, concurrent edits never clobber each other, and nothing a user saw as saved is ever lost.

Functional requirements

Use these use case names exactly: the traffic, requirements and tests in problem.proschi refer to them.

Scale

Constraints

What is given

problem.proschi declares the editor (the browser of the person typing) and the collaborators (everyone else with the document open), and holds the traffic, requirements and tests. Add the components, the connections and the four use cases.

The simulation does not run operational transformation: model the service that orders and transforms operations as a component that is called, and explain your choice in a decision. Write a delivery to the collaborators with the fan-out prefix, x2, so the simulation counts every message.

How your design is checked

You write the design as text in Proschi. Tests run in your browser: a simulation of the traffic above checks latency, availability, cost and what happens when a machine fails. How the simulation works.

Start designing

Lesson · 11 min read

Learn it: Collaborative Docs #

Collaborative Docs: one order, one log, many screens #

Two people type into the same paragraph at once. Each sees their own letter immediately, moments later both see both letters in the same order, and a server crash a second after loses neither. Google Docs, Notion and Figma all do this with the same few rules.

What you'll learn #

The problem, explained #

Who uses it. People writing together: a few collaborators per document, about a million documents open at peak.

Functional requirements.

Non-functional requirements.

RequirementTarget
DurabilityAn operation is durable before its ack
OrderingCollaborators get it only after it is stored; the editor never waits for them
PresenceCursors are never stored
OpeningNever replays the whole history
p99 (the latency 99% of requests beat)Edits under 100 ms, cursors 60 ms, opening 400 ms
AvailabilityEditing 99.95%; any machine can fail
BudgetAt most $6,500 a month

What is given, and why. The two kinds of browsers, the editor and the collaborators, and a SessionServer type for the servers that hold their WebSockets. Everything between is yours; the tests describe guarantees, not boxes.

What the tests check.

Back-of-the-envelope #

messages in (4k edits + 8k cursors)
12k/s
through the session servers
36k/s
session servers under 70%
≈ 26
log appends
4k/s
opening from snapshots (vs 1 GB/s replaying)
25 MB/s
QuantityArithmeticResult
Messages in from editors4k edits + 8k cursors12k/s
Messages out to collaborators12k × 224k/s
Session server messages12k in + 24k delivered36k/s
Session servers at 2k/s each (the model's figure), under 70%36k ÷ (2k × 0.7)about 26
Log appendsone per edit4k/s
Operations a day4k × 86,400about 350 million
Log size a day350M × ~200 bytesabout 70 GB
Snapshot reads500 opens × 50 KB25 MB/s
Replaying a history of 10k operations instead500 × (10k × ~200 bytes = 2 MB)1 GB/s

The session servers carry the fan-out. Every message arrives at one session server and leaves through others: 36k a second, three times the incoming rate.

The log is not the bottleneck. 4k appends a second is modest for a partitioned store. What matters is appending before the ack and never reading the log whole.

Latency. An edit is load balancer → session server → collab service → log append, then the ack: three short hops and a write, about 25 ms on average, with room to the 100 ms p99. The deliveries come after the ack and do not count.

Concepts #

Operations, not documents #

Sending the whole document per keystroke is heavy, and two people saving at once overwrite each other. So the browser sends operations (insert "a" at position 120, delete 3 characters at 87), each tagged with the revision it was made against. The server keeps an ordered list of accepted operations; revision n is the first n applied. That list, the operation log, is the document's source of truth.

The browser applies its own operations immediately and keeps unacknowledged ones in a pending buffer.

Operational transformation and CRDTs #

Alice inserts "x" at position 5 while Bob deletes the character at position 2, both against revision 41. Applied naively in different orders, their documents diverge. Two families of algorithms fix this.

Operational transformation (OT). The server picks an order. When Bob's delete arrives after Alice's insert was accepted as revision 42, the server transforms Bob's operation against Alice's and accepts the result as revision 43. Here nothing shifts, since the delete is before the insert; had Bob deleted at 7, his position would become 8. Each client transforms incoming operations against its pending ones the same way.

CRDTs (conflict-free replicated data types). Every character gets a unique, ordered id, so operations commute: any replica that has seen the same set of operations has the same text, whatever the arrival order, with no central order.

OTCRDTs
OrderingA single authority per document chooses itNone needed
CostNeeds that authorityMetadata per character, tombstones for deletions
GainSimple and light with a server in the middleOffline editing, peer-to-peer sync
Used byGoogle Docs, EtherpadYjs, Automerge (libraries)

With a server in the middle anyway, OT with one sequencer per document is the simpler fit, and this design uses it. A CRDT would still need the log, snapshots and fan-out.

One owner per document #

Ordering needs one place that decides. Route a document's operations to one collab service instance, by consistent hashing of the document id or a lease in a coordination service. It keeps recent operations in memory, transforms each new one, assigns the next revision and appends it to the log: no locks, no consensus round per keystroke.

Deep dive When the owner fails

Another instance takes the lease, reads the document's latest revision from the log and continues. Clients resend their unacknowledged operations, which the new owner transforms against whatever was committed. Since the log already holds every acknowledged operation, nothing acknowledged is lost.

Durable before acknowledged #

The ack turns "saving…" into "saved", so the collab service appends to the log, waits for confirmation, then acknowledges. Crash after the ack but before the write, and the user loses text they saw as saved, while collaborators who applied it disagree with the log forever.

Deep dive The same order in Proschi

A comment service stores first, answers, then publishes asynchronously:

title "Comment service"

reader  "Reader"   [Actor]
api     "Comments" [REST API]  x2
store   "Comments" [Cassandra] x3
notices "Notices"  [Kafka]     x2

reader -> api     : HTTPS
api    -> store   : CQL
api    -> notices : produce

usecase "Post comment" {
  reader  -> api     : POST /threads/7/comments
  api     -> store   : INSERT comment c_9
  store  --> api     : ok
  api    --> reader  : 201
  api    ->> notices : CommentPosted c_9
}

Fan-out through pub/sub #

The load balancer spreads WebSocket connections over many session servers, so collaborators are almost never on one. After the ack, the collab service publishes the operation on the document's subject of a pub/sub bus (NATS or Redis pub/sub; a million short-lived subjects is a poor fit for Kafka topics). Each session server with a connection to the document subscribes while it is open and pushes operations to its connections.

The editor waits for none of this, or a slow browser would slow everyone's typing. A collaborator that misses a message (a brief disconnect) sees a gap in revision numbers and fetches the missing operations from the log.

Presence is ephemeral #

Cursors, selections and "who is here" are presence: they change constantly (twice as often as the text here) and are worthless a second later. Send them over the same bus, never through the log: they would triple its writes (12k a second instead of 4k) and bury the edits in noise.

Clients throttle cursor updates to a few a second, and a reconnecting client just waits for the next update. Who is in the document is often kept with a heartbeat and a short expiry, so a closed laptop disappears on its own.

Snapshots and compaction #

A snapshot is the full text of a document at one revision. Without one, opening a document means reading and replaying its log from the start. Just 10,000 operations at about 200 bytes each is 2 MB per open, and a document edited for a year has far more. At 500 opens a second that is a gigabyte a second from the log. So every hundred or so operations, a snapshotter folds them into a new snapshot in object storage.

Opening reads the latest snapshot and the short tail after it: about 50 KB and a few dozen rows. The log can then be trimmed or archived behind the snapshot, keeping only what version history needs.

Designing it step by step #

1. Clarify. Open documents and collaborators each (about two others), how fast others see edits (well under a second), what "saved" means (durable), and whether offline editing is in scope (no: that pushes towards CRDTs).

2. Connections. Browsers hold a WebSocket to a session server, through a load balancer. Session servers are stateless apart from their connections.

3. Edit path. Session server → the document's collab instance (routed by document id) → transform, assign revision → append to the operation log → ack back to the editor. Then publish on the document's subject; subscribed session servers deliver to collaborators.

4. Cursors. Session server → bus → subscribed session servers → collaborators. No collab service, no log.

5. Open and snapshot. Docs API reads the latest snapshot from object storage, then the operations after it from the log. A snapshotter reads operations and writes new snapshots.

6. Size it. Session servers for 36k messages a second with one lost, a few collab instances for 4k operations, a replicated log, a bus, two of everything else; add up the bill.

7. Wrap up. Owner failover with leases, reconnect and resend of pending operations, version history, comments and suggestions as their own operations, and access control on every subscription.

Common mistakes #

Acknowledging before the log (wrong/ack-before-log). The ack comes a few milliseconds sooner, and a crash in that window loses text users saw as saved. It fails An edit is in the operation log before it is acknowledged and Edit is durable.

Waiting for the broadcast (wrong/broadcast-before-ack). The ack waits until every collaborator has the operation, so everyone types at the speed of the slowest browser. It fails Collaborators get an edit after it is stored, through pub/sub, and in the model Edit's p99 rises past 100 ms as well.

Delivering only from the editor's session server (wrong/same-server-delivery). It works in a demo with one server. With 26 servers, almost every collaborator is connected elsewhere and never sees the edit. It fails the pub/sub test.

Storing cursors (wrong/cursors-in-the-log). Every cursor move becomes a sequenced, stored operation: three times the writes (12k a second instead of 4k), a collab tier that saturates, and a log full of noise. It fails Cursor moves are broadcast, never stored, both p99 limits and survive any node failure.

Replaying the whole log (wrong/replay-whole-log). Without snapshots, every open reads megabytes of operations, saturating the log's and the API's bandwidth. It fails the snapshot test and the p99 of Open document, and drags Edit down with it.

Others. Sending whole documents, which makes the last save win; letting any server apply any operation, which needs a distributed lock per keystroke; and forgetting that a reconnecting client must resend its unacknowledged operations.

In the interview #

Likely follow-ups:

Further reading #

Now design it

Review cards for this problem

Short questions on the ideas it needs, from the review cards. Review them daily so they stick.

More system design problems