# Optimistic UI & Rollback Safety vs Local-First Sync & CRDTs

- **Canonical URL:** https://frontend.rocks/vs/optimistic-ui-rollback-vs-local-first-sync-crdt/
- **Relation:** Contrasts With
- **Last Verified:** 2026-11-15
- **Verdict:** Optimistic UI rolls back if the server rejects; Local-First treats local storage as primary and merges via CRDTs.

## Comparison Matrix

| Dimension | Optimistic UI & Rollback Safety | Local-First Sync & CRDTs |
| :--- | :--- | :--- |
| **Maturity** | Baseline · Widely | Experimental |
| **Domain** | State & Architecture | State & Architecture |
| **Mental Model** | Applies speculative UI state immediately on user action while retaining an immutable confirmed snapshot for atomic rollback if the network request fails. | Persists every edit locally in IndexedDB/OPFS at 0 ms network wait and uses Conflict-free Replicated Data Types (CRDTs) so offline peers merge deterministically. |
| **Prerequisites** | Stale Closures in Hooks & Callbacks (Rollback handlers must avoid closing over stale pre-mutation state when rapid consecutive edits occur.) | Service Worker Lifecycle (Offline-capable local-first apps pair IndexedDB persistence with a Service Worker shell.) |
| **When Not to Use** | When not to use Optimistic UI: Never fake success on irreversible or high-stakes actions, payment charges, inventory reservations, password changes, or destructive account deletions; for local multi-step editing history, use Undo/Redo & Structural Sharing instead. | When not to use CRDTs: For strict financial ledgers, inventory counts, or unique-username claims where two offline writes cannot both succeed, use server-authoritative transactions instead. |

## Optimistic UI & Rollback Safety — Under the Hood
Optimistic UI works like an accountant's pencil-and-ink ledger: you write the expected balance in pencil right away so the customer sees instant feedback for [Core Web Vitals](/concepts/core-web-vitals-mechanics) INP, and only ink it over (or erase it) once the bank clears the check.

1. **Cancel in-flight reads**: Abort or ignore any running `GET` refetch for the same entity so an older server payload cannot clobber the new optimistic state.
2. **Snapshot & overlay**: Save the last confirmed value (or use `useOptimistic`, which overlays temporary state over base props without mutating them) and avoid [Stale Closures](/concepts/stale-closures-hooks) by reading from a functional reducer.
3. **Reconcile or rollback**: On `200 OK`, replace the speculative entry with the server's authoritative record; on `4xx`/`5xx`, revert to the snapshot and surface an explicit retry action.

```js
async function toggleLike(postId, nextLiked) {
  const snapshot = store.get(postId);
  store.set(postId, { ...snapshot, liked: nextLiked, pending: true });
  try {
    const confirmed = await api.setLike(postId, nextLiked);
    store.set(postId, confirmed);
  } catch (err) {
    store.set(postId, snapshot); // Atomic rollback on failure
    notifyRetry('Could not save like', () => toggleLike(postId, nextLiked));
  }
}
```

## Local-First Sync & CRDTs — Under the Hood
Unlike [Optimistic UI](/concepts/optimistic-ui-rollback), where the server remains judge and jury and failed mutations roll back, a CRDT works like an append-only ledger with mathematical commutativity (`merge(A, B) === merge(B, A)`). Paired with a [Service Worker](/concepts/service-worker-lifecycle) for offline asset booting, the client never blocks on a round-trip.

1. **Local persistence**: Edits commit immediately to IndexedDB or Origin Private File System (OPFS) in sub-millisecond transactions.
2. **Causal IDs**: Each character or map key receives a unique Lamport/Hybrid Logical Clock `(clock, clientId)` tuple, immune to skewed laptop system clocks.
3. **State-vector sync**: On reconnect, peers exchange compact version vectors and stream only missing operations, converging identically with zero central lock.

```js
// Commutative LWW-Register merge: order-independent convergence
function mergeRegister(local, remote) {
  if (remote.hlc > local.hlc) return remote;
  if (remote.hlc === local.hlc && remote.clientId > local.clientId) return remote;
  return local;
}
```

## Interactive Labs & Dissections
- [Optimistic UI & Rollback Safety Lab](https://frontend.rocks/concepts/optimistic-ui-rollback/#lab) ([Markdown](https://frontend.rocks/concepts/optimistic-ui-rollback.md))
- [Local-First Sync & CRDTs Lab](https://frontend.rocks/concepts/local-first-sync-crdt/#lab) ([Markdown](https://frontend.rocks/concepts/local-first-sync-crdt.md))

## Related Architecture Autopsies
- [Autopsy #08: Surviving a 4-Hour Tunnel: Local-First Sync & Conflicts](https://frontend.rocks/autopsies/offline-first-conflict-storm/) ([Markdown](https://frontend.rocks/autopsies/offline-first-conflict-storm.md)): A user edits a document offline on a train and silently overwrites a teammate's merged changes upon reconnection.

## Primary Sources
- https://react.dev/reference/react/useOptimistic
- https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates
- https://web.dev/articles/inp
- https://www.inkandswitch.com/local-first/
- https://crdt.tech/
- https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
