Learning pathsPricingChecking sign-in…
GUIDED PRACTICE

Google Docs

Design collaborative editing for a shared document with low-latency updates, offline clients, reconnect, and durable snapshots.

Clarify this prompt before choosing components

Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.

Ask the interviewerWhy the answer changes the design
Text collaboration, comments or arbitrary document objects?Operation semantics and merging requirements change.
Offline edits, concurrent formatting and undo policy?OT/CRDT selection must match actual operations and convergence needs.
Permission revocation, history and reconnect size?Authorization, compaction and replay snapshots need explicit boundaries.

Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.

Google Docs: Understand the building blocks

Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.

Google Docs: Quick vocabulary

TermMeaning and role in this exercise
API: Application Programming InterfaceThe contract for requests, responses and errors between components. An API route does not itself enforce every business invariant.
TTL: Time to LiveAn entry/grant lifetime. Logical expiry, physical cleanup and urgent revocation are distinct conditions.
PK: Primary KeyThe declared row identity in a database schema; it does not automatically enforce every cross-row business rule.

Google Docs: Operational Transformation (OT)

What it means: A collaboration algorithm that adjusts an edit against concurrent edits accepted since its base revision. It changes the operation, not merely the order of delivery.

Why this problem needs it: Concurrent character positions must be adjusted against accepted edits.

How to use it: In the restricted central model, retain a base revision and accepted operation history, transform an incoming position, and reconcile each client’s pending edits with acknowledgements.

Example in this design: At AB, accept X at position 1, transform concurrent Y to position 2 under the declared tie rule, and produce AXYB.

When it fits: Choose it when a central document order and a fully specified edit/transform protocol fit the product.

Alternative and limits: A CRDT uses stable identities and merge rules instead. Neither acronym alone defines rich-text, undo or deletion behavior.

Mechanism reference

Google Docs: Conflict-free Replicated Data Type (CRDT)

What it means: A data type whose specified update/merge rules make replicas converge after the required updates arrive, despite permitted concurrent editing.

Why this problem needs it: Offline merge is an alternative requirement that changes the edit model.

How to use it: Use the algorithm’s character/object identities and ordering/deletion metadata. Synchronize encoded updates and recover from its supported snapshots; do not substitute timestamp sorting.

Example in this design: Stable character identities/order can support a specified merge model; do not mix its rules with the toy OT halfway through.

When it fits: Useful when offline or independently accepted edits must merge under a declared conflict policy.

Alternative and limits: A central OT model can reduce some metadata and centralize order. CRDT convergence does not grant permission or automatically preserve every user intention.

Mechanism reference

Google Docs: WebSocket

What it means: A protocol for bidirectional messages over a persistent connection after a handshake. It is a transport, not a durable message store.

Why this problem needs it: Editors exchange small operations and presence updates.

How to use it: Authenticate the session, route incoming messages to their owner, and bound outgoing buffers. Reconnect using application message IDs and cursors.

Example in this design: A live connection carries edit IDs; reconnect still needs revisioned history.

When it fits: Useful when both sides send frequent low-latency updates.

Alternative and limits: Polling is simpler at low update rates; Server-Sent Events fit one-way server updates. A new connection does not restore missed messages by itself.

Mechanism reference

Google Docs: Snapshot, retained suffix and recovery cursor

What it means: A snapshot records state at a named revision; the retained suffix contains later changes; a cursor marks a declared consumed position.

Why this problem needs it: A document needs bounded reconnect history.

How to use it: Recover from one consistent snapshot/revision and replay the necessary suffix with stable identities. Reset explicitly when required history expired.

Example in this design: Return a snapshot at revision R plus retained edits after R; reset explicitly if the needed base history expired.

When it fits: Useful to bound replay and let disconnected clients catch up.

Alternative and limits: Full replay is simpler for tiny histories. A cursor beyond unapplied events can lose updates; two unrelated reads do not form one consistent snapshot.

Google Docs: Access Control List (ACL) and current authorization

What it means: An ACL records which principals may perform specified actions on an object. Authorization evaluates the applicable current policy for this request.

Why this problem needs it: An open socket must not preserve revoked editing rights.

How to use it: Authenticate the caller, evaluate object/tenant membership and permission version at the required disclosure/mutation boundary, and declare caching/revocation behavior.

Example in this design: Recheck the applicable document permission before accepting or disclosing an edit.

When it fits: Needed when object access can change while connections, projections or cursors remain alive.

Alternative and limits: Capabilities/signed grants can fit a bounded expiry policy. A valid cursor, cached candidate or open socket is not permanent permission.

Google Docs: AB: two clients insert X and Y at position 1; OT accepts X, then transforms Y to position 2; Declared tie rule gives AXYB, not a lost edit; CRDT is an alternative merge model, not this rule
Google Docs: connect a named mechanism to the requirement and an exact exercise trace.
Read the diagram

AB: two clients insert X and Y at position 1; OT accepts X, then transforms Y to position 2; Declared tie rule gives AXYB, not a lost edit; CRDT is an alternative merge model, not this rule

Open original
Google Docs: worked example
Google Docs: AB: two clients insert X and Y at position 1; OT accepts X, then transforms Y to position 2; Declared tie rule gives AXYB, not a lost edit; CRDT is an alternative merge model, not this rule

Google Docs: connect a named mechanism to the requirement and an exact exercise trace.

Interview scope and guarantees

Edit a shared document concurrently, show collaborators, reconnect after offline edits, retain history and enforce permissions. Choose the document model before the concurrency algorithm. Plain text, rich text and nested blocks have different operation semantics.

Capacity worksheet

Assume 100,000 concurrent documents with 5 active users sending 2 operations/s: 1 million operations/s globally. At 100 bytes/operation the raw stream is 100 MB/s before fanout. One document with thousands of collaborators is a separate hot-key problem from many ordinary documents.

Concrete API contract

Contract / pseudocode
POST /documents -> {documentId}
CONNECT /documents/{id}/session {lastVersion}
operation {clientId,opId,baseVersion,payload}
GET /documents/{id}/snapshot?version=...

Data model and access paths

Contract / pseudocode
documents(id PK,owner_id,permission_version,snapshot_version,head_revision,owner_epoch)
operations(document_id,sequence,actor_id,client_id,op_id,base_version,request_hash,payload); UNIQUE(document_id,client_id,op_id); PK(document_id,sequence)
snapshots(document_id,version,object_key,checksum); PK(document_id,version)
sessions(document_id,client_id,last_ack); PK(document_id,client_id)

Evolve a solution and explain each change

Three architecture decisions for Google Docs, including the pressure each introduces.
Three architecture decisions for Google Docs, including the pressure each introduces.
Read the diagram

Centralize edits / Assign a document authority and persist a canonical revision sequence. / Concurrent offsets from old revisions cannot be applied blindly.; Choose an operation model / Use a specified OT or CRDT protocol with stable operation identity and transformation/merge rules. / Naming CRDT does not define deletion, undo, formatting, or convergence.; Recover and enforce permissions / Snapshot with a log position, replay missing operations, and recheck edit grants. / Presence messages and cursor positions are not durable content.

Open original
Google Docs · architecture decisions
Three architecture decisions for Google Docs, including the pressure each introduces.

Three architecture decisions for Google Docs, including the pressure each introduces.

Step 1: Centralize edits

Assign a document authority and persist a canonical revision sequence. Concurrent offsets from old revisions cannot be applied blindly.

Step 2: Choose an operation model

Use a specified OT or CRDT protocol with stable operation identity and transformation/merge rules. Naming CRDT does not define deletion, undo, formatting, or convergence.

Step 3: Recover and enforce permissions

Snapshot with a log position, replay missing operations, and recheck edit grants. Presence messages and cursor positions are not durable content.

Responsibility overview

Connected responsibilities for Google Docs. Trace the authoritative and derived paths separately.
Connected responsibilities for Google Docs. Trace the authoritative and derived paths separately.
Read the diagram

Editor A to Document API: submit operation ID; Document API to Merge authority: merge at base revision; Editor B to Document API: concurrent operation; Merge authority to Operation log: canonical revision log; Merge authority to Snapshot store: snapshot at revision; Document API to Operation log: replay operation suffix

Open original
Google Docs · connected architecture
Connected responsibilities for Google Docs. Trace the authoritative and derived paths separately.

Connected responsibilities for Google Docs. Trace the authoritative and derived paths separately.

Worked end-to-end scenario

Two editors start with text AB at revision 10. A inserts X between A and B; B concurrently inserts Y at the same position. In a centralized OT design, the authority orders the operations and transforms the second position using a documented tie rule, so both clients converge to the same text. A retry retains its operation ID and does not insert X twice. A disconnected client obtains a snapshot at revision R and replays operations after R. Presence can expire without changing the document. Permission revocation prevents new edits even if the client still has an open connection.

Why these access paths matter

Store document identity, permission version, snapshot revision, and ordered operations. Operations include actor, client operation ID, base revision, and payload; uniqueness scopes retries correctly. OT and CRDT are alternative protocol choices here, not interchangeable labels. A content snapshot and its revision must form one consistent recovery boundary; independent reads can lose an operation.

Build the baseline first

Google Docs: baseline request paths.
Google Docs · working baseline
Read the diagram

Client optimistic edit → document owner → operation log; Committed operation → collaborators → local reconciliation; Reconnect → snapshot plus suffix → pending edit rebase

Open original
Google Docs · working baseline
Google Docs: baseline request paths.

Google Docs · working baseline

  1. Client optimistic edit → document owner → operation log.
  2. Committed operation → collaborators → local reconciliation.
  3. Reconnect → snapshot plus suffix → pending edit rebase.

Evolve the design under load

Google Docs: additional scaling and recovery paths.
Google Docs · scale and recovery paths
Read the diagram

Document-key placement → independent collaboration owners; Periodic snapshots → bounded log replay; Presence channel → ephemeral cursor broadcasts

Open original
Google Docs · scale and recovery paths
Google Docs: additional scaling and recovery paths.

Google Docs · scale and recovery paths

  1. Document-key placement → independent collaboration owners.
  2. Periodic snapshots → bounded log replay.
  3. Presence channel → ephemeral cursor broadcasts.

Defend the hardest decision

For an OT design, transforms must preserve intended effects under concurrent operations; merely sorting arrival timestamps does not implement OT. A CRDT design uses stable identifiers and merge rules, often at the cost of metadata and tombstones. Pick one model and walk through simultaneous insertion and deletion. Presence can be best effort, but committed content must converge under replay and duplicate delivery.

Failure and recovery analysis

Two clients edit offline against the same old version. On reconnect, download a supported baseline, reconcile pending operations through the chosen algorithm and deduplicate op IDs. If the retained operation history is insufficient, the protocol needs a snapshot-based recovery path rather than silently discarding edits. Permission revocation must block new operations even on an existing socket.

Security and privacy boundary

Authorize document sessions and each mutation epoch, isolate tenants, and control access to historical snapshots.

Interview follow-ups with reasoning

Question: How do you compact history?

Show answer and explanation

Answer: Preserve the algorithm metadata and reference positions needed by supported offline clients.

Question: How do you fail over a document owner?

Show answer and explanation

Answer: Transfer a fenced epoch and replay the durable suffix.

Question: How do you validate convergence?

Show answer and explanation

Answer: Run property tests over reordered, duplicated and delayed operations.

Operate and verify the design

Operation acknowledgement lag, replay failures, pending edits and snapshot recovery time.

Reorder and duplicate concurrent edits while revoking one editor; check convergence and authorization.

A second scenario to test transfer

Alice inserts “cat” at position 5 while Bob deletes the character at position 5 from the same base version. The protocol applies both using its declared transformation or CRDT ordering, producing a deterministic result at each client. Presence cursors can move without entering the durable edit log. A reconnecting client deduplicates operation IDs.

Two clients edit the same base version offline. What must the server provide when one reconnects after operation history expires?

Show answer and explanation

Answer: A current authorized snapshot and a new version cursor, plus a reconciliation path for the client’s pending operations. The user should see a conflict or merge result if the protocol cannot safely integrate those edits. Expired history must be explicit rather than returning an incomplete operation stream.

Compare alternatives

DataDurabilityPurpose
Edit operationDurable and ordered/mergeableReconstruct document
SnapshotDurable versioned stateBound replay work
Cursor presenceShort-livedShow collaborator location
ACLAuthoritative versionProtect every sync action

A design-changing exercise

Would last-write-wins on the whole document satisfy collaborative editing?

Show answer and explanation

Answer: It can converge by discarding someone’s changes, which violates the collaborative intent. Define an operation-level conflict/merge model and prove its relevant behavior.

Design workshop: a concrete central OT protocol

Choose plain text editing with single-character insert/delete operations as the core teaching model. Rich formatting, multi-character atomic ranges and offline edits beyond retained history are extensions. This restricted model is explicit: it is not a complete Google Docs or Yjs implementation. Assume local optimistic response, ordered durable server revisions and eventual convergence after acknowledged/replayed operations.

An insert I(p,c) inserts c before zero-based position p; delete D(p) removes the character at p. An operation carries document, actor, client ID, op ID, baseRevision and payload fingerprint. The document owner serializes accepted operations into canonical revision order. It transforms an incoming operation against all accepted operations after its base. For simultaneous inserts at the same position, the already accepted server operation wins the earlier position. Clients reconcile to this order, not their local wall clocks.

python
# Transform incoming single-character operation against accepted op.
def transform(incoming, accepted):
    if incoming.kind == 'insert':
        if accepted.kind == 'insert' and accepted.pos <= incoming.pos:
            incoming.pos += 1  # accepted wins equal-position tie
        elif accepted.kind == 'delete' and accepted.pos < incoming.pos:
            incoming.pos -= 1
    elif incoming.kind == 'delete':
        if accepted.kind == 'insert' and accepted.pos <= incoming.pos:
            incoming.pos += 1
        elif accepted.kind == 'delete':
            if accepted.pos == incoming.pos: return NO_OP
            if accepted.pos < incoming.pos: incoming.pos -= 1
    return incoming

The same-position delete becomes an acknowledged no-op: it must still receive a stable result/revision mapping so a retry does not unexpectedly delete another character. Bounds are validated against the transformed current text. Log stores both base revision and canonical operation plus actor identity; request uniqueness is document/client/op, and a changed fingerprint returns 409. A valid no-op can be logged as a revision to simplify acknowledgments.

Transform against AB at base revision 7. Insert X at 1 / Insert Y at 1 -> position 2 / AXYB; Insert X at 1 / Delete original B at 1 -> position 2 / AX; Delete B at 1 / Insert X at 1 remains 1 / AX; Delete B at 1 / Delete B at 1 -> no-op / A
Transform against AB at base revision 7.
Read the diagram

First accepted operation / Incoming transformation / Final server text; Insert X at 1 / Insert Y at 1 -> position 2 / AXYB; Insert X at 1 / Delete original B at 1 -> position 2 / AX; Delete B at 1 / Insert X at 1 remains 1 / AX; Delete B at 1 / Delete B at 1 -> no-op / A

Open original
Transform against AB at base revision 7
Transform against AB at base revision 7. Insert X at 1 / Insert Y at 1 -> position 2 / AXYB; Insert X at 1 / Delete original B at 1 -> position 2 / AX; Delete B at 1 / Insert X at 1 remains 1 / AX; Delete B at 1 / Delete B at 1 -> no-op / A

Transform against AB at base revision 7.

Both clients initially see AB. A optimistically inserts X and sees AXB; B optimistically inserts Y and sees AYB. Server accepts X first as revision 8. It transforms B's Y to position 2 and accepts it as 9. Clients must replace/reconcile optimistic state using canonical acknowledgments, not append a second insertion for their own echoed operation. A simple teaching client maintains authoritative snapshot+suffix and a queue of pending intents; on server updates it reconstructs canonical text and rebases pending intents under the same deterministic protocol. Production OT clients need a fully tested pending-operation transform protocol; the server sketch alone does not prove arbitrary client transforms converge.

Concurrent inserts converge to AXYB. Editor A to Document owner: I(1,X), base 7; local AXB; Editor B to Document owner: I(1,Y), base 7; local AYB; Document owner to Revision log: Commit revision 8 I(1,X); Document owner to Revision log: Transform Y against X -> I(2,Y); commit revision 9; Document owner to Editor A: Canonical 8/9 and op acknowledgments -> AXYB; Document owner to Editor B: Reconcile own Y identity and canonical order -> AXYB
Concurrent inserts converge to AXYB.
Read the diagram

I(1,X), base 7; local AXB; I(1,Y), base 7; local AYB; Commit revision 8 I(1,X); Transform Y against X -> I(2,Y); commit revision 9; Canonical 8/9 and op acknowledgments -> AXYB; Reconcile own Y identity and canonical order -> AXYB

Open original
Concurrent inserts converge to AXYB
Concurrent inserts converge to AXYB. Editor A to Document owner: I(1,X), base 7; local AXB; Editor B to Document owner: I(1,Y), base 7; local AYB; Document owner to Revision log: Commit revision 8 I(1,X); Document owner to Revision log: Transform Y against X -> I(2,Y); commit revision 9; Document owner to Editor A: Canonical 8/9 and op acknowledgments -> AXYB; Document owner to Editor B: Reconcile own Y identity and canonical order -> AXYB

Concurrent inserts converge to AXYB.

Snapshot(text,revision) is captured consistently with the operation log. Reconnect returns snapshot S plus operations after S to a declared high watermark. Retain the suffix until all supported clients can recover or the retention policy expires. An expired base cannot be transformed without its history: return history_expired with a new snapshot. This design preserves unsent client text as a recoverable draft and asks for explicit conflict reconciliation rather than claim an arbitrary offline patch merges safely.

Resume from a consistent snapshot and operation suffix. Client to Document owner: Request reconnect using last acknowledged revision R; Document owner to Snapshot store: Read snapshot at S and durable high watermark H consistently; Snapshot store to Operation log: Load canonical operations after S through H; Document owner to Client: Return snapshot plus bounded suffix; require history_expired if R is below retention floor; Client to Document owner: Acknowledge only operations through a durable revision
Resume from a consistent snapshot and operation suffix.
Read the diagram

Request reconnect using last acknowledged revision R; Read snapshot at S and durable high watermark H consistently; Load canonical operations after S through H; Return snapshot plus bounded suffix; require history_expired if R is below retention floor; Acknowledge only operations through a durable revision

Open original
Resume from a consistent snapshot and operation suffix
Resume from a consistent snapshot and operation suffix. Client to Document owner: Request reconnect using last acknowledged revision R; Document owner to Snapshot store: Read snapshot at S and durable high watermark H consistently; Snapshot store to Operation log: Load canonical operations after S through H; Document owner to Client: Return snapshot plus bounded suffix; require history_expired if R is below retention floor; Client to Document owner: Acknowledge only operations through a durable revision

Resume from a consistent snapshot and operation suffix.

An operation log row is (document_id, revision, actor_id, client_id, op_id, base_revision, canonical_operation, fingerprint). Enforce uniqueness on (document_id, client_id, op_id) and serialize revision allocation per document owner. The fingerprint includes base revision and original intent. A retry with the same identity and fingerprint returns the original canonical operation and revision; changed payload reuse is a conflict. Even a transformed delete no-op gets an acknowledgment revision, so resending it cannot delete the next character.

For an explicit reconnect estimate, assume one hot document accepts 20 operations/s and a client is disconnected for ten minutes. That client may need 20 × 600 = 12,000 operations. At an assumed 120 bytes per canonical operation, the raw suffix is 1.44 MB before transport framing. A 1 MB replay cap means that client should receive a snapshot instead of an operation suffix. The owner is partitioned by document, but one hot document still has a serial ordering limit; distributing its edits across independent owners would invalidate this protocol.

The model in examples/system-design/google_docs.py implements this deliberately restricted protocol, snapshots/tail recovery, permissions, ephemeral presence, size bounds and owner epochs. tests/test_google_docs_model.py covers the convergence examples, no-op retries, compaction boundaries, access revocation, concurrent writers and stale-owner fencing. A production client still needs its own pending-local-intent transform tests; this server reference model does not claim a complete browser OT implementation.

A CRDT extension chooses stable character IDs and documented ordering/deletion metadata instead of offset transformations; do not mix the two models midway. If adopting Yjs, use its binary update and state-vector APIs rather than substituting this toy OT for that protocol. Yjs can merge encoded updates without loading a document, but that merge does not garbage-collect deleted content; compaction must load the document state and honor Yjs's own lifecycle. Rich-text attributes, undo and range deletes need additional transformation rules and convergence tests. This baseline excludes them honestly; their extension design must identify operation identity, range anchors and inverse intent rather than simply name CRDT.

Presence is ephemeral. Cursor positions can rebase through canonical inserts/deletes, but presence never enters the durable content log as an edit. A presence cursor at 2 moves to 3 after insertion at 1; deleted anchors need a declared nearest-valid-position rule. Permission checks apply on connect, every operation and snapshot read; a revoked editor's existing socket is not permanent authorization.

One document owner fences writes and fans out revisions. Editor socket to Document owner: Submit operation with op identity, base revision and permission context; Document owner to Durable log: Transform, allocate canonical revision and commit the operation; Document owner to Authorized sessions: Broadcast durable revision only to currently authorized sessions; Durable log to Document owner: Return operation acknowledgment after durable commit; Document owner to Editor socket: Recheck permission on every new operation, even on an open socket
One document owner fences writes and fans out revisions.
Read the diagram

Submit operation with op identity, base revision and permission context; Transform, allocate canonical revision and commit the operation; Broadcast durable revision only to currently authorized sessions; Return operation acknowledgment after durable commit; Recheck permission on every new operation, even on an open socket

Open original
One document owner fences writes and fans out revisions
One document owner fences writes and fans out revisions. Editor socket to Document owner: Submit operation with op identity, base revision and permission context; Document owner to Durable log: Transform, allocate canonical revision and commit the operation; Document owner to Authorized sessions: Broadcast durable revision only to currently authorized sessions; Durable log to Document owner: Return operation acknowledgment after durable commit; Document owner to Editor socket: Recheck permission on every new operation, even on an open socket

One document owner fences writes and fans out revisions.

The websocket is a delivery path, not the source of truth. A client may miss a broadcast after the owner commits; its reconnect cursor asks for the missing suffix. The owner epoch fences a former leader after failover: each write carries the currently issued epoch, and stale epochs cannot append even if an old process still has a network connection. Permission changes revoke existing sessions and are checked again on operation and snapshot paths.

Owner failover reads the durable head, acquires a higher document epoch and fences old write commits. An acknowledged operation survives under the selected durability contract; a lost response retries its op ID. Compaction writes a verified snapshot and only removes suffix history beyond the supported reconnect horizon. Active pending clients cannot justify indefinite retention, but expiry must be explicit.

Compaction and offline-client retention boundary. Client revision is retained / Return operations after its revision / Apply canonical suffix; Client revision is below compacted floor / Do not transform against deleted history / history_expired plus current snapshot and tail; Compaction watermark is no newer than supported minimum / Write snapshot and remove only covered prefix / Reconnect remains supported at declared floor; Offline client exceeds the declared retention horizon / Stop promising transform of its old base / Preserve local draft and request explicit rebase; Snapshot write is incomplete or checksum fails / Keep old snapshot and operation prefix / Retry compaction; acknowledge no new floor
Compaction and offline-client retention boundary.
Read the diagram

Condition / Safe action / Client response; Client revision is retained / Return operations after its revision / Apply canonical suffix; Client revision is below compacted floor / Do not transform against deleted history / history_expired plus current snapshot and tail; Compaction watermark is no newer than supported minimum / Write snapshot and remove only covered prefix / Reconnect remains supported at declared floor; Offline client exceeds the declared retention horizon / Stop promising transform of its old base / Preserve local draft and request explicit rebase; Snapshot write is incomplete or checksum fails / Keep old snapshot and operation prefix / Retry compaction; acknowledge no new floor

Open original
Compaction and offline-client retention boundary
Compaction and offline-client retention boundary. Client revision is retained / Return operations after its revision / Apply canonical suffix; Client revision is below compacted floor / Do not transform against deleted history / history_expired plus current snapshot and tail; Compaction watermark is no newer than supported minimum / Write snapshot and remove only covered prefix / Reconnect remains supported at declared floor; Offline client exceeds the declared retention horizon / Stop promising transform of its old base / Preserve local draft and request explicit rebase; Snapshot write is incomplete or checksum fails / Keep old snapshot and operation prefix / Retry compaction; acknowledge no new floor

Compaction and offline-client retention boundary.

Compaction takes a verified revision C and a declared minimum supported client revision M; require C ≤ M ≤ current_revision. Produce snapshot text exactly at C, persist it with its revision and checksum, and only then delete operations through C. The reference model checks the retention bound and reconstructs the snapshot from its prior snapshot plus canonical tail. A production implementation must make snapshot publication and log-prefix retirement crash-safe, usually by storing immutable snapshots and switching a durable pointer before asynchronous garbage collection.

Final topology and operating limits

Google Docs final topology: authority and bounded work. Edit / Per-document sequencer and revision log / Synchronous serialized append / Only canonical owner order is acknowledged; Snapshot / Immutable snapshot plus retained suffix / Async compaction through safe watermark / Never remove a prefix before snapshot commit; Live update / Authorized session gateways / Async bounded per-socket queue / Reconnect reads durable revisions; slow clients resync; Presence / Session store with expiring cursor state / Ephemeral TTL and rate cap / Presence is never durable document content; Permission / Document ACL at read/write admission / Synchronous check per operation / Existing sockets do not bypass revocation
Google Docs final topology: authority and bounded work.
Read the diagram

Path / Authority / Mode and bound / Invariant; Edit / Per-document sequencer and revision log / Synchronous serialized append / Only canonical owner order is acknowledged; Snapshot / Immutable snapshot plus retained suffix / Async compaction through safe watermark / Never remove a prefix before snapshot commit; Live update / Authorized session gateways / Async bounded per-socket queue / Reconnect reads durable revisions; slow clients resync; Presence / Session store with expiring cursor state / Ephemeral TTL and rate cap / Presence is never durable document content; Permission / Document ACL at read/write admission / Synchronous check per operation / Existing sockets do not bypass revocation

Open original
Google Docs final topology: authority and bounded work
Google Docs final topology: authority and bounded work. Edit / Per-document sequencer and revision log / Synchronous serialized append / Only canonical owner order is acknowledged; Snapshot / Immutable snapshot plus retained suffix / Async compaction through safe watermark / Never remove a prefix before snapshot commit; Live update / Authorized session gateways / Async bounded per-socket queue / Reconnect reads durable revisions; slow clients resync; Presence / Session store with expiring cursor state / Ephemeral TTL and rate cap / Presence is never durable document content; Permission / Document ACL at read/write admission / Synchronous check per operation / Existing sockets do not bypass revocation

Google Docs final topology: authority and bounded work.

Exercise: At base AB, A inserts X at 1 and B deletes B at 1. A is accepted first. What happens to B's position and final text?

Show answer and explanation

Answer: The accepted insertion at or before the delete shifts the delete to 2. Delete the original B, giving AX. Deleting position 1 without transformation would delete X and violate the intended edit.

Concurrent edits, retry, reconnect and compaction. Editor A to Document owner: Insert X at position 1 from base revision 7; Editor B to Document owner: Delete original B at position 1 from base revision 7; Document owner to Snapshot and session store: Commit X as revision 8; transform B's delete to position 2 at revision 9; Document owner to Editor B: Acknowledge both stable operation IDs; replay does not append a second edit; Editor B to Snapshot and session store: Disconnect, then reconnect with last acknowledged revision 7; Document owner to Snapshot and session store: Return snapshot plus retained suffix; if compacted past base, return history_expired; Snapshot and session store to Editor B: Rebase unsent local intent only under the same declared OT rules
Concurrent edits, retry, reconnect and compaction.
Read the diagram

Insert X at position 1 from base revision 7; Delete original B at position 1 from base revision 7; Commit X as revision 8; transform B's delete to position 2 at revision 9; Acknowledge both stable operation IDs; replay does not append a second edit; Disconnect, then reconnect with last acknowledged revision 7; Return snapshot plus retained suffix; if compacted past base, return history_expired; Rebase unsent local intent only under the same declared OT rules

Open original
Concurrent edits, retry, reconnect and compaction
Concurrent edits, retry, reconnect and compaction. Editor A to Document owner: Insert X at position 1 from base revision 7; Editor B to Document owner: Delete original B at position 1 from base revision 7; Document owner to Snapshot and session store: Commit X as revision 8; transform B's delete to position 2 at revision 9; Document owner to Editor B: Acknowledge both stable operation IDs; replay does not append a second edit; Editor B to Snapshot and session store: Disconnect, then reconnect with last acknowledged revision 7; Document owner to Snapshot and session store: Return snapshot plus retained suffix; if compacted past base, return history_expired; Snapshot and session store to Editor B: Rebase unsent local intent only under the same declared OT rules

Concurrent edits, retry, reconnect and compaction.

Operations and practice

SLIs: accepted-operation latency and rejection rate; per-document owner queue depth and lock/append time; websocket update lag; reconnect suffix length; snapshot age and compaction lag; expired-history rate; permission denial rate; and slow-session buffer drops. Measure one hot document separately from the total count of connected idle sessions.

Overload and recovery: cap document size, operation rate, transform history length, reconnect suffix bytes and per-socket queued updates. Coalesce presence and cursor updates first; never silently drop acknowledged content operations. A hot document remains serialized, so reject or backpressure edits once its owner queue exceeds the latency budget and scale by splitting unrelated documents across owners. After owner failure, acquire a higher epoch, read the durable revision head, replay committed tail, fence the old epoch and then resume sockets. If a client base is outside retained history, return the current snapshot and require an explicit rebase.

Access and cost: authorize document creation, snapshot reads, operation submission, reconnect and broadcasts by tenant/document ACL. Revoke sessions on permission change, encrypt document text, audit exports and administrative access, and rate-limit presence to avoid leaking cursor movement at excessive resolution. Durable operation history, snapshot storage, websocket connection capacity and cross-region egress are dominant costs; presence has a shorter retention horizon than content.

Practice prompt: Design collaborative plain-text editing for many documents, with ordered single-character edits, reconnect, snapshots, permissions and ephemeral cursors. State a concrete OT rule for concurrent insertion at the same position and calculate how a snapshot plus suffix bounds reconnect work.

Failure follow-up: Two clients edit from the same base, one operation is resent, a client disconnects, and the owner compacts history before it reconnects. Trace canonical text, revision identities, permission checks and the response to an expired base.

Rubric: The invariant is that every acknowledged document revision has one canonical order and replaying a client operation ID cannot create a second edit. A strong answer declares its OT or CRDT model rather than mixing them, demonstrates transform behavior, persists revision and operation identity before acknowledgment, returns snapshot plus retained suffix, refuses unsafe transforms past the retention floor, and treats presence as ephemeral. It also rechecks permissions on open sockets and fences prior owners after failover.

Yjs document updates documents a real CRDT alternative. This chapter's chosen baseline is the explicitly restricted central OT model above.

Requirement trace and verification

RequirementImplementing design blockVerification link
R1 — Complete the primary user journey within the stated scope.P01–P04; P09–P10.V1 — Exercise the successful journey and the excluded/boundary case stated in the scope.
R2 — Preserve the problem's authoritative data invariant under concurrency.P05–P06; P11–P12; DD1.V2 — Run the race/replay case below and assert the invariant at the durable authority.
R3 — Meet the declared scale and API behavior without unbounded work.P05–P08; P13–P14; relevant overload deep dives.V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity.
R4 — Recover from the named failure without losing or duplicating the user-visible outcome.P15–P16; deep dives; Operations contract.V4 — Reorder concurrent edits, resend operations, disconnect a client, and compact; replicas converge under the declared algorithm.

Operational contract

AreaDecision and signals
SLIsOperation-ack latency; document log lag; reconnect replay length; snapshot age; convergence mismatches.
Overload limitsCap document operation rate, document size, collaborator count, replay window, and snapshot workers per hot document.
RecoveryRecover from snapshot plus ordered suffix; reject stale session epochs; compact only a safe acknowledged prefix.
Access controlsCheck document permissions on connect and operation; scope presence and prevent unauthorized replay.
Dominant costOperation-log retention, snapshot storage, and hot-document fanout.

Senior-level interviewer follow-ups

Question: Two offline edits target the same text range after the base snapshot has expired. What guarantees can you make?

Show answer and explanation

Answer: The restricted single-character central OT model needs a valid base revision and canonical operation history. If required history is gone, force a resync or fork; do not claim arbitrary offline convergence.

Question: What changes if edits must continue in two regions during a partition?

Show answer and explanation

Answer: A single central sequencer cannot provide that availability. Choose a replicated CRDT or another explicit merge model, then define stable operation IDs, tombstones, permissions, and compaction costs.

A 60-second design answer

I would state the collaboration model first: this design uses a central per-document sequencer and transforms edits against a retained base revision. Operations have actor and sequence identities, snapshots bound replay, and reconnect resyncs when history expires. That is a constrained OT design, not a claim of general offline multi-region convergence. Permissions are rechecked before replay and broadcast.

Real-time Updates Dealing with Contention

Technical references

Kafka processing and external-sink boundaries.

PostgreSQL transaction isolation and concurrent updates.

Show the text an edit algorithm actually produces

Start with ab. A inserts X at position 1; B concurrently inserts Y at position 1. Declare an illustrative authoritative tie order A before B. An operational-transform design can transform B's position against accepted A so the converged text is aXYb; a CRDT design would encode stable identities/order under its own algorithm. Merely saying either acronym does not define that behavior.

Contract / pseudocode
base: ab
A: insert X at 1, op a7
B: insert Y at 1, op b8, based on same revision
chosen order/transform: aXYb
replay a7: no extra X
base: ab; A: insert X at 1, op a7; B: insert Y at 1, op b8, based on same revision; chosen order/transform: aXYb; replay a7: no extra X
Show the text an edit algorithm actually produces
Read the diagram

base: ab; A: insert X at 1, op a7; B: insert Y at 1, op b8, based on same revision; chosen order/transform: aXYb; replay a7: no extra X

Open original
Show the text an edit algorithm actually produces
base: ab; A: insert X at 1, op a7; B: insert Y at 1, op b8, based on same revision; chosen order/transform: aXYb; replay a7: no extra X

Show the text an edit algorithm actually produces

Include deletes, undo, client pending operations and snapshot/rebase rules in the real algorithm adapter; this small trace is not a complete editor implementation. Presence/cursors are ephemeral and have separate loss tolerance from durable edits. Compact accepted history only after retaining enough identity/base information for supported reconnects. Revalidate document access before accepting old offline intent; permission revocation and document deletion must not be reversed by a stale client.

Show answer and explanation

Answer: Identical starting positions need an explicit tie/transform or stable-identity rule. A server broadcasting both raw positions without the rule can leave different clients with different text.

Decision review: Google Docs

Google Docs: What it is

A collaborative text design accepts identified edits and resolves concurrent operations under a declared convergence model.

Google Docs: Why it is needed

Arrival order, offline history and current permissions must be handled explicitly; saying CRDT or OT does not specify the resulting text.

Google Docs: When to use it

Choose an operation model when character-level concurrent merging is required. Whole-document version conflict copies may suffice for simpler editing.

Google Docs: How to use it

Pin the base version and edit identity, define deterministic transformation or merge rules, retain enough operation history for replay, and reset from a snapshot under a declared policy when history is unavailable.

Google Docs: Compare an alternative

A server-ordered transform model can be easier to inspect but centralizes the accepted order. A replicated merge model changes metadata and conflict semantics; compare the same user intention and offline requirements.

Google Docs: Worked decision exercise

The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.

At text AB, A inserts X at position 1 and B inserts Y at the same base position. Under this exercise’s accepted-order tie rule, X is first and Y transforms to position 2, producing AXYB. A different rule may produce a different but explicitly defined result.

Google Docs: Base text AB; X and Y both target position 1; Accept X first: AXB; Transform Y to position 2 under declared tie rule; Result AXYB; replay uses stable edit IDs
Google Docs: a concrete state and recovery trace under the exercise assumptions.
Read the diagram

Base text AB; X and Y both target position 1; Accept X first: AXB; Transform Y to position 2 under declared tie rule; Result AXYB; replay uses stable edit IDs

Open original
Google Docs: worked example
Google Docs: Base text AB; X and Y both target position 1; Accept X first: AXB; Transform Y to position 2 under declared tie rule; Result AXYB; replay uses stable edit IDs

Google Docs: a concrete state and recovery trace under the exercise assumptions.

Can a client safely replay old edits after the server discarded their base history?

Show answer and explanation

Answer: Only with a model that supports that reconciliation. Otherwise return a current snapshot and preserve unsent local intent for explicit merge/conflict recovery. Recheck permission on reconnect; deduplication and convergence do not authorize a revoked editor.

Google Docs: Check the design

Test the actual resulting text, duplicate operations, history-reset recovery and permission changes. Define compatibility when changing the edit algorithm or operation format.

Screenshot variant: Comments and recoverable versions

Agree whether comments attach to a character range, a block or a document; whether deleted text leaves an orphaned comment; and whether restoring a version preserves later collaboration history. Keep document(id,owner,head_version), ordered/causal edit operations, periodic snapshots, comment(id,document_id,anchor,start_version,body,resolved_at) and ACL versions. Comment APIs authenticate document access and do not infer permission from knowing an anchor ID.

An anchor should survive the chosen editing model: CRDT element identities or positions transformed with accepted operations are stronger than a raw character offset. Define behavior when the anchored text is deleted: retain an orphaned thread with context, reanchor under an explicit rule or resolve it. Silent reassignment to unrelated text is a correctness bug.

For history, combine snapshots and retained operations. Reconstruct version V from an earlier snapshot plus operations through V; create a restore as a new head revision rather than erasing the log. For an illustrative document with one million 100-byte operations, raw history is 100 MB; snapshots bound replay latency at extra storage cost. Retention and deletion rules must cover old snapshots as well as current text.

Example: a comment highlights elements a7-a12. A concurrent insertion before a7 shifts visible offsets but preserves element identities, so the thread still points to the intended text. Another user deletes a7-a12; the UI shows an orphaned anchor and original context under policy. Restoring yesterday's version produces a new revision that collaborators can observe, with conflicts and history preserved according to the collaboration algorithm.

Show answer and explanation

Answer: An append-only operation log alone is insufficient unless operations contain enough information and the algorithm/version needed for replay is available. Test reconstruction, concurrent restore/edit, deleted anchors, access revocation and snapshot compaction. Monitor operation lag, reconstruction latency and anchor-resolution failures. The existing lesson's edit-order and reconnect contract remains the foundation; comments and history add state and failure cases to it.

Deep dive: stable edit identity through deletion and recovery

A collaboration design must show which text survives concurrent edits, not merely name OT or CRDT. This original exercise chooses a restricted plain-text, stable-element sequence with a single durable document admission authority. It does not describe Google's implementation or claim to solve rich-text formatting, Unicode grapheme editing or arbitrary offline collaboration. Extend those semantics explicitly before promising them.

Define the operation and dependency contract

Each inserted element has an immutable (Lamport counter, replica incarnation) identity, one predecessor identity and one character. A replica advances its counter beyond all observed counters; a new incarnation prevents reuse after lost local state. A batch has (document, generation, actor, replica, operation ID), payload hash, required dependencies and algorithm version. The authority validates size, identity ownership and document permission, then atomically records the accepted operation, receipt, next sequence and publication intent. Presence/cursor packets are ephemeral and cannot acknowledge a durable edit.

Traverse the predecessor tree depth first, visiting siblings in descending identity order with a deterministic replica tie-break. Skip a tombstoned element's character but still traverse its children. Deletion lists observed element IDs; it does not delete whatever currently occupies an old offset. This restricted representation converges for the same accepted, dependency-complete operation set. It offers no claim that every concurrent edit preserves human intent. A production sequence implementation needs an algorithm/protocol version and verified handling of batching, ordering, dependencies and all supported text operations.

Accept a referenced predecessor only when known in the current generation, including retained tombstones. Return dependency-missing without acceptance for an unknown predecessor; a client may resend after its parent commits. Bound pending client operations and bytes rather than storing unlimited unknown dependencies. A same-key changed body conflicts. A lost accepted reply returns the original receipt on compatible retry while permission still permits that disclosure. Revocation can deny receipt/content access without undoing an already committed edit.

Concurrent insertion and observed deletion preserve stable identities; compatible compaction retains dependencies and receipts before reconnect
Google Docs: recovery decision
Read the diagram

X inserts after stable element A → Concurrent delete tombstones element B → Both accepted orders preserve AXC → Compaction retains dependency and receipt evidence → Old generation requires explicit reconciliation

Open original
Google Docs: recovery decision
Concurrent insertion and observed deletion preserve stable identities; compatible compaction retains dependencies and receipts before reconnect

Google Docs: recovery decision

Work concurrent insertion and deletion by hand

Start with ABC: A=(1,S) follows root, B=(2,S) follows A, and C=(3,S) follows B. Alice observes this prefix and inserts X=(4,A) after A. Bob concurrently deletes the observed B identity. If X commits first the visible text is AXBC then AXC. If the deletion commits first the text is AC then AXC. B remains in the predecessor structure, so C is reachable; physical removal of B would break that dependency.

Now independently insert Y=(4,Z) after A, using Z>A in the declared identity ordering. Both delivery orders converge to AYXC. The tie-break is a deterministic sequence rule, not a claim that Y was typed later. If another offline writer inserts Q after tombstoned B, Q remains reachable under B; deletion of observed B does not silently delete unobserved Q. This is an intentional observed-element deletion policy. Selecting a visible range happens against a stated local version and sends its element IDs.

For a comment selecting B alone, B's deletion creates an orphaned anchor; never move it to X because X now occupies a similar offset. Store anchor element IDs, creation version, explicit boundary affinity for later insertions and minimal permitted context. For this exercise, comments highlight only selected surviving elements and show orphaned when none remain. A different range-expansion policy needs different examples. Resolving a thread changes thread state, not the underlying edit history.

Separate replay, snapshots, compaction and restoration

Use POST /documents/{id}/operations with generation, replica, operation ID, dependencies and insert/delete payload; GET .../sync?generation=G&afterSeq=S; versioned comment APIs; and POST .../restore with restore ID, expected head and selected historical version. Key tables include document head/generation/owner epoch, immutable operations and receipts, element metadata/tombstones, snapshot manifests and comments/ACL state. Sequence is authority admission order; element ordering is the sequence algorithm's rule. They are different numbers.

A snapshot manifest binds document, generation, complete sequence C, algorithm/schema, element identities, tombstones and verified content hash. Publish it only after the object is durable and verified. Tail replay starts at C+1 and cannot skip a missing C+1 because C+2 arrived. Compaction can remove replay log segments once recovery/readers/retention permit, but a snapshot of visible text alone cannot replace dependency metadata. Keep required element identities/tombstones and dedupe receipts for the advertised offline/retry horizon; garbage collection needs a proven reference/replica barrier or an explicit generation reset.

A client below the log floor receives a compatible snapshot plus suffix. If the server still retains its element dependencies and retry receipts, pending operations can reconcile under the same identities. If those guarantees expired, return resync-required with pending edits preserved locally for user review; do not blindly remap offsets or mint new operation IDs after an unknown commit. Finite retention means unlimited offline merging is outside this contract.

Restore is an expected-head conditional command creating a new durable head and generation, referencing the historical source. It never truncates accepted history. An edit committing first invalidates the restore's expected head; a restore committing first rejects old-generation new edits and requires explicit reconciliation. Preserve restored source text and historical lineage without resetting current ACLs or regranting revoked access. Existing comment anchors require an explicit mapping or orphaned presentation across generations. Do not silently merge incompatible old-generation IDs.

Enforce access and bound hot-document work

The admission decision and revocation share an authoritative permission/version boundary. If revocation wins, reject new edits even on an old WebSocket; if an edit wins, retain its accepted history. Apply current authorization to snapshots, comments, history, exports, receipt disclosure and reconnect. Closing the socket is a notification, not the enforcement mechanism. Revocation cannot erase content already downloaded; deletion/retention policy must address historical snapshots and backups separately.

Assume 100 edits/s, 200 encoded bytes/edit and twenty recipients. Raw accepted log is 20 KB/s; fanout is 400 KB/s before protocol overhead. One thousand such hot documents require 20 MB/s raw logging and 400 MB/s fanout. Snapshot every 5,000 operations bounds ordinary suffix replay to about fifty seconds of this arrival rate, but not snapshot size, retained tombstone memory or total history. A 60,000-operation recovery backlog at 250/s replay capacity with 100/s fresh arrivals needs at least 400 seconds; capacity below arrivals never catches up.

Cap participants, edit batch size, document metadata, unacknowledged bytes and per-session outbound buffers. Coalesce presence; disconnect/resync slow consumers rather than blocking durable admission. Measure accepted-to-visible lag, dependency conflicts, snapshot verification failures, orphaned anchors and stale-permission rejection. Canary algorithm versions on compatible documents; rollback cannot reinterpret committed operations under a different algorithm. The CRDT research report supplies sequence/convergence background; the admission, restoration and retention policies above are exercise choices.

Collaboration assessment: reconstruct the accepted history

Question: X is inserted after A while B is deleted. Can a server apply deletion to current offset one?

Show answer and explanation

Answer: No. Delete the observed B identity and preserve its structural descendants. Both accepted orders produce AXC in the worked example. Current offset one may now be X. Concurrent same-predecessor inserts need the declared deterministic tie-break and dependency contract.

Question: A text-only snapshot exists after compaction, and a week-old edit references a removed predecessor. Can reconnect pretend the edit is new?

Show answer and explanation

Answer: No. First resolve accepted receipts and retained element dependencies within the advertised horizon. A visible-text snapshot cannot prove either. Beyond that horizon, preserve pending local intent and require explicit resync/reconciliation rather than silently duplicating or reanchoring it.

Question: An old edit races restore and a revoked collaborator still has a socket. Which version controls admission?

Show answer and explanation

Answer: The current authoritative generation, head and ACL decision control new admission. Restore creates a new head under expected-head arbitration; it does not rewind ACLs or erase edits already accepted before it. Old sockets and historical snapshots confer no new permission.

Score one point each for identity-based sequence/deletion arithmetic; dependency-complete scoped receipts; anchored comments and compatible snapshot metadata; expected-head restore with current authorization; finite offline/fanout/recovery budgets. Deleting current offsets or silently replaying old-generation edits is a critical failure. Repair the model, then retest with a deleted predecessor that has a concurrent child and a lost accepted response just before compaction.

34:00Self-guided practice timer
The timer resets when you leave this page. Save your design separately.
Your challenge

Two clients edit the same base version offline. What must the server provide when one reconnects after operation history expires?

Your design draft

Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.

Read study notes

Self-review checklist

Self-guided practice. Automated AI feedback and code execution are not connected.