- #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 offlineon 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.
- milk
- bread
- eggslost
- chai
keeps the newest save
- milk
- bread
- chai
dropped: 10:02 list (eggs)
- milk
- bread
- chai
Both phones download the winner. Meera's eggs are gone, and nobody saw an error.
Both phones are online and agree: milk, bread. The basement has no signal. Each phone now keeps its own copy. Meera adds eggs. Her phone saves the list at 10:02. Kabir adds chai. His phone saves the list at 10:03. Back upstairs, both phones send their whole list to the server. Last-write-wins: the server keeps the newest save (10:03) and drops the other one. Both phones download the winner. Meera's eggs are gone, and nobody saw an error.
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
- 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.
Meera's phone“tea oat milk”
Kabir's phone“tea oat milk”
Same text on both phones
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”.
Both phones hold the same text. The small numbers are positions, counted from 0. At the same moment: Meera inserts “oat ” at position 5. Kabir deletes the extra “a” at position 2. Each phone sends its edit as an operation. The two operations cross on the network. 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”.
- 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:
- 01
Client sends an op
insert “oat ” @5
- 02
Server orders it
one official order for everyone
- 03
Server transforms it
against edits that client hadn't seen
- 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) = AMerging 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
- 3slot A (mine)
- 0slot B
- 1slot C
Phone Btotal 3
- 1slot A
- 2slot B (mine)
- 0slot C
Each phone only bumps its own slot. Merge in either direction, as often as you like.
A says 4, B says 3Quick 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-based | Operation-based | |
|---|---|---|
| Sends | Its whole state, like the counter above | Just the operations: “Meera inserted 'eggs' after 'bread'” |
| Merges with | A function like “max per slot” | Applying each operation |
| Good | Simple and robust | Much smaller messages |
| Bad | The state can be big | The 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
Every edit goes through the server
CRDT: sync with anyone
Any path, any order, same result
Both servers are up. Try taking them down.
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.
- cA:0after
start - hA:1after
A:0 - aA:2after
A:1 - yB:0deleted
- iA:3after
B:0
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”.
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)
Kabir (offline)
Every replica, after the merge
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". IfB:0were 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.
LaptopA:12 B:7 P:2
Phone (offline a day)A:12 B:7 P:2
Both documents now hold exactly the same items, so both show exactly the same content.
In code, that's all it takes to merge two documents:
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 phonesTry 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.
Things to try:
- 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.
- 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.
- 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.
- 01
Edit
write to the local replica: feels instant
- 02
Save
to the device's own storage
- 03
Connection appears
whenever it does
- 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-wins | Locking | OT | Server-authoritative | CRDT | |
|---|---|---|---|---|---|
| Everyday picture | Photocopying the newest page over the old one | The talking stick: only the holder speaks | A referee who rewrites every move | A teacher's attendance register: only the one at the front is official | A shared rulebook for combining notebooks |
| How it works | Keep the version with the latest timestamp | One editor at a time, or lock sections or cells | A central server orders all operations and transforms concurrent ones | A central server is the truth; simple per-field rules, like LWW per property | Merges that work in any order, on any replica |
| Needs a central server? | No | Someone has to hand out the lock | Yes, as the referee | Yes, it's the authority | No: any replica can sync with any other |
| Main cost | Silently loses data | No offline editing; lots of waiting | Hard to implement; rules out true peer-to-peer and long offline sessions | The server must be in the middle | Metadata; “converged” isn't always “what people meant” |
| Good for | Values where only the latest matters: a profile photo, a “last seen” time | A booking system, a shared spreadsheet cell | Text, 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
Same property
In the wild: case files
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.
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.
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.
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.
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.
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).
- C. A. Ellis and S. J. Gibbs, "Concurrency control in groupware systems" (opens in a new tab), ACM SIGMOD, 1989.
- 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.
- 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.
- 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).
- M. Kleppmann, A. Wiggins, P. van Hardenberg and M. McGranaghan, "Local-first software" (opens in a new tab), Ink & Switch, 2019.
- 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.
- Evan Wallace, "How Figma's multiplayer technology works" (opens in a new tab), Figma, 2019.
- Nathan Sobo, "How CRDTs make multiplayer text editing part of Zed's DNA" (opens in a new tab), Zed, 2022.
- Redis, "Active-Active geo-distributed Redis" (opens in a new tab).
- JupyterLab, "Real Time Collaboration" (3.x) (opens in a new tab) and the JupyterLab 3.1 announcement (opens in a new tab).