Ch.26: System Design: Real-Time Editing Like Google Docs

Outline

Transcript

0:00 Two people are editing one sentence in a Google Docs style editor. It reads, “Ship the beta.” Owen types the word “new” before “beta.” Nadia, on a train, adds the word “today” at the end. And let me guess, her train hits a tunnel right then. Of course it does. When the edits cross, the two screens stop matching. Nadia's happens to come out right. Owen's has “today” stuck in front of “beta”: “Ship the new today beta.” Wait, the same two edits, and the screens don't even agree with each other? Yes, and that's only one failure.

0:33 A different design erases Owen's word, and another one prints Nadia's word twice. So the target is easy to say and hard to build. Every screen ends on “Ship the new beta today.” Owen's word survives, Nadia's lands once, and the tunnel costs her nothing worse than a brief wait. Before we fix any of that: who actually decides which edit came first? Here's the map we're building toward. Browser editors on one side, each holding its own unsent changes. In the middle, a router hands each document to one live session, which writes an operation log with snapshots.

1:09 Off to the side, cursors ride their own channel, and a monitor watches for screens that disagree. So browsers type freely, but that one session decides what happened first. That's a big bet on one box. It is. We'll test it region by region, then trace Nadia's word across this same picture at the end. Then let's pin down what that bet has to deliver. The functional requirements are nothing surprising: open the latest text, see your own letters instantly, and see everyone else's edits and cursors live.

1:40 Plus typing through a short disconnect, a permission check on every edit, undo for your own edits only, and version history. But our three broken screens come from the non-functional requirements. Yeah. Owen's mangled screen breaks two at once: convergence, meaning anyone who has applied the same edits sees identical text, and intent, meaning each insert lands where its author meant it. The erased word breaks durability, and I mean that strictly: once the editor acknowledges an edit, nothing takes it back.

2:11 Not a crash, and not someone else's overwrite. And the doubled word breaks exactly-once: a retry never applies twice. Add typing that never waits on the network, best-effort cursors, and failover that may pause but never loses acknowledged work. So the bar is every acknowledged word, in its author's spot, once, on every screen. With that bar set, the tempting shortcut misses it fast. Teams assume they can just send the whole paragraph and let the server merge. Take the reconnect: Nadia's laptop sends “Ship the beta today,” the last writer wins, and Owen's “new” is gone.

2:47 Then somebody in the design review, usually whoever owns the deadline, says, “Fine, lock the paragraph while Owen's in it.” Or, “keep both versions as conflicting copies and let someone sort it out.” Google's 2010 posts about rebuilding the Docs editor say locks only sidestep the problem, and comparing whole versions doesn't rescue it either. Their example: one person bolds “brown fox” while another changes “fox” to “dog.” Compare versions, and several merges look plausible. Right, so the versions alone can't tell you who meant what.

3:19 What did they switch to? Small operations, like insert these characters here, each stamped with the revision its author was looking at. As of those 2010 posts, Google saved each document as a revision log, and the editor replayed that log to display the text. And for one shared sentence, I think that beats handing someone two conflicting copies. The stamp tells the server what each person intended. Once edits are stamped operations, Nadia's editor can echo locally. Her letters appear before any server hears about them, so network speed never limits typing speed.

3:54 Google's editor worked that way back then. Then her laptop holds edits the server hasn't seen. Walk me through where they live. Think of it as two piles and a bookmark. A pending pile for typing not sent yet. A sent pile for the one change awaiting acknowledgement. And a bookmark: the last committed revision she's seen, 41. Only one change in flight? I'd have guessed you'd stream every keystroke. I guessed that too, until I read the tradeoff in Google's 2010 Wave whitepaper. If each client waits for its acknowledgement before sending more, the server holds just one history, its own log, instead of tracking a separate view for every connected client.

4:33 And new typing just piles up behind it meanwhile. Owen sees her edits in bursts, about one round trip apart. Which means her “today” is stuck awaiting a reply when the tunnel swallows her signal. Now over at the session, Owen's edit arrives first. What does it do with two edits that both started from 41? It commits Owen's first: four characters, “new” plus a space, at offset nine. That's revision 42, “Ship the new beta.” Then Nadia's shows up: based on 41, insert space “today” at offset 13. And offset 13 used to be the period...

5:10 ...but now it's the “b” in “beta.” Replay her raw position and you get Owen's broken screen. So the session transforms her edit against everything committed since 41. Owen added four characters before 13, so her insert slides to 17. Stored as revision 43: “Ship the new beta today.” Huh. No guessing at all, then. Just arithmetic on positions. Right, and Google's post calls that shifting operational transformation, or OT. It's simple in this example, and that's exactly the catch. Hmm, what if they'd both typed at the exact same offset?

5:44 Then the transform needs a fixed tie-break, for instance, the edit already committed goes first, so every screen puts the words in the same order. Now multiply that by every pair of operation types, like inserts, deletes, and styling. Get one pair wrong, and two screens can disagree without anyone noticing. That fragility leads to the other family. A CRDT, a conflict-free replicated data type, lets every copy accept edits with no coordinator and still converge. Libraries like Yjs and Automerge are built that way; Automerge, for one, lets people edit offline and sync later.

6:21 So why aren't we using one? Honestly, I expected you to say CRDT, full stop. It's a fair pick, and nothing stops you running one behind a server. But we need that server anyway, for permissions, durable acknowledgements, and history. And with 1 server order, OT gets much tamer, not trivial: each late edit is transformed against one log, not reconciled with every other copy. The CRDT's headline trick, merging with no coordinator, mostly goes unused. Okay, but that's a reason OT is fine here, not a reason a CRDT is worse.

6:56 Fair, but my honest worry is readability. Some published text CRDTs can interleave two people's inserts letter by letter. Not all of them do, and the libraries keep getting better, but converging still isn't the same thing as readable. So it's close, but you've sold me for these requirements. If the product needed weeks of offline editing, or no server at all, I'd flip back to a CRDT. Researchers still argue about this one, so it's a call, not a universal winner. What about Figma? It has a central server too.

7:27 Figma's 2019 post says it isn't using true CRDTs, because its own server is the central authority. It keeps the latest value for each property, and text counts as one value. Take the sentence: Owen's copy now includes “new,” while Nadia's copy ends with “today,” and the server keeps whichever whole value arrived last. Great for a rectangle's color. Huh, so for a sentence, that's our erased-word problem again, and somebody's word just loses. And back in the session, there's a choice hiding in the word “acknowledged.” Do we tell Nadia her edit landed before it's on disk, or after? After. First append revision 43 to the log, then acknowledge. That adds latency to every edit, and it's the price of the durability promise.

8:12 Figma's 2022 engineering post shows the other side. Its multiplayer service used to checkpoint each file every 30 to 60 seconds, so a crash could lose up to about a minute of work. Its newer journal is written asynchronously, with 95% of edits written within 600 milliseconds. That's a whole minute of somebody's work, gone. Okay, async is reasonable for a design tool, but we're choosing the stricter version, because a vanished acknowledged word is exactly what we promised would never happen. And to avoid replaying every keystroke on each open, we write periodic snapshots tagged with their revision.

8:49 Loading means the newest snapshot plus the edits after it. ShareDB, an open-source OT server, documents the same milestone idea. So take the case we've been building toward. When Nadia's signal returns, revision 43 was committed, but the acknowledgement was lost underground. Her client still thinks “today” is unconfirmed. Hold on. So she resends it, and we get “today today”? Only with a naive session. Her client reconnects with its last synced revision and resends the same operation, tagged with its client ID and sequence number.

9:23 The session sees that pair is already committed. ShareDB's source has exactly this check, with a comment that it's important not to apply the same op twice. So instead of appending again, it replies with Owen's 42, which she missed, plus anything newer, and tells her that her own edit is already in as 43. Her client applies what she missed and transforms anything she typed underground. Yep, and her screen matches Owen's. And if that first copy never made it out of the tunnel? Then the check finds no match, so it's just a late edit: transformed, appended, then acknowledged.

10:00 Same sentence either way. What if she was gone so long the log no longer reaches back to 41? Do her words just get thrown away? No. Her pending text can't be transformed automatically anymore, so, as a last resort, we fall back on the conflicting-copy idea we passed over earlier: hand her a visible copy of her words to recover, rather than silently dropping them. How long to keep the log is a policy choice. So that covers her text. Her cursor is a different story. Owen sees a little colored marker with Nadia's name, and it never touches the log.

10:35 Presence rides a separate, temporary channel. Yjs, for example, keeps presence out of the document and deletes it when a user goes offline. Oh, so when the tunnel cut her off, her cursor just faded from Owen's screen. We've all watched a coworker's cursor freeze mid-word and wondered if they'd left. Right, and here nothing was lost. But say her cursor is saved as a plain character position. Doesn't Owen's “new” leave it pointing at the wrong letter? It would, because remote edits shift the text underneath it.

11:07 So cursors get re-anchored to the characters around them, and they move with the text. Which gives on-call a clean rule. A dropped cursor update is cosmetic. A dropped operation is a bug, and it pages someone. And that same session also checks permissions on every operation. A viewer's insert never reaches the log. If someone loses editor access mid-sentence, their pending edits come back to them visibly instead of vanishing. I'm not sure undo is that clean. Let's say Nadia hits undo. Couldn't that rewind the shared document and take Owen's word with it?

11:44 It shouldn't. I mean, undo builds the inverse of her own edit, which is deleting “today.” That delete gets transformed past anything committed since, the same way her insert slid from 13 to 17, then lands as a brand-new revision at the end. History never gets rewritten. The Yjs undo manager, similarly, tracks only local changes by default. So Owen keeps “new,” and the log shows her typing and her undo as separate revisions. Version history falls straight out of that. So far everything runs through a single session for each document, which sounds like a bottleneck.

12:20 Is it? For one extremely busy document, yes, that's honestly the ceiling. Google's help pages even cap editing at 100 open tabs or devices per file, though that's a product limit, not a peek at their servers. Different documents, though, spread across many servers. The router gives each document 1 active owner, using a lease, which is a time-limited claim, plus an owner epoch that only goes up. Why the epoch? Isn't the lease enough? Imagine an old owner that stalls, wakes up, and still believes it's in charge.

12:53 The log rejects any append carrying an older epoch, so two owners can never both write revision 44. Yeah, a zombie owner. Still holding its old badge, swiping at the door. And the log never lets it in. When an owner really crashes, the new one loads the latest snapshot and the log's tail, clients resend, and the duplicate check catches repeats. A short stall, no lost words. Now think about that transform bug again, the one where two screens disagree and nobody notices. How would we even find out?

13:26 We measure it, instead of doing what we've all done: learning about the incident from a user's screenshot. In our proposed design, each client periodically reports a checksum of its text at a given revision, and the session compares it with its own. And a mismatch bumps a divergence metric and forces that client to reload? Exactly, from snapshot plus tail. A forced reload is annoying, but it beats silently wrong text. Then beside it, I'd chart acknowledgement latency, the oldest pending edit, and duplicate resends.

13:57 Makes sense. Duplicate resends spike every time a trainload of commuters leaves a tunnel, and that's normal. A divergence count above zero never is. Finally, back on the full map, follow both words one last time. Each echoes locally, then the router passes it to the one session that owns this document. It orders Owen first, slides Nadia's insert to 17, and logs revision 43 before acknowledging. Intent and durability, settled in one place. I kept waiting for the tunnel to break it. Did it hold? It held. Her resend became a lookup, not a second “today.” A crashed owner would rebuild from a snapshot, cursors float beside it all, and if a transform bug ever split two screens, the monitor would flag the one whose checksum disagrees.

14:44 Which leaves one sentence everywhere: “Ship the new beta today.” Every keystroke the editor acknowledged stays where its author put it, exactly once. Thanks for listening to Learning Podcasts.