Lesson 6 · Mobile and offline architecture

Sync and conflict resolution

Merge changes from many devices without losing data.

About 35 minutes

Tab indents. Press Escape, then Tab, to leave the editor.

Once two devices can edit the same data while disconnected, they will diverge, and when they reconnect something has to decide what the data is now. "The last write wins" sounds like a decision but hides two hard questions: last by whose clock, and what happens to the write that lost. This lesson builds up the tools precisely: logical clocks to order events, vector clocks to detect concurrency, and conflict-free replicated data types (CRDTs) whose merge is guaranteed to converge.

Why wall clocks don't order events

Comparing Date.now() timestamps from different devices fails in ordinary conditions. Device clocks drift and are corrected by NTP, sometimes by stepping backwards. Users set their clocks by hand. A phone that spent a week in airplane mode can be minutes off. Two consequences for timestamp-based last-writer-wins (LWW):

  • Lost updates: a device whose clock runs ahead wins every conflict, even against edits made after it, causally, by someone who had already seen its change.
  • Silent loss: LWW never reports that it threw a write away. Nobody notices until a user asks where their edit went.

What you need is an ordering that respects causality: if event a could have influenced event b (same device, earlier; or b's device had received a), then a must sort before b. That's Lamport's happens-before relation (a → b).

Logical clocks

A Lamport clock is a counter per replica. Increment it on every local event; attach it to every message; on receipt, set it to max(local, received) + 1. Then a → b implies L(a) < L(b). The converse doesn't hold: L(a) < L(b) doesn't mean a happened before b. They may be concurrent. Break ties with the replica id and you get a total order consistent with causality, which is all LWW needs.

Lamport timestamps have no relationship to real time, which makes them awkward to debug and impossible to use for "show edits from the last hour". A hybrid logical clock (HLC; Kulkarni et al., 2014) fixes that: each timestamp is a pair (l, c) where l tracks the largest physical time seen and c is a counter that breaks ties when physical time hasn't advanced or a remote clock is ahead.

// A hybrid logical clock. Timestamps compare by (l, c, node).
function createHlc(node, now = Date.now) {
  let l = 0
  let c = 0
  return {
    // A local event, or sending a message
    tick() {
      const pt = now()
      if (pt > l) { l = pt; c = 0 } else { c++ }
      return { l, c, node }
    },
    // Receiving a message stamped `remote`
    receive(remote) {
      const pt = now()
      const prev = l
      l = Math.max(prev, remote.l, pt)
      if (l === prev && l === remote.l) c = Math.max(c, remote.c) + 1
      else if (l === prev) c++
      else if (l === remote.l) c = remote.c + 1
      else c = 0
      return { l, c, node }
    },
  }
}

const compareHlc = (a, b) => a.l - b.l || a.c - b.c || (a.node < b.node ? -1 : a.node > b.node ? 1 : 0)

HLC timestamps are commonly packed into 64 bits (for example 48 bits of milliseconds and 16 of counter), stay within the clock skew of real time, never go backwards on a replica even if its wall clock does, and respect happens-before. Reject, or at least flag, remote timestamps too far in the future, or a single device with a badly wrong clock can push everyone's l forward.

Vector clocks: detecting concurrency

LWW with HLCs still picks a winner when two writes are concurrent. Sometimes you need to know they were concurrent, to keep both and show the user, or to apply a type-specific merge. A vector clock holds one counter per replica: { phone: 3, laptop: 1 }. A replica increments its own entry on each event and merges incoming clocks by taking the pointwise maximum.

Compare two clocks A and B:

  • A ≤ B if every entry of A is ≤ the matching entry of B (missing entries count as 0). Then A happened before (or equals) B, and B can simply replace A.
  • If neither A ≤ B nor B ≤ A, the events are concurrent: neither saw the other. That's a genuine conflict.
function compareVectors(a, b) {
  let aBigger = false
  let bBigger = false
  for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
    const x = a[key] ?? 0
    const y = b[key] ?? 0
    if (x > y) aBigger = true
    if (y > x) bBigger = true
  }
  if (aBigger && bBigger) return 'concurrent'
  return aBigger ? 'after' : bBigger ? 'before' : 'equal'
}

The cost is size: one entry per replica that ever wrote, forever, unless you can prune replicas known to be retired. Per-object version vectors (one per record, counting writes to that record) keep it bounded by the number of devices that edited it. CouchDB-style revision trees and Riak's "siblings" are production versions of the same idea: detect concurrent versions, store all of them, let the application or user resolve.

Question

Quick check

Record versions arrive with vector clocks { phone: 2, laptop: 1 } and { phone: 1, laptop: 2 }. What's the relationship?
Pick an answer.

Conflict resolution options

From least to most work:

StrategyBehavior on concurrent writesGood for
Whole-record LWWOne device's entire record winsData edited by one person at a time; settings
Per-field LWWEach field independently keeps its latest write; edits to different fields both surviveMost form-shaped app data: notes, tasks, inventory items
Multi-value (siblings)Keep all concurrent versions, ask the app or userData where losing a write is unacceptable and merging is domain-specific
CRDTsA type-specific merge that always converges, with no coordinationCounters, sets, collaborative text, lists
Server-authoritative operationsClients send intents ("add 3 to stock"); the server orders and validates themInvariants that span records (stock ≥ 0, unique usernames)

The last row matters: no merge function can enforce a constraint across replicas that are offline. If two devices each sell the last unit while disconnected, you need a server to arbitrate, or a reservation scheme that divides the stock up in advance. Choose per data type, not per app.

CRDTs: merges that can't fail

A state-based CRDT (convergent replicated data type) defines a state, local update operations, and a merge(a, b) that is:

  • Commutative: merge(a, b) = merge(b, a), so the order replicas sync in doesn't matter.
  • Associative: merge(merge(a, b), c) = merge(a, merge(b, c)), so grouping doesn't matter (relay through a server, or gossip peer to peer).
  • Idempotent: merge(a, a) = a, so receiving the same state twice is harmless.

Formally, states form a join-semilattice and merge is the least upper bound; updates only move a state upward. Any two replicas that have received the same set of updates, in any order, with any duplication, are in the same state. That's strong eventual consistency. Operation-based CRDTs send operations instead of states, which is more compact but requires the delivery layer to provide each operation exactly once and in causal order.

The classic building blocks:

  • G-Counter (grow-only counter): a map from replica id to that replica's count. Increment your own entry. Value = sum of entries. Merge = pointwise max. Each replica's entry only ever grows, so max never loses an increment.
  • PN-Counter: two G-Counters, one for increments and one for decrements. Value = P − N.
  • LWW-Register: a value plus a timestamp (an HLC with a replica tiebreak). Merge keeps the one with the larger timestamp. A per-field LWW record is a map of these.
  • OR-Set (observed-remove set): each add attaches a fresh unique tag; remove(x) removes the tags of x that this replica has observed. An add concurrent with a remove has a tag the remove never saw, so the element survives: add wins. The cost is metadata: removed tags must be remembered (tombstones), or tracked with causal contexts as optimized variants do.
  • Sequence CRDTs (RGA, YATA as used by Yjs, the Automerge list type) give every character or list item a unique, ordered identity so concurrent inserts interleave deterministically. They're what make collaborative text editing work offline.

Challenge

Fix the G-Counter merge

Two phones count water bottles used during an outage. Each increments its own entry; the app shows value(counter). The starter merge adds the two counters together, which double-counts the moment the same state is received twice.

Rewrite merge(a, b) so it's commutative, associative and idempotent, and doesn't mutate its inputs. The checks merge random counters in random orders, with duplicates.

Console
  1. Nothing logged yet.
  • Merging a counter with itself changes nothing
  • Merge is commutative and associative
  • Replicas that gossip in any order, with duplicates, agree on the true total
  • Merge doesn't modify its inputs

Per-field LWW records

For most app data (a note with a title, body, tags and a "pinned" flag) per-field LWW with HLC timestamps is the pragmatic sweet spot. Each field is an LWW-Register; a record is a map of them; merging records merges each field. Edits to different fields on different devices both survive. Concurrent edits to the same field still lose one, deterministically, which is acceptable for short fields and not for long text (use a sequence CRDT for a document body).

Deletion needs care: if a delete removes the record, a stale replica that still has it will resurrect it on the next merge. Model deletion as a field (deleted: { value: true, ts }) so it merges like any other write, and garbage-collect those tombstones only once every replica is known to have seen them.

Challenge

Merge records field by field

Each record maps field names to { value, ts }, where ts is an HLC timestamp { l, c, node }. compareHlc(x, y) is provided: negative if x is earlier, positive if later.

Write mergeRecords(a, b) so that each field keeps the write with the greater timestamp, fields present on only one side survive, and the merge is commutative, associative and idempotent. Return a new object; don't modify a or b.

Console
  1. Nothing logged yet.
  • Each field keeps its newest write
  • A field that exists on only one side survives the merge
  • Merge is commutative, associative and idempotent
  • Merge doesn't modify its inputs

The random test generates each field's value from its timestamp. That's deliberate: two different values with an identical (l, c, node) can't happen with a correct HLC, and if they did, no merge could be commutative. In a real system, also validate that incoming timestamps aren't absurdly far in the future before accepting them.

Question

Quick check

A shared packing list is an OR-Set. Offline, the phone removes "flashlight" while the laptop, which had already synced the same list, adds "flashlight" again. After both sync, what does the list contain?
Pick an answer.

Putting it together

A workable architecture for an offline-first app with a server:

  1. Every replica has an HLC. Each local write stamps the changed fields and goes into the outbox.
  2. The server stores records as per-field LWW maps and merges each incoming mutation with the same mergeRecords the clients use, which is safe to repeat because the merge is idempotent.
  3. Clients pull changes since a cursor and merge them locally with the same function.
  4. Data that must not lose concurrent edits uses CRDT types (counters, OR-Sets, a sequence CRDT library for text); data with cross-record invariants goes through server-validated operations.

Test the merge function the way the playground does: property-based tests that generate random states and assert the three laws, plus a simulation that delivers updates in random orders with duplicates and checks every replica converges.

Recap

  • Wall-clock LWW loses updates silently when clocks are skewed. Order with logical clocks; HLCs give causality plus timestamps close to real time.
  • Vector clocks tell you whether two versions are ordered or concurrent, at the cost of one entry per writer.
  • State-based CRDTs converge because merge is commutative, associative and idempotent: order, grouping and duplicates stop mattering.
  • G-Counter merges by pointwise max; LWW-Register by greatest timestamp; OR-Set by unique tags, so concurrent add wins.
  • Per-field LWW with HLCs and tombstoned deletes covers most app data; invariants across records need a server or reservations.

Finished this lesson?

Mark it complete to track your progress on this device.