Format
Deep Engineering
Written for
For engineers and technical leads
Thread
Mobile Engineering Beyond the Interface
Mobile Engineering

Offline-First Is a Data Problem: Designing Mobile App Sync That Survives Bad Networks

An app is offline-first when the screen renders the local database, not the last server response. This issue designs the write queue, the change feed and the failure handling that make that safe.

Khalid Aboubakr
10 min read
Under the HoodMobileOffline-firstDistributed Systems

An app is offline-first when the screen renders what is in the local database, not what the server last returned. Everything else follows from that sentence. Caching responses, showing a "you are offline" banner or retrying failed requests are useful, but they are features of an online app that tolerates outages. Offline-first mobile app sync is a different architecture: the device holds a real copy of the data the user works with, changes are recorded locally first, and a sync process reconciles that copy with the server whenever the network allows. Getting it right is mostly about data design, and very little about the UI.

Offline-first mobile app sync starts with a local source of truth

Android's architecture guidance for offline-first apps states the principle directly: the local data source is the canonical source of truth, and the rest of the app reads only from it. The repository talks to the network and writes what it learns into the local store; screens observe the local store and update when it changes. The same model works on iOS with Core Data, SwiftData or SQLite through a library such as GRDB, and in cross-platform stacks through SQLite bindings.

Three consequences are easy to miss. First, reads become reactive rather than request-and-response: a screen subscribes to a query and re-renders when sync writes new rows, which removes a whole class of "stale screen after refresh" bugs. Second, the local schema is a real schema with migrations, constraints and indexes, not a JSON blob of the last API response. Third, the database engine's durability settings now matter to the product. SQLite in write-ahead-logging mode, for example, lets readers continue while a sync transaction writes, which keeps the UI responsive during large pulls.

Be explicit about scope. "Offline" rarely means the whole dataset. A field-inspection app needs today's assignments, their forms and the reference lists those forms use; it does not need five years of history. Deciding what each user's device holds, and how that subset changes as their assignments change, is the first design task, and it determines storage size, initial sync time and what the server must be able to compute per user.

Writes go into a durable outbox

When the user changes something, the app must do two things atomically: apply the change to the local data so the screen reflects it immediately, and record the change in a queue that will eventually be sent to the server. If those two steps can be separated by a crash, you will either lose changes the user saw succeed, or send changes the user never saw.

-- Local SQLite schema (simplified) CREATE TABLE pending_mutations ( mutation_id TEXT PRIMARY KEY, -- client-generated UUID, reused on every attempt entity_type TEXT NOT NULL, entity_id TEXT NOT NULL, -- client-generated ID for new records operation TEXT NOT NULL CHECK (operation IN ('create', 'update', 'delete')), payload TEXT NOT NULL, -- JSON, includes a payload schema version base_version INTEGER, -- server version the edit was made against created_at INTEGER NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'in_flight', 'rejected')) ); CREATE INDEX pending_by_entity ON pending_mutations (entity_type, entity_id, created_at);

The local update and the row in pending_mutations are written in one local transaction. Two fields carry most of the design. The mutation_id is generated once, when the user acts, and is sent with every attempt, so the server can recognise a retry. The base_version records which server version of the record the user was looking at, so the server can detect that someone else changed it in the meantime.

Records created offline should get client-generated identifiers, typically UUIDs, from the start. The alternative, temporary local IDs that are swapped for server IDs after the first sync, forces you to rewrite every queued mutation and every local foreign key that referenced the temporary ID. That rewrite is a common source of orphaned records and duplicated children.

Pushing changes: the server must expect retries

The push side drains the outbox. On a phone, every assumption about delivery is weaker than on a server: the request may reach the server and the response may never come back, the OS may suspend the app mid-request, and the same mutation may be sent again hours later. The server therefore has to treat each mutation ID as an idempotency key, applying the change once and returning the same result for every repeat. The contract that makes this work, including how to store keys and what to return on a mismatch, is covered in idempotency keys and retry-safe operations; for sync, the important addition is retention. A device can sit in a drawer for a week, so the server must remember mutation IDs at least as long as you allow a device to stay offline.

Order matters within an entity, and across entities only where records reference each other. Creating a record and then editing it must arrive in that order, and so must a parent created offline and the child that points to it; edits to two unrelated records need not. Draining sequentially per entity, or sequentially overall for simple apps, avoids reasoning about reordering. Android's guidance points the same way: when you need firmer ordering guarantees, persist the queue in the app's own database and have a worker drain it sequentially.

Classify every server response. Network errors, timeouts and 5xx responses are transient: back off and retry the same mutation. A version conflict is a conflict: hand it to the resolution policy. A validation error is permanent: retrying will never succeed, so the mutation must be marked rejected, the local state rolled back or flagged, and the user told in plain language. An outbox that retries permanent failures forever blocks every mutation behind it for that entity, and the user sees an app that "never syncs".

Pulling changes: cursors, not timestamps

The pull side brings the device up to date. The tempting implementation, "give me everything with updated_at greater than my last sync time", fails in two ways. Device clocks are wrong often enough to matter, and even with a server-side timestamp, a transaction that started earlier can commit later than one that started after it. A client that synced in between will never see the earlier transaction's rows, because their timestamp is already behind its cursor.

The robust pattern is a server-maintained change log with a monotonically increasing sequence, and an opaque cursor handed to the client.

GET /sync/changes?cursor=eyJzZXEiOjE4MzQ1fQ&limit=500 200 OK { "changes": [ { "type": "task", "id": "3f6c…", "op": "upsert", "version": 42, "data": { … } }, { "type": "task", "id": "91ab…", "op": "delete", "version": 43 } ], "next_cursor": "eyJzZXEiOjE4ODQ1fQ", "has_more": true }

Even a database sequence has the commit-order problem, because a sequence value is taken when the row is written, not when the transaction commits. A transaction holding sequence 100 can commit after one holding 101, and a client that pulled in between has already moved its cursor past 100. The reader cannot see the uncommitted row, so it cannot simply stop before the gap. Two defences are common. The first is a watermark based on transactions rather than sequence values: store the writing transaction's ID with each change (in PostgreSQL, pg_current_xact_id()) and serve only changes from transactions older than the oldest one still running (pg_snapshot_xmin(pg_current_snapshot())), with the cursor recording the watermark it was served up to. A long-running transaction then holds the watermark back and delays sync for everyone, which is the price of correctness. The second is to re-read an overlap window behind the cursor on every pull and rely on idempotent, version-checked application on the client; it is simpler, and correct only if no writing transaction ever stays open longer than the window. Ignoring the problem produces rare, unreproducible "missing record" reports.

Three more details separate a sync protocol from a demo. Deletions must be represented as tombstones in the change log, otherwise a device that was offline when a record was deleted keeps it forever. Applying a page of changes on the client must be one local transaction, together with storing the new cursor, so a crash mid-page cannot skip or half-apply data. And the server needs a way to say "your cursor is too old"; once tombstones and log entries are compacted, an old cursor cannot be served, and the honest response is an explicit signal, such as 410 Gone, that triggers a full resync of the user's subset.

Conflicts are detected by versions, resolved by policy

Every record carries a server-assigned version that increments on each change. When a mutation arrives with a base_version older than the current one, two people, or one person on two devices, changed the same thing. Detection is mechanical. Resolution is a product decision.

For many fields, last-write-wins is acceptable, and the Android guidance describes it as a common choice for mobile apps. Its example compares timestamps that devices attach to their writes; the safer qualification is that "last" should be decided by the server's ordering, not by device clocks, and ideally per field rather than per record, so that one user's change to a title does not erase another user's change to a due date. Some data cannot be resolved automatically at all: two different values for a medication dose or a payment amount should produce a visible conflict, not a silent winner. Conflict resolution strategies, from field-level merges to CRDTs, deserve their own treatment; what matters for the architecture is that versions and base versions exist from the first release, because they cannot be retrofitted onto data that was synced without them.

The operating system decides when you run

Sync code that works in the foreground often fails in the field because the OS controls background execution. On iOS, the BackgroundTasks framework lets an app request time for refresh and processing tasks, but the system decides when, and whether, they run, based on battery, usage patterns and other factors. On Android, WorkManager persists scheduled work across app restarts and reboots, supports constraints such as "only on a connected network", and retries with exponential backoff, but Doze and app standby still defer it.

Design as if background sync is a bonus. Sync when the app comes to the foreground, when the user performs an action that creates a mutation, and when connectivity returns, and treat background tasks as a way to be fresher, not as the mechanism correctness depends on. Treat connectivity signals with suspicion too: a reported network path does not mean your API is reachable, as anyone who has opened an app behind a captive portal knows. The outcome of an actual request is the only reliable signal.

Old clients, new schemas

Mobile apps live for a long time on devices you do not control. A mutation queued by version 1.4 may be sent after the user upgrades to 1.6, and the server may receive payloads from three app versions on the same day. Version the payload format inside each mutation, keep the server able to accept older formats for as long as those versions are supported, and run local schema migrations that also migrate queued mutations. A migration that changes a table but leaves the outbox in the old format will fail on the first sync after the upgrade, which is the worst possible moment.

What to test before release

Offline behaviour is rarely tested because it is awkward to reproduce. A minimum set of scenarios:

  1. Airplane mode in the middle of a push, with the request delivered but the response lost.
  2. The app killed with a non-empty outbox, then relaunched without a network.
  3. The same record edited on two devices while both are offline, then both reconnected.
  4. A device clock set days in the past or future.
  5. A cursor older than the server's retention, forcing a full resync.
  6. A mutation the server rejects as invalid, followed by valid mutations to the same record.
  7. An app upgrade with queued mutations from the previous version.

Each of these should end with the local database, the server and the user's understanding in agreement. If a product depends on field use or patchy coverage, budget for this test matrix from the first sprint; it is how we approach mobile app development for apps that must work offline. Later issues of Under the Hood return to conflict resolution in more depth.

References

Related Articles