Real-time collaboration in frontend system design: OT, CRDTs (Yjs, Automerge), presence and server ordering

Design multiplayer editing: OT vs CRDTs, Yjs and Automerge, presence and cursors, undo, offline merge, persistence, permissions and scaling rooms.

Advanced 14 min readBy , updated 23 November 2026

"Design Google Docs", "design a Figma-style canvas" and "design a collaborative whiteboard" are among the hardest frontend design prompts, because they combine a rich editor, a real-time transport, a conflict-resolution algorithm and a backend that keeps it all consistent. Interviewers do not expect you to derive a CRDT on the whiteboard. They expect a clear architecture, a reasoned choice between operational transformation (OT) and CRDTs, and good answers to the follow-ups: cursors, undo, offline edits, history, permissions and what happens when a thousand people open the same document. This guide covers each in turn.

Pin down the requirements first

Collaboration covers very different products, and the right design depends on which one you are building. Ask:

  • What is shared? Plain text, rich text with formatting, a structured document of blocks, a spreadsheet grid, or a canvas of shapes with properties.
  • How many people edit at once? Two to ten active editors is the common case. A hundred viewers watching one presenter is a different problem from a hundred people typing.
  • Is offline editing required? A few seconds of flaky Wi-Fi is not the same as a week on a plane.
  • What latency is expected? Your own keystrokes must appear instantly. Other people's changes within a fraction of a second is usually enough.
  • Is history needed? Version history, named versions and restore change how you store data.
  • Who can do what? Viewers, commenters, editors, and whether access can be revoked mid-session.

Write the answers down. "Rich text, up to about twenty concurrent editors, short offline periods, version history, three roles" is a design you can draw.

The architecture

 ┌──────────────────────── browser tab ───────────────────────────┐
 │  Editor (ProseMirror, Lexical, CodeMirror, canvas)             │
 │     ▲ render              │ local edits                        │
 │     │                     ▼                                    │
 │  Editor binding ◀──▶ Local document model (OT doc or CRDT)     │
 │                           │  ▲                                 │
 │   Awareness (cursors,     │  │ remote updates                  │
 │   selections, who is here)│  │                                 │
 │     │                     ▼  │         IndexedDB copy          │
 │  Sync provider: one WebSocket per document ◀──▶ (offline)      │
 └─────┬──────────────────────────────▲───────────────────────────┘
       │ document updates + presence  │ broadcast to the room
       ▼                              │
  Collaboration server: one room per document
   ├─ authenticates and authorises each connection
   ├─ orders (OT) or relays and merges (CRDT) updates
   ├─ fans out to everyone in the room
   └─ persists: update log + periodic snapshots ──▶ storage

The rule that shapes everything: local edits apply immediately. The editor never waits for the server before showing a keystroke. The local model changes, the UI updates, and the change goes out in the background. Remote changes arrive later and must merge into a document that has already moved on. OT and CRDTs are two answers to "how do we merge so everyone ends up with the same document?"

Presence travels on the same connection but is a separate channel with different rules, covered below. The transport is usually a WebSocket, because edits flow in both directions continuously; real-time updates compares it with SSE and polling, and covers reconnect backoff.

Operational transformation

In OT, every edit is an operation against positions: "insert x at 5", "delete 3 characters at 10". A central server keeps the authoritative document and a revision number. When a client sends an operation based on revision 41 but the server is already at 43, the server transforms the incoming operation against operations 42 and 43, shifting its positions so the user's intent is preserved, applies it as revision 44, and broadcasts it.

The client side follows a well-known state machine. At most one operation is in flight to the server. Edits made while waiting are composed into a buffer. When the server acknowledges, the buffer is sent. When a remote operation arrives, the client transforms it against its in-flight and buffered operations before applying it, and transforms those operations against it in turn. Building OT for plain text with a server history and a buffering client implements exactly this.

OT's strengths come from the central server. Operations are small, the server sees every change in order, so validation, permissions and an audit log fall out naturally, and the document carries no per-character metadata. Google Docs is the well-known OT product. Its weaknesses are the transform functions, which are easy to get subtly wrong once you add rich text, tables and moves, and its dependence on the server: long offline sessions mean transforming a large buffer against a large history on reconnect.

CRDTs

A CRDT (conflict-free replicated data type) is a data structure designed so that replicas which have seen the same set of changes are in the same state, whatever order the changes arrived in. For text, sequence CRDTs give every inserted character a unique id (a client id plus a counter) and anchor it to its neighbours' ids rather than to a numeric position, so "insert after character alice:17" means the same thing on every replica. Deletes mark characters as removed (tombstones) instead of erasing them, so later edits that refer to them still resolve. Implementing a text CRDT (RGA) shows the idea, and building state-based CRDTs covers counters, sets and maps.

Because merges commute, clients can exchange updates through any route: a server, a peer-to-peer connection, or a file synced days later. That makes CRDTs the natural fit for offline-heavy and local-first apps. The costs are metadata per item, tombstones that accumulate, and a harder time enforcing invariants, since any replica can produce any valid update and the merge will accept it.

Side by side

OT CRDT
Who decides the order A central server Nobody needs to; merges commute
Offline editing Possible, but rebasing long offline work is painful Natural
Peer to peer Impractical Supported
Metadata cost Small Ids and tombstones per item, well compressed by libraries
Validation and permissions Easy: the server sees and can reject every operation Harder: enforce at the boundary of whole documents or updates
Implementation risk Transform functions for rich types Use a mature library rather than writing one

The OT vs CRDT answer goes deeper on the algorithms.

You still want a server

A common interview mistake is "CRDTs, so no server". In a product you still run one: it authenticates users, enforces permissions, persists the document, fans out updates so clients do not need to talk to each other, and gives a single place to take snapshots. With a CRDT the server does not need to transform anything, but it is still the hub. Some products go further and use the server as the authority for a simpler model. Figma has written that its multiplayer system is not OT and is inspired by CRDTs, with the server as the central authority and last-writer-wins per property on each object, which suits a canvas where two people rarely edit the same property of the same shape at the same moment. That is a valid answer for a canvas prompt; text needs a sequence algorithm.

Yjs and Automerge

You will not implement a production CRDT in an interview or at work. Name the libraries and what they give you.

Yjs provides shared types (Y.Text, Y.Array, Y.Map, and XML types for rich text) inside a Y.Doc. Updates are compact binary messages. Two replicas sync by exchanging state vectors, a summary of what each has seen, then sending only the missing updates. Around the core are bindings for editors (ProseMirror, CodeMirror, Monaco, Quill and Lexical, among others), network providers such as y-websocket and y-webrtc, y-indexeddb for a local copy, an awareness protocol for presence, and an undo manager.

import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";
import { IndexeddbPersistence } from "y-indexeddb";

const doc = new Y.Doc();
new IndexeddbPersistence(`doc:${docId}`, doc); // instant load from disk, and edits survive going offline
const provider = new WebsocketProvider("wss://collab.example.com", docId, doc, { params: { token } });

const body = doc.getText("body");
const undo = new Y.UndoManager(body); // undoes this client's changes, not remote ones

provider.awareness.setLocalStateField("user", { name: me.name, color: me.color });
provider.awareness.on("change", () => renderCursors(provider.awareness.getStates()));

Automerge models a whole document as JSON-like data (maps, lists, text, counters) with its complete change history, so you can inspect, diff and branch past versions. Its core is written in Rust and compiled to WebAssembly for the browser, and automerge-repo adds storage and network adapters. It suits local-first apps where history and offline work are central.

Choosing between them in an interview: Yjs has a large ecosystem of editor bindings and is a common choice for rich-text collaboration; Automerge is attractive when the document is structured data and full history matters. Either is a better answer than a home-made algorithm.

Presence, awareness and cursors

Presence is "who is here, where is their cursor, what have they selected". It is different from document data in three ways:

  • It is ephemeral. Do not persist it or put it in the document history. When someone leaves, their state disappears.
  • Only the latest value matters. If ten cursor positions are queued, send the last one. Throttle updates to a fixed rate and interpolate on receivers so remote cursors glide rather than jump.
  • It must time out. A tab that closes without saying goodbye should vanish after a short period without heartbeats. Yjs's awareness protocol handles this, removing clients that stop updating.

Cursor positions must survive concurrent edits. A cursor at "index 120" is wrong as soon as someone inserts text above it. Anchor cursors and selections to positions in the document model instead: Yjs offers relative positions (Y.createRelativePositionFromTypeIndex) that stay attached to the same character as text moves around them, and OT systems transform cursor positions with each operation. On a canvas, presence is usually the pointer in document coordinates plus the ids of selected objects.

At scale, presence is noisier than edits. In a room with many viewers, send presence only for active users, cap how many remote cursors you draw, and let viewers' presence be coarse ("40 viewing"). Designing an embeddable presence and live cursors SDK is a full practice prompt, and building a collaborative rich-text editor with remote cursors combines it with editing.

Undo in a multiplayer document

Single-user undo pops the last change off a stack. In a shared document that is wrong: pressing Ctrl+Z must undo your last change, not the sentence a colleague just typed. So:

  • Keep an undo stack per user, per tab, containing only local changes.
  • Undo by applying the inverse of your change as a new change, transformed (OT) or resolved (CRDT) against everything that happened since. You never roll the shared document back in time.
  • Group keystrokes into one undo step by time and by type of action, so undo removes a word or a paste, not one character.
  • Accept that some undos cannot fully apply. If you undo inserting a paragraph that someone else has since edited, the result keeps their edits.

Y.UndoManager implements this for Yjs: it tracks changes by transaction origin, so changes from the network provider are not undone, and it merges changes made within a short window into one step. Version history is a separate feature built on snapshots, not on undo. Undo and redo with the command and memento patterns covers the single-user foundation.

Offline edits and merging

Keep a local copy of each open document in IndexedDB. The editor loads from it instantly, edits keep working when the connection drops, and on reconnect the client and server exchange what the other is missing. With a CRDT this is the normal sync path, just with a larger delta. With OT, the client rebases its buffered operations onto the server's history, which works for short gaps and becomes slow and fragile for long ones.

Convergence is not the same as a good result. Two people who each rewrote the same paragraph offline will get a merged paragraph containing both sets of edits, interleaved in a way neither intended. Tell users when a large merge happened, and make version history easy to reach so they can recover. For records rather than text, simpler strategies such as per-field last-writer-wins are often better; the offline-first sync guide covers the outbox, IndexedDB pitfalls and those simpler strategies.

Persistence and compaction

A collaborative document is naturally stored as a log of updates, but replaying a year of keystrokes to open a document is too slow. The usual design:

  • Append updates to a log as they arrive, so nothing acknowledged is lost.
  • Snapshot periodically (every N updates or when the room goes idle): store the full current state and truncate or archive the log before it. Opening a document loads the latest snapshot plus the updates after it.
  • Compact. Yjs can merge many updates into one (Y.mergeUpdates) and garbage-collects the content of deleted items by default, keeping only small tombstones. If you need full version history, keep snapshots at points you care about rather than disabling compaction everywhere.
  • Keep derived views separate. Search indexes, previews and exports are built from snapshots asynchronously, never from the live room on the request path.

Permissions

Authorise at connection time: the client presents a short-lived token for a specific document, and the server checks the user's role before joining them to the room. Then enforce on every message:

  • Viewers receive updates and send presence, but the server drops any document update they send.
  • Commenters write to a separate comments structure, not to the document body.
  • Editors can send updates.

With OT the server can inspect and reject individual operations. With a CRDT, per-field rules inside one document are hard to enforce, because an update is a merged bundle of changes. Draw permission boundaries at the document level: if some content needs different access rules, put it in a separate document. When access is revoked mid-session, the server closes that user's connection and the client discards its local copy. Never trust the client to hide edit controls as the only protection; the frontend security guide covers why.

Scaling rooms

All the clients editing one document need to exchange updates quickly, which shapes the backend:

  • Route by document. Send every connection for a document to the same server process, for example with consistent hashing on the document id. That process holds the room in memory and is the single place updates are ordered or merged. The alternative, rooms spread across processes joined by a pub/sub bus, works but adds latency and ordering complexity.
  • Load and unload rooms. The first client to join loads the snapshot and log; when the last leaves and updates are persisted, the room is evicted from memory.
  • Survive a restart. When a room's server dies, clients reconnect with backoff and jitter to the new owner, which reloads from storage and exchanges deltas with each client. Because every client also has the document locally, nothing acknowledged is lost.
  • Handle huge audiences differently. A thousand viewers of one document should not each receive every keystroke the moment it happens. Batch updates to viewers, send coarse presence, and consider a read-only fan-out tier in front of the room.
  • Keep the room's memory in check. Very large documents, such as long transcripts or big canvases, may need splitting into sub-documents that load on demand.

Designing a Miro-style collaborative whiteboard and a Figma-style canvas editor apply all of this to canvases.

How to talk about it in an interview

Interviewers want to see that you can separate the pieces and choose deliberately. A strong structure:

  1. Requirements: data type, concurrent editors, offline expectations, history and roles.
  2. Architecture: draw the editor, local model, sync provider, presence, room server and storage. State that local edits apply first.
  3. Merge strategy: OT with a central server, or a CRDT library such as Yjs or Automerge, and the reason tied to the requirements. For a canvas, consider server-authoritative per-property last-writer-wins.
  4. Presence: ephemeral, throttled, interpolated, anchored to document positions, timed out.
  5. Undo, offline and history: local undo of your own changes, an IndexedDB copy, snapshots plus a log.
  6. Permissions and scale: authorise per room, drop viewers' updates, route each document to one process, reconnect with jitter.

Name the trade-off you chose: "a CRDT costs memory and makes per-field permissions hard, which is acceptable because offline editing is a requirement and permissions are per document". Designing Google Docs collaborative editing is the prompt to rehearse on.

Follow-up questions

Why not just use last-write-wins for the whole document?

Because two people typing in different paragraphs would overwrite each other's work: one save would replace the other. Last-writer-wins is fine per property on a canvas object or per field on a record, where concurrent edits to the same value are rare and one winner is acceptable. Text needs a sequence algorithm, OT or a CRDT, so concurrent inserts and deletes all survive.

Do CRDTs remove the need for a server?

No. They remove the need for a server to order and transform edits. You still want one to authenticate users, enforce permissions, persist and snapshot documents, and fan updates out to clients efficiently. Peer-to-peer sync is possible with CRDTs, but most products use it only as an optimisation or not at all.

How do remote cursors stay in the right place while others type?

Store them as positions in the document model rather than as numeric offsets. In Yjs, relative positions stay attached to a character as text is inserted or deleted around it. In OT, cursor offsets are transformed with every operation. Send cursor updates on the ephemeral presence channel, throttled, and interpolate on the receiving side.

How does undo work when several people are editing?

Each user undoes only their own changes. Undo applies the inverse of the change as a new edit, resolved against everything that happened since, rather than rolling the shared document back. Keystrokes are grouped into larger steps, and an undo that conflicts with someone's later edit keeps their edit.

What happens to tombstones and the update log over time?

They grow. Snapshot the document periodically and archive or truncate the log behind each snapshot. Libraries compress metadata heavily, and Yjs discards deleted content by default, leaving small markers. If you need version history, keep snapshots at chosen points rather than an infinite log.

How would you handle a document with a thousand simultaneous viewers?

Separate viewers from editors. Editors stay in the room and exchange updates at full speed. Viewers receive batched updates and coarse presence, perhaps through a read-only fan-out tier, and their own presence is reduced to a count. Route all editors of the document to one room process so ordering and merging stay in one place.

Practise it

Each question opens in an editor with tests, so you can check your understanding by writing the code.

  1. Design Google Docs: collaborative editing with CRDT or OT, cursors, and conflict resolutionHard60 min
  2. Build a collaborative rich-text editor with remote cursors and offline synchronizationHard90 min
  3. Build operational transformation for plain text: compose, transform, a server history and a client that buffers editsHard70 min
  4. Implement a text CRDT (RGA) for collaborative editingHard60 min
  5. Build state-based CRDTs: a PN-counter, an add-wins OR-Set without tombstones and a last-writer-wins mapHard60 min
  6. Design an embeddable presence and live cursors SDK: transport, throttling, interpolation, privacy and scalingHard55 min
  7. Design a collaborative whiteboard like Miro: infinite canvas, shapes, presence, conflict-free edits and performanceHard60 min
  8. Design a Figma-style canvas editorHard60 min