Mobile EngineeringVol. 22 · Mobile
0 / 0

Shelves / Mobile Engineering

MB·05

Offline-First and Sync

Making apps work without a network and converge when it returns: the local database as the UI's source of truth, a pending-operations outbox with idempotency keys, delta sync with cursors and versions, conflict resolution (whole-document and per-field last-writer-wins, server-authoritative business rules, merges, CRDTs, asking the user), clocks and why device time can't be trusted, deletes and tombstones, and honest UI for pending and failed changes; with a lab in which two devices edit a weekly meal plan offline and whole-document last-writer-wins loses edits in 90% of syncs.

15 topics · ~8 min read · 16-question quiz
Updated Suggest a correction

Start here: the network is optional

A TiffinBox customer opens the app on the metro to skip tomorrow's lunch. There's no signal. A network-first app shows a spinner, then an error. An offline-first app shows the calendar from its local database, records the skip immediately, and syncs it when the train reaches a station, then tells the user if the kitchen's cut-off had already passed.

Offline-first means:

  1. The local database is the source of truth for the UI: screens read and observe local data.
  2. User actions change local data immediately and add an operation to a pending queue (an outbox, like Volume 19's, on the device).
  3. A sync engine pushes pending operations and pulls server changes in the background, whenever the network allows.
  4. When two changes collide, a conflict policy decides the result, and the UI says what happened.

Two devices, measured

A customer edits the same week's plan on a phone and a tablet, both offline: each device makes three edits (skip a day, unskip, change a meal), then both sync. Across 2,000 simulated syncs:

Conflict policy Syncs that lost an edit the user made Edits lost per sync
whole-document last-writer-wins (newest device's copy replaces the other) 90% 1.54
per-field last-writer-wins (each day's skip and meal resolved separately) 0% 0.00
per-field, but the tablet's clock is 30 minutes slow 12% 0.12

Replacing whole documents throws away the other device's work almost every time. Resolving per field keeps both devices' edits, unless timestamps come from device clocks that are wrong.

How deep to go

Volume 17 defines six mastery levels. For offline-first and sync:

Level What you can do
L1 Explain offline-first and why the local database is the UI's source of truth
L2 Build a screen that works offline with a pending-operations queue
L3 Explain delta sync, conflict policies, clocks, tombstones and CRDTs
L4 Debug lost edits, duplicate operations and divergent devices
L5 Design a sync protocol and conflict policy for a product
L6 Run sync for millions of devices across app and schema versions

The architecture

Text
UI ──observes──→ local DB (Room / SwiftData / SQLite)  ←─ apply server changes ─┐
 └─ events ─→ repository: write local + enqueue operation ─→ pending_ops table   │
                                                           ↓                     │
                                     sync engine (WorkManager / BGTask, network constraint)
                                       push: send ops in order with idempotency keys ─→ server validates, applies, returns new versions
                                       pull: GET /changes?since=<cursor> ──────────────────────────┘
  • Writes are local first: update the row, enqueue an operation (SkipDay(sub=88, date=2026-11-10, key=uuid)), return. The UI updates through observation.
  • Push sends operations in order, each with its idempotency key; the server applies business rules and responds with the authoritative result and new version.
  • Pull fetches changes since the last cursor (a server-issued, monotonically increasing version or change-log position), including tombstones for deletions, applied in one local transaction.
  • Cursors and versions come from the server, never from the device clock.

Conflict policies

Policy How Good for Risk
whole-document last-writer-wins the newest copy replaces the other single-device data loses edits (the lab: 90%)
per-field last-writer-wins each field (or each day) resolved independently settings, preferences, independent fields wrong winner with bad clocks
server-authoritative rules the server decides from business rules money, inventory, cut-offs needs clear rejection UX
operation-based merge replay intents (add skip, remove skip) rather than states sets, counters, lists needs careful operation design
CRDTs data types that merge automatically and converge (counters, sets, sequences for text) collaborative editing, notes complexity, metadata growth
ask the user show both versions rare, valuable conflicts interrupts users

Most apps mix them: TiffinBox uses server-authoritative rules for skips and payments, per-field resolution for preferences, and nothing collaborative enough to need CRDTs.

Clocks

  • Device clocks are wrong often enough to matter (manual changes, drift, time zones), so the lab's per-field LWW picked wrong winners when one clock was 30 minutes slow.
  • Prefer server-assigned versions (the server orders accepted operations), or hybrid logical clocks (physical time plus a counter, never going backwards, merged on every message), or operations that don't need ordering.
  • Show times to users in their time zone, but store and compare in UTC (Volume 23).

Deletes, schema and versions

  • Tombstones: deletions are records too, kept long enough for every device to sync; devices offline longer than the tombstone retention need a full resync.
  • Schema evolution: devices run old app versions with old local schemas; the server must accept old operation formats and send changes old clients understand (or tell them to update).
  • Initial sync and resync: paginate, resumable, and possible from any state.

The user interface of sync

  • Show pending (a small clock icon on an unsynced skip), synced, and failed states.
  • For failures, explain and offer actions: retry, undo, contact support.
  • Don't block the UI on sync; do show freshness ("updated 2 minutes ago").
  • Background sync must respect battery and data settings (chapter 07).

Security of local data

Local databases hold personal data on devices that get lost: store tokens in the Keychain/Keystore, encrypt sensitive local data where needed, wipe on sign-out, and never trust local data for authorisation (the server re-checks everything).

Common traps

  • Network-first screens that are blank offline.
  • Device timestamps deciding conflicts.
  • Replaying operations without idempotency keys.
  • Silent failure of a rejected offline change.
  • Deletes that don't sync (no tombstones).

Lab: two devices, one plan

Setup. A Python simulation on the lab machine. A customer's weekly plan has five days; each day has a skipped flag and a meal. Two devices (phone and tablet) start from the same plan, go offline, and each makes three random edits at random times within a 100-minute window: skip a day, unskip a day, or change a day's meal. Then both sync.

Ground truth is what the user intended: all six edits applied in the real order they were made. A sync "ends wrong" if the final plan differs from that truth in any field. 2,000 syncs per policy, same random seed.

  • Whole-document last-writer-wins: each device applies its own edits; the server keeps the copy from the device whose last edit is newest.
  • Per-field last-writer-wins: every edit is a timestamped change to one field (a day's skip flag or meal); edits are applied in timestamp order.
  • Clock skew: the tablet's clock runs 30 minutes slow, so its edits carry timestamps 30 minutes too early.

Results

Policy Tablet clock Syncs ending wrong Wrong fields per sync
whole-document LWW correct 90.0% 1.54
per-field LWW correct 0.0% 0.00
per-field LWW 30 min slow 11.8% 0.12
whole-document LWW 30 min slow 90.3% 1.56

In 61% of syncs both devices had touched at least one of the same fields (a genuine conflict where one edit must lose), because a five-day plan is small.

What it shows

  • Whole-document replacement discards the other device's work whenever both devices changed anything, which is almost always.
  • Per-field resolution keeps independent edits. With correct ordering it matched the user's intent exactly in this model (by construction: the truth is "latest edit per field wins"), even though most syncs contained genuine conflicts.
  • Ordering by device clocks is fragile: a 30-minute skew made one sync in eight end wrong. Server-assigned versions or hybrid logical clocks remove that failure.
  • Real policies add business rules: a skip after the kitchen's cut-off is rejected by the server whatever the timestamps say.

Try it yourself

  1. Replace device timestamps with server-assigned versions (the server orders operations as they arrive) and rerun with the skewed clock. What does "correct" mean now?
  2. Model skips as an add-wins set CRDT (an unskip only removes skips it has seen) and compare with per-field LWW.
  3. Add the cut-off rule: edits to days before a cut-off time are rejected at sync. Count rejected operations and design the message the user sees.
  4. Increase to 30 days and 10 edits per device: how does the genuine-conflict rate change?

Revision sheet: offline-first and sync

Key ideas

  • Local database as the UI's source of truth; local-first writes; pending operations with idempotency keys; background sync.
  • Push operations in order; pull deltas since server-issued cursors; tombstones for deletes.
  • Conflict policies: whole-document LWW (avoid), per-field LWW, server-authoritative rules, operation merges, CRDTs, ask the user.
  • Never trust device clocks for ordering; server versions or hybrid logical clocks.
  • Old app versions and schemas sync too; resumable initial sync.
  • Visible pending/failed states; local data security; server re-checks everything.

Numbers to remember

  • Lab: whole-document LWW lost edits in 90% of syncs; per-field LWW 0% with correct clocks, 12% with a 30-minute skew.

Glossary

  • Offline-first: designing the app to work locally and sync opportunistically.
  • Pending operations queue: a device-side outbox of user actions.
  • Cursor: a server-issued position for delta sync.
  • Tombstone: a record that something was deleted.
  • CRDT: conflict-free replicated data type.