Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Case studies · Lesson 35 of 44

Case study: design a collaborative editor

A senior-level walkthrough of a collaborative editor such as Google Docs: why positions break, operational transformation, a sequence CRDT, a room per document, logs, snapshots, retries and crashes, in tested C# with an interactive story.

Case studyApplied39 min readUpdated

  • 1 architecture diagram
  • 1 sequence flow
  • 2 data models
  • 2 API designs
  • 11 code samples
  • 8 interviewer follow-ups
  • 2 decision checkpoints
  • 4 self-checks

Read first: A framework for system design interviews, Consistency and availability, Replication and sharding

By the end you will be able to
  • A position is an address that moves. Two people editing at once send positions that were right when written and are wrong when they land, and nothing reports the error. In the test, a relay that forwards edits untouched left the two screens different in 4,536 of 5,000 random collisions.
  • Operational transformation rewrites each edit past the edits it had not seen, in an order a server decides, and a sequence CRDT gives every character a permanent name so edits commute. Both ended identical in all 5,000 runs. The price is a single point of order for OT, and tombstones and names for the CRDT (3,350 cells kept for 700 visible letters when edits are scattered).
  • Scale by the unit of contention. Edits conflict only inside one document, so each document is a room with one writer, a log written before any acknowledgement, a snapshot every few hundred edits, and ids that make retries safe.
  • Choose between OT and a CRDT by constraint, not taste: a server per document and mostly online favours server order, offline or peer-to-peer favours names, and structured data such as a design file needs neither a text algorithm nor more than one value per property.

11 code samples (478 lines), collapsed so the explanation stays in focus.

A collaborative editor looks like one document that several people edit. It is really one copy per person, each of which must show what its owner typed at once, and all of which must end up identical. Typing cannot wait for a server: past about a tenth of a second, an interface stops feeling instant, so every edit applies locally first and the network catches up afterwards. That single decision creates the whole problem, because two people can now change the same text before they hear about each other.

If you learn better by watching, the Story button in the corner of the screen opens this case study as a twelve-minute scroll: two people, one sentence, three designs that break and the one that works. This lesson is the full version, with measured code and the questions an interviewer asks. The numbers in the story and in this lesson come from the same experiments.

HLD

Clarify the collaborative editing problem

Spend the first minutes on questions. Each answer changes the design.

AskWhy it matters
Plain text, rich text, or structured data such as a canvas?Text needs a sequence algorithm. Formatting adds spans that must survive edits. A design file is mostly independent properties, and one value per property is enough
How many people edit one document at once, and how many only watch?Order is per document, so editors set the load on one room. Viewers only receive, so they scale through a separate broadcast tier
Must it work offline, or between devices with no server?A day offline is a long queue to rewrite for OT and a plain merge for a CRDT. Peer-to-peer rules out a central sequencer
What must never happen?Two screens that disagree, an edit changing meaning, an edit lost after it was acknowledged, a letter typed twice
What else rides along?Cursors and selections, comments anchored to ranges, undo, version history and permissions. Each interacts with the editing model
How fast must others' edits appear?Your own typing must be instant. Others' should land within a couple of hundred milliseconds, which is where the network round trip sits

A good scope for 45 minutes: plain text with formatting as attributes, up to about a hundred simultaneous editors per document and thousands of viewers, online first with graceful offline, durable history, and presence for cursors. Mention comments, suggestions and spreadsheets as extensions.

HLD

Estimate: edits are cheap, presence and fan-out are not

State assumptions out loud. They are illustrative and the interviewer may change them.

Example · estimate
open:         10M documents open at peak (assumed)
typing:       5% have someone typing = 500,000 active documents
typists:      1.5 per active document = 750,000 people typing
edits:        1.5 messages a second each (bursts batched) = ~1.1M a second
edit size:    ~100 bytes on the wire = ~110 MB/s in, spread across a fleet
one room:     ~2 edits a second on average; a hot one: 100 editors, ~150/s
log:          1.1M x 100 B = ~9.5 TB a day before composing keystrokes
              composing runs of typing into one stored edit: ~1-2 TB a day
presence:     2M people moving a cursor x 5 updates = ~10M a second
              ~40 bytes each, lossy, never stored
connections:  20M open sockets / 50,000 per gateway = ~400 gateways
rooms:        10M loaded rooms / 20,000 per host = ~500 hosts, x2 headroom

Five conclusions:

  1. One document is a small problem. Even a hot room handles a few hundred edits a second, which one thread does with room to spare. The work is not throughput per document.
  2. The total is large and partitions perfectly. A million edits a second is only a fleet-sizing question when no two documents ever need each other.
  3. Presence outweighs edits. Cursor updates are several times the number of edits, so they must be cheap, droppable and never written to the log.
  4. The log is the storage bill. Composing a run of keystrokes into one stored edit, and snapshotting, are what keep it affordable.
  5. Latency has two budgets. Local typing must not touch the network at all. Remote edits get the round trip, and a page that waits for the server per key press has already lost.

LLD

The editing contract and data model

A client opens one long-lived connection to a gateway, and everything below rides on it. Edits and acknowledgements are ordered by the connection and carry the ids that make a retry safe.

GET/documents/{id}/session
auth
bearer token, checked on connect and again when permissions change
upgrade
a WebSocket, which carries everything below
client
sends { clientId, seq, baseRev, op }
server
sends { ack: seq, rev } to the author, { rev, by, op } to everyone else
note
one edit in flight per client; the next waits for its acknowledgement
GET/documents/{id}?rev=latest
returns
{ rev, body, lastSeqByClient } from the newest snapshot, then the log after it
note
a client that reconnects asks for what it missed, or for a snapshot if it is too far behind
doc_opsappend-only log, partitioned by document
  • doc_iduuid

    PKSHARD KEY
  • revbigint

    1, 2, 3 ... assigned by the room, no gaps

    PK
  • client_iduuid

    INDEX
  • client_seqint

    per client, increasing; (doc, client, seq) is unique

  • opblob

    a composed edit: retain, insert and delete runs

  • created_attimestamptz

Written before the author is told the edit happened.

doc_snapshotsevery few hundred edits
  • doc_iduuid

    PKSHARD KEY
  • revbigint

    PK
  • bodyblob

    the text and its formatting at that revision

  • last_seqjson

    per client: the newest edit it has had applied, for retries

Recovery loads the newest snapshot and replays the log after it.

HLD

The high-level design of a collaborative editor

Fig. A collaborative editor: a room per document
Fig. A collaborative editor: a room per document
Fig. One edit, from key press to the other screen
Fig. One edit, from key press to the other screen

Read it as a loop around one room. The room is the single writer for its document: it numbers every edit, rewrites an edit written against an older revision, writes it to the log, and only then acknowledges the author and tells everyone else. The directory says which host holds a document's room and makes sure there is only ever one. The gateway holds the sockets and is otherwise stateless. Presence rides a separate, lossy channel, and viewers are served from a broadcast tier that never orders anything. Everything interesting happens in the first three deep dives, so the rest of the design only has to protect them.

LLD

Deep dive: why positions break

The simplest edit is a position and a change: insert this text before position 7, delete the letter at position 7. It is what an editor does locally, and it works while one person types. The trouble starts when two edits are written against the same text and applied to texts that have since changed.

C# · Edits as positions16 lines
using System;

abstract record Op;
sealed record Ins(int Pos, string Text) : Op;
sealed record Del(int Pos) : Op;
sealed record NoOp : Op;

static class Editor
{
    public static string Apply(string doc, Op op) => op switch
    {
        Ins i => doc.Insert(Math.Min(i.Pos, doc.Length), i.Text),
        Del d when d.Pos >= 0 && d.Pos < doc.Length => doc.Remove(d.Pos, 1),
        _ => doc,
    };
}
C#12 lines
using System.Diagnostics;

string typo = "THE CATT";
Op alice = new Del(7);         // Alice removes the second T
Op bob = new Ins(0, "SEE ");   // Bob adds a word at the start, at the same moment

// Each screen applies its own edit at once, then the other person's edit exactly as it was written.
string aliceScreen = Editor.Apply(Editor.Apply(typo, alice), bob);
string bobScreen = Editor.Apply(Editor.Apply(typo, bob), alice);
Console.WriteLine($"Alice: {aliceScreen}   Bob: {bobScreen}");
Debug.Assert(aliceScreen == "SEE THE CAT");
Debug.Assert(bobScreen == "SEE THECATT");   // position 7 had become the space

Alice's screen is right and Bob's is not. By the time her message arrived, Bob's insert had moved every letter four places to the right, so position 7 was the space after THE, which vanished while the typo survived. Nothing failed. Nothing was logged. Two screens now disagree and neither one knows, and every later edit builds on a different text.

Before the fix, commit to one answer.

Decision checkpoint · pick one

Two people edit one sentence at the same time and their screens end up different. What is the first change?

Commit to an answer first. The reasoning for every option appears after you pick.

The two cheap fixes fail in instructive ways. A lock turns typing into a request, and the story shows the delay as the S that appears long after the key press. Overwriting with the last whole copy converges and loses work: in the same story both screens agree on SEE THE CATT, and Alice's fix is gone. That is the lesson of this section. Convergence is necessary but not sufficient. The second property is intention: each edit must still mean what its author meant.

LLD

Deep dive: operational transformation with a server that orders edits

Operational transformation (OT) keeps positions and repairs them. A function Transform(op, other) rewrites op so that it means the same thing after other has been applied. Bob inserted four letters before position 7, so Alice's delete 7 becomes delete 11. It is a rebase for edits, the same move as git rebase: replay an edit's intention on top of whatever happened since it was written. The idea goes back to Ellis and Gibbs in 1989.

C# · Transform13 lines
static class Ot
{
    // op, rewritten to apply after `other`. On a tie, `opFirst` says who keeps the left spot.
    public static Op Transform(Op op, Op other, bool opFirst) => (op, other) switch
    {
        (NoOp, _) or (_, NoOp) => op,
        (Ins a, Ins b) => b.Pos < a.Pos || (b.Pos == a.Pos && !opFirst) ? a with { Pos = a.Pos + b.Text.Length } : a,
        (Ins a, Del b) => b.Pos < a.Pos ? a with { Pos = a.Pos - 1 } : a,
        (Del a, Ins b) => b.Pos <= a.Pos ? a with { Pos = a.Pos + b.Text.Length } : a,
        (Del a, Del b) => b.Pos < a.Pos ? a with { Pos = a.Pos - 1 } : b.Pos == a.Pos ? new NoOp() : a,
        _ => op,
    };
}

Four cases cover it: an insert and an insert, an insert and a delete, a delete and an insert, and two deletes, where deleting the same letter twice becomes a no-op. The tie rule matters: if both people insert at the same spot, somebody must go first, and every screen must make the same choice. The rule is whichever edit the server numbered first keeps the left spot.

Why does it converge? Draw the two orders as the two sides of a diamond. Apply Alice's edit and then Bob's rewritten one, or Bob's and then Alice's rewritten one: both roads end at the same text. That property is called TP1, and it is the one thing the function has to keep for every pair of edits.

A server turns this into a protocol, and that is what keeps it simple. The server numbers edits in the order it handles them and rewrites each incoming edit past every edit committed since the revision the client had seen. Each client keeps one edit in flight, applies its own typing immediately, and rewrites incoming edits past its own unsent ones, so its pending edits stay valid as news arrives. All the rewriting runs against one line of history, which is why a central server makes OT tractable. Peer-to-peer OT has to be right for every order of arrival, a second property usually called TP2, and several published algorithms were later shown to violate it.

C# · A server and a client69 lines
using System.Collections.Generic;
using System.Linq;

sealed record Msg(string Id, Op Op, int Base);                         // what a client sends
sealed record Commit(int Rev, string Id, string By, Op Op, Op Sent);   // what the server decided

sealed class OtServer
{
    public string Doc;
    public readonly List<Commit> Log = new();
    readonly Dictionary<string, int> seen = new();
    public OtServer(string doc) { Doc = doc; }

    public Commit Receive(Msg m, string by)
    {
        if (seen.TryGetValue(m.Id, out int known)) return Log[known - 1];   // a repeat changes nothing
        Op op = m.Op;
        for (int i = m.Base; i < Log.Count; i++) op = Ot.Transform(op, Log[i].Op, opFirst: false);
        Doc = Editor.Apply(Doc, op);
        var commit = new Commit(Log.Count + 1, m.Id, by, op, m.Op);
        Log.Add(commit);
        seen[m.Id] = commit.Rev;
        return commit;
    }
}

sealed class OtClient
{
    int n;
    public readonly string Name;
    public string Doc;
    public int Rev;
    public Msg Inflight;                         // at most one edit waits for the server
    public readonly List<Msg> Buffer = new();    // later edits wait behind it
    public OtClient(string name, string doc) { Name = name; Doc = doc; }

    public Msg Local(Op op)                      // typing: apply now, send if nothing is in flight
    {
        Doc = Editor.Apply(Doc, op);
        var m = new Msg($"{Name}#{++n}", op, Rev);
        if (Inflight == null) { Inflight = m; return m; }
        Buffer.Add(m);
        return null;
    }

    public void Remote(Commit c)                 // someone else's numbered edit: rewrite it past ours, then apply it
    {
        Op incoming = c.Op;
        var rewritten = new List<Msg>();
        foreach (var p in Inflight == null ? new List<Msg>() : Buffer.Prepend(Inflight).ToList())
        {
            rewritten.Add(p with { Op = Ot.Transform(p.Op, incoming, opFirst: false) });
            incoming = Ot.Transform(incoming, p.Op, opFirst: true);
        }
        if (rewritten.Count > 0) { Inflight = rewritten[0]; Buffer.Clear(); Buffer.AddRange(rewritten.Skip(1)); }
        Doc = Editor.Apply(Doc, incoming);
        Rev = c.Rev;
    }

    public Msg Ack(int rev)                      // the server numbered our edit: the next one may go
    {
        Rev = rev;
        Inflight = null;
        if (Buffer.Count == 0) return null;
        Inflight = Buffer[0] with { Base = Rev };
        Buffer.RemoveAt(0);
        return Inflight;
    }
}

Messages are immutable records on purpose. A client that rewrites its pending edit in place, when that same object is also the message already on the wire, passes every hand-written test and then diverges under random interleavings. A real network copies, so a model of one must too.

How do you know it is right? You do not, until you try to break it. A fuzz harness makes two people each write one to three edits before hearing from the other, then delivers messages in a random order, and asks one question: do the two screens end identical?

C# · A fuzz harness122 lines
using System.Text;

sealed class Rng                                  // mulberry32: the same generator and seeds as the story
{
    uint a;
    public Rng(uint seed) { a = seed; }
    public double Next()
    {
        a += 0x6D2B79F5u;
        uint t = a;
        t = (t ^ (t >> 15)) * (t | 1u);
        t ^= t + (t ^ (t >> 7)) * (t | 61u);
        return (t ^ (t >> 14)) / 4294967296.0;
    }
}

record Change(bool Insert, int Index, string Text)
{
    public Op ToOp() => Insert ? new Ins(Index, Text) : new Del(Index);
}

static partial class Fuzz
{
    const string Letters = "abcdefghijklmnopqrstuvwxyz";

    public static string Word(Rng r, int n)
    {
        var sb = new StringBuilder();
        for (int i = 0; i < n; i++) sb.Append(Letters[(int)(r.Next() * 26)]);
        return sb.ToString();
    }

    public static Change RandomChange(Rng r, int len)
    {
        if (len == 0 || r.Next() < 0.55)
        {
            int index = (int)(r.Next() * (len + 1));
            int n = 1 + (int)(r.Next() * 2);
            return new Change(true, index, Word(r, n));
        }
        return new Change(false, (int)(r.Next() * len), "");
    }

    // A starting text and the edits each of two people makes before hearing from the other.
    public static (string Start, List<Change>[] Plans, int Edits) Collision(Rng r)
    {
        string start = Word(r, 5 + (int)(r.Next() * 4));
        var plans = new[] { new List<Change>(), new List<Change>() };
        int edits = 0;
        foreach (var plan in plans)
        {
            int k = 1 + (int)(r.Next() * 3);
            string local = start;
            for (int i = 0; i < k; i++)
            {
                var c = RandomChange(r, local.Length);
                plan.Add(c);
                local = Editor.Apply(local, c.ToOp());
            }
            edits += k;
        }
        return (start, plans, edits);
    }

    // A relay that forwards every edit untouched.
    public static (string, string) Naive(string start, List<Change>[] plans)
    {
        var docs = new[] { start, start };
        for (int s = 0; s < 2; s++) foreach (var c in plans[s]) docs[s] = Editor.Apply(docs[s], c.ToOp());
        for (int s = 0; s < 2; s++) foreach (var c in plans[1 - s]) docs[s] = Editor.Apply(docs[s], c.ToOp());
        return (docs[0], docs[1]);
    }

    // The server orders and rewrites; a random channel that has something to deliver goes next.
    public static (string, string) Ot(string start, List<Change>[] plans, Rng r)
    {
        var server = new OtServer(start);
        var clients = new[] { new OtClient("alice", start), new OtClient("bob", start) };
        var up = new[] { new List<Msg>(), new List<Msg>() };
        var down = new[] { new List<Commit>(), new List<Commit>() };
        for (int s = 0; s < 2; s++)
            foreach (var c in plans[s]) { var m = clients[s].Local(c.ToOp()); if (m != null) up[s].Add(m); }
        var sent = new int[2];
        var got = new int[2];
        while (true)
        {
            var ready = new List<int>();
            for (int s = 0; s < 2; s++) if (sent[s] != up[s].Count) ready.Add(s);
            for (int s = 0; s < 2; s++) if (got[s] != down[s].Count) ready.Add(2 + s);
            if (ready.Count == 0) break;
            int pick = ready[(int)(r.Next() * ready.Count)];
            if (pick < 2)
            {
                var commit = server.Receive(up[pick][sent[pick]++], clients[pick].Name);
                down[pick].Add(commit);       // the author hears it as an acknowledgement
                down[1 - pick].Add(commit);   // everyone else hears it as news
            }
            else
            {
                int s = pick - 2;
                var commit = down[s][got[s]++];
                if (commit.By == clients[s].Name) { var m = clients[s].Ack(commit.Rev); if (m != null) up[s].Add(m); }
                else clients[s].Remote(commit);
            }
        }
        return (clients[0].Doc, clients[1].Doc);
    }

    public static (int Diverged, int Edits) Run(string design, int runs, uint seed)
    {
        int diverged = 0, edits = 0;
        for (int i = 0; i < runs; i++)
        {
            var r = new Rng(seed + (uint)i);
            var (start, plans, n) = Collision(r);
            edits += n;
            var (a, b) = design switch { "naive" => Naive(start, plans), "ot" => Ot(start, plans, r), _ => Crdt(start, plans) };
            if (a != b) diverged++;
        }
        return (diverged, edits);
    }
}
C# · The diamond: the two orders end at the same text.26 lines
// The diamond: the two orders end at the same text.
Op aliceRewritten = Ot.Transform(alice, bob, opFirst: false);   // delete 7 becomes delete 11
Op bobRewritten = Ot.Transform(bob, alice, opFirst: true);      // insert at 0 is unchanged
string leftRoad = Editor.Apply(Editor.Apply(typo, alice), bobRewritten);
string rightRoad = Editor.Apply(Editor.Apply(typo, bob), aliceRewritten);
Debug.Assert(aliceRewritten == new Del(11) && leftRoad == "SEE THE CAT" && rightRoad == leftRoad);

// The same property on 20,000 random pairs of edits.
var pairs = new Rng(11);
int broken = 0;
for (int i = 0; i < 20000; i++)
{
    string text = Fuzz.Word(pairs, 1 + (int)(pairs.Next() * 8));
    Op x = Fuzz.RandomChange(pairs, text.Length).ToOp();
    Op y = Fuzz.RandomChange(pairs, text.Length).ToOp();
    string viaX = Editor.Apply(Editor.Apply(text, x), Ot.Transform(y, x, opFirst: false));
    string viaY = Editor.Apply(Editor.Apply(text, y), Ot.Transform(x, y, opFirst: true));
    if (viaX != viaY) broken++;
}
Debug.Assert(broken == 0);

// 5,000 random collisions, two people each, delivered in random orders.
var naive = Fuzz.Run("naive", 5000, 7);
var ot = Fuzz.Run("ot", 5000, 7);
Console.WriteLine($"{naive.Edits} edits in 5,000 runs: the relay ended with different screens {naive.Diverged} times, OT {ot.Diverged}");
Debug.Assert(naive.Edits == 20167 && naive.Diverged == 4536 && ot.Diverged == 0);

A relay that forwards edits as written ended with different screens in 4,536 of 5,000 random collisions, about 91%. With a server that orders and rewrites, it never did, and that is the point of running it: the harness finds the bug that a few hand-picked examples miss. Real systems send lists of retain, insert and delete runs, so a burst of typing is one edit. The transformation is more work and the idea is the same.

LLD

Deep dive: a sequence CRDT and what names cost

A CRDT removes the problem instead of repairing it: stop using addresses that move. Every character gets a permanent name the moment it is typed, and an insert says after this named character instead of at position 7. Deleting names the character too. Neither edit mentions a position, so neither can invalidate the other, and they commute: they can arrive in any order and land in the same place.

The sequence algorithm used here is RGA (a replicated growable array). A name is a counter and a site, so two names always compare. An insert goes immediately after its anchor, but skips past any following letter with a larger name, which are inserts made concurrently at the same place, so every replica makes the same choice with no server. A delete only marks the letter dead: a tombstone.

C# · A sequence CRDT64 lines
readonly record struct Id(int C, string S)
{
    public bool Outranks(Id o) => C > o.C || (C == o.C && string.CompareOrdinal(S, o.S) > 0);
}

abstract record CrdtOp;
sealed record CIns(Id Id, Id? Anchor, char Ch) : CrdtOp;
sealed record CDel(Id Id) : CrdtOp;

sealed class Cell { public Id Id; public char Ch; public bool Dead; public Id? Anchor; }

sealed class Rga
{
    readonly string site;
    int clock;
    public readonly List<Cell> Cells = new();

    public Rga(string site, string start)            // every starting letter is named by the origin, "o"
    {
        this.site = site;
        clock = start.Length;
        for (int i = 0; i < start.Length; i++)
            Cells.Add(new Cell { Id = new Id(i + 1, "o"), Ch = start[i], Anchor = i == 0 ? null : new Id(i, "o") });
    }

    public string Text() => new string(Cells.Where(c => !c.Dead).Select(c => c.Ch).ToArray());

    public List<CrdtOp> Insert(int index, string text)   // each new letter names its left neighbour
    {
        var visible = Cells.Where(c => !c.Dead).ToList();
        Id? anchor = index > 0 ? visible[Math.Min(index, visible.Count) - 1].Id : null;
        var ops = new List<CrdtOp>();
        foreach (char ch in text)
        {
            var op = new CIns(new Id(++clock, site), anchor, ch);
            Integrate(op);
            ops.Add(op);
            anchor = op.Id;
        }
        return ops;
    }

    public CrdtOp Delete(int index)                      // the name stays, the letter goes
    {
        var cell = Cells.Where(c => !c.Dead).ElementAtOrDefault(index);
        if (cell == null) return null;
        cell.Dead = true;
        return new CDel(cell.Id);
    }

    public bool Knows(CrdtOp op) =>                      // can this edit be applied yet?
        op is CIns i ? i.Anchor == null || Cells.Any(c => c.Id.Equals(i.Anchor)) : Cells.Any(c => c.Id.Equals(((CDel)op).Id));

    public void Integrate(CrdtOp op)                     // from anywhere, in any order that respects "after"
    {
        if (op is CDel d) { var dead = Cells.Find(c => c.Id.Equals(d.Id)); if (dead != null) dead.Dead = true; return; }
        var ins = (CIns)op;
        if (Cells.Any(c => c.Id.Equals(ins.Id))) return;
        int at = ins.Anchor is Id a ? Cells.FindIndex(c => c.Id.Equals(a)) + 1 : 0;
        while (at < Cells.Count && Cells[at].Id.Outranks(ins.Id)) at++;   // concurrent inserts with larger names go first
        Cells.Insert(at, new Cell { Id = ins.Id, Ch = ins.Ch, Anchor = ins.Anchor });
        clock = Math.Max(clock, ins.Id.C);
    }
}
C# · A harness for the CRDT: convergence and cost45 lines
static partial class Fuzz
{
    public static (string, string) Crdt(string start, List<Change>[] plans)
    {
        var reps = new[] { new Rga("alice", start), new Rga("bob", start) };
        var sent = new[] { new List<CrdtOp>(), new List<CrdtOp>() };
        for (int s = 0; s < 2; s++)
            foreach (var c in plans[s])
                if (c.Insert) sent[s].AddRange(reps[s].Insert(c.Index, c.Text));
                else { var d = reps[s].Delete(c.Index); if (d != null) sent[s].Add(d); }
        for (int s = 0; s < 2; s++) foreach (var op in sent[1 - s]) reps[s].Integrate(op);
        return (reps[0].Text(), reps[1].Text());
    }

    static char Letter(Rng r) => Letters[(int)(r.Next() * 26)];

    // What a CRDT keeps: cells (letters and tombstones), and runs, the stretches a store can keep as one entry.
    public static (int Inserts, int Deletes, int Visible, int Items, int Tombstones, int Runs) Cost(string kind, int edits, uint seed)
    {
        var r = new Rng(seed);
        var doc = new Rga("alice", "");
        int inserts = 0, deletes = 0, cursor = 0;
        for (int i = 0; i < edits; i++)
        {
            int visible = doc.Text().Length;
            if (kind == "typing")                      // left to right, with some backspacing
            {
                if (visible > 0 && cursor > 0 && r.Next() < 0.12) { doc.Delete(cursor - 1); cursor--; deletes++; }
                else { doc.Insert(cursor, Letter(r).ToString()); cursor++; inserts++; }
                if (r.Next() < 0.01) cursor = (int)(r.Next() * (doc.Text().Length + 1));
            }
            else if (visible > 0 && r.Next() < 0.45) { doc.Delete((int)(r.Next() * visible)); deletes++; }
            else { int index = (int)(r.Next() * (visible + 1)); doc.Insert(index, Letter(r).ToString()); inserts++; }
        }
        int runs = 0;
        Cell prev = null;
        foreach (var c in doc.Cells)
        {
            bool joins = prev != null && c.Id.S == prev.Id.S && c.Id.C == prev.Id.C + 1 && c.Anchor.Equals(prev.Id) && c.Dead == prev.Dead;
            if (!joins) runs++;
            prev = c;
        }
        return (inserts, deletes, doc.Text().Length, doc.Cells.Count, doc.Cells.Count(c => c.Dead), runs);
    }
}
C# · A letter is deleted on one screen while someone types after it on another. The tombstone…44 lines
// A letter is deleted on one screen while someone types after it on another. The tombstone lets the second edit land.
var one = new Rga("alice", "THE CATT");
var two = new Rga("bob", "THE CATT");
var removeT = one.Delete(7);              // Alice removes the second T, named o8
var typeS = two.Insert(8, "S");           // Bob types an S after it
foreach (var o in typeS) one.Integrate(o);
two.Integrate(removeT);
Debug.Assert(one.Text() == "THE CATS" && two.Text() == "THE CATS");
Debug.Assert(one.Cells.Count == 9 && one.Cells.Count(c => c.Dead) == 1);   // the T is still there, unseen

// Three people edit at once; one new replica receives all of it in 100 random orders that respect "after".
var authors = new[] { new Rga("alice", "THE CAT"), new Rga("bob", "THE CAT"), new Rga("carol", "THE CAT") };
var everything = new List<CrdtOp>();
everything.AddRange(authors[0].Insert(7, "!"));
everything.Add(authors[0].Delete(0));
everything.AddRange(authors[1].Insert(3, "-"));
everything.AddRange(authors[1].Insert(0, ">>"));
everything.AddRange(authors[2].Insert(7, "?"));
everything.Add(authors[2].Delete(4));
var shuffle = new Rng(5);
var outcomes = new HashSet<string>();
for (int round = 0; round < 100; round++)
{
    var fresh = new Rga("fresh", "THE CAT");
    var waiting = new List<CrdtOp>(everything);
    while (waiting.Count > 0)
    {
        var ready = waiting.Where(fresh.Knows).ToList();
        var next = ready[(int)(shuffle.Next() * ready.Count)];
        fresh.Integrate(next);
        waiting.Remove(next);
    }
    outcomes.Add(fresh.Text());
}
Debug.Assert(outcomes.Count == 1);

// The same 5,000 random collisions, and what the names cost.
var crdt = Fuzz.Run("crdt", 5000, 7);
var typing = Fuzz.Cost("typing", 6000, 3);
var scattered = Fuzz.Cost("random", 6000, 3);
Console.WriteLine($"CRDT ended different {crdt.Diverged} times. Typing: {typing.Visible} letters, {typing.Items} cells, {typing.Runs} runs. Scattered edits: {scattered.Visible} letters, {scattered.Items} cells, {scattered.Runs} runs.");
Debug.Assert(crdt.Diverged == 0);
Debug.Assert(typing == (5291, 709, 4582, 5291, 709, 1293));
Debug.Assert(scattered == (3350, 2650, 700, 3350, 2650, 3334));

The CRDT also ended identical in all 5,000 runs, and in 100 random orders of the same six edits. It did so without any server deciding order, which is its advantage, and the second half of the output is the bill.

  • Cells outlive their letters. After 6,000 scattered edits there are 700 visible letters and 3,350 cells, 2,650 of them tombstones: nearly five cells for every letter you can see.
  • Runs help when people type in order. Typing left to right left 4,582 letters and 5,291 cells, and 1,293 runs, because consecutive letters by one site with consecutive names can be stored as a single entry. Yjs merges left-to-right insertions in this way. Edits scattered through the text gain almost nothing: 3,334 runs for 3,350 cells.
  • Tombstones are only safe to drop when everyone has seen the delete. A replica cannot erase a name while any copy might still send an edit that anchors to it. Garbage collection needs to know that every replica has seen the delete, which is hard when devices go offline for weeks.
  • Rich text and ordering have their own problems. Concurrent inserts at one place can interleave two people's words in some algorithms, which Kleppmann and others catalogued; formatting spans need extra rules, as in the Peritext work.

HLD

Deep dive: choosing between them

Decision checkpoint · pick one

A team builds a shared whiteboard of sticky notes, shapes and text. People work on trains and in aeroplanes, and edits must merge when they reconnect. There is no budget for a server per board. What should the sync use?

Commit to an answer first. The reasoning for every option appears after you pick.

OT, server ordersSequence CRDT
Where order livesA server, one per documentIn the names, on any copy
Server needed for correctnessYesNo
RemembersThe text and a short logEvery letter ever typed, with names
Offline for a dayA long queue to rewriteA plain merge
Hardest partRewriting every pair of edits correctlyTombstones, garbage collection, rich text
Seen inGoogle Docs, Etherpad, ShareDBYjs, Automerge, local-first tools

Choose by constraint. With a server per document and mostly online users, order from a server is simpler and cheaper, and it is how Google Docs is widely described. With offline or peer-to-peer, use names. With structured data, a text algorithm is the wrong tool: Figma describes a centralized system, inspired by CRDTs, that keeps one value per property and lets the server pick the last write. Different properties of one object merge without any rewriting at all.

LLD

Deep dive: one room per document, a log and snapshots

Edits conflict only inside one document, so the document is the unit of coordination. Each document is a room with exactly one writer, hosted on one machine. Documents are placed on hosts by hashing the id, as in replication and sharding, so adding a host moves only a few rooms. A small directory records which host owns each room, with a lease and a fencing token, as in consensus and leader election: a host that loses its lease must stop writing, because two rooms for one document are two truths.

The room does four things in a fixed order, and the order is the whole reliability story.

  1. Deduplicate. Each client sends its edits numbered, one in flight at a time, so the room only needs the newest number per client. A repeat gets the same acknowledgement and changes nothing.
  2. Rewrite and number. The edit is rewritten past whatever was committed since its base revision and gets the next revision.
  3. Write to the log. The edit is appended durably before anyone is told it exists.
  4. Apply and acknowledge. Only then does the document change in memory and the author hear back.

A snapshot every few hundred edits bounds recovery: a restarted room loads the newest snapshot and replays only the edits after it.

C# · A room: dedupe, log first, snapshot, recover41 lines
sealed record Entry(int Rev, string By, int Seq, Op Op);
sealed record Ack(int Rev, bool Duplicate);

sealed class Storage                                  // stands in for a replicated log and a snapshot store
{
    public readonly List<Entry> Log = new();
    public (int Rev, string Doc, Dictionary<string, (int Seq, int Rev)> Last)? Snapshot;
    public bool FailNextAppend;                       // the machine dies just before the write reaches disk
}

sealed class Room
{
    const int SnapshotEvery = 500;
    readonly Storage store;
    readonly Dictionary<string, (int Seq, int Rev)> last = new();   // per client: its newest edit and the revision it got
    public string Doc;
    public int Rev;
    public int Replayed;                              // how many edits a recovery had to replay

    public Room(Storage store, string start)          // a new room, or one recovering after a crash
    {
        this.store = store;
        Doc = start;
        if (store.Snapshot is { } s) { Doc = s.Doc; Rev = s.Rev; foreach (var kv in s.Last) last[kv.Key] = kv.Value; }
        foreach (var e in store.Log.Where(x => x.Rev > Rev)) { Apply(e); Replayed++; }
    }

    void Apply(Entry e) { Doc = Editor.Apply(Doc, e.Op); Rev = e.Rev; last[e.By] = (e.Seq, e.Rev); }

    public Ack Submit(string by, int seq, int baseRev, Op op)
    {
        if (last.TryGetValue(by, out var l) && seq <= l.Seq) return new Ack(l.Rev, true);   // a retry: same answer, no change
        foreach (var e in store.Log.Skip(baseRev)) op = Ot.Transform(op, e.Op, opFirst: false);
        var entry = new Entry(Rev + 1, by, seq, op);
        if (store.FailNextAppend) { store.FailNextAppend = false; throw new Exception("crashed before the write"); }
        store.Log.Add(entry);                         // 1. durable
        Apply(entry);                                 // 2. visible
        if (Rev % SnapshotEvery == 0) store.Snapshot = (Rev, Doc, new Dictionary<string, (int, int)>(last));
        return new Ack(Rev, false);                   // 3. acknowledged, last
    }
}
C# · A retry after a lost acknowledgement is recognised and changes nothing.26 lines
// A retry after a lost acknowledgement is recognised and changes nothing.
var disk = new Storage();
var room = new Room(disk, "THE CAT");
var firstAck = room.Submit("alice", 1, 0, new Ins(7, "S"));
var retryAck = room.Submit("alice", 1, 0, new Ins(7, "S"));
Debug.Assert(firstAck.Rev == 1 && retryAck.Rev == 1 && retryAck.Duplicate && room.Doc == "THE CATS");

// Crash after the write and before the acknowledgement: the recovered room recognises the retry.
var afterCrash = new Room(disk, "THE CAT");
Debug.Assert(afterCrash.Doc == "THE CATS" && afterCrash.Submit("alice", 1, 0, new Ins(7, "S")).Duplicate);

// Crash before the write: nobody was told, so the client retries and the edit lands once.
var disk2 = new Storage { FailNextAppend = true };
try { new Room(disk2, "THE CAT").Submit("alice", 1, 0, new Ins(7, "S")); } catch (Exception) { }
var restarted = new Room(disk2, "THE CAT");
Debug.Assert(restarted.Doc == "THE CAT");
var landed = restarted.Submit("alice", 1, 0, new Ins(7, "S"));
Debug.Assert(!landed.Duplicate && restarted.Doc == "THE CATS");

// Snapshots bound recovery: after 1,234 edits a restart replays 234, not 1,234.
var disk3 = new Storage();
var busy = new Room(disk3, "");
for (int i = 1; i <= 1234; i++) busy.Submit("alice", i, i - 1, new Ins(busy.Doc.Length, "x"));
var reloaded = new Room(disk3, "");
Console.WriteLine($"Recovered revision {reloaded.Rev}, replaying {reloaded.Replayed} edits");
Debug.Assert(reloaded.Doc == busy.Doc && reloaded.Rev == 1234 && reloaded.Replayed == 234);

Because each client has one edit in flight, the room keeps only a high-water mark per client instead of every id it has ever seen, and a snapshot carries those marks so retries stay safe across restarts. Two limits follow from the single writer. One hot document cannot be sharded, so products cap the number of simultaneous editors, on the order of a hundred, and let everyone else watch. And viewers should not load the room: it publishes its ordered stream to a broadcast tier that fans it out to thousands of read-only connections without ever ordering anything.

HLD

Deep dive: presence, offline and undo

Presence is the cursors and selections of other people. It is several times the traffic of edits, so it takes a separate channel, is throttled to a handful of updates a second, is never written to the log, and is replaced, not replayed: if one update is dropped the next supersedes it. A cursor is a position, so it must be moved by the same rewriting as the text, or, in a CRDT, anchored to a character name.

Offline is where the two designs part. An OT client that was away holds a queue of edits, each written against an old revision, and the server must rewrite all of them against everything committed since, one pair at a time. That works and is slow, and the result may surprise the author, because edits to a paragraph that someone else deleted have no good meaning. A CRDT merges the same queue by name. Either way a product has to decide what a conflict means to a person, which is why some show suggestions instead of silently merging.

Undo is the edit that makes people regret their algorithm. Undoing my last edit is not the same as restoring the previous text, because other people's edits have happened since. The inverse of my edit must be rewritten past everything that followed, in OT, or applied by name, in a CRDT, and it must leave other people's work alone.

Three more details belong in any honest design. Positions need an agreed unit: JavaScript strings count UTF-16 code units, so one emoji occupies two positions, and a server that counts code points will disagree with every browser. Comments anchor to ranges, which move like cursors. Version history is free from the log, which is a reason to keep it.

HLD

Collaborative editor failure modes and edge cases

What goes wrongWhat prevents or limits it
An acknowledgement is lost and the client resendsEvery edit carries a client id and sequence number, and the room remembers the newest per client, so a repeat is acknowledged and not applied
The room crashes after acknowledging but before savingWrite to the log first and acknowledge last, so an acknowledged edit is always durable
Two machines both believe they own a documentA lease from the directory with a fencing token that the log checks, so the old writer's appends are refused
Everyone reconnects at once after a deployJittered backoff, resume from the last known revision, and a snapshot for clients too far behind
A client sends an edit with an impossible positionValidate against the document length, drop the edit and resync that client, and never let one malformed edit stop a room
A huge paste or an automated edit floods the roomCap edit size and rate per client, split large edits and keep one slow client from stalling the rest
A snapshot is corrupt or missingRebuild from the log, which is the source of truth, and checksum snapshots when they are written
Permissions change while someone is connectedCheck on every edit, not only at connect, and close the socket on revocation
The edit format must changeVersion every stored edit and keep a reader for each version, because the log outlives the code

Senior depth

What senior interviews ask about a collaborative editor

Interviewer follow-upL5Why not simply lock the document while someone types?How to answer

A lock turns every key press into a round trip: the letter cannot appear until the server grants permission, which on a slow link feels like filing a request. A lost or stale lock holder also blocks everyone else. The point of the design is that typing never waits for the network, so edits apply locally at once and the system repairs the differences afterwards.

Interviewer follow-upL5What happens if the same edit is delivered twice?How to answer

Every edit carries a client id and a sequence number, and the room keeps the newest sequence number per client. A repeat is recognised, gets the original acknowledgement, and changes nothing. Delivery is at least once and the effect is exactly once. In the test, a repeat after a crash returned the same revision and left the text alone, while a server that forgets ids applies the edit twice.

Interviewer follow-upL6Two people insert at the same position at the same moment. How do both screens end with the same text?How to answer

Someone has to go first, and everyone must pick the same one. In OT the server numbers the edits and the earlier one keeps the left spot, and every client applies the same tie rule when it rewrites. In a CRDT the two new letters have names that always compare the same way, so the larger name goes first on every copy, with no server involved.

Interviewer follow-upL6How would you scale to a million documents, and what happens with one document that has ten thousand viewers?How to answer

Edits conflict only inside one document, so each document is a room with one writer, placed on a host by hashing its id, with a directory and lease so there is never a second room. Capacity grows by adding hosts. One hot document cannot be sharded, so cap the editors, on the order of a hundred, and publish the room's ordered stream to a broadcast tier that fans it out to the viewers without ordering anything.

Interviewer follow-upL6How do cursors and presence work, and why are they not stored?How to answer

Presence is several times the traffic of edits, short-lived and replaceable, so it rides a separate lossy channel, is throttled, and is never written to the log. A dropped update is replaced by the next one. A cursor is a position, so it is moved by the same rewriting as the text in OT, or anchored to a character name in a CRDT, which keeps it correct while others edit around it.

Interviewer follow-upL7The product wants editing to work offline for days. What changes?How to answer

Order can no longer come from a server that is always reachable, which moves the design toward names. With a CRDT the queue merges by name and the cost is memory and garbage collection, which needs to know when every replica has seen a delete. With OT a long queue is rewritten against everything that happened, which works but is slow and can surprise users. Then decide what a conflict means to a person: some products merge silently, others show suggestions.

Interviewer follow-upL7How would you add undo and redo?How to answer

Undo means undoing my edit, not restoring the previous text. Record each local edit with its inverse, then when the user undoes, rewrite the inverse past everything that has been committed since, in OT, or apply it by name, in a CRDT, so other people's work stays. Group a burst of typing into one undo step, and decide what undoing an edit that someone else has since changed should do.

Interviewer follow-upL7A CRDT document has grown to hundreds of megabytes, mostly tombstones. What do you do?How to answer

Store runs, not cells, so consecutive letters are one entry. Then garbage collect: a tombstone can be dropped once every replica has seen the delete, which needs a way to know that, such as a periodic checkpoint that every active client acknowledges and a rule for clients that have been away too long, who must reload from a snapshot. Archive the old history. In the test, scattered edits left nearly five cells per visible letter.

HLD

How to present a collaborative editor design in an interview

Start by saying what makes it hard: local edits apply at once, so replicas diverge unless every edit means the same thing wherever it lands. Show the failure in one line, the position that points at the wrong letter, then offer the two repairs, rewriting edits past the ones they had not seen, with a server to order them, or naming every letter. Say which you would choose and why, ask whether users edit offline, and move on. Spend your time on what makes it a system: one room per document, the log written before the acknowledgement, ids on every edit, snapshots, and presence on its own lossy channel.

Summary

A collaborative editor applies edits locally at once, so its copies diverge unless every edit means the same thing wherever it lands. A position is an address that moves, and a relay that forwards positions left the screens different in 4,536 of 5,000 random collisions. Operational transformation rewrites each edit past the edits it had not seen, in an order a server decides, and a sequence CRDT names every character so edits commute: both ended identical every time, one at the price of a sequencer and one at the price of names and tombstones (3,350 cells for 700 visible letters when edits are scattered). Choose by constraint: a server per document, offline or peer-to-peer, or structured data. Scale by the document: a room with one writer, an edit written to the log before it is acknowledged, a snapshot every few hundred edits, and an id on every edit so a retry changes nothing, with presence on a lossy channel and viewers on a broadcast tier.

Check yourself

Try answering out loud before you reveal each answer.

QuestionWhy can't two editors simply send each other positions?Reveal answer

A position is an address that shifts whenever someone inserts or deletes before it. Alice's delete 7 meant the typo when she wrote it and meant the space after THE by the time it reached Bob, whose insert had moved everything four places along. Nothing reports the error, and the screens silently differ.

QuestionWhat does a server that orders edits do to an edit written against an older revision?Reveal answer

It rewrites the edit's position past every edit committed since that revision, so the intention survives, then applies and numbers it. Bob inserted four letters before position 7, so Alice's delete becomes delete 11. Each client does the same to its own unsent edits when news arrives, and a tie between two inserts at one spot goes to the edit the server numbered first.

QuestionWhy does a CRDT keep tombstones?Reveal answer

Edits name letters, including deleted ones. If Bob types an S after the letter that Alice deletes, Alice's copy must still know where that letter sat, or it cannot place the S. A tombstone is dropped only when every replica has seen the delete, which is why garbage collection is the hard part of a CRDT.

QuestionWhen a room accepts an edit, what comes first: the acknowledgement or the save?Reveal answer

The save. An acknowledgement is a promise that the edit is durable. A crash between the two would lose an edit that the client was told was safe, so the order is deduplicate, rewrite and number, write to the log, then apply and acknowledge. If the crash comes before the write, nobody was told, the client retries, and the edit lands once.

Sources and further reading

  • Clarence Ellis and Simon Gibbs, Concurrency control in groupware systems, SIGMOD 1989: the origin of operational transformation.
  • David Nichols, Pavel Curtis, Michael Dixon and John Lamping, High-latency, low-bandwidth windowing in the Jupiter collaboration system, UIST 1995: the client and server shape that this lesson uses.
  • Abdessamad Imine, Pascal Molli, Gérald Oster and Pascal Urso, Proving correctness of transformation functions in real-time groupware, ECSCW 2003, and Gérald Oster and others, Data consistency for P2P collaborative editing, CSCW 2006: why peer-to-peer transformation is hard.
  • Hyun-Gul Roh, Myeongjae Jeon, Jin-Soo Kim and Joonwon Lee, Replicated abstract data types: building blocks for collaborative applications, Journal of Parallel and Distributed Computing, 2011: RGA.
  • Marc Shapiro, Nuno Preguiça, Carlos Baquero and Marek Zawirski, Conflict-free replicated data types, SSS 2011.
  • Petru Nicolaescu and others, Near real-time peer-to-peer shared editing on extensible data types, GROUP 2016, and the Yjs documentation (opens in a new tab): the YATA algorithm and a CRDT library that stores runs.
  • Martin Kleppmann, Victor Gomes, Dominic Mulligan and Alastair Beresford, Interleaving anomalies in collaborative text editors, PaPoC 2019.
  • Geoffrey Litt, Sarah Lim, Martin Kleppmann and Peter van Hardenberg, Peritext: a CRDT for collaborative rich text editing, CSCW 2022.
  • Evan Wallace, How Figma's multiplayer technology works (opens in a new tab) (2019): a centralized, CRDT-inspired design with one value per property.
  • The Google Drive blog series on the new Google Docs (opens in a new tab) (2010), which describes how simultaneous edits are reconciled.
  • Leslie Lamport, Time, clocks, and the ordering of events in a distributed system, 1978, and the lesson on time, clocks and ordering.
  • Jakob Nielsen, Response times: the 3 important limits: about 0.1 second as the limit for an interface to feel instant.
Lesson 35 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 36Case study: design a file sync serviceA senior-level walkthrough of a file sync service such as Dropbox: blocks cut by content, one stored copy of each, a change journal with cursors, conflicts and garbage collection, in tested C# with an interactive story.

Send a message

It goes straight to my inbox. I usually reply within a few days.