Design: collaborative editor

In one sentence

One session server per document orders every edit, transforms or merges concurrent edits (OT or CRDT), appends them to an operation log and broadcasts them; cursors travel on a separate, ephemeral presence channel.

One server per document orders, transforms and logs every op before acking; cursors take the same socket but skip the log.

How it works

  • One session server per document orders every edit with a revision number and appends it to an op log.
  • Clients apply edits locally first, then send {base_rev, op}; the server acks and broadcasts.
  • OT shifts an op past the ops it missed: simple with a central server, tricky to get right.
  • CRDTs give each character a unique id so edits commute: great offline, but heavier metadata.
  • Presence (cursors) is ephemeral and throttled; never write it to the op log.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your editor autosaves the full document text every 2 s to one DB row. Users report paragraphs vanishing when two people type at once. What's the right redesign?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: several people edit one rich-text document at once, see each other's edits and cursors live, browse version history, and keep typing offline. Non-functional: every replica converges to the same text; no acknowledged keystroke is lost; typing never waits on the network. Assume 1M concurrent editors, most documents with 1–5 at a time (Google Docs lets up to 100 people work in a file at once).

Data model and API

  • A document = latest snapshot + an append-only operation log (doc_id, rev, client_id, seq, op), where op is insert(pos, text) or delete(pos, len).
  • WebSocket: the client sends {base_rev, op}; the server acks with the new rev and broadcasts {rev, op} to the others.

Architecture

Clients apply edits locally at once, then send them. A router pins each doc_id to one session server (Consistent hashing) that holds the document in memory, gives every op a total order (rev), appends it durably, then acks and fans out. A snapshot every ~1,000 ops (assumed) keeps load time bounded. Presence (cursors, selections) shares the socket but is never logged.

The hard part: concurrent edits

Alice inserts at position 11 while Bob deletes positions 0–5, both from rev 41. Applied naively, Alice's text lands in the wrong place.

  • OT (Google Docs): the server transforms an incoming op against every op committed since its base_rev (Alice's 11 becomes 5); clients do the same with their pending ops. Simple with a central server, but transform rules multiply with each op type and are easy to get subtly wrong.
  • CRDT (Yjs, Automerge): each character gets a unique id and positions refer to neighbours' ids, so concurrent ops commute without a server. Great offline and peer-to-peer; costs per-character metadata.

Figma uses neither classic OT nor a true CRDT: its server is the authority, with CRDT-inspired last-writer-wins per property.

Code OT core: transform, order, append, broadcast
pythonOT core: transform, order, append, broadcast
from dataclasses import dataclass, replace

@dataclass(frozen=True)
class Op:
    kind: str       # "ins" or "del"
    pos: int
    text: str = ""  # inserted text
    n: int = 0      # chars deleted
    site: str = ""  # client id: breaks ties so every replica decides the same way

def transform(op: Op, prior: Op) -> Op:
    """Shift `op` so it applies after `prior`; both were made from the same rev."""
    if prior.kind == "ins":
        if prior.pos < op.pos or (prior.pos == op.pos and prior.site < op.site):
            return replace(op, pos=op.pos + len(prior.text))
        return op
    if prior.pos + prior.n <= op.pos:     # deletion entirely before op
        return replace(op, pos=op.pos - prior.n)
    if prior.pos >= op.pos:               # deletion after op: unaffected
        return op
    return replace(op, pos=prior.pos)     # op inside the deleted range (overlap cases elided)

class DocSession:                         # one per doc_id, pinned to one server
    def __init__(self, log):
        self.log = log                    # durable, append-only; rev = len(log)

    def submit(self, base_rev: int, op: Op) -> int:
        for prior in self.log[base_rev:]: # every op this client hadn't seen
            op = transform(op, prior)
        self.log.append(op)               # durable append BEFORE the ack
        broadcast(rev=len(self.log), op=op)
        return len(self.log)              # ack: the client's op is now this rev
Real example

Alice and Bob share "Hello world" at rev 41. Alice types "!" at the end (insert at 11); Bob deletes "Hello " (delete 6 chars at 0). Both apply locally and send with base_rev 41. Bob's op arrives first and becomes rev 42. Alice's insert is transformed against it: 11 − 6 = 5, committed as rev 43. Alice receives rev 42 and transforms it against her pending insert (no change, it's before); Bob receives rev 43 as insert at 5. Both read "world!". Their cursors moved on the presence channel and were never logged.

Trade-offs +3 · −3

+ You gain

  • Typing feels instant: edits apply locally and the network catches up behind the UI.
  • One server per document gives a single total order, which keeps OT, auth and history simple.
  • The op log plus snapshots give version history and crash recovery almost for free.

− You pay

  • A very popular document is a hot spot on its one server; live editors must be capped.
  • OT transform rules grow with every op type, and their bugs cause silent divergence.
  • CRDT metadata and tombstones grow with edit history, inflating memory and document size.

Use it when

Text, slides, whiteboards or design files where several people edit the same object at once and expect to see each other live.

Avoid it when

Single-writer content or form-like records: optimistic locking with a version number and a "changed by someone else, reload" message is far simpler.

Numbers to know 4
  • Load (assumed): 1M concurrent editors × ~1 batched op/s ≈ 1M ops/s in; at ~3 editors per doc, ~2M broadcasts/s out.
  • Log volume (assumed ~100 B per op): 1M ops/s ≈ 100 MB/s at peak; compact old ops into snapshots.
  • Snapshot every ~1,000 ops (assumed): opening a doc replays at most ~1,000 ops on top of it.
  • Google Docs: up to 100 people with view, edit or comment access can work in a file at once (checked Nov 2026).
Common pitfalls 4
  • Saving the whole document with last-write-wins: concurrent typists silently overwrite each other.
  • Writing cursor positions to the op log: history and write load bloat with data nobody replays.
  • Resending unacked ops after a reconnect without (client_id, seq) dedup: text appears twice.
  • Letting a doc's editors land on different servers with no single orderer: replicas diverge.
Interview questions 3

Answer out loud first, then reveal.

OT or CRDT? Defend your choice.Show answer

It hinges on offline and peer-to-peer. With a central server already enforcing auth and persistence, both converge. OT keeps ops and history compact, but every new op type needs transform rules, and those bugs surface as silent divergence. A mature CRDT such as Yjs gives commutative merges and offline for free, at the cost of per-character metadata. For a new product I'd pick the CRDT, behind a server that orders, persists and authorizes.

A document goes viral and 5,000 people open it. What breaks, and what do you do?Show answer

Its one session server: every keystroke fans out to 5,000 sockets, and every transform runs in one process. I'd cap live editors, as Google Docs does once 100 people are in a file, and serve everyone else read-only: a snapshot plus committed ops through a separate fan-out tier, batched about once a second. Presence becomes an aggregate count instead of 5,000 cursors. Editing stays fast for the people actually writing.

A session server dies mid-edit. How do you recover without losing text?Show answer

The log is the truth; the server is a cache. The router reassigns the document, and the new owner loads the latest snapshot plus the log tail. Clients reconnect, report their last acked rev and resend pending ops tagged with (client_id, seq), so the server drops anything it had already committed. Since I only ack after a durable append, no acknowledged edit is lost; unacked ones are simply resent.

Deep dive 3

OT or CRDT: what I'd pick

With a central server already doing auth, persistence and access control, both work. OT keeps ops and history compact, but every new op type (formatting, tables, comments) needs transform rules against every other, and a bug shows up as silent divergence between users. CRDT libraries such as Yjs and Automerge make merges commutative, so offline and peer-to-peer sync come for free; the price is ids and tombstones per character, which grow with edit history. Either way, convergence is syntactic: two people fixing the same typo differently both land. For a new product I'd use a mature CRDT behind a server that orders, persists and authorizes.

Op log, snapshots and recovery

The log is the source of truth and the session server is a cache. Ops are keyed (doc_id, rev) in a store partitioned by doc_id; replaying them rebuilds any version, which gives version history. Every ~1,000 ops (assumed) a snapshot goes to object storage, so opening a doc means snapshot plus a short tail. Each op also carries (client_id, seq): after a reconnect the client resends unacked ops, and the server drops ones it already committed. If a session server dies, the router reassigns the doc; the new owner loads snapshot plus tail. Only ops acked after a durable append were promised, so nothing acknowledged is lost.

Offline and reconnect

The client queues ops locally (IndexedDB) with the base_rev they were made on. With OT, on reconnect it sends them and the server transforms them against everything committed since, possibly thousands of ops; cap offline time, or rebase on a fresh snapshot. Figma's approach: download a fresh copy of the document and reapply the offline edits on top. With a CRDT, peers exchange what each is missing and merge automatically. Either way, show an "offline" badge, and surface large divergent edits in version history so users can review what merged.