Skip to content
Design19 min readUpdated 3 Nov 2026

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#

Two replicas of one shopping list that starts as milk and eggs. The phone is offline and adds bread; at the same time the laptop removes eggs. Each edit applies to its own replica at once. When they reconnect, each replica sends what changed through a relay, in any order and possibly twice. Merging ignores order, grouping and duplicates, so both replicas end with the same list: milk and bread.PHONE, OFFLINELocal editadd("bread")Replica A{milk, eggs, bread}applied at once, saved locallyAfter the merge{milk, bread}LAPTOP, ONLINELocal editremove("eggs")Replica B{milk}applied at once, saved locallyAfter the merge{milk, bread}SYNC: ANY ORDER, ANY NUMBER OF TIMESRelay, one per documentstores what changed and passes it on;it merges like any other replicamerge(state, delta), on every replicathe order deltas arrive in does not matterhow deltas are grouped does not mattera delta that arrives twice changes nothing+bread−eggs−eggs+breadNeither replica waits for the other.A rule such as "at most six members" still needs an actor.
Each replica applies its own edits at once. When changes meet, the merge gives every replica the same value, whatever order they arrive in.

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 as phone.at(1.0) { likes.increment() } and laptop.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") } and sync(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 a tablet and 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 needsUseWhyExamples
A rule across concurrent writers: at most six members, a balance above zero, a unique handleAn actor or a database transactionOnly an owner that sees every write in order can refuse the one that breaks the ruleCircle membership, payments, usernames
One writer at a time through a lifecycleA PersistentActorNodeIts store orders the transitionsCircle lifecycle, document verification
Edits that keep working offline and merge laterA CRDTEach replica accepts writes alone, and the merge never conflictsShopping lists, notes, drafts, settings on several devices
A position that only moves forwardA max registerThe merge keeps the larger valueRead cursors, the last message seen
Counts from many writersA PN-counterEach replica counts its own changesReaction totals, view counts
A setting where the latest value winsAn LWW register with a hybrid logical clockSmall and simple; one of two concurrent writes loses by designProfile fields, device preferences
Text or ordered lists edited togetherA sequence CRDT from a maintained libraryConcurrent inserts have to interleave sensibly, which is hard to get rightShared documents, outlines
History that one server already ordersNeitherThe clients copy the server's orderA 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#

LawIn plain wordsWhat 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) = aReceiving 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#

TypeStateMergeGood forWatch out for
G-CounterA count per replicaMaximum per replica; the value is the sumCounts that only growEvery writer needs a replica id
PN-CounterTwo G-Counters, up and downAs G-Counter; the value is up minus downLikes, stock movementsIt cannot keep the total above zero
Max registerOne valueThe larger valueRead cursors, high-water marksIt only moves one way
LWW registerA value, a timestamp and a replica idThe later timestamp, ties broken by replica idSettings, profile fieldsIt drops one of two concurrent writes and needs a good clock
MV registerEvery concurrent valueKeeps the values neither side has overwrittenFields where a person should pickThe app has to show and resolve the siblings
G-SetA setUnionThings that are never removedNo removal
2P-SetAn added set and a removed setUnion of eachRemoval without re-addingA removed element can never come back
OR-SetElements tagged with dotsKeeps each dot that both sides have, or that the other side has not seenLists, tags, members of a draftWithout a causal context, tombstones grow forever
OR-MapA map of nested CRDTsMerges each key's value; keys behave like an OR-SetDocuments, settings objectsDeleting a key while another replica edits inside it
Sequence (RGA, Fugue)Elements with unique ids and positionsUnion, ordered by the idsText and ordered listsConcurrent inserts can interleave; use a library
Tree with moveNodes with parents and a log of movesReplays the moves in timestamp orderFolders, outlines, groups in HangarConcurrent 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 proposed design. A replica actor, one per document key, owns the local copy. Screens send edits, the sync socket sends deltas from other replicas, a timer asks for a flush and the relay acknowledges what it has stored; all of them arrive in one mailbox, so merging needs no lock. The actor keeps the state, its causal context and the unsent deltas in its own ObjectStore, publishes the merged value as a StateFlow, and reaches a relay Durable Object per document through a replication service.SENDERSREPLICA ACTOR, ONE PER DOCUMENTone mailbox, first in first outEditRemoteFlushAckScreensend(Edit(add("bread")))Sync socketsend(Remote(delta))send(Ack(version))A timerevery(1.seconds) { Flush }receive(message)Edit: apply it and keep its deltaRemote: merge the incoming deltaFlush: push the unsent deltasAck: drop deltas the relay has storedStateFlow of the merged valuewhat screens readThe actor's ObjectStorethe state and its causal context, the unsent deltas,and the version the relay has acknowledgedReplication servicepush(deltas) and pull(since), over a WebSocketRelay: a Durable Object per documentkeeps the merged state in its storage and fans deltas outpushWebSocketDesign only: no CRDT code exists in Reaktor yet.
Proposed: an actor owns each local replica, so local edits and remote deltas change it one at a time.

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) }
MessageFromWhat 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 socketMerges the delta, saves, and publishes the new value
FlushA timer from every()Pushes the unsent deltas in one batch
Ack(version)The relayDrops the unsent deltas the relay has stored
Snapshot(state)The relay, for a replica that fell too far behindMerges 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. WorkPlanStore in reaktor-conductor applies 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-board keeps Excalidraw's element scheme. Each element carries a version, a random versionNonce and an isDeleted flag, 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-board does 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. RepresentativeDefinitionsTest in reaktor-graph-port declares a "Local CRDT replica" node with a CRDTDeltaV1 port 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 approachWhat goes wrongThe CRDT approach
The server decides and clients wait onlineNothing 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 winsConcurrent 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 documentLocks 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 featureEach 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#

  1. 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.
  2. The replica actor. ObjectStore persistence, deltas batched on a timer, a StateFlow of the value and an outbox of unsent deltas.
  3. Sync. A replication service contract, a Durable Object relay per document, WebSocket fan-out, membership checks and compaction after acknowledgements.
  4. 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.
  5. Text. Bind Yrs or Automerge for shared documents, chosen per platform.
  6. The graph. Declare Replicates with its merge law and check it in Hangar.

Sources#

Papers:

Essays, talks and books:

Libraries and systems:

  • 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.