← All articles
· 2 min read

A gentle introduction to CRDTs for app developers

Conflict-free replicated data types sound academic until you need offline edits to merge cleanly. Two small ones you can build this afternoon.

The first time you build an app that edits data offline and syncs later, you meet merge conflicts the hard way: two devices changed the same thing and now the server has to pick a winner, usually by throwing one change away. Conflict-free replicated data types (CRDTs) are a way to design the data so that any two versions merge into the same result, automatically, with no central referee.

The idea rests on a merge that is commutative, associative and idempotent — apply updates in any order, any number of times, and you land in the same place. The smallest useful example is a grow-only counter. Each replica only ever increments its own slot; merging takes the max of each slot.

gcounter.js
// each replica owns one key and only increments it
function inc(state, replicaId) {
  state[replicaId] = (state[replicaId] || 0) + 1;
  return state;
}

function merge(a, b) {
  const out = { ...a };
  for (const id in b) out[id] = Math.max(out[id] || 0, b[id]);
  return out;
}

function value(state) {
  return Object.values(state).reduce((s, n) => s + n, 0);
}

Because merge takes the max per replica, syncing twice is harmless and order does not matter. That is the whole magic.

For a single editable field, a last-write-wins register attaches a timestamp (a logical clock is safer than wall time) and keeps the higher one on merge. Compose these — counters, registers, add-wins sets — and you can build a surprising amount of a collaborative app whose sync is "merge everything you have, periodically" with no conflict dialog in sight. The cost is that CRDTs only express merges that are genuinely order-independent; anything needing "reject if the balance would go negative" still wants a coordinator.