SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design Ride Sharing (Uber/Lyft)
  • Design a Payment System
  • Design Ticket / Hotel Booking
  • Design a Search Engine
  • Design Google Maps
  • Design a Collaborative Editor (Google Docs)
  • Design a Metrics and Monitoring System
  • Design a Distributed Message Queue (Kafka-like)
  • Design an E-commerce System (Amazon)
  • Design a Content Recommendation System (YouTube/Netflix)
System Design/Case Studies/Hard
Interview case study

Design a Collaborative Editor (Google Docs)

Let many people edit one document at the same time and always end up with the same text.

⏱ 38 min readHard case studyAdvanced24 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a collaborative document editor like Google Docs.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Seeing the real problemSending edits is easy. Making every copy end up the same, while keeping what each person meant, is the whole question. A strong candidate says this in the first two minutes.
Convergence and intentThe interviewer wants a concrete example of two edits crossing, and a mechanism (OT or CRDT) that fixes it. “Last write wins” fails this test.
A single order per documentA central server that numbers every edit makes OT simple. Knowing why, and what it costs, shows depth.
Real-time delivery at scaleMillions of open sockets, one serialised writer per document, hot documents with thousands of viewers, and reconnects after a crash.
Durability and recoveryAn edit that was acknowledged must never be lost. Log first, then acknowledge, then broadcast. Snapshots keep recovery short.

TL;DRThe whole design in 60 seconds

Every document is owned by one session server at a time. Clients connect with WebSockets, apply their own edits at once (optimistic), and send each edit with the revision it was based on. The session server puts all edits into one order, rewrites a late edit against the edits it missed (operational transformation), writes it to an append-only log, then sends it to everyone.

  • The invariant: every replica applies the same edits in the same order, after the same rewriting, so every copy ends with the same text. Nobody's intent is lost.
  • Scale: 5M open documents and 10M connections is about 100 gateways, and 100 session servers each owning 50,000 documents. A document is routed to its session server by consistent hashing.
  • Why one owner: a single writer per document means ordering is a local counter, not a distributed transaction. The cost is a short pause when that server fails.
  • Storage: the operation log is the source of truth. A snapshot every 1,000 edits keeps replay under 100 KB, and old logs are compacted into version history.
  • CRDT alternative: give every letter an id so edits commute with no rewriting and no central order. The price is per-letter metadata and tombstones.
  • Hot documents: editors stay in the session. Thousands of read-only viewers are served by a fan-out tier, so one document cannot melt one server.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
4
5
7
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Plain or rich text, how many editors, offline, how fast remote edits must appear, what history means.
2. Estimate4Connections, edits per second, gateways, session servers, log growth and snapshots.
3. API and data5The WebSocket messages (join, op, ack), the revision rule, and the log and snapshot tables.
4. High-level design7Gateway, session server per document, log, snapshots, presence. Follow one edit.
5. Deep dives15Convergence (OT), OT versus CRDT, delivery at scale, storage and recovery, offline and permissions.
6. Scale and failures7Session server dies, gateway dies, hot document, a very long offline merge.
7. Wrap up3Recap, the cost of one owner per document, and what you would build next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change the design. Hint: think about what a character is (plain or rich text), how many people type at once, what happens offline, and how soon a remote edit must show up.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
Plain text, or rich text with formatting, tables and images?Rich text needs more kinds of edits (format, split, merge) and more transform rules. Plain text keeps the core idea clear.Start with plain text. Say that formatting is the same idea with more operation types.We design the engine for insert and delete, and name formatting as an extension.
How many people edit one document at once, and how many just view?Typical is 2 to 10. A few documents have thousands of viewers. The two cases need different tiers.Up to 100 editors, usually 2 to 10. A few documents have 10,000 read-only viewers.Editors share one session. Viewers are served through a separate fan-out tier.
How fast must a remote edit appear, and how fast must my own typing feel?Your own typing must be instant, so it cannot wait for the server. That forces optimistic local apply.Local edits instant. Remote edits visible within 200 to 500 ms.Clients apply edits locally first, and the server must reconcile them afterwards.
Must it work offline, and merge when I come back?Offline means long runs of edits that conflict with others. It strongly favours one design over another.Yes, for a few hours or days, and merge on reconnect.Edits queue on the client with ids, and rebase on reconnect. We compare OT and CRDT here.
Do we need version history and undo?History decides whether we keep the full log. Undo in a shared document is its own problem.Named versions and a restore, plus per-user undo.An append-only log with snapshots. Undo is a new edit, not a rewind.
Who may do what: view, comment, edit? Can access be removed while the document is open?Permissions must be checked on every edit, not only when the document opens.Three roles. Removing access must stop a live session within seconds.The session server checks the role on every edit and can close a socket.
How big can one document get?Size sets snapshot size, load time and how much metadata per letter we can afford.Up to about 1 MB of text, around a million characters.A snapshot loads in one read. A CRDT with 20 bytes per letter would be 20 MB, which hurts.
Are comments, suggestions and cursors in scope?Comments and cursors must move with the text, which makes them transform targets too.Live cursors and presence yes. Comments as an extension.Presence is ephemeral and transformed with edits. Comment anchors are left for later.
How many documents and users, and how many are open at the same moment?Concurrently open documents and connections size the gateways and session servers.1B documents, 50M daily users, about 5M documents open at once.About 10M connections, so 100 to 200 gateway servers.
One region or several? What happens if a region fails?Cross-region editing of one document means either one owner region or a CRDT.One region per document at a time, with failover to another.No cross-region writes to the same document. Multi-region is an extension.

Write the scope on the board

Functional (must do)
  • •Create, open, edit and share documents, with view, comment and edit roles
  • •Several people edit the same document at once and all see the same final text
  • •Your own typing appears instantly. Remote edits appear within about half a second
  • •Live cursors and who is here (presence)
  • •Version history, restore, and edit while offline with a merge on reconnect
Non-functional (how well)
  • •Convergence: every copy of a document ends with identical content
  • •Intent: no one's edit is silently lost or placed in the wrong spot
  • •Latency: local edits instant, remote edits under 500 ms at p99
  • •Durable: an acknowledged edit survives a server crash
  • •Available: 99.95%, and a session server failure heals within seconds
Out of scope (say it)
  • •Rich text layout, tables, images and fonts (same engine, more edit types)
  • •Comments, suggestions and spell check (extensions)
  • •Cross-region editing of one document (one owner region at a time)
  • •End-to-end encryption (it conflicts with a server that must transform edits)
🎤
Say it out loud
“Let me confirm the scope. We build plain-text collaborative editing: up to 100 people per document, usually 2 to 10, plus up to 10,000 read-only viewers on a few documents. Your own typing must be instant and remote edits must show within about 500 milliseconds. All copies must end identical and no edit may be lost. We need offline editing with a merge, version history, per-user undo and three roles. I will size for 5 million documents open at once. Rich text, comments and cross-region editing are extensions. Does that sound right?”

Step 2Estimate the scaleabout 4 min

🤔
Pause. Try it yourself first
On paper: open connections, edits per second, gateways, session servers, and how much log and snapshot data a day produces. Which number forces a design choice?

Assumptions (say them first)

AssumptionValue
Documents stored1 billion
Daily users50 million
Documents open at the same moment5 million
Connections (editors and viewers)10 million, about 2 per open document
Share of connections actually typing10%
Edits per typing user, after batching1 a second at the busiest moments
Average over a day (versus the busiest moment)25% of the busiest rate
Edit message sizeabout 100 bytes
Average document50 KB of text (a snapshot)
One gateway100,000 connections
Session servers100, each owning many documents

The arithmetic, line by line

WhatMathsResult
Busy-moment edits per second10,000,000 × 10% × 1 per second1,000,000 edits per second
Edit traffic into the system1,000,000 × 100 bytes100 MB per second
Messages out (each edit goes to about 2 other people)1,000,000 × 22,000,000 messages per second (200 MB per second)
Gateway servers10,000,000 ÷ 100,000, then × 2 for headroom100 minimum, so about 200
Documents and edits per session server5,000,000 ÷ 100, and 1,000,000 ÷ 10050,000 documents and 10,000 edits per second each
Memory per session server50,000 documents × (50 KB text + 10 KB recent edits)about 3 GB (small)
Average edits per day1,000,000 × 25% × 86,400about 21.6 billion edits a day
Raw log per day21.6 billion × 100 bytesabout 2.2 TB a day (6.5 TB with 3 copies)
Log after merging bursts of typing (about 5 keystrokes into one edit)2.2 TB ÷ 5about 0.43 TB a day
Hot log for 30 days0.43 TB × 30, then × 3 copiesabout 13 TB, 39 TB with copies
Snapshots of every document1,000,000,000 × 50 KB50 TB (75 TB with erasure coding, 150 TB with 3 copies)
Replay after a crash with a snapshot every 1,000 edits1,000 × 100 bytesat most 100 KB per document
A session server dies: documents to reload50,000 documents ÷ 5,000 per secondabout 10 seconds, and about 100,000 clients reconnecting
One hot document with 10,000 viewers and 10 edits a second10 × 10,000100,000 messages per second from one server (the problem)
The same document with a fan-out tier (5 edge nodes of 2,000 viewers)10 × 550 messages per second from the session server
What the numbers tell us about the design
  • •Edits are small (100 MB a second in), but the number of connections is large: 10 million sockets means 100 to 200 gateways. Sockets, not CPU, size the front tier.
  • •One document's edits are tiny: 10 a second even for a busy one. So a single server can own the whole document and number its edits locally. We do not need a distributed transaction.
  • •The load is spread over 100 session servers, 10,000 edits a second each, and 3 GB of memory. That is easy. The hard part is correctness, not capacity.
  • •A 30-day hot log is 13 TB (39 TB with copies), but snapshots are 50 TB. History is the larger cost, so we compact old logs and tier cold documents.
  • •A crash costs about 10 seconds of reloading and 100,000 reconnecting clients. We need fast recovery and a reconnect that asks for edits since revision N, not the whole document.
  • •A hot document with viewers breaks the single-server model (100,000 messages a second). Viewers must go through a fan-out tier, so the session only serves editors.
🎤
Say it out loud
“Let me do the maths. About 5 million documents are open at once, which is about 10 million connections, so 100 to 200 gateway servers at 100,000 sockets each. If 10% are typing at one edit a second, that is 1 million edits a second, or 100 megabytes a second, which is spread over 100 session servers at 10,000 edits a second each. That is easy. A single busy document is only about 10 edits a second, so one server can number its edits. The log is about 2 terabytes a day raw, a fifth of that after merging keystrokes, and snapshots are 50 terabytes. The one thing that breaks is a hot document with 10,000 viewers: 100,000 messages a second from one machine, so viewers go through a fan-out tier.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the messages a client sends when it opens a document and when it types. What number does each edit carry so the server can tell what it was based on? What does the server send back?

Endpoints

MethodPathRequestResponseNotes
GET/v1/docs/{id}/connectupgrade to WebSocket101 Switching ProtocolsThe gateway checks the user's role and routes to the session server for this document (consistent hashing). Sticky: all editors of one document reach the same server.
WSjoin{ docId, lastKnownRevision, clientId }{ revision, snapshot or edits since lastKnownRevision, collaborators }A reconnect sends the last revision it saw and gets only the missing edits. A new client gets the latest snapshot plus the log tail.
WSop{ opId, baseRevision, ops: [insert(pos, text) or delete(pos, len)] }{ ack: revision } to the sender, { op, revision } to everyone elsebaseRevision is the revision the client had when it typed. opId makes a resend harmless (dedup). One edit in flight per client.
WSpresence{ cursor, selection }broadcast to collaboratorsEphemeral and throttled (for example 5 a second). Never written to the log. Transformed with edits so a cursor stays on its letter.
GET/v1/docs/{id}/history?from=&to=none200 { versions, nextCursor }Named versions and revision ranges. Reads the history store. Restore creates a new edit, it does not rewrite the log.
PUT/v1/docs/{id}/permissions{ user, role }204Takes effect immediately: the session server drops the socket if the role is removed. Needs the owner role.

Data model

Table or storeKeyHolds
doc_meta (sharded SQL or KV)doc_idTitle, owner, created time, current head revision, snapshot pointer, owner session server hint.
acldoc_id, user_idThe role (view, comment, edit) and link-sharing settings. Cached at the gateway with a short TTL, checked again by the session server.
op_log (append-only, wide-column or log store)doc_id, revisionOne edit per row: opId, author, baseRevision, the transformed op, time. Never updated.
snapshots (object storage)doc_id, revisionFull text at a revision. Written every 1,000 edits and at close. Used to load fast.
versionsdoc_id, version_idA name, a revision number and an author. A version is a pointer into the log, not a copy.
The rule every edit follows (server side)
on op(client, opId, baseRevision, ops):
  if seen(opId): return ack(existing revision)          # resend is harmless
  for e in log[baseRevision+1 .. head]:                 # edits the client had not seen
      ops = transform(ops, e.ops)                       # rewrite against each one, in order
  head += 1
  append(log, head, opId, ops)                          # durable BEFORE we answer
  ack(client, head)
  broadcast(everyone except client, ops, head)
📝Which store, and why
The edit log is an append-only sequence keyed by (document, revision): it only ever adds rows, reads are by range, and a wide-column or log-structured store fits. Snapshots are whole blobs, so object storage. Metadata and permissions are small and relational, so a sharded SQL or key-value store. The live state of a document (text, head revision, the last few edits) lives in the memory of one session server and can be rebuilt from the snapshot and log tail at any time, so losing a server loses nothing.
🎤
Say it out loud
“A client connects over a WebSocket and the gateway routes it to the session server that owns this document. It sends join with the last revision it saw, and gets the missing edits. Every edit carries an id and the revision it was based on. The server numbers it, rewrites it against any edits it missed, appends it to the log, acknowledges the sender and broadcasts it. The log is append-only and keyed by document and revision, snapshots go to object storage every 1,000 edits, and cursors are never stored.”

Step 4Draw the high-level designabout 7 min

🤔
Pause. Try it yourself first
Draw the path of one keystroke from a laptop to another laptop. Where is the edit given its number? Where is it saved? What happens to the text on the sender's own screen while it waits?
Collaborative editor: high-level design
💻Clientslocal copy + pending edit
→↓WebSocket
🚪Gatewaysauth, role, 100k sockets each
→↓by doc id (hash)
Session tier (one owner per document)
🧠Session serverorder, transform, broadcast
📍Presencecursors, ephemeral
Storage
📜Op logappend-only, replicated
📸Snapshotsobject storage
Control
🗳️Owner mapdoc to server, with epoch
🔐Permissionsroles, links, revoke
Read side
📡Fan-out tierviewers of hot documents
🕘History serviceversions, restore, export
One session server owns each document and numbers its edits. The log is saved before anyone is told. Viewers of a hot document are served by a fan-out tier.
ComponentWhat it does
Client (editor engine)Keeps the local text, one edit in flight and a buffer of the rest. Applies its own edit at once, then rewrites incoming edits against what it has pending.
GatewayTerminates WebSockets, authenticates, checks the role, and forwards each connection to the session server that owns the document.
Session serverThe single writer for a document. Numbers edits, rewrites late edits, appends to the log, acknowledges, and broadcasts. Holds the live text in memory.
Owner map (with epoch)Says which session server owns a document, using consistent hashing and a lease. The epoch grows with each new owner, so an old owner can be fenced.
Operation logAppend-only record of every accepted edit. The source of truth. Replicated, and written before any acknowledgement.
Snapshot storeFull text at a revision, every 1,000 edits. Bounds recovery time and makes opening a document fast.
Presence serviceCursors and who is online. In memory only, throttled, and transformed with edits. Losing it loses nothing important.
Fan-out tierDelivers each edit to thousands of read-only viewers of a hot document, so the session server sends a handful of messages, not thousands.
Write path (follow one request)
  1. The user types a letter. The client applies it to its own text at once, adds it to its pending edit, and (if none is in flight) sends { opId, baseRevision, op }.
  2. The gateway has already routed the socket to the session server that owns this document (consistent hashing on doc id, checked against the owner map and epoch).
  3. The session server checks the role, then drops a resend by opId. It rewrites the edit against every logged edit after baseRevision, so it fits the current text.
  4. It increments the head revision, and appends the rewritten edit to the log with the new revision. The append is replicated and durable before the next step.
  5. It acknowledges the sender with the new revision, and broadcasts the edit and revision to every other editor (and to the fan-out tier).
  6. Each receiving client rewrites the incoming edit against its own pending edit, applies it, and moves its revision forward. Every 1,000 edits the session server writes a snapshot.
Read path (follow one request)
  1. A user opens the document. The gateway checks the role and picks the session server for the doc id.
  2. The server loads the latest snapshot and the log tail after it into memory (if it is not already open), at most about 100 KB of replay.
  3. It sends the client the text and the head revision, and adds the client to the document's collaborator list.
  4. From now on the client receives edits with revision numbers, in order. A gap in revisions makes it ask for the missing range.
  5. On a reconnect the client sends its last revision. The server replies with only the edits since then, or a fresh snapshot if too much time has passed.
  6. A read-only viewer of a hot document connects to the fan-out tier, which holds a copy of the text and subscribes to the document's edits.
🎤
Say it out loud
“Here is the picture. Clients connect over WebSockets to gateways, which route each document to one session server using consistent hashing. That server is the only writer for that document. When an edit arrives, it rewrites it against the edits the client missed, appends it to a replicated log, acknowledges the sender, and broadcasts it. Snapshots go to object storage every 1,000 edits, so opening a document replays at most about 100 kilobytes. Cursors live in memory only. Viewers of a hot document are served by a separate fan-out tier so one server never sends 100,000 messages a second.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Convergence: two edits at the same moment

The problem: Two people edit the same text at once. Each applies their own edit at once, then receives the other's. An edit is “insert at index 0” or “delete index 2”, but by the time it arrives, the text has already changed and the index now points at something else. Invariant: every copy ends with the same text, and each person's edit still means what they meant.

OptionHow it worksGoodBad
Lock the document or a paragraphOnly one person may edit a region at a time. Others wait or are blocked.No conflicts at all. Simple to build.Typing is not instant. People cannot work together, which defeats the product.
Last write wins (send the whole text)Each save replaces the document with the sender's copy. The newest one wins.Trivial. Always converges.Destroys the other person's work. Fails the intent test completely.
Send raw edits by indexSend “insert X at 0” and apply it at that index on every copy.Small messages, instant local apply.Copies diverge or delete the wrong letter, because an index means different things on different copies. This is the bug that OT exists to fix.
Operational transformation with one server orderThe server numbers edits. A later edit is rewritten against the edits it had not seen, so its index fits the current text. Clients do the same for incoming edits against their one pending edit.Instant local typing, small messages, convergence, intent kept. Proven in large products.Needs a central order. The transform rules are subtle and must be tested for every pair of edit types.
Pick
Operational transformation with a single order per document

The invariant is every replica applies the same edits in the same order after the same rewriting. The session server enforces the order with one revision counter. The rewriting follows a rule: for two concurrent edits A and B, applying A then B' gives the same text as applying B then A'. Because the server keeps one history, a late edit only needs rewriting against the edits after its base revision, not against everyone's.

The cost is a central writer per document and a transform function you must get right. We accept both: one writer per document is cheap (a document is only about 10 edits a second), and we test the transform with every pair of operations and random sequences.

🍵Walk through it: the text is “ABC”
Alice inserts “X” at index 0. Bob, at the same moment, deletes index 2 (the letter “C”). With raw edits Alice applies Bob's “delete index 2” to “XABC”, which removes the “B”. Bob applies “insert at 0” to “AB” and gets “XAB”. Alice has “XAC”, Bob has “XAB”: diverged, and Alice lost the wrong letter. With OT, Bob's edit is rewritten against Alice's insert: the insert moved everything right by one, so “delete index 2” becomes “delete index 3”, and both end with “XAB”.
Pair of concurrent editsHow the later one is rewritten
insert vs insertIf the other insert is before mine, or at the same index and from a lower site id, my index goes up by 1. The tie-break must be the same everywhere.
insert vs deleteIf the other delete is before my index, my index goes down by 1.
delete vs insertIf the other insert is at or before my index, my index goes up by 1.
delete vs deleteIf it is the same letter, my edit becomes nothing (it is already gone). If before, my index goes down by 1.
🎤
Say it out loud
“Locking kills real-time work and last-write-wins destroys edits, and sending raw indexes diverges, because an index means something different once the text has moved. So I would use operational transformation with one order per document. The server numbers every edit and rewrites a late edit against the edits after its base revision: an insert before my position moves my index up by one, a delete before it moves it down. Clients do the same against their one pending edit. The invariant is that every copy applies the same edits in the same order after the same rewriting.”
5.2

OT or CRDT: where does the order come from?

The problem: OT needs a central order and careful transform rules. A CRDT avoids both by making edits commute. Which do we choose, and what does each cost? This decides offline support, memory use and whether a central server is required at all.

OptionHow it worksGoodBad
OT with a central serverOne server per document orders edits and rewrites them. Clients keep one edit in flight.Small metadata: the text is just text. Mature for rich text. Easy to enforce permissions on one server.Needs the server to be reachable. Transform functions grow with each edit type. Long offline sessions mean a big rebase.
Sequence CRDT (RGA, Logoot, Yjs, Automerge style)Every letter has a unique id, and an insert says “after letter with id N”. Deleted letters stay as tombstones. Edits commute, so any order gives the same text.No transformation and no central order. Works peer to peer and offline. Merges are easy to reason about.Metadata per letter (often 10 to 30 bytes), tombstones that need cleanup, and history that grows. A 1M-character document can use 20 MB or more.
Hybrid: CRDT for the data, server for everything elseUse a CRDT for the text, but still route through a server for permissions, ordering of snapshots and persistence.Offline and merge strength of a CRDT, with a server for access control and storage.Two sets of ideas to run and debug. The server cannot easily inspect or limit an edit.
Operation log with last-write-wins per fieldTreat the document as a map of paragraphs and keep the newest write of each paragraph.Simple and fits form-like data.Two people typing in one paragraph overwrite each other. Not collaborative text editing.
Pick
OT with a single order per document, and name CRDT as the answer when offline-first or peer-to-peer matters

For a hosted editor with a server and permission checks, OT is a good fit: the document is plain text with no per-letter metadata, the server is already the one place that owns order, and large products such as Google Docs are known to use OT. A CRDT is the better answer when offline-first, peer-to-peer or no central server matters, and many newer editors use CRDTs for that reason.

The deciding trade-off is metadata against coordination. OT pays with a central writer and subtle transform code. A CRDT pays with memory and tombstones on every letter. Say both, pick one for this product, and say what would flip the choice.

OT (server order)Sequence CRDT
Needs a central orderYes, per documentNo
Extra data per letterNoneAn id, and a tombstone after deletion
1M-character documentAbout 1 MB of textOften 10 to 30 MB with ids and tombstones (illustrative)
Long offline editsA large rebase against many editsA merge of two sets of edits, usually easier
Hardest partGetting every transform pair rightCleaning up tombstones and long history

Try the visualizer below: it runs the same two edits through raw sending, OT and CRDT-style ids, and shows which copies agree.

🎤
Say it out loud
“Both fix the same problem. OT keeps the text clean and uses one server to order edits, but the transform rules are subtle. A sequence CRDT gives every letter an id so edits commute and no server order is needed, which is great offline and peer to peer, but it costs metadata and tombstones: a million-character document can become tens of megabytes. For a hosted editor with permissions I would choose OT with one writer per document, and I would switch to a CRDT if offline-first or peer-to-peer became the main requirement.”
5.3

Delivering edits in real time, at scale

The problem: 10 million sockets, 1 million edits a second, and every edit must reach the right people in order. One busy document must stay on one writer. A hot document with 10,000 viewers would make one server send 100,000 messages a second. And every server crash drops thousands of connections at once.

OptionHow it worksGoodBad
Any server handles any edit (stateless)Edits go to any app server, which reads and writes the document in a database with a lock or transaction.Easy to scale and restart.Every edit pays a database round trip and a lock. Latency and contention are high, and ordering is hard.
One owner session server per document (consistent hashing)Route each document to a single server that keeps it in memory and orders its edits.Ordering is a local counter. No distributed transaction. Memory is fast.A failed owner pauses its documents until another takes over. Hot documents must be handled separately.
Pub/sub between servers with a per-document topicAny server accepts edits and publishes them to a topic. Subscribers apply them.Easy fan-out. Decouples servers.Needs a single order for the topic anyway. Adds a hop of latency to every edit.
Owner session for editors + fan-out tier for viewersEditors stay in the owner session. Read-only viewers connect to edge nodes that subscribe to the document and relay edits.The owner sends a handful of messages, not thousands. Viewers scale horizontally.Viewers lag by a hop. A second tier to run, and viewers who become editors must move.
Pick
One owner session server per document, with a fan-out tier for viewers

A document is tiny in write terms (about 10 edits a second even when busy), so putting all editors of one document on one server costs nothing and makes ordering trivial: a counter in memory. Consistent hashing on the document id gives routing and spreads documents evenly. This is the same trade as a single leader per partition: a short pause on failure, in exchange for no distributed coordination on the hot path.

For the rare hot document, the fan-out tier turns 100,000 messages a second from one server into 50 (5 edge nodes of 2,000 viewers each). Viewers need only the final text and the stream of edits, so they never join the transform logic.

ConcernHow we handle it
Reconnect after a dropThe client sends its last revision. The server replies with the edits since then, or a fresh snapshot if too much time has passed. A revision gap on the client triggers the same request.
Reconnect storm after a server dies100,000 clients return at once. Jittered retry with backoff on the client, a gateway rate limit, and snapshots in a cache so the load is on memory, not on the log.
Batching and compressionMerge a burst of keystrokes into one edit (about 5 to 1), and send at most a few messages a second per client. Compress frames.
Slow clientNever block the session on one slow socket. Buffer a bounded queue, and past the limit drop the socket and let it re-sync from a revision.
Presence and cursorsEphemeral and throttled (about 5 a second). Kept in memory only, and transformed with edits so a cursor stays on its letter.
💡What about 1,000 editors in one document?
That is 500 edits a second, with a fan-out of 500,000 messages a second from one server (illustrative). Cap editors per document (for example 100), push the rest to view-only through the fan-out tier, and batch edits in 50 ms rounds.
🎤
Say it out loud
“I would send all editors of a document to one session server, picked by consistent hashing on the document id. Edits are tiny, about 10 a second even for a busy document, so one server can number them with a local counter and no distributed transaction. A failed owner pauses its documents for a few seconds while another takes over. For a hot document with thousands of viewers, I would add a fan-out tier: the session server sends to five edge nodes instead of ten thousand clients. Clients reconnect with their last revision, and with jitter so a crash does not cause a storm.”
5.4

Durability, history and recovery

The problem: An edit that was acknowledged must never be lost, even if the session server dies a millisecond later. The log grows forever, a recovery must be quick, and there is a nasty case: an old owner that was only paused wakes up and keeps accepting edits for a document another server now owns. Invariant: an acknowledged edit is in the replicated log, and only one owner appends at a time.

OptionHow it worksGoodBad
Keep the document in memory, save every few secondsThe session server holds the text and writes snapshots on a timer.Very fast. Little storage.A crash loses up to a few seconds of acknowledged edits. Breaks the durability promise.
Write the log first, then acknowledgeAppend each edit to a replicated log, wait for it to commit, then ack and broadcast. Snapshots every N edits.No acknowledged edit is lost. Recovery is snapshot plus log tail. The log doubles as version history.A write on every edit (about 1M a second in total), so use batching (group commit) and a log store built for appends.
Store only snapshots, no logSave the whole document often and drop the edits.Small and simple.No history, no undo, and no way to repair a crash that happened mid-merge.
Log first, plus fencing by epochAs option 2, and every append carries the owner epoch. The log rejects an append from an older epoch.A paused old owner cannot corrupt the log after a new one took over.An epoch check on each append, and a lease to hand out the epoch.
Pick
Write the log first, acknowledge after it commits, and fence every append with the owner epoch

The append-only log is the source of truth (the same idea as event sourcing and a write-ahead log). We acknowledge only after it is replicated, so any edit the user saw confirmed survives a crash. A snapshot every 1,000 edits caps replay at about 100 KB, so recovery takes seconds.

The epoch is a fencing token. When a new owner takes a document, the epoch goes up. If the old owner was just paused and wakes up, its appends carry the old epoch and are rejected. Without this, two servers could number different edits with the same revision and the document would fork.

Moment the owner diesState left behindRecovery
Before the log appendThe edit was never acknowledgedThe client still has it pending and resends it with the same opId to the new owner.
After the append, before the ackEdit is in the log, sender not toldThe sender resends the same opId. The new owner sees it in the log and returns the existing revision (no duplicate).
After the ack, before the broadcastEdit in the log, others not toldOther clients see a revision gap on reconnect and fetch the missing edits from the log.
History and undoHow it works
Version historyA named version is just a (document, revision) pointer. To view it, load the nearest snapshot and replay to that revision.
RestoreCompute the changes from the current text to the old text and apply them as new edits. The log never rewinds.
Per-user undoUndo creates the inverse of your edit, transformed against everything that happened since. It does not remove anyone else's work.
CompactionOld log ranges are folded into a snapshot, and fine-grained history is kept only for recent weeks, to control the 13 TB hot log.
🎤
Say it out loud
“The log is the source of truth, so I write each edit to a replicated log before I acknowledge it. Then no acknowledged edit is lost if the server dies. Every 1,000 edits I write a snapshot, so recovery replays at most 100 kilobytes and takes seconds. The tricky case is a paused old owner waking up after a new one took over, so every append carries the owner epoch and the log rejects the old one, which is a fencing token. If the client never got an ack it resends with the same edit id, so a repeat returns the same revision and nothing is applied twice.”
5.5

Offline editing, permissions and security

The problem: A user edits for three days on a plane and then reconnects. Another has their access removed while the document is open. Both are about the server not trusting the client. Invariant: no edit is applied without a current permission check, and no edit that was made offline is silently dropped.

OptionHow it worksGoodBad
Block editing offlineThe editor is read-only without a connection.No merge problem.Fails a core user need, and users will switch tools.
Queue offline edits and rebase on reconnect (OT)Keep the local edits with ids. On reconnect, send them from the last known revision. The server rewrites them against every edit that happened meanwhile.Edits are not lost. Uses the same engine as online editing.A long offline period means rewriting against thousands of edits, and the result can surprise the user.
CRDT merge on reconnectExchange the sets of edits and merge them. The result does not depend on order.Merges are order-independent. Offline-first is natural.More metadata kept on the client, and a long offline session can still produce a confusing text.
Keep both versions and ask the userOn a large conflict, save the offline copy as a separate document or a suggestion.Safe: nothing is lost and nothing is decided silently.Manual work for the user. Use only for big conflicts.
Pick
Queue offline edits with ids and rebase on reconnect, with a conflict copy for very large divergences

The same engine handles online and offline: an edit has an id and a base revision, and the server rewrites it against everything after that revision. A size limit protects the system: if an offline session is too far behind (for example thousands of edits), the server offers a conflict copy rather than a huge rewrite that may not match what the user meant.

For security, the rule is never trust the client. The session server checks the role on every edit (not only at connect), so removing access takes effect on the next edit and the server closes the socket. It also checks sizes, rates and edit shape, because a client can send malformed or huge edits.

Security topicWhat we do
Permission checksRole checked at the gateway and again at the session server on every edit. Roles are cached with a short TTL and a revoke message closes the socket.
Link sharingRandom, long link ids that carry a role, can be disabled, and are rate limited against guessing.
Abuse and limitsA cap on edit size, edits per second per client, and document size. Over the limit, drop the edit and warn the user.
Data at rest and auditEncrypt logs and snapshots at rest, write an audit trail of share and permission changes, and honour deletion and retention rules (check with legal for what applies).
End-to-end encryptionIt would stop the server from transforming edits, so it needs a different design (client-side CRDT). Out of scope here.
🎤
Say it out loud
“For offline, the client keeps its edits with ids and the revision it last saw. On reconnect it sends them and the server rewrites them against everything that happened in between, using the same engine as online editing. If the gap is huge, I would save the offline version as a conflict copy instead of forcing a surprising merge. For permissions, I never trust the client: the session server checks the role on every edit, and revoking access closes the socket, so it takes effect within seconds. I would also cap edit size and rate per client.”
VisualizerTwo people edit “ABC” at the same moment: raw, OT or CRDTPick two concurrent edits, then step through. First send raw edits and watch the copies split. Then try OT (server order and rewriting) and CRDT (letter ids). Swap which edit reaches the server first.
What do the clients send?
The two concurrent edits (A types X, B types Y)
Whose edit reaches the server first?
Server
rev 0
ABC
Client A (site 1)
rev 0
ABC
Client B (site 2)
rev 0
ABC
Step 1 of 5
Everyone starts from the same document
Client A and client B both hold “ABC” at revision 0. The server holds it too.
Server ends with
XAC
Client A ends with
XAC
Client B ends with
XAB
Same text everywhere?
No
Intent kept?
No
right letters survive
Diverged. The server holds “XAC”, client A “XAC” and client B “XAB”. Each side applied the other's edit at its old index, but the text had already moved, so the same operation meant a different thing on each copy. This is why “just send the edit” does not work.

A teaching model with fixed edits (no random numbers). Small numbers under a letter in CRDT mode are its permanent id (counter·site). In OT mode a client sends one edit at a time and rewrites what it receives against its one pending edit. Real systems handle long runs of edits, rich text and many clients.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
Which part breaks first when one document gets popular, or when a server dies? Name three failures and say what the user sees in each.

What breaks first, and the fix

BottleneckFix
A hot document with thousands of viewers (100,000 messages a second from one server)Editors stay in the session. Viewers connect to a fan-out tier of edge nodes. The session server sends a handful of messages.
10 million open socketsAbout 200 gateways at 100,000 sockets each. Gateways are stateless and hold only the connection, so they scale out and restart easily.
1 million log appends a secondGroup commit: batch many edits per write (for example every 10 ms). Merge bursts of typing. Use an append-friendly log store, partitioned by document.
Log grows by about 0.4 TB a day (13 TB hot, 30 days)Snapshots every 1,000 edits, fold old log into snapshots, keep fine-grained history for recent weeks only, and tier cold documents to cheaper storage.
Reconnect storm after a session server or gateway failsJittered backoff on clients, a rate limit at the gateway, cached snapshots, and fast reload from the log tail.
One uneven server (a few huge documents on one machine)Consistent hashing with virtual nodes, and the ability to move a single document by closing it and letting it reopen elsewhere.
Transform cost with a very long offline rebaseCap the rebase size, process it off the hot path, or offer a conflict copy. Keep the transform linear in the number of missed edits.

What if a part fails?

FailureHow the design copes
A session server crashesIts lease expires, another server takes the documents with a higher epoch, loads snapshot plus log tail (about 10 seconds for 50,000 documents), and clients reconnect from their last revision.
A session server is paused (garbage collection) and then resumesIt still believes it owns the document. Its appends carry the old epoch and the log rejects them. It drops its sockets and reloads.
A gateway crashesClients reconnect to another gateway. No document state lives there, so nothing is lost.
The log store is unavailableEditors become read-only for a moment, with a clear message. Local edits stay pending on the client and are sent when the log returns. We never acknowledge without a commit.
A client sends the same edit twice (retry)The edit id is already in the log, so the server returns the existing revision and does nothing else.
A bug in the transform code makes copies divergeClients and server compare a hash of the text at a revision. A mismatch triggers a full reload from the snapshot and an alert. Property tests with random edits catch most cases before release.
What to monitor
  • •Edit round-trip latency (type to remote screen), p50 and p99
  • •Divergence checks: hash mismatches between client and server at the same revision
  • •Session server load: documents, edits per second, memory, and queue depth per socket
  • •Log append latency and replication lag, and snapshot age per document
  • •Reconnect rate and failover time after a server loss
Security and abuse
  • •Check the role on every edit at the session server, and close sockets on revoke
  • •Limits on edit size, edits per second, and document size to stop abuse
  • •Random, revocable share links with rate limits against guessing
  • •Encryption in transit and at rest, and an audit trail of sharing changes
  • •Treat document content as untrusted when exporting or rendering (escape it)

Step 7Wrap upabout 3 min

One session server owns each document, numbers every edit, rewrites late edits against the ones they missed, writes them to a replicated log before acknowledging, and broadcasts them. Clients apply their own edits at once. Snapshots bound recovery, an epoch fences stale owners, and a fan-out tier serves viewers of hot documents.

Trade-offs you made

DecisionWhat we gainWhat it costs
One writer per documentOrdering with a local counter, no distributed transaction, simple OTA pause of several seconds when the owner fails, and hot documents need a separate tier
OT instead of CRDTNo metadata per letter, small documents, easy permission checks on the serverA central order, and transform rules that must be tested for every pair
Log first, then acknowledgeNo acknowledged edit is ever lost, and the log is the historyA write on every edit (a million a second), solved with group commit
Optimistic local applyTyping feels instantThe client must rewrite incoming edits against its pending edit
Rebase offline edits, conflict copy if hugeOffline work is kept and merged by the same engineA long offline merge can surprise the user
If we had more time, we would…
  • •Rich text: formatting and structure edits, with their own transform rules
  • •Comments and suggestions that stay attached to text as it moves
  • •Cross-region failover with a fenced owner, and a CRDT mode for offline-first apps
  • •Fuzz and property tests that prove convergence on random edit sequences
  • •Cheaper history: tier old logs and keep snapshots at coarser intervals
🎤
Say it out loud
“To recap: each document has one session server that orders edits, rewrites late ones and saves them to a replicated log before acknowledging. Clients apply their own edits straight away, so typing feels instant, and rewrite what they receive against their pending edit, so every copy converges. Snapshots every thousand edits keep recovery short, an owner epoch fences a paused old server, and a fan-out tier serves big audiences. The trade-off is a pause on failover and careful transform code. With more time I would add rich text, comments and a fuzz test suite.”

Q&ACross-questions (24)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Convergence and transformation

The heart of the question. Be ready to walk an example by hand.

OT, CRDT and the client

Show that you know both approaches and what the client does while waiting.

Scale, routing and real time

Where the single-owner design is tested.

Failures, history and offline

What happens when it goes wrong, and how you prove it will not lose work.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Offline-first and peer-to-peer (no central server)Switch to a sequence CRDT with letter ids. Replicas exchange edits directly or through a relay, and tombstone cleanup needs a version vector. Permissions become harder because there is no server to enforce them.
Rich text with tables and imagesA richer edit language (format range, split and merge paragraphs, table row edits) and a transform rule for each pair. Often a tree document model. Same session server, log and snapshots.
Comments and suggestionsComment anchors are positions that must be transformed with every edit. Suggestions are edits stored as proposals and applied or discarded later. Store them with the document, with their own permissions.
Spreadsheet instead of textEdits are cell writes and row or column moves. Concurrent writes to one cell need a rule (last write by revision wins), and structure edits (insert row) are transformed like text inserts.
Multi-region active-active editing of one documentEither keep one owner region per document and route everyone to it (higher latency for far users), or use a CRDT and replicate between regions. Say the trade-off: consistency and simplicity versus latency.
End-to-end encryptionThe server can no longer read or transform edits, so it only orders and stores encrypted blobs, and the clients must use a CRDT. Search, history diffing and server-side permissions on content are limited.
10,000 simultaneous editorsShard the document into sections with separate owners, or restrict most users to view-only. Batch edits in short rounds and send diffs. Accept that cross-section edits need coordination.
Real-time code editor with language featuresThe same engine for text, with extra services (language server, run) on the side. Cursors, selections and lock-free edits matter more, and conflicts are more visible to users.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts drawing at once. Never asks about offline, rich text or the number of editors.Asks about editors, latency, offline and history, and writes the scope down.Also settles intent versus convergence as the key requirement, permissions on live sessions, and a hot-document case, and says what is out of scope.
EstimationNo numbers, or only a user count.Gets edits per second, connections and gateways, and log growth.Shows that one document is only about 10 edits a second so one owner is cheap, finds the hot-document fan-out as the real limit, and sizes snapshots and the hot log.
Core problemSends raw edits or last write wins, and does not see the divergence.Names OT or CRDT and gives a simple example of an insert shifting an index.Walks a concrete example by hand, states the convergence property, explains the single order and the client state machine, and compares OT with CRDT honestly.
ReliabilitySaves the document to a database now and then.Uses an append-only log and snapshots.Logs before acknowledging, dedups by edit id, fences stale owners with an epoch, and explains each crash window.
Trade-offsPresents one design as obviously best.Compares OT and CRDT and picks one with a reason.Says what would flip the choice, what the single owner costs, and how long a failover pauses editing.
Operations and securityNo testing or monitoring plan, trusts the client.Checks permissions server side and monitors latency.Property-based tests and hash checks for divergence, revoke closes sockets, limits on edit size and rate, and a safe migration plan.

AvoidCommon mistakes on this question

MistakeDo this instead
Saying “last write wins” or “lock the document”Explain that both fail the goal: either work is destroyed or people cannot type together. Move straight to merging edits.
Sending edits by index with no rewritingShow the “ABC” example where an index points at a different letter once the text has moved, and introduce transformation or ids.
Making the local keystroke wait for the serverApply local edits at once (optimistic) and reconcile later. Waiting for a round trip makes typing feel broken.
Acknowledging before the edit is durableAppend to the replicated log first, then acknowledge, then broadcast. Otherwise a crash loses an edit the user saw confirmed.
Ignoring the paused old ownerFence every append with the owner epoch so a stale server cannot fork the document.
Giving a hot document one server for editors and viewersKeep editors in the session and serve viewers through a fan-out tier. Do the 100,000 messages a second sum.
Forgetting permissions on a live sessionCheck the role on every edit and close the socket on revoke, not only when the document opens.
Presenting CRDT or OT as freeName the cost: a central order and transform code for OT, per-letter metadata and tombstones for CRDT.

Revise60-second revision sheet

  • ✔The problem: concurrent edits by index diverge. Goal: every copy equal and everyone's intent kept.
  • ✔Local first: apply your own edit at once, send it with baseRevision and an edit id.
  • ✔OT: one server order per document. Rewrite a late edit against the edits after its base revision. Insert before me shifts my index +1, delete before me shifts it -1.
  • ✔Client state: one edit in flight, the rest buffered, incoming edits rewritten against both.
  • ✔CRDT: a unique id per letter, so edits commute with no server order. Cost: metadata and tombstones.
  • ✔One owner per document: consistent hashing on the doc id. About 10 edits a second per document, so a local counter orders them.
  • ✔Durability: log first, then ack, then broadcast. Snapshot every 1,000 edits (replay under 100 KB). The log is the history.
  • ✔Fencing: the owner epoch on every append, so a paused old owner is rejected.
  • ✔Hot documents: editors in the session, viewers through a fan-out tier (100,000 messages a second becomes 50).
  • ✔Prove it: property tests with random edits, plus a text hash check at each revision in production.

Read these topics next

Operational Transformation→

The rewriting rules and the client-server model used here.

CRDTs→

The alternative: letter ids so edits commute without a central order.

WebSockets→

How every client stays connected for real-time edits.

Write-Ahead Log (WAL)→

The idea behind logging each edit before acknowledging it.

Event Sourcing→

The operation log as the source of truth and the history.

Consistent Hashing→

How a document is routed to its one session server.

Fencing Tokens→

What stops a paused old owner from appending after a new one took over.

Lamport Timestamps→

A growing counter that orders events, like our revision numbers.

← Previous
Design Google Maps
Next →
Design a Metrics and Monitoring System