Offline-First Sync Conflicts in Mobile Apps
· 22 min read
Offline-first UX promises continuity; sync promises eventual consistency. Without explicit conflict models, users see duplicated payments, lost edits, and tickets that reproduce only on airplanes. Staff engineers separate duplicate intents from true edits, enforce server merge rules, and measure queue health like payments.
Name the conflicts users will actually hit
Not every collision is a merge problem. Some are duplicate intents: tap pay twice on a flaky tunnel, queue two transfers, and reconcile when connectivity returns. Others are true edits to the same field from two devices. Your sync layer needs separate strategies—idempotency keys for actions, structured merges for state.
Staff teams document conflict classes per entity: append-only events, scalar fields with last-write-wins, set unions, and human-required merges. If product cannot describe the desired outcome, engineering should not guess in the client.
Treat the test system as product infrastructure. When sync queues exceed a threshold, freeze new specs until each failure has an owner, a reproduction artifact, and a root-cause hypothesis. Adding more tests on a flaky foundation multiplies noise, not safety.
Mobile is not small web: OS kills background tasks, keyboards cover inputs, and native modules initialize asynchronously. sync queues often reveal missing contracts in the app, not "bad tests." Fixing synchronization is engineering work with the same priority as a production crash.
Instrument sync queue rate in the same analytics warehouse as crashes. When sync queue reliability drops below a threshold, auto-page the mobile platform owner—not the last engineer who touched a unrelated feature.
Prefer boring server rules with honest client UX
Prefer explicit merge RPC epochs via headers or path prefixes over implicit "we deployed Friday." Document what is additive, what is deprecated, and what requires a new epoch. Clients should send build identity on every request so you can route, shadow, or block safely.
Never remove fields without a measured deprecation period. Return sunset hints in structured error payloads and analytics events so product can message upgrades before hard cutoffs. "Silent removal" is how support discovers a spreadsheet of minimum versions at 2 a.m.
Publish machine-readable compatibility notes alongside human release notes. Client engineers should not reverse-engineer behavior from production traffic or Slack threads.
| Practice | Why mobile cares | | --- | --- | | Explicit epoch header | Route old parsers without guessing | | Additive JSON fields | Old apps ignore unknown keys | | Structured sunset errors | In-app upgrade copy before hard stop | | Build id on every request | Skew metrics before you cut |
Treat OpenAPI or protobuf schemas as contracts checked into the repo—not as documentation that drifts after merge. CI should fail when server responses violate the published schema for each active epoch. Offline queues replay payloads against those contracts before drain.
Mobile parsers are often strict JSON decoders in Swift or Kotlin wrappers around JavaScript. "Optional" on the server must mean "absent is fine," not "sometimes null, sometimes missing" unless every shipped build handles both.
Idempotency keys and the outbox pattern
```typescript // Mobile client — send epoch + build on every API call const headers = { "X-Api-Epoch": "2026-03", "X-App-Build": Application.nativeBuildVersion ?? "unknown", "X-App-Platform": Platform.OS, };
export async function apiFetch(path: string, init?: RequestInit) { return fetch(`${API_BASE}${path}`, { ...init, headers: { ...headers, ...init?.headers }, }); } ```
Server-side, map epoch + build to capability flags. Shadow traffic from deprecated epochs in staging before you enforce blocks in production. For Expo and React Native apps, expose build metadata through `expo-application` or native modules—do not rely on JavaScript bundle version alone when store build numbers differ.
When you must introduce a breaking epoch, run both epochs in parallel with routing keyed on `X-Api-Epoch`. Dual-write or dual-read periods belong in the runbook, not in improvised hotfixes during launch week.
Log rejected epochs at the edge with counts, not full payloads. Product needs "how many daily active users are below minimum" more than stack traces.
Rotate API keys and auth independently of epoch when possible—forcing auth migration on the same train as field removal doubles client risk. If they must move together, extend dual-mode auth until skew dashboards clear both dimensions.
Every user-visible mutation should carry a stable client-generated id sent on every retry. An outbox persists mutations across app kills; workers drain when connectivity returns with per-aggregate ordering.
Supabase and Expo offline patterns
```typescript // app.config.ts — expose test-only deep link handler in dev builds export default { scheme: "myapp", extra: { offline queueSeed: process.env.offline queue_SEED ?? "default", }, };
// tests/helpers/offline queue.ts — intercept before UI spec runs export async function stubCheckoutSuccess(page: offline queuePage) { await page.mockNetwork({ url: "**/api/checkout", response: { status: 200, body: { id: "ord_test_123" } }, }); } ```
Seed data through the same API the app uses, not by SQLite hacks unless you own the offline layer. Supabase row-level security must allow test service roles in staging only—never production keys in CI logs.
Use MSW or runner-native mocking at the fetch boundary so components stay unchanged. Tests that patch `global.fetch` inside the app bundle are fragile across Metro cache and release builds.
For streaming or LLM features, stub SSE and WebSocket endpoints with canned chunks. Flaky streaming tests are often timing on first token, not model quality—separate eval suites from UI smoke.
Check secrets into CI via platform stores, not repository env files. Rotated staging keys break offline queue silently when tests still hit production-like URLs with expired tokens—fail fast with a dedicated health spec that runs before the matrix.
Expo apps pair Supabase Auth with Postgres or custom REST. Row-level security must match online and offline paths—never embed production service roles in mobile binaries.
Example outbox enqueue in TypeScript
```typescript // app.config.ts — expose test-only deep link handler in dev builds export default { scheme: "myapp", extra: { e2eSeed: process.env.E2E_SEED ?? "default", }, };
// tests/helpers/stubFetch.ts — intercept before UI spec runs export async function stubCheckoutSuccess(page: MaestroPage) { await page.mockNetwork({ url: "**/api/checkout", response: { status: 200, body: { id: "ord_test_123" } }, }); } ```
Seed data through the same API the app uses, not by SQLite hacks unless you own the offline layer. Supabase row-level security must allow test service roles in staging only—never production keys in CI logs.
Use MSW or runner-native mocking at the fetch boundary so components stay unchanged. Tests that patch `global.fetch` inside the app bundle are fragile across Metro cache and release builds.
For streaming or LLM features, stub SSE and WebSocket endpoints with canned chunks. Flaky streaming tests are often timing on first token, not model quality—separate eval suites from UI smoke.
Check secrets into CI via platform stores, not repository env files. Rotated staging keys break E2E silently when tests still hit production-like URLs with expired tokens—fail fast with a dedicated health spec that runs before the matrix.
CRDTs when collaboration is the product
When multiple users edit shared artifacts offline, CRDTs or OT can beat naive timestamps. The cost is complexity and support narratives. Adopt when offline collaboration is core value.
Pair API sunsets with in-app upgrade prompts and support macros. Success teams need a single matrix of minimum versions, epoch cutoffs, and user-visible error strings—otherwise every incident rediscovers the same skew spreadsheet.
Mobile release managers should see API deprecation dates in the same calendar as store submissions. Shipping a backend cutoff the day before a holiday app review is a predictable outage.
Document which errors are "upgrade required" versus "try again." Mobile users cannot open devtools; error copy is UX and versioning policy at once.
Align marketing site promises with minimum app versions when public APIs power mobile features. Nothing erodes trust faster than a landing page feature that requires a build not yet approved in the store.
Run a short tabletop exercise twice a year: "We deprecate epoch N in 30 days—what breaks, who pages, what do support scripts say?" Staff engineers treat that drill like fire drills for on-call.
Localization matters: upgrade modals shipped only in English still block non-English users who never understood why the app suddenly logged them out. Versioning policy includes copy review in every supported store locale.
Prove sync health outside the lab
Pick one sync health metric, one quarantine SLA, and one real-device tier to improve this sprint. Ask release managers whether confidence actually moved—not whether the badge turned green after retries.
Staff ownership turns sync health from a lottery into an instrument the team trusts when shipping Expo apps weekly. Link postmortems for store rejections or hotfixes back to missing or quarantined coverage so the organization learns.
Compare sync health trends before and after SDK upgrades, navigation refactors, or new animation libraries. Regressions in test stability often precede user-visible jank by a sprint.
Share a monthly "mobile sync health" note with eng and product: top sync healths fixed, top sync healths remaining, minutes saved, specs deleted as low value. Transparency prevents the suite from becoming a haunted forest nobody edits.
Celebrate deleting redundant specs as much as adding coverage. Mobile teams drown when every historical bug gets a forever test without an owner or journey mapping.
Operational checklist for offline sync
Version-control a quarantine registry beside the test folder. Each entry lists spec name, owner, SLA date, last sync rate, and link to artifacts. Pull requests that add sleeps or retries must justify the synchronization gap in the description.
Define required checks explicitly: PR smoke on emulator, nightly full matrix on two OS versions, pre-release real-device spot check for push and payments. Document what is not covered so product does not assume store-ready proof from login-only smoke.
Align with sibling posts on performance budgets and API versioning—slow marketing sites and breaking API changes show up as mobile sync timeouts before they show up as unit test failures.
Finally, delete specs that no longer map to user journeys. Zombie tests sync forever because nobody remembers the feature flag they guarded. Prune aggressively; coverage quality beats coverage count.
Invest in local reproduction scripts: one command that runs a single spec against staging with the same env vars as CI. Engineers fix syncs faster when reproduction does not require guessing runner secrets.
Pair sync stabilization with contract tests on API responses mobile consumes. When backend shape drift causes UI spinners to hang, unit-level contract failure is cheaper than debugging a red sync flow at midnight.
Document environment parity in README: Node version, Expo SDK, runner CLI, and staging URL. Onboarding engineers should reproduce CI failures on day one, not after a week of local-only green runs.
Treat overtime syncs during release week as a signal to freeze scope, not to disable checks. Shortcuts taken under deadline pressure become permanent blind spots in checkout and auth. Schedule stabilization sprints after major SDK jumps the same way you schedule security patches. Both protect users when velocity is high.
Coordinate with API versioning: offline clients replay old payload shapes long after backend deploys. Version-control a conflict policy registry beside API docs.
Frequently asked questions
Is last-write-wins ever OK for money paths?
Does Supabase replace an outbox?
Should MVPs start with CRDTs?
Which sync metrics matter first?
Sources
- Supabase — Row Level Security — supabase.com
- Expo — Network — expo.dev
- Automerge — CRDT library — automerge.org
- Stripe — Idempotent requests — stripe.com
Related on this site
Related service
Mobile application development
iOS/Android mobile products with production architecture, store readiness, and backend integration.
Published on September 13, 2026 by Berktug Berke Ates.