Design Google Docs
hard 55 minMany people type into one document at once and all of them must end with the same text.
See it run
One document, many typists: follow an edit, a clash, a cursor and an offline afternoon, one hop at a time.
Operations
One edit, start to finish
The typist sees the letter at once. The owner gives it a place in history, stores it, and only then tells everyone.
Step 1 of 9
Alice types Hello
shown
under 1 ms
The screen shows it immediately. Why: typing must never wait for a network.
Step 1: Alice types Hello
def on_edit(client, seq, base, op): if (client, seq) in doc.seen: # a retry return ack(doc.seen[(client, seq)]) check_permission(client, doc) for earlier in doc.log[base:]: op = transform(earlier, op) rev = len(doc.log) + 1 store.insert_if_absent((doc.id, rev), op) # durable doc.apply(op, rev) ack(client, rev) broadcast(op, rev)- Latency
- 24-74 ms
- Load
- 580K/s
- Peak (3x)
- 1.74M/s
- Size
- about 200 B
The conditional insert on the pair (document, revision) does two jobs: it makes the edit durable and it stops a second owner from writing the same revision.
In the real world
The same design google docs doing real jobs. Pick one and step through it.
A server dies with your last word, and then comes back confused.
Step 1 of 5
Normal
epoch
7
Server 12 holds the lease and owns the document at revision 42.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Saving the whole document
criticalThe last save wins, so someone's paragraph disappears.
WrongPUT /docs/7 {whole text}Rightsend({"base": 41, "op": [5, "Hello"]})Confirming before storing
criticalThe owner can crash with edits that people believe are safe.
Wrongack(client, rev)store_later(op)Rightstore.insert_if_absent((doc, rev), op)ack(client, rev)Two owners without a guard
criticalA paused server can wake up and still think it owns the document. Hashing alone does not stop it.
Wrongstore.put((doc, rev), op) # overwritesRightstore.insert_if_absent((doc, rev), op) # second owner failsRetrying without a sequence number
majorIf the reply was lost, the word is typed twice.
Wrongresend(op)Rightresend(op, client_id, seq) # the owner drops repeatsUndo that removes the last edit
majorThe last edit may belong to somebody else.
Wrongundo(doc.log[-1])Rightop = invert(my_last_op)for later in newer_than(my_last_op): op = transform(later, op)
Interview tips
Name the crux early
- Same text on every screen, whatever the timing.
- One order per document is enough.
- Say convergence, then show HeXllYo.
Keep it small
- Text and insert or delete first.
- Formatting is an attribute on a range.
- Comments are ranges that move.
Expect these failures
- Owner crash: lease, log, retries.
- Two owners: the revision key refuses one.
- Hours offline: same transform, longer lists.
Close well
- OT here, CRDT for peer-to-peer or encrypted documents.
- Presence may be lost; text may not.
- Next: undo, suggestions, very long documents.