All posts
  • #collaboration
  • #crdt
  • #offline-first

CRDTs and Yjs: How Apps Merge Edits Without Losing Your Work

Why 'last write wins' silently loses data, how Operational Transformation and CRDTs each solve concurrent editing, how Yjs works under the hood, and when a simpler server-authoritative design is the better call. With two real Yjs docs you can take offline.

Akshit Bansal20 min readPart 5

take a phone offline
on this page

In one minute

  • Several people (or devices) edit the same data at once, sometimes offline. Every copy must end up the same, and nothing may be lost.
  • Last-write-wins keeps the newest save and silently drops the rest. Locking avoids conflicts but kills offline editing.
  • OT (Google Docs) rewrites each edit through one central server. CRDTs are data structures whose merges work in any order, so any device can sync with any other, with no referee.
  • Yjs, a CRDT library: every insert gets a permanent ID, deletes leave tombstones, and sync sends only what the other side is missing. The price is extra metadata. If a server is always in the middle, a simpler design (like Figma's) can be enough.

Words you need

  • Replica

    One copy of the shared data. Each phone, browser tab or server holding the grocery list has a replica.

    Like each family member's own copy of the holiday notebook

  • Concurrent edits

    Changes made without either side having seen the other's change yet. Two offline edits made an hour apart still count.

    Like two people writing on their own copies of the same page

  • Conflict

    Concurrent edits that touch the same thing, where the combined result isn't obvious.

    Like two people writing different names on the same blank line

  • Convergence

    Once every replica has seen the same set of edits, they all hold exactly the same data. Also called strong eventual consistency.

    Like every notebook ending up word-for-word the same

  • Last-write-wins (LWW)

    When two versions disagree, keep the one with the later timestamp and drop the other.

    Like photocopying the newest page over everyone else's

  • Lost update

    An edit that was saved fine, then silently disappears during a sync.

    Like your note vanishing under someone's photocopy

  • Locking

    Only one person may edit at a time. Everyone else waits.

    Like a talking stick: only the holder may speak

  • Operation

    One edit written as an instruction, like 'insert x at position 5' or 'delete position 2'. Positions count from 0.

    Like a move in a board game: 'knight to f3'

  • Operational Transformation (OT)

    Adjusting an incoming operation for edits it didn't know about, so it still means what its author meant.

    Like a referee who rewrites every move to fit the board as it is now

  • Server-authoritative

    One central server is the source of truth. Clients send changes; the server decides the order and the result.

    Like a teacher's attendance register: only the one at the front is official

  • Peer-to-peer

    Devices syncing directly with each other, with no server in the middle.

    Like passing notes across the table instead of through the teacher

  • CRDT

    Conflict-free Replicated Data Type: data designed so replicas can change independently and always converge when they merge, with no referee.

    Like a shared rulebook for combining notebooks that gives the same result whoever does it

  • Commutative, associative, idempotent

    Three properties of a safe merge: order doesn't matter, grouping doesn't matter, and merging the same thing twice changes nothing.

    Like pooling two stamp collections: any order, any grouping, and a stamp you already have adds nothing

  • Grow-only counter

    The simplest CRDT: each replica keeps one slot per replica, only bumps its own, and merging takes the biggest value per slot.

    Like a scoreboard where each player only writes their own score

  • State-based / operation-based

    The two CRDT families. State-based ones send their whole state; operation-based ones send each edit.

    Like posting the whole notebook vs posting just today's new lines

  • Yjs

    An open-source CRDT library for JavaScript. Its shared types (Y.Text, Y.Array, Y.Map) look like normal data and merge themselves. A document is a Y.Doc.

    Like a ready-made rulebook you import instead of writing your own

  • Item and ID

    How Yjs stores each inserted character or list entry: a permanent ID (a random client ID plus that client's counter, like A:2) and the ID of its neighbour.

    Like a numbered sticky note that says 'I go after note A:2'

  • Tombstone

    A deleted item that Yjs keeps, marked deleted, so late edits that point at it still find their place.

    Like a crossed-out line you don't erase, because someone's note says 'after line 4'

  • State vector

    For each client, the highest counter a replica has seen. Two replicas compare them to find exactly what's missing.

    Like a 'last page I've read' bookmark for each author

  • Metadata

    Extra data a CRDT keeps so merging works: IDs, links, tombstones. Users never see it.

    Like page numbers and margin notes in a notebook

  • Local-first

    Apps where your data lives on your device first and syncs when it can. The cloud is a sync partner, not the owner. Offline-first is the same idea.

    Like a diary you keep at home and share copies of, not one kept at the post office

The grocery list in the basement

  • Meera and Kabir share a grocery list app. On Saturday they split up in a big supermarket whose basement has no mobile signal.
  • Meera adds "eggs". Two aisles away, Kabir adds "chai". Neither phone can reach the internet, so each saves its own version.
  • Back upstairs, both phones sync. A simple sync sees that Kabir saved a minute later, and keeps Kabir's list.
  • The eggs are gone. No error, no warning.
Server rule
7/7

Both phones download the winner. Meera's eggs are gone, and nobody saw an error.

Press play or step through, then switch the server's rule. Last-write-wins throws away a perfectly good edit; a merge keeps both.

The two easy answers, and why they fail

Last-write-wins

  • Keep the version with the latest timestamp. Used everywhere, often by accident.
  • It converges, because everyone agrees on the winner. But it gets there by throwing data away: the lost update above.
  • Fine where only the latest value matters: a profile photo, a "last seen" time.

Locking

Meeraholds the lock, editing
Shared listone editor at a time
Kabirwaits; can't edit offline
Locking: whoever opens the list first gets the lock. Everyone else waits, and nobody can edit offline.
  • Prevents conflicts completely.
  • Fine for a booking system or a shared spreadsheet cell. Painful for writing together, and no use in a basement.

Round 1: Operational Transformation

  • 1989: Clarence Ellis and Simon Gibbs publish OT, from research on software for groups.
  • Describe every edit as an operation. When two happen concurrently, transform one against the other before applying it, so it still means what its author intended.
Kabir's phone
4/4

Kabir's phone transforms Meera's insert: a character before position 5 was deleted, so it now goes at 4. Both phones read “tea oat milk”.

Meera inserts at 5 while Kabir deletes at 2. By the time Meera's insert reaches Kabir, his text has shifted left by one. Flip Kabir's phone to 'applies it as sent' to see what goes wrong.
  • OT turned out to be very hard to get right for complex documents, especially with many users and no central coordinator.
  • 1995: Xerox PARC's Jupiter system made it manageable by routing every edit through a central server:
  1. 01

    Client sends an op

    insert “oat ” @5

  2. 02

    Server orders it

    one official order for everyone

  3. 03

    Server transforms it

    against edits that client hadn't seen

  4. 04

    Everyone applies it

    same order, same result

  • Google Wave was built on ideas from Jupiter. Google Docs was built on OT with a central server (case file #1).

Quick check: Shared text: 'teaa milk'. Kabir's phone has already deleted position 2. Meera's 'insert “oat ” at 5' arrives. Where should Kabir's phone insert it?

Round 2: CRDTs

  • 2011: Marc Shapiro, Nuno Preguiça, Carlos Baquero and Marek Zawirski formalise Conflict-free Replicated Data Types.
  • Replicas update independently, in any order, and always converge. It's mathematically guaranteed, with no coordination.
  • The trick is to design the data type so that merging is safe in every order:
  • Commutative

    merge(A, B) = merge(B, A)

    Merging A then B gives the same result as B then A.

  • Associative

    merge(merge(A, B), C) = merge(A, merge(B, C))

    It doesn't matter how you group merges.

  • Idempotent

    merge(A, A) = A

    Merging the same thing twice is harmless.

  • With all three, it doesn't matter what order updates arrive in, whether they're delayed, or whether some arrive twice. Everyone ends up in the same place.

The simplest CRDT: a grow-only counter

  • Say you count "likes" across phones. Instead of one number, each replica keeps one slot per replica and only increments its own.
  • To merge, take the maximum of each slot. The total is the sum of the slots.

Phone Atotal 4

  1. 3slot A (mine)
  2. 0slot B
  3. 1slot C
max per slot

Phone Btotal 3

  1. 1slot A
  2. 2slot B (mine)
  3. 0slot C

Each phone only bumps its own slot. Merge in either direction, as often as you like.

A says 4, B says 3
Like on either phone, then merge in any order, any number of times. Both phones always land on the same slots and the same total.

Quick check: The network retries, and phone B receives the same merge from phone A twice. Which property makes that harmless?

Two families of CRDTs

State-basedOperation-based
SendsIts whole state, like the counter aboveJust the operations: “Meera inserted 'eggs' after 'bread'”
Merges withA function like “max per slot”Applying each operation
GoodSimple and robustMuch smaller messages
BadThe state can be bigThe network must deliver every operation, exactly once (or operations must be safe to replay)
  • Real systems, Yjs included, mix the two. They send small operations during normal editing. When two replicas reconnect after a long time, they swap a compact summary of what each has seen, then send just the missing pieces.

Who has to be online?

OT: one referee

serverorders + transformsclient 1client 2client 3

Every edit goes through the server

CRDT: sync with anyone

serveroptional relaypeer 1peer 2peer 3peer 4

Any path, any order, same result

Both servers are up. Try taking them down.

OT relies on a central server to order and transform edits. A CRDT replica can sync with any other, directly or through a server, and still converge. Take the server down and compare.

How Yjs works

  • Yjs is an open-source CRDT library for JavaScript, created by Kevin Jahns.
  • It's based on YATA, an algorithm described in a 2016 paper by Nicolaescu, Jahns, Derntl and Klamma.
  • You use shared types that look like normal data structures (Y.Text, Y.Array, Y.Map), and Yjs handles the merging.

Step 1: every insert gets a permanent ID

  • Text editing is the hard case. "Insert at position 5" breaks as soon as someone else edits before position 5: you just saw it in the OT demo.
  • So Yjs doesn't use positions at all. Every inserted character (or list item) becomes an item with:
    • a unique ID: who created it (a random client ID) and their counter (0, 1, 2…);
    • a reference to the item it was inserted after (and before), at the moment it was typed.
  • "Insert 'i' after item A:2" means the same thing on every replica, whatever else has changed.
  1. cA:0after
    start
  2. hA:1after
    A:0
  3. aA:2after
    A:1
  4. yB:0deleted
  5. iA:3after
    B:0
Visible text: “chai”stored: 5 items, 1 tombstone client A client B
4/4

Client A was offline and still saw “chay”. It types “i” after B:0. Because the tombstone is still there, every replica knows where “i” goes: “chai”.

How Yjs builds the word 'chai': a chain of items, each with a (client, counter) ID and a link to its neighbour. The deleted 'y' stays in the chain as a tombstone, and that's what lets a late edit land in the right place.

Step 2: inserts at the same spot get the same order everywhere

  • Meera and Kabir both insert right after "bread" at the same time. Both new items point to the same neighbour.
  • Yjs breaks the tie with rules every replica applies the same way, based on the items' IDs and origins.
  • Neither item is lost. The order is just consistent everywhere.

Meera (offline)

insert “eggs”after “bread”

Kabir (offline)

insert “chai”after “bread”

Every replica, after the merge

milk, bread, eggs, chaiMeera's phone
milk, bread, eggs, chaiKabir's phone
Two concurrent inserts after the same item. The order shown is one possible outcome; what matters is that every replica picks the same one.

Step 3: deletes leave tombstones

  • When you delete an item, Yjs doesn't throw it away. It marks it deleted: a tombstone.
  • Why: an edit from an offline phone might still say "insert after item B:0". If B:0 were gone, nobody would know where to put the new text.
  • Yjs keeps just enough of deleted items for this, and works hard to keep tombstones small, for example by merging runs of consecutive items into one.

Quick check: Why does Yjs keep a deleted item as a tombstone instead of removing it straight away?

Step 4: sync by asking "what haven't you seen?"

  • Every Yjs document keeps a state vector: for each client, the highest counter it has seen. "I have everything from client A up to 12, and from B up to 7."
  • To sync, a replica sends its state vector. The other side replies with exactly the missing items.
  • That's how a phone that's been offline for a day catches up quickly. It works the same through a server, directly between browsers, or even by passing a file around.
5/5

Both documents now hold exactly the same items, so both show exactly the same content.

Each square is one item. The phone sends a few numbers; only the items the other side lacks travel back, in both directions.

In code, that's all it takes to merge two documents:

merge.tsts
import * as Y from "yjs";const meera = new Y.Doc();const kabir = new Y.Doc();meera.getArray("groceries").push(["eggs"]); // offlinekabir.getArray("groceries").push(["chai"]); // offline, at the same time// Reconnect: each side sends exactly what the other is missing.Y.applyUpdate(kabir, Y.encodeStateAsUpdate(meera, Y.encodeStateVector(kabir)));Y.applyUpdate(meera, Y.encodeStateAsUpdate(kabir, Y.encodeStateVector(meera)));meera.getArray("groceries").toArray(); // both items, in the same order on both phones

Try it: two phones, one list

Both phones below run real Yjs documents, wired together on this page with no server. Each phone also runs a naive last-write-wins copy, so you can watch them disagree.

InteractiveTwo phones, one list
go offline, edit both!
loading the demo…
Each phone holds a real Y.Doc. While both are online, updates flow instantly. Offline edits are kept locally; on reconnect, the docs swap exactly what the other is missing. The last-write-wins lists use the same edits but keep only the newest snapshot.

Things to try:

  1. Lost update. Take both phones offline, add a different item on each, reconnect. Yjs keeps both; last-write-wins keeps only the newer phone's list.
  2. Back from the dead. Offline, delete an item on one phone and tick it off on the other. Reconnect. Yjs keeps both intentions consistent everywhere. Last-write-wins either loses an edit or brings the deleted item back.
  3. The cost. Watch the document size. It grows a little even when you delete things, because the history needed for merging is part of the data.

Offline-first, for free

Because a CRDT doesn't need a referee, offline stops being a special case.

  1. 01

    Edit

    write to the local replica: feels instant

  2. 02

    Save

    to the device's own storage

  3. 03

    Connection appears

    whenever it does

  4. 04

    Merge

    swap only what's missing

  • This is the heart of what researchers at Ink & Switch called local-first software, in a 2019 essay: your data lives on your device first, and the cloud is a helpful sync partner rather than the owner of your data.

Which approach should you use?

Last-write-winsLockingOTServer-authoritativeCRDT
Everyday picturePhotocopying the newest page over the old oneThe talking stick: only the holder speaksA referee who rewrites every moveA teacher's attendance register: only the one at the front is officialA shared rulebook for combining notebooks
How it worksKeep the version with the latest timestampOne editor at a time, or lock sections or cellsA central server orders all operations and transforms concurrent onesA central server is the truth; simple per-field rules, like LWW per propertyMerges that work in any order, on any replica
Needs a central server?NoSomeone has to hand out the lockYes, as the refereeYes, it's the authorityNo: any replica can sync with any other
Main costSilently loses dataNo offline editing; lots of waitingHard to implement; rules out true peer-to-peer and long offline sessionsThe server must be in the middleMetadata; “converged” isn't always “what people meant”
Good forValues where only the latest matters: a profile photo, a “last seen” timeA booking system, a shared spreadsheet cellText, when every edit goes through your servers anyway (Google Docs)Objects with properties, with a server always in the middle (Figma)Offline-first, peer-to-peer, or no single referee

What CRDTs cost

  • Metadata overhead

    Every item carries its ID and links, and deleted items leave tombstones, so a document can be bigger than its visible content. Yjs works hard to compress this, and for typical documents it's modest, but it never goes to zero.

  • Converged isn't 'right'

    CRDTs promise that replicas converge, not that the result is what humans wanted. Two people rename a file to two different names at once: the CRDT picks one, consistently. Someone still has to notice.

  • Some rules need coordination

    A rule like “the account balance must never go negative” can't be enforced by merging alone. That still needs someone in charge.

When the simpler design wins

  • Figma's 2019 engineering post explains that the team looked at both OT and CRDTs, then built a system inspired by CRDTs but simpler, because Figma always has a central server.
  • Each property on each object (a rectangle's colour, say) uses last-write-wins, and the server is the authority on the order of changes.
  • A design file is a tree of objects with properties, not one long string of text. So per-property LWW gives the right behaviour almost everywhere, and the central server avoids much of the metadata a fully decentralised CRDT needs.
  • Google Docs sticks with OT, which suits a world where every edit goes through Google's servers anyway.

Different properties

Meera: colour → bluerectangle 1
Kabir: width → 200rectangle 1
Both keptblue, 200 wide

Same property

Meera: colour → bluerectangle 1
Kabir: colour → redrectangle 1
Server's order decidesthe latest change wins
Figma's rule, as its post describes it: two changes only conflict if they hit the same property of the same object. Then the server's order decides.

In the wild: case files

Case file #01

Google Docs

Big tech · 2010

OT + one referee

The problem
Google rebuilt Docs so many people could type in the same document at once and see each other's changes character by character. Concurrent edits to the same region had to merge sensibly for everyone.
The fix
Google's 2010 blog series describes storing a document as a log of changes (inserts, deletes, style changes) and using operational transformation, with a collaboration protocol through Google's servers, to merge simultaneous edits. The series noted support for up to 50 simultaneous editors at the time.
The lesson
With a central server always in the loop, OT is a proven, efficient choice. The server becomes the referee that makes transformation tractable.
Source: Google Drive Blog: Conflict resolution (2010)(opens in a new tab)
Case file #02

Figma

Startup turned big tech · 2019

CRDT-inspired, server-decided

The problem
Figma wanted real-time multiplayer for design files: many people moving, recolouring and editing objects on the same canvas simultaneously.
The fix
Figma's engineering post describes a system inspired by CRDTs but simplified because Figma has a central server. Two simultaneous changes are independent unless they affect the same property of the same object, in which case the latest change wins, with the server deciding the order. The team prototyped it in a test harness that simulated several clients and a server.
The lesson
You don't need a 'pure' CRDT to benefit from CRDT ideas. Matching the conflict model to your data (objects with properties) and your architecture (a central server) can give a simpler system.
Source: Figma: How Figma's multiplayer technology works(opens in a new tab)
Case file #03

Zed

Startup · 2022

collaboration in the editor's DNA

The problem
Zed set out to build a code editor where multiplayer editing is a core feature, not a plugin: several programmers in the same buffer, with no lag and no lost keystrokes.
The fix
In the first post on its blog, Zed explains that its buffers are built on CRDTs, so each collaborator edits a local replica that converges with the others over time, and it walks through the history of collaborative editing that led there.
The lesson
Designing the core data structure as a CRDT from day one makes collaboration a property of the editor rather than an add-on.
Source: Zed: How CRDTs make multiplayer text editing part of Zed's DNA(opens in a new tab)
Case file #04

Redis

Database company · ongoing

CRDTs in a database

The problem
Companies running in several regions want users in each region to write to a nearby copy of the database with very low latency, even though writes in different regions can conflict.
The fix
Redis's Active-Active geo-distribution is built on CRDTs: every participating cluster accepts writes, the databases use only CRDT data types so conflicts resolve predictably without application logic, and replicas converge to a consistent state (strong eventual consistency).
The lesson
CRDTs aren't just for documents. Any data that's written in many places and synced later (counters, sets, sessions) can use them.
Source: Redis docs: Active-Active geo-distributed Redis(opens in a new tab)
Case file #05

JupyterLab

Open source · 2021 onward

notebooks, together

The problem
Data scientists wanted to work in the same Jupyter notebook together, Google Docs-style, including editing and running cells.
The fix
JupyterLab 3.1 added real-time collaboration for documents and notebooks built on Yjs, enabled with a flag. From JupyterLab 4, collaboration is provided by the jupyter_collaboration extension, still on the Yjs shared editing framework.
The lesson
A general-purpose CRDT library lets a project add collaboration to complex, structured documents without inventing its own merge algorithm.
Source: JupyterLab docs: Real Time Collaboration(opens in a new tab)

Learn next and sources

  • Next ideas: other CRDT types (sets, maps, registers); how rich-text editors bind to Y.Text; causality and vector clocks; read-your-writes and other consistency guarantees.
  • Best long reads: the CRDT papers (source 3) and the local-first essay (source 5).
  1. C. A. Ellis and S. J. Gibbs, "Concurrency control in groupware systems" (opens in a new tab), ACM SIGMOD, 1989.
  2. D. A. Nichols, P. Curtis, M. Dixon and J. Lamping, "High-latency, low-bandwidth windowing in the Jupiter collaboration system" (opens in a new tab), ACM UIST, 1995.
  3. M. Shapiro, N. Preguiça, C. Baquero and M. Zawirski, "Conflict-free Replicated Data Types" (opens in a new tab), SSS 2011, and "A comprehensive study of Convergent and Commutative Replicated Data Types" (opens in a new tab), INRIA, 2011.
  4. P. Nicolaescu, K. Jahns, M. Derntl and R. Klamma, "Near Real-Time Peer-to-Peer Shared Editing on Extensible Data Types" (opens in a new tab), ACM GROUP, 2016 (YATA, the algorithm behind Yjs), and the Yjs documentation (opens in a new tab).
  5. M. Kleppmann, A. Wiggins, P. van Hardenberg and M. McGranaghan, "Local-first software" (opens in a new tab), Ink & Switch, 2019.
  6. Google Drive Blog, "What's different about the new Google Docs: Conflict resolution" (opens in a new tab) and "Making collaboration fast" (opens in a new tab), 2010.
  7. Evan Wallace, "How Figma's multiplayer technology works" (opens in a new tab), Figma, 2019.
  8. Nathan Sobo, "How CRDTs make multiplayer text editing part of Zed's DNA" (opens in a new tab), Zed, 2022.
  9. Redis, "Active-Active geo-distributed Redis" (opens in a new tab).
  10. JupyterLab, "Real Time Collaboration" (3.x) (opens in a new tab) and the JupyterLab 3.1 announcement (opens in a new tab).