Skip to content

Conflict Resolution, OT and CRDTs

Advanced 55 min read Part 9 of 18

How replicas and editors converge under concurrent edits: last-writer-wins, operational transformation, CRDTs, server vs peer-to-peer, presence, Docs and Figma.

Summary#

Whenever two copies of the same data can be changed at the same time, by two users in a shared document or by two database replicas in different regions, the copies can diverge, and the system needs a rule for bringing them back together. That is conflict resolution. The simplest rule is last-writer-wins (LWW): attach a timestamp to every write and keep the newest. It always converges but silently throws away the losing write, and with skewed clocks, the "newest" may not be the latest. Operational transformation (OT), the technique behind Google Docs, sends every edit as an operation, such as "insert 'x' at position 5", and transforms each incoming operation against concurrent ones, so that it still means what its author intended after other edits shifted the text. OT is subtle to get right and is almost always run with a central server that orders operations. CRDTs, conflict-free replicated data types, design the data structure itself so that concurrent updates commute: replicas can apply updates in any order, even after days offline, and still end up identical. Examples include G-counters, which keep a count per replica, OR-sets, which tag each addition uniquely so adds and removes merge sensibly, and sequence CRDTs for text, such as RGA and the algorithm in Yjs, which give every character a unique, ordered identity. Systems are either server-authoritative, with one process per document ordering every edit, as Google Docs and Figma do, or peer-to-peer and local-first, where CRDTs let devices merge without any server. Alongside the document itself runs presence: who is online, where their cursors and selections are, sent as ephemeral, throttled messages that are never stored. Figma's design is the practical lesson: with a central server, a much simpler scheme, last-writer-wins per property of each object, is enough for design documents, and real CRDTs are needed mainly for collaborative text.

Why It Exists#

Distributed systems replicate data for availability and latency. A user in Sydney edits a local replica instead of waiting 200 ms for a round trip to Virginia; a phone keeps working on a plane; a database stays writable in every region during a network partition. But as soon as two replicas accept writes independently, they can receive concurrent writes, neither of which knew about the other, and they must later agree on the result.

The problem appears at every level:

  • Collaborative editors: Google Docs, Figma, Notion and code editors let many people edit one document at once, each seeing their own keystrokes instantly, before the server has confirmed them.
  • Offline-capable apps: notes, to-do lists and field-service apps accept edits with no connection, and must merge hours of changes when they reconnect.
  • Multi-leader and leaderless databases: Cassandra, DynamoDB global tables, Riak and CouchDB accept writes on several replicas, and must reconcile them. See Quorums and Leaderless Replication.
  • Shared counters and sets across regions: likes, view counts, shopping carts and presence lists updated in many places at once.

The choices are limited. You can prevent conflicts, by sending every write through one leader or locking the data, which costs latency and availability. You can detect and surface them, letting the user or the application choose, as Git does with merge conflicts. Or you can resolve them automatically, with a rule that every replica applies identically, so that all replicas converge to the same state without coordination. This page is about the automatic rules: what each one guarantees, what it loses, and when each is the right choice.

How It Works#

The concurrent-edit problem#

Take a shared text document containing cat. Two users edit it at the same moment, each on their own copy:

  • Alice inserts the at position 0, giving the cat.
  • Bob deletes the character at position 0, the c, giving at.

Each sends their operation to the other. Alice receives "delete position 0" and applies it to the cat, deleting the t and producing he cat. Bob receives "insert the at position 0" and applies it to at, producing the at. The two copies now disagree, and both are wrong: Alice's deletion of the c has turned into the deletion of a t.

The problem is that positions are relative to a state. Bob's "position 0" meant "the c", in the document as Bob saw it. Once Alice's insert shifted everything right by four characters, position 0 points at something else. Any scheme for concurrent editing must deal with this.

What a correct system must guarantee. Chengzheng Sun and colleagues ("Achieving Convergence, Causality Preservation, and Intention Preservation in Real-Time Cooperative Editing Systems", ACM TOCHI, 1998) framed the requirements as three properties, often called the CCI model:

  • Convergence: when all users have received all operations, every copy of the document is identical.
  • Causality preservation: if one operation happened before another, for example, Bob typed a word and then Alice corrected it, every copy applies them in that order.
  • Intention preservation: each operation's effect on every copy is the effect its author intended. Bob meant to delete the c, so every copy should delete the c.

Convergence alone is easy: everyone could just discard every concurrent edit. The hard part is converging and preserving intentions.

Why not just lock? If only one person could edit at a time, there would be no conflicts. Early collaborative tools locked paragraphs or whole documents. But locking feels terrible in practice: users wait for permission to type, and a user who goes offline with the lock blocks everyone. Modern editors are optimistic: they apply each user's edit locally immediately, so typing never waits for the network, and sync afterwards. That creates a window, milliseconds online, hours offline, in which copies genuinely differ, and the system must reconcile them.

The concurrent-edit problem, in depth#

Detecting concurrency. Two operations are concurrent if neither happened before the other: neither author had seen the other's operation when they made their own. Systems detect this with version vectors, one counter per replica, attached to each operation or state. If every entry of A's vector is at least B's, A has seen everything B saw, and A happened after B; if each vector has some entry larger than the other's, the operations are concurrent. Wall-clock timestamps cannot tell concurrency from ordering, because clocks drift and do not capture what each writer had seen. See Time, Clocks and Ordering.

Kinds of conflict.

  • Same-value conflicts: two users set the same field, a title or a colour, to different values. One must win, or both must be kept for a human to choose.
  • Positional conflicts: edits to an ordered sequence, such as text or a list, whose positions shift because of concurrent inserts and deletes, as in the example above.
  • Structural conflicts: in a tree, such as a document outline or a design file, two users move the same node to different parents, or one moves A under B while the other moves B under A, creating a cycle. Or one deletes a section while the other edits inside it.
  • Semantic conflicts: two edits that each look valid and merge without any structural problem, but break an application rule together, such as two users booking the last seat, or two edits that each keep a budget under its limit but together exceed it. No generic merge algorithm can catch these, because the rule lives in the application. They need coordination, such as a transaction or a lock, at the moment of the write. See Concurrency Control and Locking.

The spectrum of strategies.

StrategyHow it worksLoses data?Examples
AvoidA single leader or lock per itemNo, but costs latency and availabilitySingle-leader databases, checked-out files
Last-writer-winsKeep the write with the highest timestampYes, silentlyCassandra cells, DynamoDB global tables
Keep all versionsStore concurrent versions as siblings; the application or user mergesNo, but pushes work to the applicationRiak siblings, CouchDB conflicts, Git merges
Transform operationsAdjust each operation for concurrent onesNo, for supported operationsGoogle Docs (OT)
Commutative data typesDesign data so that every order of updates convergesNo, within the type's semanticsCRDTs: Yjs, Automerge, Riak data types
Application-specific mergeCustom code merges two versionsDepends on the codeDynamo's shopping cart union

Strong eventual consistency. Ordinary eventual consistency only promises that replicas converge eventually, if writes stop, possibly after a conflict-resolution step. CRDTs offer a stronger guarantee, strong eventual consistency: any two replicas that have received the same set of updates, in any order, are in the same state, immediately, with no further coordination or rollback. This is the property that makes offline editing and peer-to-peer sync tractable. See Consistency Models.

Last-writer-wins#

Last-writer-wins resolves a conflict by keeping the value with the highest timestamp and discarding the other. Each write carries a timestamp, and when replicas exchange values, each keeps the newer one. Ties are broken deterministically, such as by replica ID, so every replica picks the same winner.

Why it is popular. It is trivial to implement, needs only a timestamp per value, always converges, and gives a sensible answer when the loser genuinely does not matter: if two devices update a user's profile photo at almost the same moment, keeping either one is fine.

What it costs. The losing write is silently discarded. In the shopping-list example, LWW on the whole list keeps one friend's copy and loses every change the other made. LWW on each field loses much less, since edits to different fields both survive, and only the same field's concurrent writes lose one value. That is the key design choice: the granularity of the LWW register.

Clock skew makes "last" unreliable. Timestamps come from clocks, and clocks on different machines disagree, typically by milliseconds with NTP, sometimes by seconds or more after a misconfiguration or a VM pause. If server A's clock runs 2 seconds fast, its writes beat any write from server B made within the next 2 seconds, even writes that happened after A's and were made by someone who had seen A's value. The newer edit loses. Worse, a server with a clock far in the future can make its writes unbeatable until real time catches up.

Mitigations.

  • Logical clocks: a Lamport timestamp, a counter that each replica sets to one more than the largest timestamp it has seen, guarantees that a write made after seeing another has a higher timestamp, so causal overwrites always win. Concurrent writes still lose one value, but at least the loser is genuinely concurrent.
  • Hybrid logical clocks: combine physical time with a logical counter, staying close to wall-clock time while preserving causality. CockroachDB and others use them.
  • A single orderer: if every write passes through one server, "last" means "last to arrive at the server", and no clocks are needed. This is Figma's approach.

Where LWW is used. Cassandra resolves every cell, each column of each row, by write timestamp, normally assigned by the coordinator or the client. DynamoDB global tables reconcile concurrent writes to the same item in different regions with last-writer-wins. Many sync engines and mobile databases use LWW per field. Within CRDTs, the LWW-register is a standard building block.

Last-writer-wins, in depth#

Deletes need tombstones. If one replica deletes a value and another still holds it, a later sync could resurrect the deleted value, since the second replica's copy looks like a value the first lacks. So a delete must be recorded as a tombstone, a marker with a timestamp that beats older writes. Tombstones must be kept until every replica has seen them, then garbage-collected. Cassandra keeps tombstones for gc_grace_seconds, 10 days by default, and a replica that is offline longer than that, then rejoins without a repair, can resurrect deleted data. Workloads that delete heavily accumulate tombstones, which slow reads that must scan past them.

Dynamo's shopping cart. Amazon's Dynamo (Giuseppe DeCandia and colleagues, SOSP 2007) chose not to use LWW for shopping carts: losing an "add to cart" loses a sale. Instead, Dynamo kept concurrent versions as siblings, detected with vector clocks, and the cart application merged them by union. The paper notes the consequence: an item deleted in one version but present in a concurrent one could reappear after merging. A union keeps every addition, which is the right bias for carts, but it does not handle removals, the exact problem that the OR-set CRDT, described below, solves.

Riak's siblings and data types. Riak exposed siblings to applications, which had to merge them on read, and many applications got merging wrong. Riak later added built-in data types, counters, sets, maps, registers and flags, implemented as CRDTs, so applications could get correct merges without writing merge code.

When LWW is the right call. When the value is replaced as a whole and either concurrent value is acceptable: a status, a preference, a profile field, the position of a shape. When concurrent writes to the same value are rare and a lost write is visible and easily redone. Or when a single orderer makes "last" meaningful. LWW is the wrong call for counters, where both increments must count, for collections, where both additions must survive, and for text, where both edits must be merged.

Operational transformation#

Operational transformation keeps the familiar model of an editor, a document of characters addressed by position, and fixes the concurrent-edit problem by rewriting operations. Each edit is an operation, such as insert("x", 5) or delete(3). When a replica receives a remote operation that was made concurrently with operations it has already applied, it first transforms the remote operation against them, adjusting its position so that it has the effect its author intended in the current state.

The core idea: a transform function. For two concurrent operations a and b, both made against the same document state, a transform function T(a, b) returns a version of a that can be applied after b. For text, the rules are intuitive:

  • Insert against insert: if b inserted text before a's position, shift a right by the length of b's text. If both insert at the same position, break the tie deterministically, such as by site ID, so both replicas order the two insertions identically.
  • Insert against delete: if b deleted a character before a's position, shift a left by one.
  • Delete against insert: if b inserted before the character a wants to delete, shift a right.
  • Delete against delete: if b deleted the same character a wants to delete, a becomes a no-op, because the character is already gone.

Applied to the example above: Alice receives Bob's delete(0), made concurrently with Alice's own insert("the ", 0), and transforms it: Alice's insert was at position 0, at or before Bob's delete position, so Bob's delete shifts right by 4, to delete(4), which removes the c from the cat, leaving the at. Bob receives Alice's insert("the ", 0) and transforms it against Bob's own delete(0): the delete was at position 0, not before position 0, so the insert stays at 0, giving the at. Both copies converge to the at, and both intentions are preserved.

The convergence condition, TP1. Transformation must satisfy a property, called TP1 or the convergence property: applying a then T(b, a) must give the same document as applying b then T(a, b). Written as a diagram, the two paths around the square must meet. For two concurrent operations, TP1 is enough.

TP2: three or more concurrent operations. With three or more concurrent operations, operations may be transformed along different paths on different replicas, and convergence additionally requires TP2: transforming an operation against two others must give the same result regardless of the order in which those two were combined. TP2 is notoriously hard to satisfy for text with inserts and deletes. Many published transform functions were later shown to violate it. Abdessamad Imine and colleagues used theorem provers to find counterexamples in several well-known algorithms in the early 2000s, and Du Li and Rui Li observed that correctness proofs for such algorithms are long, intricate and easy to get wrong. This is the main reason OT has a reputation for being hard.

The escape: a central server. If one server orders all operations, the system never needs TP2. Every client transforms only against the server's single sequence, so all transformations happen along the same path. This is the design of the Jupiter collaboration system (David Nichols, Pavel Curtis, Michael Dixon and John Lamping, "High-Latency, Low-Bandwidth Windowing in the Jupiter Collaboration System", UIST 1995, at Xerox PARC). Each client talks only to the server, the server and each client run a two-party protocol that needs only TP1, and the server rebroadcasts each transformed operation to every other client. Google Wave, and then Google Docs, adopted this client-server form of OT.

Operational transformation, in depth#

How a client-server OT protocol works. The design used by Google Docs-style editors, and in open-source form by ShareDB and the ot.js library, has these parts:

  • The server keeps the document and an operation log, with a revision number per accepted operation. When an operation arrives tagged "based on revision r", the server transforms it against every operation accepted after r, appends the result as the next revision, and broadcasts it.
  • Each client has three pieces of state: the last revision it has received from the server, at most one operation in flight, sent but not acknowledged, and a buffer of local operations typed since then, composed into one operation.
  • When the user types, the client applies the edit locally at once, then either sends it, if nothing is in flight, or composes it into the buffer.
  • When a remote operation arrives, the client transforms it against the in-flight operation and the buffer, applies the transformed remote operation to the screen, and replaces the in-flight and buffered operations with their transformed versions, so they still apply correctly after the remote one.
  • When an acknowledgement arrives, the buffer becomes the new in-flight operation and is sent.

Sending only one operation at a time, and buffering the rest, keeps the client's transformation simple and the server's transformation cheap: the server never has to transform against more than the operations the client had not yet seen.

Composition and operation types. Practical OT operations are not single-character edits but sequences of components that walk the whole document: "retain 5 characters, insert 'abc', retain 10, delete 2, retain to the end". Two such operations can be composed, combined into one equivalent operation, which shrinks buffers and lets the server squash history. Rich text adds attributes, such as bold, on retained ranges, and structured documents, such as JSON, need transform functions for every pair of operation types on every kind of node: insert into a list, delete from a list, set a map key, move a subtree, and so on. That combinatorial growth is the practical cost of OT: n operation types need on the order of n² transform cases, each with edge cases, and each must satisfy TP1.

Intention is not always obvious. If Alice deletes a word while Bob makes the same word bold, the transformed result deletes the word, and Bob's bold applies to nothing. If Alice deletes a paragraph while Bob types inside it, Bob's characters are either kept, as an orphaned fragment, or dropped. Different OT and CRDT systems make different choices. Neither is "correct"; each system must define its semantics and apply them consistently.

Undo. Undo in a collaborative editor must undo my last operation, not the last operation in the document, which may be someone else's. That requires transforming the inverse of my old operation against every operation that came after it, which is another source of OT complexity, studied in its own literature, such as Matthias Ressel and colleagues' work on undo in group editors in the late 1990s.

OT's history in brief.

  • 1989: Clarence Ellis and Simon Gibbs ("Concurrency Control in Groupware Systems", SIGMOD 1989) introduced OT with the GROVE outline editor, a peer-to-peer design. Its algorithm, dOPT, was later shown to diverge in some cases.
  • 1995: Jupiter at Xerox PARC introduced the client-server, two-party approach.
  • 1996 to 1998: Sun, Ellis and others developed adOPTed, GOT and GOTO, and the CCI correctness framework.
  • 2009: Google Wave launched with server-ordered OT, and published its protocol. Google Docs' real-time editor, rebuilt around 2010, uses OT with a central server.
  • 2010s: open-source OT frameworks such as ShareDB, formerly ShareJS, brought the approach to many applications. Etherpad is another server-based editor, using its own changeset model, which is closely related to OT.

Why OT still makes sense. With a server, OT is efficient: operations are small, documents stay plain text plus formatting, there is no per-character metadata, and the server's log is a natural history and audit trail. Its downside is that it requires the server, and that each new operation type needs careful transform functions.

CRDTs: counters and sets#

A CRDT, a conflict-free replicated data type, is a data type designed so that replicas can be updated independently and concurrently, without coordination, and are guaranteed to converge once they have received the same updates. The idea was formalised by Marc Shapiro, Nuno Preguiça, Carlos Baquero and Marek Zawirski ("Conflict-Free Replicated Data Types", SSS 2011, with a longer technical report, "A Comprehensive Study of Convergent and Commutative Replicated Data Types", INRIA, 2011). Where OT repairs operations after the fact, a CRDT makes conflicts impossible by construction: the merge rule is part of the type.

Two flavours.

  • State-based CRDTs, also called convergent replicated data types, or CvRDTs: replicas periodically send their entire state, and the receiver merges it with its own using a merge function. Convergence requires the merge to be commutative (merge(a, b) = merge(b, a)), associative (the grouping of merges does not matter) and idempotent (merging the same state twice changes nothing). Mathematically, the states form a join-semilattice and merge computes the least upper bound. These properties mean messages can be delayed, reordered or duplicated, and gossip in any pattern still converges.
  • Operation-based CRDTs, also called commutative replicated data types, or CmRDTs: replicas send each update operation, and every replica applies every operation. Concurrent operations must commute. The messaging layer must deliver every operation exactly once to each replica, usually in causal order, which is a stronger requirement on the network but sends much less data than whole states.

The two are equivalent in power: each can emulate the other. Practical systems mix them, and delta-state CRDTs (Paulo Sérgio Almeida, Ali Shoker and Carlos Baquero, 2015 and later in the Journal of Parallel and Distributed Computing, 2018) send only the part of the state that changed, a delta, which merges like a state but costs like an operation.

G-Counter: a grow-only counter. Suppose three replicas count page views. If each kept a single number and sent it to the others, merging 7 and 5 would give no correct answer: taking the maximum loses increments, and adding double-counts on every exchange. A G-Counter keeps one entry per replica: replica A increments only A's entry, B only B's. The value is the sum of entries, and merge takes the per-entry maximum. If A's state is {A: 4, B: 2, C: 0} and B's is {A: 3, B: 5, C: 1}, the merge is {A: 4, B: 5, C: 1}, value 10. Taking a maximum is commutative, associative and idempotent, so any gossip pattern converges, and no increment is lost or double-counted, because each entry is written by only one replica.

PN-Counter: increments and decrements. A counter that can go down, such as items in stock or likes that can be removed, keeps two G-Counters: P for increments and N for decrements. The value is sum(P) − sum(N). Note that a PN-Counter cannot enforce a lower bound: two replicas that each see a stock of 1 can each decrement it, giving −1. Enforcing "never below zero" needs coordination, or a CRDT variant that pre-allocates escrow rights to each replica, such as the bounded counter in Antidote and Riak-based research.

Registers. An LWW-Register holds one value plus a timestamp, and merge keeps the higher timestamp, with a replica-ID tie-break: last-writer-wins as a CRDT. A Multi-Value Register, or MV-Register, keeps all concurrent values, each tagged with a version vector, and a later write that has seen them all replaces them all. This is exactly Dynamo's and Riak's siblings: concurrent writes are both kept, and the application or user resolves them.

Sets. Sets show the central difficulty of CRDTs: what should happen when one replica adds an element while another concurrently removes it?

  • G-Set, grow-only: add only, merge by union. Trivially correct, and useful for things that are never removed, such as "users who have seen this message".
  • 2P-Set, two-phase: a G-Set of added elements and a G-Set of removed elements, the tombstones. An element is present if it is added and not removed. But once removed, an element can never be added again, because the tombstone wins forever.
  • LWW-Element-Set: each add and remove carries a timestamp, and an element is present if its latest add is newer than its latest remove. It allows re-adding but inherits LWW's clock problems and silent losses.
  • OR-Set, the observed-remove set: every add creates a unique tag, such as (replica ID, counter), and stores the pair (element, tag). A remove deletes only the tags the remover has observed. If Alice re-adds "milk" while Bob concurrently removes it, Alice's add has a new tag that Bob never saw, so Bob's remove does not delete it, and "milk" stays. This is add-wins semantics: a concurrent add beats a remove, which usually matches what users expect, such as an item someone added to a shared cart staying there. Removal semantics now depend on what each replica had seen, not on clocks.

Maps and nested types. An OR-Map maps keys to nested CRDTs: a map of counters, a map of sets, a map of registers, recursively. JSON-like documents are built this way: Automerge and Yjs represent documents as nested maps, lists and text, each a CRDT. Riak's data types, counters, sets, maps, registers and flags, were built from the same constructions.

CRDTs: counters and sets, in depth#

Why the semilattice properties matter. Gossip protocols deliver state at any time, in any order, sometimes twice. If merge is commutative, the order of two merges does not matter; if associative, merging through intermediate replicas does not matter; if idempotent, duplicates do no harm. Together, they mean that any two replicas that have merged, directly or indirectly, the same set of updates hold the same state. The update operations must also be inflationary, always moving the state upward in the lattice, so a merge never undoes a local update. A G-Counter increment raises one entry; an OR-Set add adds a tag; neither can be undone by merging older state.

The cost of state-based CRDTs. A G-Counter grows by one entry per replica that has ever written: fine for 5 database replicas, problematic for a million phones. Every exchange ships the whole state unless deltas are used. OR-Sets store a tag per add and must remember removed tags somewhere, or use a version vector to summarise which tags each replica has seen, as in the optimised OR-Set of Annette Bieniusa and colleagues (2012), which avoids keeping tombstones for removed elements by comparing tags against version vectors.

Tombstones and garbage collection. Many CRDTs keep metadata for deleted things, as tombstones, because a replica that has not yet seen the delete might otherwise reintroduce the item on merge. Safely discarding a tombstone requires knowing that every replica has seen the delete, which is a global, coordinated fact. Systems handle this with version vectors and a stability check, by periodically compacting when all known replicas are in sync, or by accepting that replicas offline longer than some window must resync from a snapshot.

Other set semantics. Remove-wins sets exist, where a concurrent remove beats an add, which suits cases where removal is a safety action, such as revoking access. The choice between add-wins and remove-wins is a product decision about intent, not an algorithm detail.

CRDTs in databases.

  • Riak shipped CRDT data types, counters in 1.4 and sets, maps, registers and flags in 2.0, around 2013 to 2014, built with Basho's riak_dt library.
  • Redis Enterprise's Active-Active databases replicate across regions with CRDT-based conflict resolution for strings, counters, sets, hashes, lists and other types, so each region accepts writes locally.
  • Azure Cosmos DB offers multi-region writes with last-writer-wins by default, or custom merge procedures.
  • AntidoteDB, a research database from the SyncFree project, offers transactional causal consistency over CRDTs.
  • Akka Distributed Data provides replicated CRDTs, counters, sets, maps and registers, gossiped between cluster nodes.

A worked G-Counter example with gossip. Three regions count likes for a post. In one second, US increments 120 times, EU 80 times and Asia 50 times. US state {US: 120, EU: 0, Asia: 0}; EU {0, 80, 0}; Asia {0, 0, 50}. US gossips to EU: EU becomes {120, 80, 0}, value 200. EU gossips to Asia: Asia becomes {120, 80, 50}, value 250. Asia gossips to US: US becomes {120, 80, 50}, value 250. Suppose the EU-to-Asia message is delivered twice, or US hears from EU's stale state later: merge by maximum ignores both. All three converge to 250, the true total, without any coordinator.

Sequence CRDTs for text#

Counters and sets are the easy cases. Text is the hard one, because order matters and positions shift. A sequence CRDT solves the positional problem from the concurrent-edit example by never using positions in operations. Instead, every character gets a unique, permanent identifier, and operations refer to identifiers: "insert 'x' after character (alice, 17)", or "delete character (bob, 4)". A character's identity does not change when other text is inserted or deleted around it, so an operation means the same thing on every replica, whatever arrived first.

Two families.

  1. Ordered-identifier sequences: each character's identifier is a position in a dense total order, so a new identifier can always be created between any two neighbours, much as there is always a fraction between 0.25 and 0.5. The document is the characters sorted by identifier.
    • Treedoc (Nuno Preguiça, Joan Manuel Marquès, Marc Shapiro and Mihai Leția, ICDCS 2009) uses paths in a binary tree as identifiers.
    • Logoot (Stéphane Weiss, Pascal Urso and Pascal Molli, ICDCS 2009) uses lists of (digit, site ID) pairs, compared lexicographically, like an infinitely divisible decimal with tie-breaking by site.
    • LSEQ (Brice Nédelec, Pascal Molli, Achour Mostefaoui and Emmanuel Desmontils, DocEng 2013) chooses new identifiers with alternating strategies, so identifiers grow more slowly under typical typing.
  2. Linked-list sequences: each character records which character it was inserted after, its left neighbour at the time of insertion, plus its own unique ID. Concurrent insertions after the same character are ordered by a deterministic rule.
    • WOOT (Gérald Oster, Pascal Urso, Pascal Molli and Abdessamad Imine, "Data Consistency for P2P Collaborative Editing", CSCW 2006), "WithOut Operational Transformation", records both the left and right neighbours of each insertion and never truly deletes characters, only hiding them.
    • RGA, the Replicated Growable Array (Hyun-Gul Roh, Myeongjae Jeon, Jin-Soo Kim and Joonwon Lee, "Replicated Abstract Data Types: Building Blocks for Collaborative Applications", JPDC 2011), records the left neighbour and orders concurrent inserts at the same place by timestamp, newest first. Automerge's text type is based on RGA.
    • YATA, Yet Another Transformation Approach (Petru Nicolaescu, Kevin Jahns, Michael Derntl and Ralf Klamma, GROUP 2016), records both the left and right origins of each insertion; it is the algorithm behind Yjs, which Kevin Jahns maintains.

How an RGA-style insert works. The document cat is three nodes, linked in order, each with an ID: c (b,1), a (b,2), t (b,3), where b is Bob's replica. Alice types h after c; Alice's editor creates node h (a,7) with the instruction "insert after (b,1)". Bob, concurrently, deletes a, which marks node (b,2) as a tombstone, hidden but kept. On every replica, Alice's insert finds (b,1) and places h after it, and Bob's delete hides (b,2), whichever arrives first. Both replicas show cht. Nothing was shifted, so nothing needed transforming.

Concurrent inserts at the same place. If Alice inserts x after c and Bob concurrently inserts y after c, both new nodes claim the same left neighbour. Every replica orders them by a deterministic rule, in RGA by comparing their timestamps, Lamport clocks with replica-ID tie-breaks, and placing the larger first. All replicas then show the same order, cyxat or cxyat, without coordination.

The cost: metadata. Every character carries an ID, a reference to its origin and, for deleted characters, a tombstone. A naive implementation stores dozens of bytes per character, so a 100,000-character document with its editing history might take megabytes instead of 100 KB. Modern libraries make this practical:

  • Run-length encoding: a user typing a sentence creates consecutive IDs, (a,7), (a,8), (a,9) and so on, each inserted after the previous one. Yjs and Automerge store such runs as a single item, such as "(a,7) to (a,40): 'the quick brown fox...'", splitting it only when someone edits inside it. Since most text is typed in runs, this cuts metadata by orders of magnitude.
  • Compact binary encodings: Automerge 2.0, rewritten in Rust and released in 2023, uses a columnar binary format that stores the full editing history of a typical document within a small factor of the size of the text itself.
  • Garbage collection of tombstones: Yjs can discard the content of deleted items while keeping minimal markers, unless history is needed.

Joseph Gentle and Martin Kleppmann's work on Eg-walker ("Collaborative Text Editing with Eg-walker: Better, Faster, Smaller", EuroSys 2025) showed a different trade-off: store the edit history as an event graph with plain indices, like OT, and build CRDT-style state only temporarily when merging concurrent branches, which gives small steady-state memory and fast loading.

Sequence CRDTs, in depth#

The interleaving anomaly. Suppose Alice and Bob both type at the same spot while offline: Alice types "Hello " and Bob types "Hi ". A correct merge should show either "Hello Hi " or "Hi Hello ", keeping each person's words together. Some sequence CRDTs instead produce something like "HHeil lo " with the characters interleaved, because each character's identifier is chosen independently, and the two users' identifiers alternate in the dense order. Martin Kleppmann, Victor Gomes, Dominic Mulligan and Alastair Beresford ("Interleaving Anomalies in Collaborative Text Editors", PaPoC 2019) showed that Logoot and LSEQ can interleave in this way, while RGA avoids interleaving for text typed forwards, since each character attaches to the previous one, but can still interleave in a subtler case, and they proposed a fix. The Fugue algorithm (Matthew Weidner and Martin Kleppmann, "The Art of the Fugue: Minimizing Interleaving in Collaborative Text Editing", 2023) was designed to have minimal interleaving in both directions.

Proving CRDTs correct. Because CRDT correctness is about every possible ordering of operations, it is well suited to formal verification. Victor Gomes, Martin Kleppmann, Dominic Mulligan and Alastair Beresford ("Verifying Strong Eventual Consistency in Distributed Systems", OOPSLA 2017) proved the convergence of RGA, the OR-Set and counters in the Isabelle theorem prover. This contrasts with OT's history of broken proofs.

Rich text. Formatting adds another layer. If Alice bolds "quick brown" while Bob inserts "very " inside it, should "very" be bold? Most users expect yes for text inserted inside a bold range, and no for text typed just after the end of a link. Peritext (Geoffrey Litt, Sarah Lim, Martin Kleppmann and Peter van Hardenberg, "Peritext: A CRDT for Collaborative Rich Text Editing", CSCW 2022) stores formatting as spans anchored to character IDs, with rules for whether each mark expands at its boundaries, so concurrent formatting and insertion merge the way users expect.

Moving items in lists and trees. A CRDT list supports insert and delete, but a move, such as dragging a to-do item to the top, is usually implemented as delete plus insert, and if two users move the same item concurrently, it can be duplicated. Martin Kleppmann ("Moving Elements in List CRDTs", PaPoC 2020) gave a move operation that uses an LWW register for each item's position, so concurrent moves pick one destination. For trees, such as file systems or outlines, concurrent moves can create cycles: Kleppmann, Mulligan, Gomes and Beresford ("A Highly-Available Move Operation for Replicated Trees", IEEE TPDS 2021) gave an algorithm that orders move operations by timestamp, undoes and redoes them on arrival, and skips any move that would create a cycle.

OT and CRDT are closer than they look. Both must produce the same result for concurrent inserts, and both need a tie-break for inserts at the same place. A CRDT's unique IDs are, in effect, a way to compute the transformed position without a central history. The practical differences are architectural: CRDTs work without a server and tolerate arbitrary delay and reordering, at the cost of per-element metadata, while OT keeps operations and documents compact but needs a central ordering point to stay tractable.

Server-authoritative versus peer-to-peer#

Every collaborative system must decide who orders and stores the edits. There are two broad architectures, and most products sit closer to one end.

Server-authoritative. A server is the source of truth. Clients apply their own edits optimistically, send them to the server, and receive everyone else's edits from it. The server orders operations, validates them, enforces permissions, persists them and rebroadcasts them.

  • One process per document. Real-time edits for one document all go to one server process, or one actor, that holds the document in memory. It is the natural serialisation point: OT needs it, and even a CRDT system benefits from it, since the server can validate edits and compact history. Clients connect over WebSockets, and a routing layer sends every client of a document to the process that owns it, for example by consistent hashing on the document ID or by a lookup in a coordination service. See Polling, Long Polling, SSE, WebSockets and Webhooks.
  • Strengths: a single order makes semantics simple, the server can reject invalid or unauthorised edits, there is one authoritative history for versioning and audit, and clients stay thin.
  • Weaknesses: no collaboration without the server, the owning process is a single point of failure for that document until it is reassigned, and every edit costs a round trip to wherever the server runs.

Peer-to-peer and local-first. Each device holds a full replica and is authoritative for its own copy. Devices exchange updates directly, over WebRTC or a local network, or through relays that forward and store encrypted updates without understanding them. CRDTs are the enabling technology, because they converge with any delivery order and need no central coordinator.

  • Local-first software (Martin Kleppmann, Adam Wiggins, Peter van Hardenberg and Mark McGranaghan, "Local-First Software: You Own Your Data, in Spite of the Cloud", Onward! 2019) argued for seven ideals: fast because data is local, multi-device, works offline, supports collaboration, lasts for decades, private and secure by default, and gives users ownership and control. CRDTs were their proposed foundation.
  • Strengths: works offline and on poor networks, low latency because every read and write is local, no server needed for correctness, and end-to-end encryption becomes possible because a relay need not read the data.
  • Weaknesses: every device stores the full history and metadata, permissions are hard to enforce without a trusted party, since a malicious peer can send any operation, and schema changes and validation must be agreed by all peers.

The middle ground, which most products use. Use a CRDT for the data model, so clients can work offline and merge freely, but run a server that every client syncs with: it persists documents, enforces permissions, compacts history and relays updates. Yjs's y-websocket server and Hocuspocus, Liveblocks, and Automerge's sync servers all work this way. Many sync engines, such as Linear's, Replicache and Zero, take a related approach: clients write locally and optimistically, and a server is authoritative, rebasing or rejecting client mutations.

Server-authoritative versus peer-to-peer, in depth#

Routing clients to the document's owner. With millions of documents and one owner per document, the system needs a placement layer. Common designs: hash the document ID onto a ring of servers; keep an assignment table in a coordination service, such as ZooKeeper or etcd, with leases, so an owner that dies loses its lease and the document is reassigned; or use a platform that provides single-instance actors, such as Cloudflare Durable Objects, which guarantees one instance per object ID globally, or actor frameworks such as Orleans and Akka Cluster Sharding. Clients first ask a lookup service where the document lives, then open a WebSocket there. See Leader Election and Coordination.

Avoiding two owners. If the owner of a document is partitioned from the coordination service, a new owner may be assigned while the old one still accepts edits from clients that can reach it, and the two will accept conflicting histories. With OT, that is corruption. Defences are the standard ones: leases that expire before reassignment, fencing tokens that the storage layer checks so a stale owner's writes are rejected, and clients that reconnect through the lookup service rather than trusting a cached address.

Persistence and compaction. The document server appends each accepted operation to a durable log, such as a database table keyed by (document ID, revision) or a stream, before acknowledging it, so an acknowledged edit survives a crash. Replaying millions of operations on load would be slow, so the server writes periodic snapshots, the full document at revision r, and keeps only operations after the latest snapshot for fast loading, with older operations archived for version history or discarded. This mirrors snapshots in Event Sourcing and CQRS.

Scaling connections. A single server can hold tens of thousands to a few hundred thousand idle WebSocket connections, depending on memory and the runtime. Most documents have one to a few editors at a time, so the load per document is small, and the scaling challenge is the number of documents and connections, not per-document throughput. Separate the connection layer, which terminates WebSockets, from the document layer, which holds document state, and connect them with an internal pub/sub or RPC, so a document process can serve clients connected through many gateways. See Pattern: Pushing Realtime Updates.

Security in peer-to-peer systems. Without a server, any peer can forge or corrupt operations. Research on Byzantine fault-tolerant CRDTs, such as Martin Kleppmann's "Making CRDTs Byzantine Fault Tolerant" (PaPoC 2022), uses hash-linked operations, like a Git commit graph, so peers can detect tampering and equivocation, while access control in local-first systems remains an open, actively researched problem.

Presence and cursors#

Alongside the document, a collaborative editor shows presence: who is viewing the document, their avatars, and where each person's cursor and selection are, sometimes with their name and colour. Presence makes collaboration feel live and prevents people from editing the same sentence at once, but its requirements are the opposite of the document's.

PropertyDocument editsPresence
DurabilityMust survive crashesEphemeral, never stored
OrderingCausal, or a total orderOnly the latest value matters
Loss toleranceNoneHigh: the next update replaces it
RatePer keystroke, batchedThrottled, a few per second per user
Conflict ruleOT or CRDT mergeEach user owns their own state, so no conflicts

How presence works. Each client periodically sends its own presence state, such as {user, name, colour, cursor, selection, lastActive}, to the document server, which rebroadcasts it to the document's other clients and keeps it in memory only. Each user's state is written only by that user, so there are no conflicts: the newest message simply replaces the previous one. Clients send a heartbeat and the server removes users who have been silent for, say, 30 seconds, or immediately when their connection closes. Yjs's awareness protocol is a standard example: each client's state has a clock that increases with every update, it is sent alongside but separately from document updates, and states that are not renewed time out.

Cursors must be relative, not absolute. If a cursor is stored as "position 120" and another user inserts text earlier in the document, position 120 now points at the wrong character. Cursor positions must be transformed like operations: with OT, each remote operation transforms every cursor; with a CRDT, a cursor is anchored to a character ID, such as Yjs's relative positions, which stays attached to the same character as text changes around it, and is converted to an absolute index only for display.

Throttling and smoothing. Mouse movement produces 60 or more events a second. Sending each one to every collaborator would multiply traffic by the number of viewers, so clients throttle cursor updates to perhaps 10 to 20 per second and receivers interpolate between positions so movement looks smooth. A document with 50 viewers at 10 updates per second each generates 500 presence messages per second in and 25,000 out, which is far more than the editing traffic, and a strong argument for coalescing presence into periodic batches and for capping how many live cursors are shown.

Presence and cursors, in depth#

Separate channels, or at least separate handling. Presence and document edits often share one WebSocket but must be handled differently: presence messages are never written to the document log, are never part of undo history, may be dropped under load, and should not delay document operations. Some systems send presence through a separate lightweight pub/sub path entirely, so a presence storm in a big meeting cannot slow editing.

Large audiences. A company-wide document open by 2,000 people, or a design file during an all-hands review, cannot show 2,000 cursors or fan out every cursor update to every viewer: that would be 2,000 × 2,000 × 10 = 40 million messages per second. Systems cap fan-out by showing only active editors' cursors, sending viewers a summary such as "and 1,994 others", and degrading to slower update rates as the audience grows.

Follow mode and selections. Features such as "follow" a presenter's viewport, or highlighting another user's selection, are just richer presence state: a viewport rectangle or a selection range anchored to IDs. They follow the same rules: owned by one user, latest value wins, and ephemeral.

Typing indicators and locks as presence. Soft locks, such as "Alice is editing this cell", are often built on presence rather than on real locks: they warn others but do not block them, because a stale lock held by a disconnected user would block everyone. A real lock, if one is truly needed, must have a lease that expires.

Real examples: Google Docs and Figma multiplayer#

Google Docs: OT with a central server. Google Docs' real-time collaboration, rebuilt in 2010 using the operational-transformation lineage of Jupiter and Google Wave, keeps each document's edits ordered by Google's servers. Each client sends operations against the last revision it saw, the server transforms them against operations it has accepted since, assigns the next revision, and broadcasts. The revision log supports version history, and presence shows coloured cursors for each collaborator. A typical system design breakdown of a Docs-like editor focuses on four requirements, creating documents, many users editing concurrently, seeing others' changes in real time, and seeing their cursors and presence, and leaves rich document structure, permissions and history out of scope. Its two deep dives are the ones above: scaling millions of WebSocket connections across document servers with a routing layer, and keeping storage under control with snapshots and compaction of the operation log. See Design a Collaborative Editor.

Figma multiplayer: a simpler scheme made possible by a server. Figma launched multiplayer editing in 2016, and Evan Wallace, its co-founder and then chief technology officer, described the design in a 2019 engineering post. The team considered OT and rejected it as more complex than they needed. A design file is not a long string of characters; it is a tree of objects: frames, shapes, text layers, components, each with properties such as position, size, colour and text. And Figma always has a server. So Figma took ideas from CRDTs but simplified them, relying on the server as the single authority.

  • The data model: a document is a map from object ID to a map from property name to value. A tree is represented by each object storing its parent as a property.
  • Conflict resolution: two clients changing different properties, or different objects, never conflict. Two clients changing the same property of the same object are resolved by last-writer-wins, where "last" means last to reach the server, so no clocks are needed. A property value is atomic: if one user changes a text layer's content from "B" to "AB" and another to "BC", the result is "AB" or "BC", never "ABC". Figma accepted that for design properties.
  • Avoiding flicker: when a client has sent a change to a property that the server has not yet acknowledged, it ignores incoming server updates to that property, because they are older than its own pending edit from the server's point of view, and would make the property briefly flicker back.
  • Creating and deleting objects: clients generate object IDs that include a unique client ID, so they can create objects offline without collisions. Deleting an object removes it, and a property update cannot recreate a deleted object. The deleted object's data is kept in the deleting client's undo history, so undo can restore it.
  • Reparenting: moving an object to a new parent is a change to its parent property, not a delete and re-create, so concurrent edits to the object survive the move. Two concurrent moves can create a cycle, A inside B and B inside A. The server rejects any parent change that would create a cycle; a client that has applied such a change locally temporarily hides the affected objects until the server's correction arrives.
  • Ordering children: siblings are ordered by fractional indexing: each child has a position, a fraction between 0 and 1, and inserting between positions 0.25 and 0.5 uses their midpoint, 0.375. Positions use arbitrary precision, so there is always room for another between any two. The parent and position are written together as one property, so a move is atomic. Two users inserting at the same spot concurrently can pick the same position, so an implementation needs a deterministic tie-break, such as comparing object IDs.
  • Infrastructure: each document gets one server process, reached over a WebSocket. On connect, a client downloads the latest document state and from then on exchanges property updates. On reconnecting after a drop, it downloads the document again and reapplies its own unacknowledged edits on top, which also gives offline editing almost for free.

Figma's lessons. The server makes "last" meaningful, which removes the need for clocks, version vectors or tombstones. Property-level granularity makes most edits conflict-free. And where precise merging matters, as for long text, a real sequence CRDT, or OT, is still needed: Figma's choice of whole-value text was acceptable for short design labels, not for a word processor.

Real examples, in depth#

Making Figma's flicker rule precise. The server applies updates in arrival order and broadcasts each one in that order, so every client receives them in the server's sequence. A client with a pending, unacknowledged write to property p ignores server updates to p until its own write is acknowledged, because any update to p that the server sends before the acknowledgement was ordered before its own write and will be overwritten by it. After the acknowledgement, it accepts updates again, since those were ordered after its write. This yields the same final state on every client, without flicker, and it is a small, server-assisted version of the "my pending writes win locally" rule that sync engines use.

Text inside Figma-like tools. Short labels can be atomic values, but a design tool's long text, comments, or a whiteboard's sticky notes can benefit from a sequence CRDT per text property. This hybrid is common: a structured document of objects and properties with LWW per property, plus a sequence CRDT for the few properties that are long text.

Other products.

  • Notion stores pages as trees of blocks, each with properties, and collaboration resolves changes at block granularity, so concurrent edits to different blocks do not conflict.
  • Linear built a sync engine in which clients hold a local copy of their workspace data in IndexedDB, apply changes optimistically, and receive ordered change packets from the server, which is authoritative.
  • Apple Notes has been reported to use CRDTs for syncing notes between devices; treat this as reported rather than documented.
  • Zed, a code editor, built its collaborative editing on CRDTs, as its developers have described.
  • Microsoft Fluid Framework, used in Microsoft Loop, uses a central ordering service that stamps each operation with a sequence number, and distributed data structures that merge using that total order.
  • Riak, Redis Enterprise Active-Active and Akka use CRDTs for server-side replicated data, not text editing.

When to Use It#

  • Real-time collaborative editing: documents, spreadsheets, whiteboards, design files and code, where several people edit at once and each must see their own changes instantly.
  • Offline-first and multi-device apps: notes, tasks, field data collection and personal knowledge tools that must accept edits without a connection and merge later.
  • Multi-region, multi-leader databases: when every region must accept writes locally for latency or availability, and writes to the same data in different regions must be reconciled. See Multi-Region and Global Data.
  • Counters, sets and flags updated in many places: view counts, likes, presence lists, feature flags and shopping carts, where CRDT counters and sets give exact merges without coordination.
  • Peer-to-peer and end-to-end encrypted collaboration: where no server can read or order the data, CRDTs are the only practical way to merge.

When NOT to Use It#

  • When an invariant must hold across replicas: account balances that must not go negative, unique usernames, the last seat on a flight, or inventory that must not oversell. Merging cannot undo a violation after the fact; these need coordination, such as a single leader, a transaction or consensus. See Pattern: Dealing with Contention.
  • When single-leader writes are fast enough: if every user is near one region and the app needs no offline mode, a single database with ordinary transactions avoids the whole problem.
  • Full CRDTs for data that one user edits at a time: a profile or a settings page needs, at most, last-writer-wins per field.
  • Hand-written OT for a new product: unless you have a strong reason, use a proven library or a CRDT. Transform functions for rich structures are where teams lose months.
  • LWW for data where every write matters: counters, collections and text lose real user work under LWW.
  • Unbounded CRDT history on constrained devices, without a plan for compaction and snapshots: metadata can grow far beyond the visible data.

How to Implement It#

  1. Decide whether conflicts can be avoided: if one leader per item is acceptable, use it, and stop here.
  2. Pick the unit of conflict: whole document, object, property, list item or character. Smaller units mean fewer conflicts, at the cost of more metadata.
  3. Choose the semantics per field: LWW for scalar properties, a counter for counts, an add-wins or remove-wins set for collections, a sequence CRDT or OT for text, and a move-aware tree for hierarchies.
  4. Choose the architecture: a server-authoritative document process, a CRDT with a sync server, or peer-to-peer. Most products should start with a CRDT library and a sync server.
  5. Use a library: Yjs or Automerge for CRDT documents, ShareDB for OT, or a hosted service such as Liveblocks. Do not write sequence CRDTs or OT from scratch for production unless collaboration is your core product.
  6. Persist and compact: an append-only update log plus periodic snapshots, with a policy for history and tombstone garbage collection.
  7. Route documents to owners with leases or single-instance actors, and fence stale owners.
  8. Add presence as a separate ephemeral channel: throttle, time out, and anchor cursors to element IDs.
  9. Handle permissions and validation on the server, rejecting operations a user may not perform, even in a CRDT system.
  10. Test with randomised concurrency: generate random concurrent edits on several simulated replicas, deliver them in random orders with duplicates and delays, and assert that all replicas converge.

An add-wins OR-Set, in TypeScript, as a state-based CRDT:

type Tag = string; // unique per add: `${replicaId}:${counter}`
 
class ORSet<T> {
  private adds = new Map<T, Set<Tag>>();  // element -> live tags
  private removed = new Set<Tag>();        // tombstoned tags
  private counter = 0;
  constructor(private replicaId: string) {}
 
  add(x: T): void {
    const tag = `${this.replicaId}:${++this.counter}`;
    if (!this.adds.has(x)) this.adds.set(x, new Set());
    this.adds.get(x)!.add(tag);
  }
 
  remove(x: T): void {                     // removes only tags seen here
    for (const tag of this.adds.get(x) ?? []) this.removed.add(tag);
    this.adds.delete(x);
  }
 
  has(x: T): boolean {
    return (this.adds.get(x)?.size ?? 0) > 0;
  }
 
  merge(other: ORSet<T>): void {           // commutative, associative, idempotent
    for (const tag of other.removed) this.removed.add(tag);
    for (const [x, tags] of other.adds) {
      if (!this.adds.has(x)) this.adds.set(x, new Set());
      for (const t of tags) this.adds.get(x)!.add(t);
    }
    for (const [x, tags] of this.adds) {
      for (const t of tags) if (this.removed.has(t)) tags.delete(t);
      if (tags.size === 0) this.adds.delete(x);
    }
  }
}

Each add mints a fresh tag, a remove tombstones only the tags this replica has seen, and merge unions both maps, then drops tombstoned tags. A concurrent add's new tag is not in the remover's tombstones, so the element survives: add wins. Production versions replace the tombstone set with version vectors, as in the optimised OR-Set, so removed tags need not be stored forever.

TechnologyFits when
YjsReal-time text and structured documents in the browser; YATA-based; many editor bindings; y-websocket or Hocuspocus servers
AutomergeJSON-like documents with full history, offline-first apps; Rust core with JavaScript and other bindings
ShareDBServer-authoritative OT over JSON documents, with MongoDB or PostgreSQL persistence
Liveblocks, PartyKit and similar hosted servicesPresence, storage and CRDT-backed collaboration without running your own servers
Cloudflare Durable ObjectsOne authoritative instance per document, at the edge, with WebSockets and storage
Microsoft Fluid FrameworkDistributed data structures with a central ordering service
Replicache, Zero, ElectricSQL, PowerSyncSync engines: local-first apps over a server database, with server-authoritative mutations
Riak data typesServer-side CRDT counters, sets and maps in a Dynamo-style store
Redis Enterprise Active-ActiveMulti-region Redis with CRDT-based conflict resolution
Akka Distributed DataIn-cluster replicated CRDTs for JVM services

Trade-offs#

OptionProsConsPick when
Avoid conflicts with a single leaderSimple semantics; invariants enforceableWrite latency to the leader; unavailable in partitions; no offlineMost CRUD apps; invariants matter
Last-writer-winsTrivial; small metadata; always convergesSilently drops writes; clock skew picks wrong winnersScalar fields, rare conflicts, single orderer
Siblings, application mergeNever loses dataEvery reader must merge; merge bugsDomain-specific merges, Dynamo-style stores
OT with a central serverCompact operations and documents; mature for textNeeds a server; transform functions are hard; TP2 without a serverOnline editors with a server, such as Docs-style
State-based CRDTsAny delivery order; simple gossipWhole-state transfer; metadata per replicaCounters, sets, replicated databases
Op-based and delta CRDTsSmall messagesNeed reliable causal delivery, or deltasCollaboration over a sync server
Sequence CRDT for textOffline and peer-to-peer; provable convergencePer-character metadata, tombstones, interleaving risksLocal-first editors, offline text
Figma-style LWW per property with a serverVery simple; few conflicts; no clocksNo merge within a value; needs a serverObject-and-property documents: design tools, boards

Common Pitfalls#

  • Trusting wall clocks for LWW: a server with a fast clock wins every conflict, and a newer write can lose. Use logical or hybrid clocks, or a single orderer.
  • LWW on a whole object, so concurrent edits to different fields lose one user's changes. Resolve per field.
  • Implementing a counter as an LWW integer, so concurrent increments are lost. Use a G-Counter or PN-Counter.
  • Expecting a CRDT to protect an invariant, such as non-negative stock. Merging cannot prevent a violation; coordinate.
  • Storing cursors as absolute indexes, so they jump when others edit. Anchor them to element IDs or transform them.
  • Persisting presence, or putting cursor updates into the document log and undo history.
  • Unbounded tombstones and history, so a long-lived document grows to many times its visible size and loads slowly. Snapshot and compact.
  • Two document owners after a partition, accepting conflicting histories. Use leases and fencing.
  • Writing OT transform functions by hand for rich structures without exhaustive randomised tests.
  • Move as delete plus insert, which duplicates items under concurrent moves, and tree moves without cycle checks.
  • Assuming "conflict-free" means "what users expected": a CRDT always converges, but to its own semantics, such as add-wins, or interleaved characters, which may still surprise users.
  • Skipping server-side validation in a CRDT system, letting a client write anything it likes into a shared document.

Real-World Examples#

  • Google Docs uses operational transformation with a central server that orders every document's operations, a design descended from Jupiter (Xerox PARC, 1995) and Google Wave (2009).
  • Figma built multiplayer in 2016 with a server process per document, last-writer-wins per object property as ordered by the server, fractional indexes for child order, and server-side cycle rejection for reparenting, as described by Evan Wallace in 2019.
  • Yjs powers collaboration in many editors and products, with bindings for ProseMirror, Tiptap, CodeMirror, Monaco and Quill.
  • Automerge, led by Martin Kleppmann and the Ink & Switch research lab, provides JSON-like CRDT documents with full history, and was rewritten in Rust for version 2.0 in 2023.
  • Zed builds collaborative code editing on CRDTs, and Microsoft Loop builds on the Fluid Framework's ordered distributed data structures.
  • Amazon's Dynamo (2007) kept shopping-cart siblings and merged them by union; Riak later added CRDT data types; Redis Enterprise offers CRDT-based Active-Active replication; Cassandra and DynamoDB global tables use last-writer-wins.

In the Interview#

Deep Dive: Designing the document service for a collaborative editorShow

Requirements. 50 million documents, 2 million concurrently open, up to 100 simultaneous editors in one document, edits visible to others within 200 ms, no acknowledged edit lost, and history retained for version restore.

Edit traffic. Suppose 2 million open documents have about 4 million connected clients, and 20% of them, 800,000 people, are typing at any moment. A typist produces about 5 keystrokes a second, so the system receives about 4 million operations a second. Clients batch keystrokes every 50 to 100 ms, which coalesces them into roughly 2 to 3 million messages a second, and each accepted operation is broadcast to the document's other editors, usually one to three. At about 100 bytes per message with framing, total edit traffic is a few hundred megabytes a second in each direction: substantial, but spread across thousands of document processes, each of which handles only its own documents' handful of operations a second.

Architecture.

  1. Gateways terminate WebSockets, authenticate users, and route each document's messages to its owner. With 4 million connections and 50,000 to 100,000 connections per gateway, 40 to 80 gateways suffice, plus headroom.
  2. Document servers each own thousands of open documents in memory. Ownership is recorded in a coordination service with leases, or via a consistent-hash ring, and every write to storage carries the owner's fencing token.
  3. The operation log is a durable store keyed by (document ID, revision), written before acknowledging, such as a wide-column store or a partitioned relational table, plus snapshots in object storage every few hundred operations or every few minutes.
  4. Presence flows from gateways to the document server and back out, never stored, throttled to about 10 updates a second per user, and capped for large audiences.
  5. Cold documents are unloaded after minutes of inactivity; opening one loads the latest snapshot and replays the operations after it, typically in tens of milliseconds.

Failure handling. If a document server dies, its leases expire, perhaps after 10 seconds, the documents are reassigned, and clients reconnect, resend their unacknowledged operations based on their last known revision, and the new owner transforms or merges them. Because every acknowledged operation was durable before the acknowledgement, nothing acknowledged is lost, and unacknowledged operations are retried by the clients that hold them.

OT or CRDT? With this server-centred design, either works. OT keeps the server's in-memory state as plain text plus formatting, which is compact. A CRDT such as Yjs allows offline editing and makes reconnecting simpler, because the server merges client state without needing to know the client's base revision, at the cost of more memory per document. Many new systems choose a CRDT for that flexibility. See Design a Collaborative Editor.

Deep Dive: Version vectors, causal delivery and the cost of metadataShow

Version vectors. A version vector maps each replica ID to the number of updates from that replica that a state includes, such as {A: 5, B: 3}. Comparing two vectors entry by entry tells whether one state includes the other, in which case the newer replaces the older, or whether they are concurrent, in which case they must be merged. Dynamo, Riak and many CRDT sync protocols use them. Their size grows with the number of replicas that have ever written, which is why systems with many short-lived clients, such as browser tabs, use dotted version vectors (Nuno Preguiça, Carlos Baquero and colleagues, around 2010 to 2012), server-side vectors, or periodic pruning.

Causal delivery for op-based CRDTs. An op-based CRDT may require that an operation is applied only after the operations it depends on: deleting a character only after inserting it. Each operation carries its dependencies, such as the version vector of its origin, or the IDs of the operations it builds on, and a replica buffers operations until their dependencies have arrived. Automerge records each change's dependencies as hashes, forming a directed acyclic graph like Git's commit graph, and two replicas sync by exchanging the changes the other lacks, using Bloom filters or hash comparisons to find the difference efficiently.

Worked metadata example. A 20-page document has about 50,000 characters. Typed by three people over a week, with 30% of all typed characters later deleted, its history contains about 71,000 insertions and 21,000 deletions. A naive sequence CRDT storing a 16-byte ID, a 16-byte origin reference and a deleted flag for each character would need about 2.3 MB, more than 40 times the 50 KB of text. With run-length encoding, where most runs are tens of characters typed in one go, the overhead falls to perhaps a few bytes per character, and with columnar compression the full history can be within a small multiple of the text size. Whether the history must be kept at all is a product decision: a version-history feature needs it, while a pure sync use can garbage-collect it.

Snapshots in a CRDT world. A CRDT document can be snapshotted by encoding its current state, including the metadata needed for future merges. A client that has been offline for a month and still holds operations against an older state can merge them with the snapshot, as long as the snapshot kept the IDs those operations refer to. If tombstones were garbage-collected, that client's edits may no longer merge cleanly, so systems either keep tombstones for a generous window or force long-offline clients to rebase their edits on a fresh copy.

Deep Dive: Choosing conflict semantics, with worked casesShow

A shared to-do list. Items are added, completed, edited, reordered and deleted, sometimes offline. Model the list as an OR-Map from item ID to an item object; each item's title as a short text CRDT or an LWW register, its "done" flag as an LWW register, and its order as a fractional index, also an LWW register. Concurrent edits to different items or different fields merge cleanly. If one user deletes an item while another edits it, add-wins semantics, or "edit revives", keeps the item, which is usually friendlier than losing the edit.

A multi-region like counter. Each region increments its own entry of a G-Counter, and unlikes go in the N side of a PN-Counter. Regions gossip states every second. The displayed count is eventually exact, never loses an increment, and never double-counts, and no region waits on another. The price is one entry per region, which is tiny.

Stock levels. Each region's PN-Counter decrement for a purchase converges, but two regions can both sell the last unit. Options: route each item's stock to one home region, which coordinates, or give each region an escrow allocation, such as 30 of 100 units, sell freely within it, and rebalance allocations through coordination when a region runs low.

A design document. Follow Figma: LWW per property, ordered by a server, with fractional indexes for order and cycle checks for reparenting. Use a sequence CRDT only for long text properties.

A wiki or code file. Text dominates, so use a sequence CRDT or OT, and add Peritext-style marks for formatting. For code, character-level merges preserve both users' work, but the combined code may not compile, a semantic conflict, so editors show each other's presence prominently to discourage simultaneous edits in the same place.

Key Takeaways#

  • Concurrent edits make replicas diverge, and positions in operations are relative to a state, so naive replay corrupts documents.
  • A correct collaborative system preserves convergence, causality and intention.
  • Last-writer-wins always converges but silently drops the loser, and wall clocks can make the wrong write win; use it per field, ideally with a single orderer.
  • OT transforms operations against concurrent ones; it is compact and proven in Google Docs, but tractable mainly with a central server, because TP2 is hard.
  • CRDTs make merges commutative, associative and idempotent, giving strong eventual consistency with any delivery order.
  • G-Counters keep one entry per replica; OR-Sets tag every add so concurrent adds beat removes; registers are LWW or multi-value.
  • Sequence CRDTs such as RGA and Yjs's YATA give every character a permanent ID, at the cost of metadata, tombstones and possible interleaving.
  • Most products are server-authoritative, with one process per document, even when they use CRDTs; local-first systems push CRDTs to every device.
  • Presence is ephemeral, owned per user, throttled, and anchored to stable positions.
  • Figma shows that with a server, LWW per property plus fractional ordering and cycle checks is enough for structured documents.
  • Merging cannot protect invariants; anything like stock, balances or uniqueness needs coordination.