Skip to content

    Frontend System Design

    Front-End Case Study: Google Docs-Style Collaborative Editor

    Design the front end of a Google Docs-style editor: input capture, operation sync, carets, undo, offline and long documents, with runnable labs.

    By Published 22 min read

    • frontend-system-design
    • case-study
    • collaboration
    • real-time
    Share

    Case studyadvancedReact labFrontend System Design

    Before this: How to Read and Reproduce a Front-End Case Study, Collaborative Editing Basics

    What you'll learn: By the end of this lesson you will be able to design the browser side of a collaborative document editor as a set of small, testable parts: an input layer that turns keystrokes into operations, a document model with a schema, a sync client that applies your own edits at once and reconciles everyone else's, a separate presence channel for carets, an undo history that only undoes your own work, a save status the user can trust, and a rendering strategy for long documents. You will also be able to run the labs that model the hard parts and walk the design through a 45-minute interview.

    This is an educational reference design, not the verified internal architecture of Google Docs or of any other product. It is a generic design assembled from public documentation (CodeMirror, ProseMirror, Yjs, MDN) and from labs you can run. Nothing here says how any named product is built. Every number marked illustrative is an assumption chosen to make the arithmetic easy to follow.

    Think of a whiteboard in a meeting room with four people holding markers. Everyone writes at the same time, nobody waits for a turn, and nobody erases another person's work by accident. The hard part is not the marker, it is the etiquette that keeps four people from writing over each other. An editor is software for that etiquette, and the front end is the part that has to keep feeling like a private notepad while it is secretly a shared whiteboard.

    The core idea

    1. The browser owns the keystroke, the server owns the order. What the user types must appear within a frame, so the client applies its own edits immediately and reconciles later. A single authority puts every edit into one history, and the client rewrites what it has not yet confirmed.
    2. Edits are operations against a version, not new copies of the text. Whole-document saves make the last writer win. Small operations, each tagged with the version they were made against, let two people's work both survive.
    3. Presence is not the document. Where someone's caret is, who is online and what they have selected are short-lived and need no history. They travel on their own channel and never enter the document history.
    4. Undo is personal. In a shared document "undo" means "undo my last step", not "undo whatever happened last", and it has to cope with someone else having changed the same place.
    5. The interface must say what is true. "All changes saved", "Saving" and "Offline, changes will sync" are claims. They must be computed from the real state of the sync client, never from a timer.

    Read three lessons first: Collaborative Editing Basics (operations, a central order, the client state machine), CRDTs and Operational Transformation and Undo, Redo and Event Sourcing in the UI. This case study does not repeat them; it decides how the pieces fit into one product front end and what each decision costs. The method (requirements, scale, architecture, deep dives, failure, evolution, interview) is the Case Study Method lesson, named here in plain text.

    Requirements and scope

    Functional requirements.

    • Several people edit one document at once and see each other's changes appear within a moment.
    • Typing never waits for the network.
    • Each person sees the other editors' carets and names.
    • Undo and Redo affect only the current person's own steps.
    • Short disconnects (a lift, a train tunnel) do not lose work, and the user can see the state of their changes.
    • Text has structure: paragraphs, headings, lists and inline formatting such as bold and links.

    Non-functional requirements.

    • No lost edits and no silent divergence: every open copy ends on the same document.
    • Local latency within one frame. At 60 frames a second a frame lasts about 16.7 ms (1000 divided by 60), so anything slower than that on the typing path is felt.
    • Accessible: keyboard operable, screen-reader friendly, and a status that is announced, not only shown.
    • A long document stays smooth to open, scroll and edit.

    Out of scope here. Comments and suggestion mode (they are anchored ranges that ride on the same position mapping), sharing and permission screens, export, and the back-end storage of history. Permissions must be enforced by the server; the interface only reflects them.

    Scale assumptions (illustrative)

    Numbers drive the design, so write them down and label them. These are assumptions for the exercise, not measurements of any service.

    Assumption (illustrative) Value Consequence
    Editors in one document at a time 10 Fan-out is bounded by a small room, not by the whole user base
    Typing rate while someone types 5 characters a second One operation per character is 50 operations a second per document
    Batching window on each client 500 ms At most 2 messages a second per client
    Messages into the server per document 10 clients x 2 = 20 a second After batching, 20 a second instead of 50
    Messages out of the server per document 20 x 10 recipients = 200 a second Each batch goes to all 10 clients, the author's copy being its acknowledgement
    Document length 400 paragraphs Rendering and memory matter more than operation rate

    Two conclusions follow. A document is a small room, so one ordering process per document is plausible, which is what the lab's server assumes. And batching trades up to one window of latency for others (never for the author) against fewer messages; the lab does not batch, which its README lists as a stretch.

    High-level architecture

    Figure 1. Editors, one ordering server, history and presence

    Collaborative editor: system overviewEditor A to Collab server (ops + revision); Editor B to Collab server (ops + revision); Editor B to Presence relay (caret); Collab server to Op history (append); Collab server to Snapshots (periodic)Editor A: local copy + pendingEditor Alocal copy +pendingEditor B: local copy + pendingEditor Blocal copy +pendingCollab server: orders + rewritesCollab serverorders + rewritesPresence relay: carets, namesPresence relaycarets, namesOp history: append onlyOp historyappend onlySnapshots: resync pointsSnapshotsresync pointsops + revisionops + revisioncaretappendperiodic

    How to read this: each editor sends operations together with the revision it made them against. The server rewrites late operations, appends them to one history and sends the result to every editor. Carets go through a separate relay that keeps no history. Snapshots let a late or reconnecting editor start from a recent state instead of replaying everything.

    CodeMirror's collaboration example describes the same shape: a central authority builds up a history of changes, each update pairs a change set with a client ID, and the length of the updates array gives the current version. ProseMirror's guide says its collaborative editing system employs a central authority which determines in which order changes are applied, and that the authority's step list length denotes its version. Both pages are the basis for treating "revision" as a plain counter in this design.

    Component deep dives

    1. Input capture: from keystrokes to operations

    A collaborative editor must know what changed, not only the new text. In a browser the natural place to learn this is the beforeinput event. MDN says it fires on input and textarea elements and on elements with contenteditable enabled, before the value is modified. Then it adds a caution that shapes the design: not every user modification results in beforeinput, and the event may fire but be non-cancelable, for example when the change comes from autocomplete, a spell-checker correction, password-manager autofill or an input method editor. The InputEvent.inputType property, MDN says, returns the type of change (insert, delete, format) and has many values such as insertText, deleteContentBackward, insertFromPaste and formatBold.

    So an input layer has two jobs. Handle the cases it understands from beforeinput and inputType, and keep a fallback that compares the document before and after (the text-area panel in the lab turns each change into operations by diffing old and new text). Never assume you saw every edit.

    Composition needs its own rule. MDN says compositionstart fires when a text composition system such as an input method editor starts a new composition session, for example when someone enters a Chinese character with a Pinyin editor. While that session is open the text on screen is provisional. A sound design is to hold back sending operations until the composition ends, and to treat the whole composed result as one edit. That rule is a design choice stated here, not something the lab implements: the lab has no composition handling.

    2. The document model and its schema

    Plain text needs two operations. A real document is a tree of blocks (paragraph, heading, list item) holding text with marks (bold, link). ProseMirror's guide says every document has a schema, that updates are decomposed into steps, and that a step can give you a map to convert positions from before to after it. Three ideas carry over:

    • A schema decides what is a valid document. An operation that would break it (a list item outside a list) is rejected at the model, not discovered by the renderer.
    • Every operation is small and typed. Insert text, delete a range, set or clear a mark, split a block, join two blocks.
    • Every operation can map a position. A caret, a selection end or a comment anchor is a position, and each operation must say how it moves one.

    Each new operation type multiplies the cases the transform function has to handle, because every pair of types needs a rule. That is a reasoning point, not a measurement: it is why teams keep the set of operations small and why the lab stops at insert and single-character delete. It is also the strongest argument for adopting a mature editor core instead of writing one.

    3. The sync client

    The sync client is a small state machine. The lab's client has three states: synchronized (nothing pending), awaiting acknowledgement (one operation in flight), and awaiting with a buffer (more local edits queued behind it). A remote operation is transformed across everything pending before it is applied, and the pending operations are transformed across it. The visible text is always the server's text plus the user's pending edits, which is why typing never waits.

    Figure 2. Inside the browser: four parts and a socket

    Editor client: input, model, sync and viewInput layer to Document model (local edits); Document model to Sync client (local ops); Sync client to Document model (remote ops); Document model to Renderer (render); Sync client to Connection (send)Input layer: beforeinput, diffInput layerbeforeinput, diffDocument model: schema + opsDocument modelschema + opsRenderer: DOM, caretsRendererDOM, caretsSync client: pending + bufferSync clientpending + bufferConnection: WebSocketConnectionWebSocketlocal editslocal opsremote opsrendersend

    How to read this: the input layer produces operations, the model applies them to the user's own copy at once and hands them to the sync client. Remote operations come back through the sync client, are transformed against pending ones, and reach the model, which tells the renderer what changed. The socket is a detail below the sync client, so it can be replaced.

    Keeping the sync client free of the DOM and the socket makes it testable: in the lab a session object holds the messages and a test delivers them in any order it wants. Transports have their own lessons (WebSockets in Depth, WebSockets, SSE and Long Polling). CodeMirror's example uses a pull loop instead: its pullUpdates request blocks until new changes arrive when the client is already at the current version. Either works as long as messages carry revisions.

    4. Carets and presence

    A caret is a position, so it moves with the same rules as text. The lab maps a caret across an operation: an insert strictly before it, or a delete strictly before it, moves it; an insert exactly at it leaves it before the new text. Other people's carets are a different problem: they are short-lived, they change many times a second, and losing one does no harm. Yjs's documentation describes this split. Its awareness feature is "a tiny state-based Awareness CRDT that propagates JSON objects to all users" for presence and cursor locations, editor bindings commonly use the cursor field for cursor locations and the user field for names and colours, awareness information is not stored in the Yjs document because it does not need to persist across sessions, and when a client goes offline its own awareness state is removed and others are told it left. Presence design is covered in Presence and Pub/Sub.

    The decision for the case study is the split itself. Carets travel on a relay with no history. They are sent as positions against a revision, mapped through later operations on arrival, and expire if a client stops sending (the Yjs page documents removal on going offline, not a timeout, so a timeout is something you add and test).

    5. Undo and redo

    A shared document breaks the single-user model of "one stack, undo the last thing". The three sources agree on the shape of the fix. Yjs's UndoManager tracks changes by transaction origin: by default every local change without an origin is tracked, and the manager merges edits made within a captureTimeout, which defaults to 500 ms. ProseMirror's history option newGroupDelay also defaults to 500 ms, and its source says the collab module tells the history when some of its content has been rebased, and that steps must be preserved exactly as they came in so they can be rebased. The lesson on undo and event sourcing builds the same idea with a log, with a 500 ms window in its lab.

    The case-study decision: the history stores the user's own steps; remote operations are passed through it so stored steps are mapped to the new document; a step that can no longer apply is refused or transformed, never half applied.

    6. Save status, offline and resync

    The status line is a promise. Derive it from the sync client: nothing pending means everything is acknowledged, pending operations mean "saving", and a connection that is down while operations are pending means "offline, changes will sync". The lab's panel shows a status region that says either "All changes acknowledged (revision N)" or how many changes are waiting for the server, and the status is a region with the status role so assistive technology can announce it.

    Figure 3. The state the status line is computed from

    stateDiagram-v2 accTitle: Save status states of the editor accDescr: Saved means nothing is pending. A local edit moves to saving. An acknowledgement of all pending operations returns to saved. If the connection drops while edits are pending the state is offline with pending changes. When the connection returns, the client resends and moves back to saving. A gap in revisions forces a resync from a snapshot, after which the state is saving or saved. [*] --> Saved Saved --> Saving: local edit Saving --> Saving: more edits Saving --> Saved: all acknowledged Saving --> Offline: connection lost Saved --> Offline: connection lost Offline --> Saving: reconnected, resend Saving --> Resync: revision gap Resync --> Saved: snapshot loaded

    How to read this: only the sync client can tell which state is true, so the interface asks it instead of keeping its own flag. The Resync state exists because a client that missed revisions cannot patch its way back; it needs a snapshot.

    Offline behaviour of the model is shown in the lab's third scenario below. Storage and merge policy are in Offline-First Apps: Sync and Conflict Resolution and the user-facing patterns in Offline UX Patterns.

    7. Rendering a long document

    The document model is data; the browser still has to lay it out. MDN says content-visibility: auto enables the user agent to skip an element's rendering work, including layout and painting, until it is needed, and that off-screen content remains in the document object model and the accessibility tree, and stays available to find-in-page, tab order navigation and selection. Its examples pair it with contain-intrinsic-size, which supplies a placeholder size so skipped content does not collapse and cause layout shift. A 400-paragraph document with each block as its own section is a natural fit. By contrast a virtualized list removes off-screen rows from the DOM, so browser find-in-page cannot find text in rows that are not rendered; that is why the case study prefers content-visibility first and virtualization only when the DOM itself becomes the problem (List Virtualization). Remote edits in a skipped block are a model update; they cost rendering only when the block is scrolled into relevance.

    Data flow

    Figure 4. One keystroke, one remote edit, from end to end

    sequenceDiagram accTitle: A local keystroke and a remote edit in the collaborative editor accDescr: The user types. The input layer creates an operation, the model applies it at once and the sync client sends it with a base revision. Meanwhile another editor's operation reaches the server first. The server rewrites the first user's operation across it, appends it and acknowledges. The first user's client receives the other operation, transforms it across its pending operation, applies it and maps the caret. participant U as User A participant C as Client A participant S as Server participant O as Editor B U->>C: types a character C->>C: operation applied to the local copy, screen updates C->>S: operation + base revision O->>S: operation + base revision Note over S: B's operation is ordered first S-->>O: ack, revision n S->>S: rewrite A's operation across B's, append S-->>C: B's operation, revision n C->>C: transform it across A's pending operation, apply, map caret S-->>C: ack for A's operation, revision n+1

    How to read this: the screen changes first and the server's answer comes later. The two operations were made against the same revision, so whichever the server orders second is rewritten. The client does the mirror-image rewrite on what it receives.

    Consistency and failure handling

    Consistency means every copy ends on the same document, not that the result is what each author meant. Failures to design for:

    • Duplicate or lost messages. A retry after a lost acknowledgement applies an operation twice unless each operation has an id the server remembers. The lab's messages carry no id, and its README says so.
    • Gaps. A client that sees a revision jump cannot repair the text; it asks for a snapshot and replays.
    • Stale rejection. CodeMirror's example warns that rejecting out-of-date pushes can starve a client with higher latency whose peers keep submitting, and recommends rebasing whenever practical.
    • Silent divergence. Compare a hash of each client's text with the server's at intervals and treat a mismatch as an incident.

    Build it

    Three published labs model the hard parts; nothing new was needed for this case study.

    • examples/frontend/labs/collab-editing-basics: server-ordered OT for plain text, a three-state client, caret mapping, a thin React text area with a status region.
    • examples/frontend/labs/undo-event-sourcing: an append-only log with undo and redo as events, time-window coalescing and refusal when someone else changed the same item.
    • examples/frontend/labs/crdt-basics: the CRDT side and an OT model for comparison.
    cd examples/frontend/labs/collab-editing-basics
    ../../node_modules/.bin/vitest run   # 29 tests, including 200 + 100 seeded random sessions and the React panel in jsdom
    node src/demo.ts
    
    cd ../undo-event-sourcing
    ../../node_modules/.bin/vitest run   # 20 tests
    node src/demo.ts

    Illustration 1: the minimal example

    Two people act on "abc" at once. One inserts "x" at the start, the other deletes the last letter.

    Expected output, captured from a real run (the first scenario of the collab-editing-basics demo):

    1. Insert and delete at the same time, on "abc" (a inserts "x" at 0, b deletes the "c")
      without transformation               server="xac"  a="xac"  b="xab"
        server history                     1: insert(0, "x"); 2: delete(2)
      with transformation                  server="xab"  a="xab"  b="xab"
        server history                     1: insert(0, "x"); 2: delete(3)

    Without rewriting the server deleted the wrong letter and the copies differ. With it, the second operation is stored as delete(3) and all three copies hold "xab".

    Illustration 2: the realistic example

    Picture a runbook that a duty engineer, offline in a data centre, and an online manager edit at once. The lab's offline scenario has the same shape.

    Expected output, captured from a real run (the third scenario of the collab-editing-basics demo):

    3. One client offline (text "milk eggs"; b edits twice while offline, a edits twice and its edits go through first)
      b has 2 unacknowledged changes; only the first is in flight
      edits made                           server="milk eggs"  a="milk, eggs bread"  b="buy milk eggs!"
      a's edits delivered, b offline       server="milk, eggs bread"  a="milk, eggs bread"  b="buy milk eggs!"
      b reconnects, all delivered          server="buy milk, eggs bread!"  a="buy milk, eggs bread!"  b="buy milk, eggs bread!"
        server history                     1: insert(4, ","); 2: insert(10, " bread"); 3: insert(0, "buy "); 4: insert(20, "!")

    Both people's edits are in the result. The offline client's "!" was typed at position 13 and landed at 20 because seven characters were added before it. This is also where the status line earns its keep: while b is offline the interface must say that two changes are waiting, which is exactly the lab's pending count.

    Illustration 3: a failure and an edge

    The failure that surprises users is undo after someone else touched the same thing. The undo lab models a picking list, not text, but the rule transfers: an inverse that no longer fits the current state is refused whole, not half applied.

    Expected output, captured from a real run (the sixth scenario of the undo-event-sourcing demo):

    === 6. undo after someone else changed the same item (a remote event reaches the log)
      local 3, remote sets 5 [milk=5]  log 3
      undo "milk to 3"       refused: QtyChanged does not fit the current state: quantity is 5, the event expects 3
      after the refusal      [milk=5]  log 3  undo depth 2 (nothing was half-applied)

    Refusing is safe but unfriendly. The stretch exercise of that lab is to transform the inverse across the remote change, which is what collaboration-aware histories do for text. The edge case on the text side is that every copy can agree and still be wrong for the authors. Two people typing "ABC" and "123" at the same place end with A1B2C3 when each character is its own message. No copy diverged and nobody wrote that.

    Expected output, captured from a real run (the last scenario of the collab-editing-basics demo):

    6. 200 seeded random sessions (3 clients, 40 steps, random delivery order)
      with transformation      200 of 200 converged, 0 threw while applying, 3225 edits in total
      without transformation   0 of 200 converged, 81 threw while applying, 2858 edits in total

    Verified. Both demos' tests passed and each block above is a verbatim excerpt of a golden file (examples/frontend/golden/collab-editing-basics.txt, examples/frontend/golden/undo-event-sourcing.txt). The React tests ran in jsdom, a JavaScript model of the DOM: no real typing, IME composition, layout, caret drawing or screen reader was observed. The labs cover plain text and a list, not rich text, and they have no network, no presence and no duplicate protection.

    Trade-offs

    Decision Gain Cost Choose when
    Server-ordered OT Simple order, small state, plain server One ordering point per document; transform rules grow with operation types Online-first, bounded room size
    CRDT library (Yjs-style) No central order; Yjs states that documents sync as long as all changes eventually arrive, whatever the order Extra state and a library to adopt Offline-heavy or peer-to-peer
    One operation per message Easy to reason about More messages, as the scale table shows Prototype
    Batching window Fewer messages Others see edits up to one window later Busy rooms
    Hold input during composition Fewer provisional operations More code in the input layer Any IME language
    content-visibility for long documents Skips off-screen rendering, keeps find-in-page and accessibility tree Needs placeholder sizes; support and behaviour must be checked per browser Long structured documents
    Refuse stale undo Never corrupts Annoying Early versions
    Transform stale undo Friendlier More logic and more tests Mature product

    Alternatives considered

    • Locks per paragraph. Simple, but people wait, and a lock held by a closed tab blocks others until it expires.
    • Last writer wins on the whole document. Silently drops edits, the problem this design exists to avoid.
    • CRDT first. Reasonable when long offline editing is a core promise. Both families still need this lesson's input capture, status line, presence and undo.

    Cross-cutting concerns

    Security. Treat everything arriving over the connection as untrusted, operations included: validate against the schema and the user's role on the server. Map pasted HTML into the schema and drop what it does not allow. The client may hide controls; the server decides.

    Accessibility. Announce the save status with a status region, keep keyboard shortcuts for formatting, Undo and Redo, and never let a remote edit steal focus or move the user's caret unexpectedly. See Keyboard, Focus and Screen Readers and Accessible Forms and Dynamic Content.

    Observability. Track pending count and age, resyncs, rejected operations, reconnects, hash mismatches and input-to-paint time (INP and Responsiveness).

    Cost. Client memory grows with document size and undo history, so cap the depth; server memory grows with history until a snapshot lets it be trimmed. Set both limits by measurement.

    Evolution path

    1. Version 1: plain text, a server-ordered model, a status line (what the labs model).
    2. Version 2: a schema, rich-text operations, composition handling, local-only undo.
    3. Version 3: persisted pending operations, operation ids, snapshots and resync.
    4. Version 4: comments anchored with the same position mapping; reconsider a CRDT if long offline sessions dominate.

    Interview outline (45 minutes)

    Minutes Topic What a strong answer includes
    0 to 5 Requirements Typing never waits, no lost edits, presence, undo, offline; says what is out of scope
    5 to 10 Estimates A small room per document; fan-out arithmetic; batching trade-off
    10 to 20 Architecture Client applies its own edits, server orders, revisions, history and snapshots
    20 to 30 Deep dive Transform of insert and delete, three-state client, carets, or the CRDT alternative
    30 to 38 Failure Duplicates, gaps, stale undo, silent divergence, IME
    38 to 45 Evolution and trade-offs OT versus CRDT, rich text, observability

    In practice: the incident runbook editor

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    An operations team keeps its incident runbooks in an internal web page. During an incident two or three people edit the same runbook; today each Save sends the whole page and the last save wins. Responders report that lines they added "disappeared".

    Starting architecture

    Figure 5. Starting point: whole-page saves

    Starting architecture: last whole-page save winsResponder 1 to Pages API (PUT); Responder 2 to Pages API (PUT); Pages API to Page row (overwrite)Responder 1: edits pageResponder 1edits pageResponder 2: edits pageResponder 2edits pagePages API: PUT whole pagePages APIPUT whole pagePage row: one valuePage rowone valuePUTPUToverwrite

    How to read this: the warning box replaces the stored page with whatever arrives last, so a save made from an older copy erases everything added since that copy was loaded.

    Options considered

    Option What it fixes What it costs Risk
    Lock the page for one editor No lost edits Waiting; a stuck lock during an incident Locks held by closed tabs
    Server-ordered operations (this lesson) Both edits kept, typing never waits History, transform code, resync Transform bugs
    A CRDT library No central order A dependency and larger state Format lock-in

    The decision

    Field Decision record
    Context Two or three people edit one structured page; a server is always in the loop; offline is rare and short.
    Decision Server-ordered operations over the existing real-time connection, a revision on every message, snapshots to resync, a status line computed from the sync client.
    Consequences, good Both responders' edits survive; the sync client is testable without a browser.
    Consequences, bad History must be kept; retries need operation ids; input method editors need explicit handling.
    Revisit when Long offline sessions or very large rooms become common.

    Rollout and verification

    1. Test the transform and the client with scripted message orders and seeded random sessions, as the lab does.
    2. Dark-launch by recording operations while the old whole-page save still runs, and compare final texts.
    3. Verify accessibility by checking that the status region announces changes in a real screen reader (the labs cannot show this).
    4. Watch divergence hash mismatches, pending age and resync counts from day one.

    The 2 a.m. failure

    A responder on a bad connection types for several minutes, sees "3 changes waiting", and closes the laptop. The edits are in memory only and are gone. First three checks: (1) was the pending list persisted anywhere; (2) did the interface make the waiting state impossible to miss; (3) does an operation id exist so a resend on the next open is safe. Mitigation: persist pending operations locally and resend with ids on the next open (State Persistence and Synchronization). Follow-up: a test that kills the client with pending operations and restores it.

    Architect's notes

    • Make the sync client a pure module. If it can run without a DOM or a socket, you can test the ugly message orders.
    • Never rely on seeing every input event. beforeinput can miss changes or be non-cancelable; keep a diff-based fallback.
    • Keep presence out of the document. It is cheap, disposable and noisy.
    • Decide the undo rule before the editor. Local-only, mapped through remote changes, refused or transformed when stale.
    • Name the limits. Maximum room size, history depth, document length: each needs a stated number, chosen with measurement, not a guess.

    Common mistakes

    • Sending whole documents and calling it collaboration.
    • Making the author wait for the acknowledgement before showing a keystroke.
    • Computing the save status from a timer instead of the sync client.
    • Storing carets in the document history.
    • Sharing one global undo stack.
    • Ignoring input method editors until a user reports garbled text.
    • Hiding off-screen content in a way that breaks find-in-page and screen readers.

    Key takeaways

    • The browser applies its own edits at once; one authority orders everything.
    • Operations carry the revision they were made against; late ones are rewritten.
    • Presence is a separate, history-free channel.
    • Undo is personal and must survive other people's edits.
    • The status line is computed from the sync client, never guessed.
    • beforeinput is not a complete record of changes; composition needs its own rule.
    • Long documents are a rendering problem as much as a sync problem.

    Practice exercises

    Exercise 1: Starter (30 min). Run the collab-editing-basics demo. For the offline scenario, work out by hand why the final "!" lands at position 20, then say what the status line should read at each step.

    Exercise 2: Intermediate (3 hours). Extend the lab's text area panel so it never sends while an IME composition is in progress (simulate with compositionstart and compositionend events in a test). Decide what happens to the pending diff when the composition ends.

    Exercise 3: Advanced (1 day). Make the undo lab's refused step transform its inverse across the remote change for the list item case. Write down which cases still have to be refused.

    Exercise 4: Interview (45 min). Whiteboard this design from the outline above and defend OT against a CRDT for a product whose users edit on trains.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments