CRDTs
A CRDT, a conflict-free replicated data type, is a data structure that several replicas can change on their own and then merge, always arriving at the same value without asking each other, or a server, to decide. A shopping list edited on a phone in airplane mode and on a laptop at the same time merges when the phone reconnects, and both devices end with the same list.
This page is a design. Reaktor has no CRDT library yet. The agent plan store already applies several CRDT ideas behind a single writer, the data layer names convergent replicated state as one of its consistency profiles, and the Reaktor V2 paper puts Hangar's presentation state in CRDTs; What exists today lists each of these. Everything under Design is proposed.
Overview#
Every replica applies its own edits immediately, so editing never waits for the network and works offline. Replicas then exchange what changed, by any route: directly, through a relay, or by gossip. Changes can arrive in any order and more than once.
The merge makes that safe. It ignores the order in which changes arrive, it ignores how they are grouped, and a change that arrives twice has no further effect. Two replicas that have received the same set of changes therefore hold the same value, which is called strong eventual consistency. Mathematically, the possible states form a join-semilattice, every edit moves a state upward, and the merge computes the smallest state above both inputs.
The price is metadata and invariants. A replica has to remember enough about past edits to merge correctly: which edits it has seen, and tags that tell a re-added element from a removed one. And a CRDT cannot enforce a rule that needs to see every write in order, such as "a Circle has at most six members". That rule needs one owner, an actor or a database transaction.
Try it#
The box below runs two replicas of a shopping list, an OR-Set, through a script. Each line replica.at(seconds) { list.add("bread") } is an edit on one replica, and sync(at = 4.0) exchanges everything between all replicas. The phone removes milk while the laptop, which has not heard about it, adds milk again.
- With CRDT merge, both replicas end with bread and milk. The laptop's add of milk was concurrent with the phone's remove, and in an OR-Set an add wins over a concurrent remove.
- Choose Overwrite on sync to see what many apps do when they save documents whole: at each sync, the replica with the newest edit replaces the other's whole list. The laptop edited last, so the phone's bread disappears.
- Change the first line to
val likes = pnCounter(0)and the edits to lines such asphone.at(1.0) { likes.increment() }andlaptop.at(1.5) { likes.increment(2) }. Merged, every increment counts. Overwritten, the replica that edited last wins and the others' increments vanish. - Try a register with a slow clock:
val title = lwwRegister("Draft"),laptop.skew(-1.5),phone.at(1.0) { title.set("Plan") },sync(at = 1.5),laptop.at(2.0) { title.set("Agenda") }andsync(at = 3.0). The laptop wrote after it had seen "Plan", yet "Plan" wins, because the laptop's clock reads earlier. Clocks explains the fix. sync(phone, laptop, at = 3.0)syncs two replicas. Add atabletand sync in different orders: once every replica has every change, the result is the same.
The playground's OR-Set keeps a set of removed tags, the simplest form to follow. The design uses a form that keeps no per-element tombstones.
val list = orSet("milk", "eggs")
phone.at(1.0) { list.add("bread") }
laptop.at(1.5) { list.remove("eggs") }
phone.at(2.0) { list.remove("milk") }
laptop.at(2.5) { list.add("milk") }
sync(at = 4.0)
When to use a CRDT#
Choose by the rule the data has to keep.
| The data needs | Use | Why | Examples |
|---|---|---|---|
| A rule across concurrent writers: at most six members, a balance above zero, a unique handle | An actor or a database transaction | Only an owner that sees every write in order can refuse the one that breaks the rule | Circle membership, payments, usernames |
| One writer at a time through a lifecycle | A PersistentActorNode | Its store orders the transitions | Circle lifecycle, document verification |
| Edits that keep working offline and merge later | A CRDT | Each replica accepts writes alone, and the merge never conflicts | Shopping lists, notes, drafts, settings on several devices |
| A position that only moves forward | A max register | The merge keeps the larger value | Read cursors, the last message seen |
| Counts from many writers | A PN-counter | Each replica counts its own changes | Reaction totals, view counts |
| A setting where the latest value wins | An LWW register with a hybrid logical clock | Small and simple; one of two concurrent writes loses by design | Profile fields, device preferences |
| Text or ordered lists edited together | A sequence CRDT from a maintained library | Concurrent inserts have to interleave sensibly, which is hard to get right | Shared documents, outlines |
| History that one server already orders | Neither | The clients copy the server's order | A chat history stored by the chat service |
The data layer lists the same choice as consistency profiles. Convergent replicated state is one of five, next to transactional authority, serialized entity or room authority, replicated consensus authority, and immutable append and derivation.
How a CRDT converges#
State, operations and deltas#
There are three ways to exchange changes, and they share the merge.
- State-based. Replicas send their whole state, and the receiver merges it. Any transport works, including one that drops, reorders and repeats messages, because the merge tolerates all three. The cost is sending the whole state each time.
- Operation-based. Replicas send each operation. Messages are small, but the transport must deliver every operation exactly once and after the operations it depends on.
- Delta-state. Each edit produces a delta, a small piece of state holding only what the edit changed, and deltas merge with the same rule as whole states. Deltas are as small as operations and as tolerant as states, so the design uses them.
The merge laws#
| Law | In plain words | What it allows |
|---|---|---|
Commutative: merge(a, b) = merge(b, a) | The order in which replicas exchange changes does not matter. | No coordination on order |
Associative: merge(merge(a, b), c) = merge(a, merge(b, c)) | How changes are batched or relayed does not matter. | Relays, batching and gossip |
Idempotent: merge(a, a) = a | Receiving a change twice has no further effect. | Safe retries over at-least-once delivery |
A local edit always moves the state upward, so a later merge can never undo it. When the playground was built, its model was checked against these laws on 300 generated histories: for each history, three different sync orders and a repeated sync gave the same result.
Causality#
To merge a remove correctly, a replica must know which adds the remove had seen. Each edit gets a dot, a pair of a replica id and that replica's counter. A version vector maps each replica to the highest counter seen from it, so it summarizes everything a replica has seen. Two edits are concurrent when neither replica had seen the other's edit when it made its own. In the playground, an OR-Set keeps an element when a remove met an add it had not seen, and the result message names that remove.
The building blocks#
| Type | State | Merge | Good for | Watch out for |
|---|---|---|---|---|
| G-Counter | A count per replica | Maximum per replica; the value is the sum | Counts that only grow | Every writer needs a replica id |
| PN-Counter | Two G-Counters, up and down | As G-Counter; the value is up minus down | Likes, stock movements | It cannot keep the total above zero |
| Max register | One value | The larger value | Read cursors, high-water marks | It only moves one way |
| LWW register | A value, a timestamp and a replica id | The later timestamp, ties broken by replica id | Settings, profile fields | It drops one of two concurrent writes and needs a good clock |
| MV register | Every concurrent value | Keeps the values neither side has overwritten | Fields where a person should pick | The app has to show and resolve the siblings |
| G-Set | A set | Union | Things that are never removed | No removal |
| 2P-Set | An added set and a removed set | Union of each | Removal without re-adding | A removed element can never come back |
| OR-Set | Elements tagged with dots | Keeps each dot that both sides have, or that the other side has not seen | Lists, tags, members of a draft | Without a causal context, tombstones grow forever |
| OR-Map | A map of nested CRDTs | Merges each key's value; keys behave like an OR-Set | Documents, settings objects | Deleting a key while another replica edits inside it |
| Sequence (RGA, Fugue) | Elements with unique ids and positions | Union, ordered by the ids | Text and ordered lists | Concurrent inserts can interleave; use a library |
| Tree with move | Nodes with parents and a log of moves | Replays the moves in timestamp order | Folders, outlines, groups in Hangar | Concurrent moves can form cycles; the move operation of Kleppmann and colleagues prevents them |
Clocks#
A Lamport clock is a counter that every replica increments and advances past any value it receives, so an edit always carries a larger number than every edit its replica had seen. A version vector keeps one counter per replica and tells concurrent edits apart from ordered ones.
Wall clocks drift. A last-writer-wins register stamped with wall time can let a write lose to one it had already seen, when the later writer's clock runs behind, as the skew example in the playground shows.
A hybrid logical clock, or HLC, combines the two. It stays close to wall time, never goes backward, and gives a write made after seeing another a larger timestamp. Stamp LWW registers with an HLC. An HLC still lets one of two concurrent writes lose, because the register keeps only one value, and as the data layer puts it, an HLC is not a consensus protocol.
Design: CRDTs in Reaktor#
The design has three parts. CRDTs are immutable values with a merge. A replica is an actor, one per document key, that owns the local copy. A Durable Object per document relays and stores deltas.
Types are values#
Each type is a serializable Kotlin value with one law-abiding merge. Mutators return a delta, which is a value of the same type, so applying an edit, sending it and storing it all use merge:
interface Crdt<S : Crdt<S>> {
infix fun merge(other: S): S
}
@Serializable
data class OrSet<E>(val entries: Map<E, Set<Dot>> = emptyMap(), val context: CausalContext = CausalContext()) : Crdt<OrSet<E>> {
val elements: Set<E> get() = entries.keys
fun add(element: E, dot: Dot) = OrSet(mapOf(element to setOf(dot)), CausalContext.of(entries[element].orEmpty() + dot))
fun remove(element: E) = OrSet<E>(emptyMap(), CausalContext.of(entries[element].orEmpty()))
override fun merge(other: OrSet<E>): OrSet<E> {
val merged = (entries.keys + other.entries.keys).associateWith { element ->
val mine = entries[element].orEmpty()
val theirs = other.entries[element].orEmpty()
(mine intersect theirs) + mine.filterNot { it in other.context } + theirs.filterNot { it in context }
}.filterValues { it.isNotEmpty() }
return OrSet(merged, context merge other.context)
}
}
The causal context records every dot a replica has seen. A dot survives a merge when both sides have it, or when the side that lacks it has never seen it. A remove is a delta whose context holds the removed dots and whose entries are empty, so removing leaves no per-element tombstone, and an add the remover had not seen survives. An add's context also covers the element's older dots, so adding an element again leaves it with just the new dot. The same pattern gives counters, registers stamped with an HLC, and maps of nested CRDTs.
A replica is an actor#
A replica actor owns one document's local copy. Local edits and remote deltas both arrive as messages, so they change the state one at a time without locks, the property the actor model already guarantees. Its key names the document, and its messages form a sealed ReplicaMessage<S>:
val groceries = actorKey<ReplicaMessage<OrSet<String>>>("list/groceries")
provideActor(groceries) { Replica(it, groceries, OrSet()) }
private val list: ConsumerPort<Replica<OrSet<String>>> by actorConsumes(groceries)
list { edit { dot -> add("bread", dot) } }
list().value.collect { render(it.elements) }
| Message | From | What receive() does |
|---|---|---|
Edit(change) | Screens, through edit() | Runs the change with a fresh dot, merges the delta into the state, adds it to the unsent deltas and saves both |
Remote(delta, version) | The sync socket | Merges the delta, saves, and publishes the new value |
Flush | A timer from every() | Pushes the unsent deltas in one batch |
Ack(version) | The relay | Drops the unsent deltas the relay has stored |
Snapshot(state) | The relay, for a replica that fell too far behind | Merges the whole state |
The actor keeps the state, its causal context, the unsent deltas and the relay's acknowledged version in its own ObjectStore. An edit is saved before the screen sees it, so it survives an app restart and is sent once the app is back online, the same outbox pattern ChatOutbox uses. The replica id in each dot is a stable id per installation.
Sync and the relay#
Sync is a Reaktor service, declared contract-first like any other: push(document, deltas) and pull(document, since), where since is a version vector, plus a WebSocket stream of live deltas. The data layer's sync section lists this as its "CRDT or domain merge" protocol.
The relay is a Durable Object per document, found with idFromName(document). It is single-threaded, merges incoming deltas like any replica, keeps the merged state in its storage, and fans deltas out over hibernating WebSockets; reaktor-cloudflare already ships the PartyServer and WebSocket hibernation bindings it needs. Because it holds the merged state, it can answer a new device's pull with one snapshot.
The relay is also where the rules live. It accepts deltas only from members of the document, checks that every dot in a delta carries the sender's own replica id, bounds delta sizes, and records each replica's acknowledged version. When every replica has acknowledged a dot, the dot is causally stable and its metadata can be compacted. A replica that disappears, such as a lost phone, would block compaction forever, so replicas expire after a retention period and must then resync from a snapshot.
End-to-end encryption#
A relay that merges must read the state. Under end-to-end encryption, the relay can only store and forward encrypted deltas, and devices merge after decrypting them. The relay then cannot answer a pull with a merged snapshot or compact metadata, so a new device replays the deltas or receives a snapshot from another member's device. The choice is made per document type.
In the graph#
Each replica appears in the graph as an actor node wired to the replication service, and a relation joining the replicas of one document names their merge law. The Reaktor V2 paper calls this relation Replicates; it joins an optional authority to its replicas and carries the direction, checkpoints and conflict law of the replication. With the law named, Hangar can flag two replicas of one document that merge differently, which would otherwise diverge without an error.
Libraries#
Write the simple types in Kotlin: counters, registers, sets and maps are short, well understood, and serialize with kotlinx.serialization like any other state. Text needs a sequence CRDT, which is hard to get right: concurrent inserts must not interleave letter by letter, and the metadata must stay small. Use a maintained library for it: Yjs in the browser, its Rust port Yrs bound through reaktor-ffi on native and JVM targets, or Automerge, which has a Rust core with JavaScript bindings. Loro is another option. All four repositories had commits in October 2026, and y-partyserver already runs Yjs on Durable Objects.
What exists today#
- The agent plan store.
WorkPlanStoreinreaktor-conductorapplies every write to a plan in one process, the agent owner, so it needs no merge. Its write rules still borrow from CRDTs, because several agents and people write to one plan. Adding an item never conflicts with anyone else's edits; a writer may choose the new item's key, and the store refuses a key that is taken. Edits to different items all apply. A write names the plan revision its writer last read, and an operation on an item that someone else changed after that revision is refused for that item only, while the rest of the write applies. Connecting two items counts as a change to the item that waits. Each write enters the plan's change log with its author, its revision and a line per change, and the log keeps the last 200 writes. A replica protocol could start from that log if plans ever sync across machines. - The board.
reaktor-boardkeeps Excalidraw's element scheme. Each element carries a version, a randomversionNonceand anisDeletedflag, and erasing an element marks it deleted with a higher version, so it stays in the scene as a tombstone. When two copies of an element meet, Excalidraw keeps the one with the higher version and breaks ties with the nonce, which makes each element a last-writer-wins register ordered by version.reaktor-boarddoes not reconcile copies itself yet. - The data layer. Consistency profiles include convergent replicated state, and the sync protocols include CRDT merge with causal metadata and compaction conditions.
- The Reaktor V2 paper. Change and the protocol keep presentation state, such as layout, folds and comments, in CRDT operations outside commits, with a tree-move CRDT for regrouping. In Systems, shared documents declare their conflict laws on
Replicates, the paper's relation between an optional authority and its replicas. - Representative designs.
RepresentativeDefinitionsTestinreaktor-graph-portdeclares a "Local CRDT replica" node with aCRDTDeltaV1port among its thirty example systems.
Prior art#
- Akka Distributed Data replicates counters, sets, maps, registers and flags across an Akka cluster by gossip. Each read and write picks a consistency level, from the local replica to a majority or all nodes, which lets a caller wait for a majority when it must read its own write elsewhere.
- Riak shipped maps, sets, counters, flags and registers as database data types, built on
riak_dt, an Erlang library of state-based CRDTs. - Phoenix Presence, in Elixir, replicates who is online across a cluster with a CRDT and no central store.
- Automerge, Yjs and Loro are CRDT libraries for local-first documents, with JSON-like data, text and rich text.
The actor page maps the rest of Akka and Erlang/OTP onto Reaktor.
What CRDTs improve#
| Usual approach | What goes wrong | The CRDT approach |
|---|---|---|
| The server decides and clients wait online | Nothing works offline, and every edit waits for a round trip. | Edits apply locally at once and merge later. |
| Save the whole document; the last save wins | Concurrent edits made on another device disappear without a trace. | Each change merges. Concurrent edits survive, or lose by a rule chosen in advance. |
| Lock or check out the document | Locks held by devices that went offline go stale, and editors wait for each other. | There are no locks, and replicas never wait. |
| Merge code written per feature | Each feature invents its own rules, and they break when messages are reordered or repeated. | The merge laws hold by construction and can be checked on generated histories. |
Limitations#
- Nothing is built. Reaktor has no CRDT types, replica actor, sync service or relay.
- No invariants beyond the merge law. A CRDT cannot keep a limit, a uniqueness rule or a balance above zero. Use an actor or a transaction for those, or split a budget into shares that each replica may spend alone.
- Metadata grows. Dots, version vectors and tombstones grow with replicas and edits. Compaction needs every replica's acknowledgement, and a replica that vanishes blocks it until it expires.
- Last-writer-wins loses writes. It drops one of two concurrent writes by design, and with wall clocks it can drop a later write.
- A merged value is not always the intended one. Two people editing the same sentence get both edits interleaved, or one of them by rule. The merge keeps the data consistent, and the meaning can still need a person.
- State formats are hard to change. Every replica must understand every delta it can receive, so each type's format needs versioning from the first release.
- A replica can lie. Any replica can send any delta, so the relay validates the sender, the dots, the size and the membership.
- Encryption limits the relay. With end-to-end encryption, the relay cannot merge, snapshot or compact.
Next work#
- Types. A G-Counter, PN-Counter, max register, LWW register with an HLC, a dot-based OR-Set and an OR-Map in commonMain, serialized with kotlinx.serialization. Check the three merge laws on generated histories in the test suite, the way the playground's model was checked.
- The replica actor.
ObjectStorepersistence, deltas batched on a timer, aStateFlowof the value and an outbox of unsent deltas. - Sync. A replication service contract, a Durable Object relay per document, WebSocket fan-out, membership checks and compaction after acknowledgements.
- First adopters. Read cursors as a max register per user and chat; Hangar's presentation state, with node positions, folds and comments as maps and sets; and the plan store, if plans start to sync across machines.
- Text. Bind Yrs or Automerge for shared documents, chosen per platform.
- The graph. Declare
Replicateswith its merge law and check it in Hangar.
Sources#
Papers:
- Marc Shapiro, Nuno Preguiça, Carlos Baquero and Marek Zawirski, Conflict-free Replicated Data Types, SSS, 2011, and the companion report A comprehensive study of Convergent and Commutative Replicated Data Types, INRIA, 2011. The papers that defined CRDTs and catalogued the basic types.
- Nuno Preguiça, Carlos Baquero and Marc Shapiro, Conflict-free Replicated Data Types (CRDTs), 2018. A short overview.
- Paulo Sérgio Almeida, Ali Shoker and Carlos Baquero, Delta State Replicated Data Types. The delta-state model this design uses.
- Annette Bieniusa, Marek Zawirski, Nuno Preguiça, Marc Shapiro, Carlos Baquero, Valter Balegas and Sérgio Duarte, An optimized conflict-free replicated set, 2012. The OR-Set without tombstones.
- Martin Kleppmann, Dominic P. Mulligan, Victor B. F. Gomes and Alastair R. Beresford, A highly-available move operation for replicated trees, IEEE Transactions on Parallel and Distributed Systems, 2022.
- Matthew Weidner and Martin Kleppmann, The Art of the Fugue: Minimizing Interleaving in Collaborative Text Editing, 2023.
- Geoffrey Litt, Sarah Lim, Martin Kleppmann and Peter van Hardenberg, Peritext: A CRDT for Collaborative Rich Text Editing, CSCW, 2022.
- Sandeep Kulkarni, Murat Demirbas, Deepak Madeppa, Bharadwaj Avva and Marcelo Leone, Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases, 2014. The hybrid logical clock.
- Leslie Lamport, Time, Clocks, and the Ordering of Events in a Distributed System, Communications of the ACM, 1978.
Essays, talks and books:
- Martin Kleppmann, Adam Wiggins, Peter van Hardenberg and Mark McGranaghan, Local-first software: you own your data, in spite of the cloud, Onward!, 2019.
- Martin Kleppmann, CRDTs: The Hard Parts, 2020. Interleaving, moves and other traps.
- Matthew Weidner, CRDT Survey, 2023. A practical series on designing with CRDTs.
- Martin Kleppmann, Designing Data-Intensive Applications, O'Reilly, 2017. Chapter 5 covers replication and conflict resolution.
- crdt.tech, a community index of CRDT papers, talks and implementations.
Libraries and systems:
- Akka Distributed Data,
riak_dtand Phoenix Presence. - Automerge, Yjs, Yrs, Loro and y-partyserver.
Related docs#
- Actors - One owner per piece of state, and the replica actor this design builds on.
- Data layer - Consistency profiles and sync protocols, including convergent replicated state.
- Security - End-to-end encryption, which decides whether a relay can merge.
- Service Layer - How the replication contract would be declared and bound to Workers.