System Design

Problem Breakdowns

Design Google Docs (Collaborative Editing)

Most answers spend the hour on operational transformation against CRDTs. The transform is the small part. Once one server numbers each document's edits, convergence, history, offline merges and fast opens all become questions about one log.

"Design Google Docs" usually turns into a lesson on operational transformation. The candidate draws two clients, one inserts and one deletes, and works out how far an index has to shift. That arithmetic matters, but it's the smaller half of the problem. The rest is about the server. Where is the order of edits decided? What happens when that server dies? How does a laptop rejoin after six hours offline, and how does a document of 1 million characters open in 2 seconds?

Google described its answer in three blog posts in 2010. A Google document is stored as a revision log, a list of changes of three kinds: insert text, delete text and apply a style. Each client applies its user's edits at once and sends them to the server. The server puts every change in one order and passes it to the other editors. Each editor adjusts what it receives so it fits its own copy.

That protocol goes back to Jupiter, a collaboration system built at Xerox PARC in 1995. Its authors started from an algorithm with no central server. They wrote that having one let them "substantially simplify" it.

Collaborative editing is an ordering problem before it's a merge problem. When one server puts each document's edits in a single order, the merge rule only has to fix the edits that crossed on the wire.

The rest of the design depends on where that order lives. Routing sends every editor of a document to the one server that holds it. Storage is the order written down, with snapshots so that nobody replays it from the first keystroke. Version history is the same log read back. An offline laptop brings back a long run of edits that crossed everything. And a document with 10,000 readers is one server that has to send every edit to all of them.


Understanding the problem

The general method for this part of the interview is in The First Five Minutes: Requirements.

Several people type in one document at the same time. Each sees their own keystrokes at once and everyone else's within a fraction of a second, with a coloured cursor for each person. When they all stop, every copy says the same thing.

Four kinds of product go by similar names, and each is built differently.

  1. File sync, such as Dropbox. The server stores files as bytes it can't read, so two edits to one file become two versions and a person merges them. Dropbox and Google Drive designs that one. A document editor's server stores operations it understands, so it can merge them itself.
  2. A design tool, such as Figma. Its document is a tree of objects with properties, and when two people set one property, the last value the server received wins. Figma's 2019 write-up says simultaneous editing of the same text value doesn't work in Figma.
  3. Peer-to-peer editing, with no server in charge. Libraries such as Yjs and Automerge are built for it, and section 1 explains why this design doesn't use them.
  4. Live co-editing of rich text, such as Google Docs or Overleaf. This is the one we're designing.

Functional requirements

  1. Edit together. Several people type in one document at once. Each sees their own edits instantly and the others' within half a second, and every copy ends up the same.
  2. See who's there. Each person sees the others' names, cursors and selections as they move.
  3. Keep working offline. Edits made without a connection are kept on the device and merged when it reconnects.
  4. Version history. Show earlier versions and who changed what, and restore any of them.
  5. Comments and sharing. Comment on a range of text, and share a document with viewers, commenters and editors.

Out of scope, deliberately:

  • The layout engine that turns the document into lines and pages.
  • Spreadsheets and slides, whose operations differ.
  • Suggestion mode, export, and search across documents.
  • Peer-to-peer editing with no server.

Non-functional requirements

  1. Scale. 1 billion documents stored. At peak, 10 million clients are connected to 5 million open ones. One client in 50 is typing at any moment, so 200,000 typists make about 3 operations a second each. That's 600,000 operations a second at peak, three times the average. These are assumptions, sized for a large product.
  2. Typing never waits for the network. A keystroke shows on the typist's screen at once. A collaborator in the same region sees it within 500 ms at p99, the latency that 99 percent of edits beat.
  3. Durability. An operation the server has acknowledged survives the loss of any machine or any one availability zone.
  4. Convergence. Once everyone has received every operation, every copy of the document is identical, and each edit sits where its author put it.
  5. Fast open. A document of up to 1.02 million characters, Google Docs' own limit, opens in under 2 seconds at p99.

Requirement 4 carries the design, so read what it leaves out. It doesn't say everyone sees each keystroke at the same moment, or that copies merge with nobody in charge. One order per document does most of the work: there's one true sequence of operations, the server's, and every copy only has to end up equal to it. The merge rule makes that true for the edits that crossed, and keeps each one where its author put it.

Requirement 2 is where the crossing comes from. A client that waited for the server before showing a keystroke would lag by a round trip on every letter. So each client holds edits the server hasn't seen yet, and the server receives edits made on a copy that's already out of date.


The set up

Core entities

  • Document. An id, a title, an owner, and its current revision, the number of the last operation in its log.
  • Operation. One edit: insert text at a position, delete a range, or apply a style to a range. It names the revision it was made on, and the server gives it the next revision when it puts it in order. The operation is the only interesting entity: a document is its operations applied in revision order.
  • Snapshot. The whole document at one revision, saved so that opening it doesn't replay the log from the start.
  • Session. An open document in memory on one server: its text at the current revision, its recent operations, and who's connected.
  • Presence. One person's cursor and selection in one document. It lives only in memory.

How does a keystroke reach the server?

The transport comes before the interface, because the interface is mostly messages on it. The course's page on WebSockets, server-sent events and polling covers the general choice. Two facts settle it here: the delay is half a second, and a typist's client sends about 3 operations a second as well as receiving everyone else's.

Polling every half second would send 20 million requests a second from 10 million clients, mostly empty, because most open documents have one person in them. Server-sent events (SSE) remove the empty polls, but they carry only the server's half, so every operation the client sends is still an HTTP request of its own.

A WebSocket carries both directions on one connection. Its cost is a held connection per client, and those drop on every deploy and network change. So the client has to be able to resume: it sends the last revision it has, and the server sends what came after.

System interface

Opening a document is one HTTPS request. Editing it is messages on a WebSocket.

GET /v1/docs/d_7f3a
→ 200 { "role": "editor",
        "snapshot": { "rev": 18000,
                      "url": "https://snap.example.com/d_7f3a/18000?Expires=...&Signature=..." },
        "ticket": "wst_9c1e..." }

wss://collab.example.com/v1/docs/d_7f3a?ticket=wst_9c1e...

client → { "type": "join", "rev": 18000 }
server → { "type": "ops", "from_rev": 18001, "ops": [ ... 240 operations ... ] }

client → { "type": "op", "base_rev": 18240, "client_id": "c_19", "client_seq": 412,
           "op": { "insert": "pm", "at": 9 } }
server → { "type": "ack", "client_seq": 412, "rev": 18242 }               -- to the author
server → { "type": "op", "rev": 18242, "author": "u_bob", "client_id": "c_19",
           "client_seq": 412, "op": { "insert": "pm", "at": 12 } }       -- to everyone else

client → { "type": "presence", "rev": 18242, "anchor": 14, "head": 14 }
client → { "type": "resume", "rev": 18242 }     -- after a reconnect, then ops as usual

Four things to note.

base_rev is what makes a merge possible. It names the revision the client's copy was at when the user typed. The server adjusts the operation for everything numbered after that revision. Here that's one insert of three characters at the start, so at: 9 becomes at: 12.

The server hands out revisions, and clients never do. The ack tells the author where its operation landed. Everyone else gets the adjusted operation with its revision, so every copy ends at the server's text.

client_id and client_seq name an operation before it's sent. After a reconnect, the client resends anything that wasn't acknowledged. The server remembers the highest client_seq it has numbered for each client, so a resend of an operation it already numbered is acknowledged again, not applied twice. Every operation the server sends carries both fields, so a client that finds its own operation in a catch-up takes it as the ack.

Presence carries a revision too. A cursor at 14 means position 14 at revision 18242. A client that's further ahead moves the cursor through the operations in between before drawing it.

The ticket is single-use and short-lived, fetched over HTTPS just before connecting. A browser can't put an Authorization header on a WebSocket, and a long-lived token in a URL ends up in proxy logs, as WebSockets, SSE and polling explains. The snapshot URL is signed and expires within minutes, so a link that leaks, or a user who loses access, can't keep fetching the document.


High-level design

1. How do edits made at the same time converge?

Each client applies edits before the server sees them, so the server keeps receiving operations made on revisions that are already old. What to do with them depends on how often it happens.

Back of envelopeHow often two edits cross
The question is whether an edit made on an old revision
is rare enough to refuse and retry. An edit crosses another
when the server numbers someone else's edit after the
revision yours was made on, and before yours arrives.
That window is about one round trip.

  round trip, client to server and back      100 ms, assumed
  each other typist                          3 operations/s
  others' operations in your window,
  with k others typing        k × 3 × 0.1 s  =  0.3k
  chance at least one lands, treating
  arrivals as random          1 − e^(−0.3k)

  k = 1                       1 − e^(−0.3)   ≈  26%
  k = 3                       1 − e^(−0.9)   ≈  59%
  k = 9                       1 − e^(−2.7)   ≈  93%
  ─────────────────────────────────────────────────────────
With one other person typing, one edit in four was made on
a revision that's already old. With nine, nearly all of
them. A retry faces the same odds.
Naive

Refuse an edit made on an old revision

This is how the key-value store and Dropbox handle a race. A write names the version it started from, and it fails if that version is no longer current. It's simple, and it never merges anything wrongly.

The worksheet rules it out. With one other person typing, a quarter of your keystrokes are refused, and each retry faces the same odds. With nine others typing, 93 percent are refused. Each refusal means the client has to undo the edit on screen or try it again.

The old Google editor tried something softer: compare whole versions and merge them. Google's 2010 post shows why that fails. John bolds "brown fox" while Luiz replaces "fox" with "dog". From the two versions alone, "brown fox dog", "brown dog" and "brown dog fox" are all valid merges, and nothing says which one they meant.

Senior

A text CRDT: every character gets an ID

A conflict-free replicated data type (CRDT) is a data structure whose copies take edits on their own and merge them, in any order, to the same result. A text CRDT gives every character an ID that never changes, usually the id of the client that typed it plus a counter, such as a10. An insert says "after a10" instead of "at position 9". A delete marks the character as deleted, because another edit may still name it as its neighbour. That marker is called a tombstone.

An insert names its neighbour, not a position
The text is meet at 5, and each character has an ID under it, a1 to a10. The 1, a9, was deleted earlier and stays as a tombstone, in grey. Alice inserts we after the start (1), and Bob inserts pm after a10, the 5 (2). No ID changes when Alice's three characters arrive in front of Bob's, so every copy reads we meet at 5pm, in green (3).The text is meet at 5, and each character has an ID under it, a1 to a10. The 1, a9, was deleted earlier and stays as a tombstone, in grey. Alice inserts we after the start (1), and Bob inserts pm after a10, the 5 (2). No ID changes when Alice's three characters arrive in front of Bob's, so every copy reads we meet at 5pm, in green (3).
IDs don't shift when text is inserted before them, so nothing needs adjusting. The text is meet at 5, and each character has an ID under it, a1 to a10. The 1, a9, was deleted earlier and stays as a tombstone, in grey. Alice inserts we after the start (1), and Bob inserts pm after a10, the 5 (2). No ID changes when Alice's three characters arrive in front of Bob's, so every copy reads we meet at 5pm, in green (3).

Two inserts made at the same time after the same character are ordered by ID, the same way on every copy. So copies converge whatever order the operations arrive in. Yjs says it "doesn't need a central source of truth", and Automerge merges "without requiring any central server". Both are libraries you can add to a project, which makes this a common answer in interviews.

The cost is the IDs. Every character carries one in memory, and so does every deleted character. Gentle and Kleppmann's 2025 paper measured the best CRDT libraries at more than 10 times the memory of operational transformation (OT), the next approach, for viewing and editing a document. The paper gives that as the reason Google Docs, Microsoft Office and Overleaf use OT.

Staff

Operational transformation, with one owner per document

Question the premise that copies have to merge with nobody in charge. That's true for peer-to-peer editing. Here every client already holds a connection to a server, so let one server, the document's owner, put its operations in order. Positions stay plain numbers, and only the operations that crossed need fixing.

The fix is OT. A transform takes two operations made on the same revision and adjusts one so it can apply after the other. For two inserts the rule is short. If the other insert landed before yours, move yours right by its length. If both are at the same position, a tie-break decides, and every copy applies the same one, such as the server's order.

Take the text "meet at 5" at revision 41. Alice inserts "we " at position 0. At the same moment, Bob inserts "pm" at position 9. Both were made on revision 41.

Two inserts made on the same revision
Time runs down the page. Both start from meet at 5 at revision 41. Alice's insert reaches the owner first and becomes revision 42 unchanged (1). Bob's client gets revision 42 while its own pm is unacknowledged. Alice's insert is before his, so it applies as it is, and his pending pm moves to position 12 (2). Bob's operation reaches the owner made on revision 41, so the owner moves it past revision 42, from position 9 to 12, and numbers it 43 (3). Alice applies revision 43, and both copies read we meet at 5pm, in green (4).Time runs down the page. Both start from meet at 5 at revision 41. Alice's insert reaches the owner first and becomes revision 42 unchanged (1). Bob's client gets revision 42 while its own pm is unacknowledged. Alice's insert is before his, so it applies as it is, and his pending pm moves to position 12 (2). Bob's operation reaches the owner made on revision 41, so the owner moves it past revision 42, from position 9 to 12, and numbers it 43 (3). Alice applies revision 43, and both copies read we meet at 5pm, in green (4).
The server numbers Alice's first, and moves Bob's past it. Time runs down the page. Both start from meet at 5 at revision 41. Alice's insert reaches the owner first and becomes revision 42 unchanged (1). Bob's client gets revision 42 while its own pm is unacknowledged. Alice's insert is before his, so it applies as it is, and his pending pm moves to position 12 (2). Bob's operation reaches the owner made on revision 41, so the owner moves it past revision 42, from position 9 to 12, and numbers it 43 (3). Alice applies revision 43, and both copies read we meet at 5pm, in green (4).

The server did one transform, and so did Bob's client. Alice's operation needed none, because nothing was numbered between the revision she typed on and her arrival.

This is Jupiter's design. Each client keeps an exchange with the server alone, and the server applies each operation and passes it on, so every client only has to agree with the server.

Google Wave added one rule, and Google's Docs posts describe the same one. A client sends one change at a time and waits for its acknowledgement, holding later edits as pending. The server then keeps a single history, and moves each arriving operation past the ones numbered after its base revision.

What you give up. Every edit passes through one owner, so that server's failure pauses its documents, which deep dive 2 covers. The transform has to be right for every pair of operation types: insert, delete and style, each against the others. And merging after a long time offline costs at least the product of the two branches' lengths. Gentle and Kleppmann's OT implementation took an hour to merge one long-diverged editing history. Deep dive 6 handles that case.

Where is the order decided?

Each open document has one owner: a session server that holds it in memory and numbers its operations. Figma's 2019 write-up describes the same arrangement, with a separate process for each file in multiplayer. On the owner, one thread handles all of a document's operations, so two are never numbered at once.

Clients don't connect to the owner directly. Each client holds its WebSocket on a gateway, a server whose only job is holding connections. The gateway forwards operations to the owner and passes the owner's messages back. This adds a hop of about a millisecond inside a region. In return, an owner can fail or move without dropping a single socket, and deep dive 4 uses the gateways to fan out a busy document.

The gateway finds the owner in a header row, kept in the log table for each document. It names the owner, the owner's lease and an epoch, a number raised every time the owner changes. Session servers register in etcd, a coordination service, with a lease that expires 10 seconds after a server stops renewing it. An owner counts only while the lease named in the header is live. A server that restarts gets a new lease, so it can't be mistaken for the owner of documents it no longer holds in memory.

When a document has no live owner, the gateway picks a session server by rendezvous hashing over the live ones, so every gateway picks the same server. That server claims it by raising the epoch in the header row, with a write that succeeds only if the epoch hasn't changed. If two gateways disagree about who's alive, only one claim wins.

Every editor of a document reaches one owner
Three clients of d_7f3a hold sockets on two gateways (1). Each gateway reads the document's header row, owner S7 with lease L7 at epoch 6, and checks that lease L7 is still live in etcd (2). Both forward to S7, which numbers every operation (3). With no live owner, the server that rendezvous hashing ranks first, here S12, would claim the document by raising the epoch, in orange (4).Three clients of d_7f3a hold sockets on two gateways (1). Each gateway reads the document's header row, owner S7 with lease L7 at epoch 6, and checks that lease L7 is still live in etcd (2). Both forward to S7, which numbers every operation (3). With no live owner, the server that rendezvous hashing ranks first, here S12, would claim the document by raising the epoch, in orange (4).
The header row names the owner, and the claim on it is conditional. Three clients of d_7f3a hold sockets on two gateways (1). Each gateway reads the document's header row, owner S7 with lease L7 at epoch 6, and checks that lease L7 is still live in etcd (2). Both forward to S7, which numbers every operation (3). With no live owner, the server that rendezvous hashing ranks first, here S12, would claim the document by raising the epoch, in orange (4).

Adding a session server moves nothing that's open. A document closes when its last client leaves, and its next open goes wherever rendezvous hashing sends it, so a new server fills up as new sessions start.

Which data store holds the log, and what forces it

The log is every operation in order, and it's the copy that has to be right. Everything else, the owner's memory and the snapshots, can be rebuilt from it, which is the point write-ahead logs makes about a database. The owner appends each operation before anyone hears about it. So it needs three things from the data store. An append must fail if the writer's epoch is old. Every owner starts from the true end of the log, so an old owner is the only way two writers could reach the same revision. A read must return one document's operations in order, from any point. And it must keep up with 600,000 operations a second.

Back of envelopeWhat the log costs to keep
The question is which data store takes the log, and which
number forces the choice. 200,000 operations a second on
average, 600,000 at peak, about 100 bytes each with keys.
Per node figures are the course's working figures, and
3.2 TB is a 4 TB drive kept 80 percent full.

Writes at peak
  Postgres primaries   600,000 / 5,000 to 20,000  = 30 to 120
  DynamoDB transactions, one per batch; a lone typist's
  operations come ~330 ms apart, so most hold one
                                                  ≈ 600,000/s
  each checks the header and puts the batch, and
  writes both items twice, to prepare and commit  = 4 units
                       600,000 × 4                = 2.4M units/s
  as key-value nodes, 3 replicas each
                 2.4M × 3 / 10,000 to 50,000      = 144 to 720

Storage
  per day          200,000 × 86,400 × 100 B  ≈  1.73 TB
  per year         1.73 TB × 365             ≈   631 TB
  every operation kept, 3 replicas
    after one year      631 TB × 3 / 3.2 TB  ≈   590 nodes
    after two years   1,262 TB × 3 / 3.2 TB  ≈ 1,180 nodes
  only the last 7 days kept
                   1.73 TB × 7 × 3 / 3.2 TB  ≈    12 nodes
  ─────────────────────────────────────────────────────────
Writes need 144 to 720 nodes, and stay there. Keeping every
operation in the same data store adds about 590 nodes a
year, forever. Keep a week there and move the rest out,
and writes set the size.
Naive

One Postgres table, one row per operation

The key (doc_id, rev) gives each document an ordered log, and a unique index refuses a second write at one revision. It's the right first answer for a product with a few thousand typists.

At 600,000 appends a second at peak, it needs 30 to 120 primaries, so it's a sharded Postgres from day one. Then 631 TB arrives every year. A table of hundreds of terabytes can't be vacuumed or restored in any window you'll get. Partitioning and sharding describes how that pushed Figma to split its own Postgres.

Senior

A key-value store, keyed by doc_id and rev

Figma's 2022 write-up puts its multiplayer log, which it calls the journal, in DynamoDB, and this design does too. The partition key is doc_id and the sort key is the first revision in each row, so one document's operations sit together in order. Loading the recent ones is one range read.

The append is a transaction, TransactWriteItems. It checks that the header still holds the writer's epoch, and puts the new row. The epoch check is what refuses a batch from an old owner that overlaps the new owner's revisions. A DynamoDB condition can only test the item being written, so checking the header takes a transaction. Figma's journal does the same: each write is conditional on a lock ID held in a separate table.

A transaction costs more than a plain write. DynamoDB writes every item in one twice, to prepare and to commit, so an append costs about 4 write units instead of 1. And two transactions on the same header cancel each other, so each document appends one batch at a time. Everything the owner numbers while one append is in flight goes into the next, which is called group commit.

On writes alone, the 144 to 720 nodes this needs are no cheaper than 30 to 120 Postgres primaries and their replicas. DynamoDB buys partitions that split and move with nobody running them, and no vacuum. Its cost is storage. Kept forever, the log grows by 631 TB a year, in three copies, on the SSDs that serve the live appends.

Staff

Keep a week of operations hot, and the rest in object storage

Question the premise that the log lives in one data store forever. The operations that get read are recent ones. A client reconnecting after a weekend needs the operations since Friday. Version history and recovery start from a snapshot.

So the hot log in DynamoDB keeps about 7 days of operations, 36 TB in three copies. Every 1,000 operations, the owner writes a snapshot to object storage, such as S3, and seals the operations before it into a segment, a file that never changes again. A slow or closing document has its segment sealed sooner (deep dive 3). Each row in DynamoDB gets an expiry time when it's written, 7 days later, and DynamoDB deletes it after that. Writes now set the size of the hot log at 144 to 720 nodes, and storage grows only in object storage, at one copy, priced per gigabyte a month.

What you give up. A read older than a week, from history or from a client offline that long, fetches segments from object storage and takes hundreds of milliseconds instead of a few. And the owner now writes three things: operations, snapshots and segments.

data storewhat goes in itwhat forces it
DynamoDB, one tableeach document's header row and its last 7 days of operationsup to 600,000 appends a second at peak, each a transaction checked against the epoch
object storage, such as S3snapshots, and sealed segments of operations631 TB of operations a year, rarely read
Postgresdocument metadata, sharing grants, comment threads, named versionssmall, changes rarely, queried by user as well as by document
etcdthe live session servers and their leasesa few hundred keys, with leases that expire on their own

The records

-- DynamoDB table doc_log: partition key doc_id, sort key rev
header (                    -- the row at rev 0
  doc_id       text,
  owner        text,        -- the session server holding it now
  lease_id     text,        -- that server's lease in etcd, indexed;
                            -- cleared once the document is closed and sealed
  owner_epoch  bigint,      -- raised by every claim
  snapshot_rev bigint,      -- newest snapshot, always at a batch's end
  sealed_rev   bigint       -- last revision in a segment, raised after
                            -- each seal, always at a batch's end
)

batches (                   -- one row per append
  doc_id       text,
  rev          bigint,      -- the first revision in this batch
  epoch        bigint,      -- owner_epoch when it was written
  ops          list,        -- each: rev, author, client_id, client_seq,
                            --   the operation as adjusted, and the time
  expires_at   timestamp,   -- 7 days after the append
  primary key (doc_id, rev)
)

-- Object storage, never changed once written
snapshots/d_7f3a/18000      -- the text at rev 18000, and each client's
                            -- highest client_seq
segments/d_7f3a/17001-18000 -- the operations before that snapshot, and a
                            -- summary of who edited and when

-- Postgres
documents       (doc_id primary key, title, owner_user, created_at)
grants          (doc_id, principal, role, primary key (doc_id, principal))
comment_threads (thread_id primary key, doc_id, anchor_id, resolved)
named_versions  (doc_id, rev, name, primary key (doc_id, rev))

Three things to note.

The revision is the order, and the time isn't. The owner's counter decides where each operation goes. No client's clock decides anything, and the time is only shown in history.

The header names a lease, not only a server. A gateway forwards to the owner only while that lease is live in etcd, and a secondary index on lease_id lists the documents each lease holds. sealed_rev says how far the segments reach, so a new owner can find the tail even after its rows in the hot log have expired. Each row holds one batch, keyed by its first revision, and carries its own expiry.

The snapshot carries each client's highest client_seq. A new owner loads a snapshot and the operations after it. Without that map, it couldn't recognise a resend of an operation it numbered before the snapshot.

The operations that carry the product

-- 1. The owner receives an operation (one thread per document)
on_op(client_id, client_seq, base_rev, op):
  if client_seq <= last_seq[client_id]:
    ack again with its rev, once its batch is in the log; return
  if base_rev < oldest rev in memory: reply rebase (deep dive 6); return
  for each operation p numbered after base_rev: op = transform(op, p)
  rev = head_rev + 1; head_rev = rev; last_seq[client_id] = client_seq
  apply op; add (rev, op) to the next batch

-- 2. The appender: one batch in flight per document
transact: header.owner_epoch = epoch, and put the batch
  -- a failed check means another server owns it: stop
ack each author; send the batch to every gateway with clients here
in a background task, off the document's thread:
  every 1,000th operation ends a batch: a snapshot there, and a segment
  5 minutes after the oldest unsealed operation: a segment
  once a seal's files are written: raise header.sealed_rev, and
    snapshot_rev after a snapshot, in one write, only if higher than now
  on close: a segment, raise sealed_rev, then clear header.lease_id,
    if owner_epoch is still mine

-- 3. A client joins, or resumes after a reconnect
on_join(rev):
  send the operations after rev, from memory, the hot log or segments,
  each with its author's client_id and client_seq

-- 4. A gateway finds the owner
if header.lease_id is live in etcd: forward to header.owner
else: ask the live server with the top rendezvous score to claim it

-- 5. A session server claims a document (every open of a closed one, too)
read the header, strongly consistent: e = owner_epoch
set owner and lease_id to mine, owner_epoch = e + 1, if it's still e
then read the newest snapshot, the segments after it up to sealed_rev,
  and the batches after sealed_rev, strongly consistent

-- 6. Every minute, for every registered lease that has expired,
--    until the index has listed nothing for it for an hour
for each header with that lease_id, from the index:
  if I rank first by rendezvous hashing, and the header, read strongly
  consistent, still names the expired lease: claim it as in 5,
  seal the operations after sealed_rev, and close it if nobody has it open
  -- a seal after a crash may overlap an earlier segment;
  -- readers take each revision once

Operation 1 runs most often, about 600,000 times a second at peak. Operation 3 runs on every open and every reconnect. The interviewer pushes on operation 2, usually by asking what happens if the owner dies after the append and before the ack. The batch is in the log, so the client's catch-up after reconnecting includes its own operation, with its client_seq, and the client takes that as the ack. A resend that crosses the catch-up gets acked again by the last_seq check.

Operation 5 reads with a strongly consistent read, because DynamoDB's default read can miss a write that just committed. Figma's 2022 write-up does the same: its new owner reads the journal only after taking ownership, with strongly consistent reads. After the claim, the old owner's next transaction fails, so the two can't both append.

Nothing leaves the owner before the append succeeds, not the ack and not the broadcast. So every revision any client holds is in the log, and a new owner can serve any reconnecting client. The transaction takes about 10 ms at p99 inside a region, an assumed figure. An operation numbered just after a 1,000th operation waits for two batches ahead of it, so it takes up to 30 ms, against a budget of 500 ms.

2. How does everyone see each other's cursors?

Presence is each person's name, colour, cursor and selection. It changes with every click, arrow key and drag, and it's worthless a second later. So it never goes in the log. WhatsApp sends online status and typing on a separate best-effort path for the same reason.

A client sends its cursor to the owner through its gateway, and the owner passes it to everyone else in the document. Nothing is stored or acknowledged. After a reconnect, the client sends its cursor again. It also resends it every 15 seconds while nothing changes. The owner drops a person who hasn't been heard from for 30 seconds. Yjs uses the same timeout for its awareness state, its name for this data.

A cursor is a position in the text, so it has to move with the text. Bob's cursor at 9 stays after the "5" only if it moves to 12 when Alice inserts "we " at the start. That's the same transform as an insert. Each cursor message carries the revision its position belongs to, and the client that gets it moves the position through any operations it has applied since.

A typist needs no cursor messages at all. Their cursor sits at the end of their own insert, and every client already has the insert. Cursor messages are for a cursor that moves without an edit: a click, an arrow key or a drag.

3. How do offline edits merge on reconnect?

The client already keeps one operation in flight and the rest pending. Offline is the same thing, for longer. The client keeps its state in IndexedDB, the browser's local database: its unacknowledged operation, and the edits typed after it composed into one pending operation. It also keeps the last revision it received, and a copy of the document at that revision. Wave's client composes pending operations the same way while it waits for an acknowledgement. The edits apply locally, so nothing looks different while offline.

On reconnect, the client sends resume with that revision. The owner sends every operation numbered since, each with its author's client_id and client_seq. If the client's own unacknowledged operation is among them, that's its ack: the owner numbered it before the connection dropped. The client moves its own operations past everyone else's, as Bob's client did in section 1. Then it carries on as usual. If its unacknowledged operation wasn't in the catch-up, it resends it under its old client_seq. It sends the composed one once that's acknowledged.

Figma's client, in its 2019 write-up, reconnects a little differently. It downloads a fresh copy of the document and reapplies its offline edits on top. For Figma's properties that means setting the values again. For text, reapplying needs the operations, not only the new copy, because an insert at 9 made on an old revision has to move past every insert numbered since.

Two cases need a rule. An insert inside a range someone else deleted lands where the deleted range was, so the offline text survives. And a user who lost edit access while offline gets a refusal. The client keeps the pending text and offers it as a new document.

The expensive case is a long time offline with many edits on both sides. Deep dive 6 sizes it.

4. How does version history work?

History is the log read back. Each operation has an author and a time, and the history view groups consecutive operations into versions. A new version starts when the author changes or after a few minutes with no edits. Each segment carries a short summary of who edited and when. So the history view reads summaries, not every operation in a big document's log, and costs nothing on the edit path. A name someone gives a version is one row in named_versions.

To show revision r, the server starts from the newest snapshot at or before r and applies the operations up to r. With a snapshot every 1,000 operations, that's at most 999 operations. Old snapshots stay in object storage for this reason.

Restoring a version doesn't rewind the log. The owner works out one operation that turns the current text into the text at r, and numbers it like any edit. Anyone typing at that moment has their edits moved past it, as they would past any other operation, and the history keeps everything, including the restore.

5. How do comments and sharing fit in?

A comment thread lives in Postgres: its text, replies and whether it's resolved. Its anchor, the range of text it's about, lives in the document as an annotation, a mark over a range of characters. Google's style operations work the same way: a bold range grows when someone types inside it. So the transforms that move text move the anchor too, with no bookkeeping of their own.

Creating a comment is two writes: an annotate operation through the owner, carrying a new anchor_id, and the thread row with that anchor_id. If the operation fails, the thread has no anchor, and the side panel shows it without a highlight.

Sharing is a role per person: viewer, commenter or editor. The docs API checks it against current grants when the client opens the document, which is the decision Auth: sessions, JWT and OAuth reaches for shared documents. The ticket carries the role to the owner.

The owner checks the role on every operation. A viewer can send none, and a commenter can send only annotate operations.

A connection outlives the check that opened it, often by hours. So a change to a grant publishes an event, and so does a revoked session. The owner of each open document then re-checks its connected users, and closes or downgrades the ones who lost access within seconds.


Deep dives

Deep dives 1, 2 and 3 come up in most versions of this interview. Deep dive 4 is the usual follow-up.

1. How many servers, and what actually needs scaling?

The system has three tiers: gateways, session servers and the hot log. Each one is sized by a different number.

Back of envelopeGateways and session servers
The question is how many of each to run, and which number
decides it. At peak: 10M clients, 5M open documents,
600,000 operations a second.

Gateways
  connections      10M / 100,000 per node (LinkedIn)  =  100

Session servers, by memory
  open documents   5M × 100 KB each, assumed  =  500 GB
  servers          500 GB / 64 GB each        ≈    8

Session servers, by CPU
  600,000/s × 20 µs to transform, apply and send, assumed
                                    = 12 s of CPU per second
  one core gives 1 s of CPU per second, so    =   12 cores

What one crash costs
  a reopen reads a snapshot, ~20 KB, and a tail of
  about 500 operations, ~50 KB                  ≈  70 KB
  on 8 servers     5M / 8 = 625,000 documents × 70 KB  ≈ 44 GB
  on 100 servers   5M / 100 = 50,000 documents × 70 KB ≈ 3.5 GB
  ─────────────────────────────────────────────────────────
Memory says 8 session servers and CPU says one. On 8, a
crash stalls an eighth of all open documents and reads
44 GB at once. Run 100, and a crash touches 1 percent.

The session servers are sized by what one failure costs, not by load, the same argument WhatsApp makes for its chat servers. The gateways are sized by connections, at 100,000 a node, the figure WebSockets, SSE and polling gives for LinkedIn's messaging servers. A gateway's crash drops its sockets. Those clients reconnect with a random delay, as the same page describes, and resume from their last revision.

The hot log is sized by writes, at 144 to 720 nodes, once a week of storage needs only 12. The docs API and the Postgres behind it see only opens and sharing changes. 10 million clients, each opening a document about every half hour, assumed, make about 5,600 opens a second. One Postgres primary with read replicas handles that.

2. What happens when a document's owner dies?

An owner holds 50,000 open documents. When its machine dies, those documents stop taking edits until another server owns them.

An owner dies, and an old one wakes up
Time runs left to right. S7 owns d_7f3a at epoch 6 and freezes (1). Its lease in etcd expires 10 seconds after its last renewal (2). S12 claims the document by raising the epoch to 7, then loads the snapshot and the tail (3). Clients resume, S12 numbers their pending edits, in purple, and others see edits again, in green (4). S7 wakes, still sure it's the owner, and appends at epoch 6. The condition fails, in red, and S7 drops the document (5).Time runs left to right. S7 owns d_7f3a at epoch 6 and freezes (1). Its lease in etcd expires 10 seconds after its last renewal (2). S12 claims the document by raising the epoch to 7, then loads the snapshot and the tail (3). Clients resume, S12 numbers their pending edits, in purple, and others see edits again, in green (4). S7 wakes, still sure it's the owner, and appends at epoch 6. The condition fails, in red, and S7 drops the document (5).
The epoch in the header row refuses the old owner's next append. Time runs left to right. S7 owns d_7f3a at epoch 6 and freezes (1). Its lease in etcd expires 10 seconds after its last renewal (2). S12 claims the document by raising the epoch to 7, then loads the snapshot and the tail (3). Clients resume, S12 numbers their pending edits, in purple, and others see edits again, in green (4). S7 wakes, still sure it's the owner, and appends at epoch 6. The condition fails, in red, and S7 drops the document (5).

Some of the recovery isn't in the figure. The gateways watch etcd, so they see the lease go and stop forwarding to the dead server. For each document they have clients in, they ask the live server that rendezvous hashing now ranks first to claim it, and every gateway picks the same one. Then each gateway tells its clients the owner changed, and they resume from their last revision, as in section 3.

Documents with no clients left need recovering too. The dead owner may not have sealed their last operations, and the hot log deletes each one 7 days after it's written. So every session server, when it starts, also writes its lease ID to a key in etcd that never expires. A lease listed there that is no longer live belongs to a dead server. Each server reads the documents that lease held from the index on lease_id, and claims the ones it ranks first for by rendezvous hashing, clients or not. It claims only if the header, read strongly consistent, still names the expired lease. It seals their unsealed operations, and closes the ones nobody has open.

The index is a global secondary index (GSI), and DynamoDB updates it asynchronously, so it can lag. And the server that ranks first may die before it finishes. So every server repeats this every minute for every dead lease on that list, and the key is deleted only after the index has listed nothing for it for an hour. A server that started after the crash finds the lease there too. Each document it finds counts toward the documents without a live owner in deep dive 7.

The clients' sockets stay up, because the gateways hold them. People keep typing the whole time, and their edits wait as pending operations. They notice only that other people's edits stop arriving for about 10 seconds, and then arrive together.

The dangerous case is an owner that isn't dead. A long garbage collection pause looks the same as a crash from outside, as replication and leader election explains. So S7 can wake still sure it owns the document, the last step in the figure. Its next transaction checks for epoch 6, finds 7, and fails. It never acknowledged that batch, so its clients resend those edits to S12. The check happens in the data store, not in S7, because S7's own view of whether it's the owner is the one thing nobody can trust.

Most changes of owner are planned, because every deploy restarts session servers. A planned move is a handover. The old owner stops numbering and waits for its last append, and the new owner claims with a higher epoch and reads the tail. The pause is well under a second.

3. The log and its snapshots: storage, history and fast open

Google's 2010 post says "To display a document, we replay the revision log from the beginning." That's the model. For a document at the 1.02 million character limit, an open can't work that way.

Back of envelopeOpening a document of 1.02 million characters
The question is what an open has to read, and whether
replaying the whole log can meet 2 seconds.

Replay every operation
  about one insert per character, if typed  1.02M operations
  with deletes and styles, say twice that   ≈  2M operations
  bytes to read          2M × 100 B         ≈  200 MB
  time to apply          2M / 1M a second, assumed  =  2 s

Snapshot every 1,000 operations
  snapshot, ~2 bytes a character with styles  ≈  2 MB
  tail, at most 999 operations × 100 B        ≈  100 KB
  time to apply          999 / 1M a second    ≈  1 ms

What the snapshots cost, for an average document
  20 KB snapshot, assumed, against 1,000 × 100 B
  of operations it covers                    =  a fifth
  operations a day     200,000 × 86,400     ≈  17.3B
  snapshots a day      17.3B / 1,000 × 20 KB  ≈  346 GB
  ─────────────────────────────────────────────────────────
Replaying from the start spends the whole 2 seconds
before reading 200 MB. A snapshot every 1,000 operations
makes the open read about 2.1 MB, and the snapshots cost
a fifth of the log they cover.

A snapshot never changes once written, and its URL names its revision: /d_7f3a/18000. So the open fetches it from object storage through a content delivery network (CDN), with a signed URL from the docs API. The owner sends only the operations after it, over the socket. The bytes of a large document never pass through the owner.

Where each part of one document's log lives
Revisions run left to right. A snapshot every 1,000 operations sits in object storage (1), with a sealed segment of the operations before it (2). DynamoDB keeps the last 7 days of operations, so for a document edited this week it holds the tail after the newest snapshot (3). An open reads the newest snapshot and that tail (4). For a document left longer, the tail comes from segments, up to the header's sealed_rev. Showing revision 16,500 reads the snapshot at 16,000 and 500 operations from a segment (5).Revisions run left to right. A snapshot every 1,000 operations sits in object storage (1), with a sealed segment of the operations before it (2). DynamoDB keeps the last 7 days of operations, so for a document edited this week it holds the tail after the newest snapshot (3). An open reads the newest snapshot and that tail (4). For a document left longer, the tail comes from segments, up to the header's sealed_rev. Showing revision 16,500 reads the snapshot at 16,000 and 500 operations from a segment (5).
Every read starts from a snapshot and replays at most 999 operations. Revisions run left to right. A snapshot every 1,000 operations sits in object storage (1), with a sealed segment of the operations before it (2). DynamoDB keeps the last 7 days of operations, so for a document edited this week it holds the tail after the newest snapshot (3). An open reads the newest snapshot and that tail (4). For a document left longer, the tail comes from segments, up to the header's sealed_rev. Showing revision 16,500 reads the snapshot at 16,000 and 500 operations from a segment (5).

Snapshots do three jobs. An open starts from the newest one. A new owner starts from it after a crash. And history builds any revision from the nearest one before it. So the log can be trimmed behind snapshots and nothing has to replay it from the start, the role a checkpoint plays in a write-ahead log.

The owner seals a segment on whichever comes first: 1,000 operations, 5 minutes after the oldest unsealed operation, or the document closing. Only the 1,000th operation also gets a snapshot. The appender ends a batch there, so every snapshot falls at the end of a batch and no batch straddles one. A background task does the upload, so a 2 MB snapshot never holds up the document's thread. The timer matters for a document edited slowly. Each row in the hot log expires 7 days after it's written, and the timer puts every operation in a segment within minutes of being numbered.

The 1,000 trades three costs. At every 100 operations, the snapshots grow to twice the size of the log they cover. At every 10,000, an open reads up to a megabyte of tail, and a new owner replays up to 10,000 operations per document. 1,000 keeps all three small. The timer and the close seal only segments, which hold each operation once, so the snapshots stay a fifth of the log.

Figma's 2022 write-up describes the same shape with different numbers. It writes a checkpoint of the whole file to S3 every 30 to 60 seconds. It recovers by loading the newest one and replaying the journal entries with higher sequence numbers.

Regions split documents rather than copy them. Each document's owner and hot log live in one region, its home, chosen where it was created, and every edit lands there. An editor on another continent waits 60 to 200 ms longer for each ack, the round trip consistency models gives, and their typing doesn't wait at all. Object storage copies snapshots and segments to a second region. Losing the home region loses at most about the last 5 minutes of each document's edits, plus whatever that copy hasn't caught up on.

4. Hot documents

Most open documents have one or two people in them. Some have thousands: a company's all-hands agenda, a public sign-up sheet, a document linked from a popular post. One owner numbers every edit for that document, and it can't be split. Contention and hot keys covers why adding machines never divides one key.

The edits aren't the problem. Say five people are typing, 15 operations a second. The problem is the 10,000 people reading. So what does each of them need?

Naive

Every viewer joins the session

Each viewer is a client like any other, and the owner sends every operation to each of them. That's 15 × 10,000 = 150,000 messages a second from one thread, plus state on the owner for every viewer. Cursors are worse: 10,000 people each seeing 9,999 cursors once a second is about 100 million messages a second.

Senior

Gateways fan out, and viewers only listen

The owner sends each operation once to each gateway with clients in the document, at most 100 gateways, so 1,500 messages a second. Each gateway writes it to its own viewers. A viewer sends no operations and holds no pending ones, so it needs no transform and no state on the owner. Only editors' cursors are shown, and viewers see a count.

This is the standard answer, and it holds at a few thousand viewers. Its cost is that every viewer still holds a socket and receives every keystroke, 150,000 frames a second across the gateways for a document most of them are only reading.

Staff

Cap the live session, and publish the document to everyone else

Question the premise that every reader needs every keystroke. Google doesn't promise it. Its help pages say up to 100 people can work in a file at the same time. Above that, only the owner and some editors can edit. For a bigger audience, Google says to publish the file as a web page.

So the live session holds at most 100 people. Everyone past that gets a published copy. Every 5 seconds while the document changes, the owner writes a snapshot, and a small latest object names it. These published snapshots are separate from the log's: they don't move snapshot_rev, and the owner takes each at the last appended revision. The CDN caches latest for 1 second. Viewers poll latest through the CDN every 5 seconds and fetch the snapshot it names. A signed cookie from the docs API means only people the document is shared with can read the copy. WebSockets, SSE and polling builds the same thing for live comments.

In numbers: 10,000 viewers polling every 5 seconds make 2,000 requests a second at the CDN's points of presence (PoPs), its serving locations. With 300 PoPs, the origin sees about 60 snapshot fetches a second, one per PoP for each new snapshot. It sees up to 300 a second for latest, one per PoP each second, whatever the audience.

A live session of 100, and everyone else on the CDN
Up to 100 people are in the live session, through gateways, and see every keystroke (1). Every 5 seconds the owner writes a snapshot and updates latest (2). Viewers past the cap poll latest through the CDN and fetch the snapshot it names (3). Each point of presence fetches each snapshot once, so the origin's load is set by the number of points of presence, whether there are 1,000 viewers or 100,000.Up to 100 people are in the live session, through gateways, and see every keystroke (1). Every 5 seconds the owner writes a snapshot and updates latest (2). Viewers past the cap poll latest through the CDN and fetch the snapshot it names (3). Each point of presence fetches each snapshot once, so the origin's load is set by the number of points of presence, whether there are 1,000 viewers or 100,000.
The owner's work stops growing with the audience. Up to 100 people are in the live session, through gateways, and see every keystroke (1). Every 5 seconds the owner writes a snapshot and updates latest (2). Viewers past the cap poll latest through the CDN and fetch the snapshot it names (3). Each point of presence fetches each snapshot once, so the origin's load is set by the number of points of presence, whether there are 1,000 viewers or 100,000.

What you give up. Viewers past the cap see the document about 5 seconds late on average and up to about 11 at worst. That's up to 5 seconds waiting for the next snapshot, 1 for latest to refresh and 5 for the next poll. They see no cursors, and they can't edit until someone leaves. For an agenda being read by a whole company, that's the right trade.

The editors are fine on one owner. 100 people typing 3 operations a second is 300 operations a second, 6 ms of CPU a second at 20 µs each. The appends are the tighter limit. A document appends one batch at a time, about 100 a second at 10 ms each, so each batch carries about 3 operations. At 4 write units a transaction, that's about 400 a second on the document's partition key, under the 1,000 a second a partition takes, a limit partitioning and sharding lists.

5. Presence fan-out, and how often to send it

In a busy document, cursors cost more than edits, because every person sees every other person. Size it at Google's cap of 100 people.

Back of envelopeCursors in a document of 100 people
The question is what presence costs when everyone sees
everyone, and what batching saves. Each client sends at
most 10 cursor updates a second, an assumed throttle.

Send each update as it arrives
  messages from the owner   100 × 99 × 10    =  99,000/s
  frames each browser receives   99 × 10     =     990/s

Batch every 100 ms, one message per client
  messages from the owner   100 × 10         =   1,000/s
  frames each browser receives               =      10/s
  each message, up to 99 cursors × ~30 B     ≈    3 KB
  ─────────────────────────────────────────────────────────
The bytes are the same either way. Batching cuts the
messages 99 times, and each browser handles 10 frames a
second instead of 990.

Two rules make cursors cheap. The client sends only its latest position, at most 10 times a second, because a cursor's old positions are worthless. And the owner collects every cursor update in a document for 100 ms, then sends each client one message with all of them.

6. Long offline edits

Tom spends a six-hour flight editing a design document. His four colleagues keep editing it on the ground. When he lands, his client gets their operations in the catch-up and has to move his edits past all of them.

Back of envelopeMerging six hours offline
The question is how long the catch-up takes. Tom makes
5,000 operations offline, at 40 places in the document.
His colleagues make 20,000 meanwhile.

Keep Tom's operations separate
  transforms          5,000 × 20,000          =  100M
  at 1 µs each, assumed                       =  100 s

Compose Tom's branch into one operation as he types
  ~80 parts: a skip and an insert per place
  transforms          20,000, one per colleague operation
  each walks ~80 parts, at 1 µs a part        ≈  80 µs
  total               20,000 × 80 µs          ≈  1.6 s
  ─────────────────────────────────────────────────────────
Composing cuts the work about 60 times, and it runs on
Tom's laptop, so his colleagues never wait for it.

Composition comes from Google Wave. Wave writes an operation as a walk over the whole document: skip 9 characters, insert "pm", skip the rest. Any two operations compose into one. Transforming two operations walks both once, so the cost grows with how many places they touch, not with how many keystrokes made them.

Rebasing six hours of offline edits
Tom's copy and the server both start at revision 18,000 (1). Tom makes 5,000 operations offline, and the server numbers 20,000 (2). Tom's client composes his 5,000 into one operation (3), downloads the server's 20,000, and moves his operation past each of them on his laptop (4). It sends one operation made on revision 38,000, which the owner numbers 38,001 with nothing left to move (5).Tom's copy and the server both start at revision 18,000 (1). Tom makes 5,000 operations offline, and the server numbers 20,000 (2). Tom's client composes his 5,000 into one operation (3), downloads the server's 20,000, and moves his operation past each of them on his laptop (4). It sends one operation made on revision 38,000, which the owner numbers 38,001 with nothing left to move (5).
Compose the offline branch, then move it past the server's operations on the client. Tom's copy and the server both start at revision 18,000 (1). Tom makes 5,000 operations offline, and the server numbers 20,000 (2). Tom's client composes his 5,000 into one operation (3), downloads the server's 20,000, and moves his operation past each of them on his laptop (4). It sends one operation made on revision 38,000, which the owner numbers 38,001 with nothing left to move (5).

The owner's part is reading 20,000 operations, from the hot log or from segments, and numbering one. It never does the merge itself. It keeps the last 1,000 operations in memory, and it transforms an arriving operation only if its base revision is among them. An older one gets a rebase reply with the operations it lacks, so the client that fell behind does the work.

7. How do you know it is working?

During an incident you need five answers fast: are edits being acknowledged, are copies the same, are owners failing over, is any document hot, and is every edit reaching object storage.

  • Time from send to ack, at p99, per region. It includes the append, so a slow log shows up here first.
  • Checksum mismatches. Each client sends a hash of its text at a revision now and then, and the owner compares it with its own at that revision. Any mismatch is a bug in a transform. The client reloads from a snapshot, and the event is a page.
  • Claims a minute, and documents without a live owner, including those the every-minute recovery finds. Many claims with no failed servers point to leases expiring on servers that are only slow.
  • Operations a second and connected people per document, top 100. A hot document shows here before its owner falls behind.
  • Cursor messages dropped. It should be zero, and it rises first when an owner is overloaded.
  • Age of the oldest unsealed operation, across the fleet. The timer seals at 5 minutes, so alert when it passes 10. A rising age means a seal is stuck, and the hot log will delete that operation 7 days after it was written.

Final design

The final design, with the path of one edit
Blue is the clients, purple the gateways and session servers on the edit path, orange the hot log, object storage and Postgres, teal the docs API and the sharing service, yellow etcd, and grey the CDN, telemetry and the copy in a second region. The badges follow the eight steps below.Blue is the clients, purple the gateways and session servers on the edit path, orange the hot log, object storage and Postgres, teal the docs API and the sharing service, yellow etcd, and grey the CDN, telemetry and the copy in a second region. The badges follow the eight steps below.
One owner per document numbers every edit, and the log is the copy that has to be right. Blue is the clients, purple the gateways and session servers on the edit path, orange the hot log, object storage and Postgres, teal the docs API and the sharing service, yellow etcd, and grey the CDN, telemetry and the copy in a second region. The badges follow the eight steps below.

One edit, end to end:

  1. The client asks the docs API to open the document. The API checks the user's role against current grants and returns a signed URL for the newest snapshot and a single-use ticket. The client fetches the snapshot through the CDN.
  2. The client opens a WebSocket to a gateway with the ticket and the snapshot's revision. The gateway reads the document's header row and checks that the lease it names is live in etcd. If not, the live server that rendezvous hashing ranks first claims the document.
  3. The owner sends the operations after the client's revision.
  4. The user types. The client applies the edit at once and sends it with its base revision, client_id and client_seq. Later edits wait as pending operations until the ack.
  5. On the document's one thread, the owner drops a resend it has already numbered, moves the operation past everything numbered after its base revision, and gives it the next revision. The next batch appends it in one transaction that checks the header still holds the owner's epoch.
  6. When the append succeeds, the owner acks the author and sends the operation to every gateway with clients in the document. Each client moves it past its own pending operations and applies it.
  7. A background task seals a segment after 1,000 operations, 5 minutes or a close, and writes a snapshot every 1,000 operations. Object storage copies both to a second region. The hot log's rows expire 7 days after they're written.
  8. Cursors travel the same way as edits, through the gateway and the owner, batched every 100 ms, and are never stored.

Each part of the design comes from one owner numbering each document's edits. The transform runs only on edits that crossed. The log is that order written down, and a failover hands the same order to a new owner. A hot document is one order with too many readers, so most of them get a copy instead.

The numbers behind the shape: 600,000 operations a second at peak fit on 8 session servers by memory, and we run 100 so a crash touches 1 percent of documents. The hot log needs 144 to 720 nodes for its writes and 12 for a week of storage, because older operations move to object storage. An open reads a snapshot and at most 999 operations, about 2.1 MB for the largest document.


What is expected at each level

How interviewers turn what they see into these levels is in How a System Design Interview Is Scored.

Mid-level

Breadth matters more than depth at this level, and it's fine to be led.

You should apply edits on the client at once, send them as operations rather than whole documents, and push changes to the other editors over a WebSocket. You should be able to work the two-insert example: one index moves, the other doesn't, and both copies end the same.

You aren't expected to raise epochs, snapshots or composition without being asked. You are expected to answer sensibly when asked "two people type in the same paragraph at once, what happens?" A good answer says who decides the order.

Senior

You drive the structure, and three things should come up without prompting.

One owner per document. Say how every editor's operations reach the same server, and what numbers them.

The log and its snapshots. Say what an open reads, and why replaying from the first keystroke fails for a big document.

What happens after a disconnect. Say what the client sends when it comes back, its last revision, and how it recognises its own operation in the catch-up. Say what stops a resend being applied twice.

Two things are disqualifying: ordering edits by client timestamps, and a design where a client waits for the server before showing a keystroke.

Staff+

A correct design is still the bar. A staff+ answer also decides what not to build.

Name the order as the problem, early. Choosing OT or a CRDT follows from who numbers the edits, and with an owner per document the transform only fixes edits that crossed.

Fence the owner. An epoch in the header row, checked in the same transaction as every append, and a strongly consistent read when a new owner takes over.

Price the long offline merge. 100 million transforms if the offline edits stay separate, against a composed rebase on the client in under 2 seconds, and an owner that refuses operations based on revisions it no longer holds.

Cap the live session. 100 people get keystrokes, and everyone else gets a snapshot through the CDN every few seconds.

Be able to say what you would not build. No CRDT when every edit already passes through a server, because its IDs cost 10 times the memory. No cursors in the log. No version history stored apart from the log. No operations kept hot forever. No live session for 10,000 readers. A team could spend a quarter on any one of these.


Sources

The figures about real systems above come from these, read for this page. The fleet sizes, rates and timings are assumptions, worked through in the worksheets where they're used.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.