Offline-first sounds like an architecture problem for large teams, but a small app usually needs only a few well-chosen pieces. The goal is modest: the app works without a connection, nothing the user does gets lost, and nothing gets saved twice. This post covers a blueprint we would use on either platform. It doesn't need a sync framework, just a local database, a queue and a few rules you write down before you write any code.
Decide what offline-first means for your app
Before picking libraries, sort your data into three groups. Each group needs different handling.
- Read-mostly reference data (catalogs, settings from the server, content). Cache it, refresh it when you can, and show the cached copy otherwise. No conflict handling needed.
- User-owned data (notes, logs, drafts, favorites). Only one person edits it, but possibly on several devices. This is where most indie apps need real offline support.
- Shared data (lists edited by several people, collaborative documents). Conflicts are normal here. If this is a core feature, look at a purpose-built sync service or CRDT library instead of building your own.
If most of your data is in the first two groups, everything below will cover it.
Make the local database the source of truth
The most important rule: the UI reads only from the local store. The network writes into the local store, and the UI observes it. Screens never wait on a request to show data. On iOS that might be SwiftData, Core Data or GRDB. On Android it's usually Room or SQLDelight. All of them can expose observable queries (@Query, Flow, publishers), so when sync updates a row, the screen updates without extra code.
This also helps launch time. A screen that renders from disk doesn't block on a network call, which fits the approach in our startup time pass.
Use client-generated IDs
Create every record's primary key on the device as a UUID. Don't wait for the server to assign one. That way, offline-created records can be referenced by other records straight away, and you never have to rewrite foreign keys after the first upload. The server accepts the client ID as is.
Queue writes in an outbox
When the user changes something, do two things in one local transaction: update the record, and add an entry to an outbox table. The sync process sends entries from the outbox in order and deletes each one only after the server confirms it.
CREATE TABLE outbox (
id INTEGER PRIMARY KEY AUTOINCREMENT,
mutation_id TEXT NOT NULL UNIQUE, -- UUID, used as idempotency key
entity TEXT NOT NULL, -- e.g. 'note'
entity_id TEXT NOT NULL,
op TEXT NOT NULL, -- 'upsert' | 'delete'
payload TEXT, -- JSON of changed fields
base_version INTEGER, -- server version the edit was based on
attempts INTEGER NOT NULL DEFAULT 0,
last_error TEXT,
created_at INTEGER NOT NULL
);Because the record change and the outbox entry are committed together, a crash can't leave one without the other. Send entries in id order so a create always reaches the server before an edit to the same record.
You can merge entries to cut traffic. For example, three edits to the same note's title can become one upsert. But do it only for entries that haven't been sent yet, and only once the basic version works.
Make every write idempotent
Networks fail in the worst possible spot: the server applies the change, and the response is lost. The client retries, and without protection you get duplicates. Send mutation_id with each request and have the server store the IDs it has processed. A repeated ID returns the original result and changes nothing.
POST /sync/push
Idempotency-Key: 4f0c2a1e-...
{ "entity": "note", "id": "b71e...", "op": "upsert",
"base_version": 12, "fields": { "title": "Groceries" } }Of all the steps, this is the one people skip most often, and it's the one that makes retrying safe. Once it's in place, the client can retry as often as it likes.
Pull changes with a cursor, and keep tombstones
For the download side, the client stores an opaque cursor that the server returns, and asks for "everything changed since this cursor." Use a server-side, always-increasing change sequence for this, not device timestamps. Device clocks drift and users change them.
Deletes need special care. If the server removes a row outright, a client that was offline has no way of finding out it's gone. Keep tombstones instead: a deleted flag plus a change sequence. That way, deletes show up in the change feed like any other edit. Purge old tombstones on a schedule, and make sure a client whose cursor is older than your purge window does a full resync.
The order matters: push first, then pull. If you pull first, the server's copy can overwrite a local edit that hasn't been sent yet.
Pick a conflict rule and write it down
A conflict happens when an edit's base_version no longer matches the server's current version. For user-owned data, these options cover most apps:
- Last writer wins, per field. Merge field by field, so editing the title on a phone and the body on a tablet keeps both changes. This is simple, and the best fit for most indie apps.
- Server wins, client is told. Reject the stale write and send back the current record. The client shows it and, where it matters, offers to reapply the user's change.
- Keep both. Save the losing version as a copy ("Note (conflict)"). This is clumsy, but it never loses data, so it's useful for long-form text.
Whichever you pick, the server decides the outcome. Never resolve conflicts by comparing device clocks.
Schedule sync without fighting the OS
Trigger a sync when the app comes to the foreground, shortly after a local write (debounced by a second or two), and when connectivity returns. Treat background sync as a bonus, not something to rely on.
On Android, WorkManager handles constraints and backoff for you:
val request = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork("sync", ExistingWorkPolicy.KEEP, request)With KEEP, a second request is dropped while a sync is already queued or running. So have the worker keep looping until the outbox is empty, rather than sending a single batch and stopping.
On iOS, sync when scenePhase becomes .active and after writes. You can also register a BGAppRefreshTask, but the system decides when it runs, and it may not run at all. Design so the app works correctly even if the background task never runs.
.onChange(of: scenePhase) { _, phase in
if phase == .active { Task { await syncEngine.run() } }
}On both platforms, make the sync engine single-flight: one run at a time, guarded by an actor, a mutex or the unique-work name.
Show sync state honestly
Users don't need a spinner on every row, but they should be able to tell when something hasn't been saved to the server yet. A small "Not synced yet" marker on records with pending outbox entries goes a long way. For an entry that keeps failing (validation errors, or a 4xx that won't change on retry), stop retrying after a few attempts. Mark the record as needing attention and let the user fix or discard it. Report these to your crash and error tool with the entity type and error code, but not the user's content. The crash triage post covers how to keep that signal readable.
Test the failure cases on purpose
Normal use will cover the happy path. These cases are where sync bugs actually hide:
- Create, edit and delete records in airplane mode, then reconnect. Check that the server ends up in the same state as the device.
- Kill the app in the middle of a sync, using a debugger breakpoint or a forced crash after the request is sent. On relaunch, check that nothing is duplicated.
- Replay the same push request twice on purpose. The server should return the same result both times.
- Edit the same record on two devices while both are offline, then bring both online. Check that the result matches the rule you wrote down.
- Delete a record on device A while device B is offline and editing it. Decide whether the edit or the delete wins, and test that.
- Set the device clock a day ahead. Nothing should change, because nothing should depend on it.
- Leave a device offline longer than your tombstone retention period. Check that the full resync kicks in.
Many of these can run as automated tests against a fake server that can drop responses and reorder requests. Building that fake server tends to pay off fast.
Checklist
- Data sorted into reference, user-owned and shared groups
- UI reads only from the local store
- Client-generated UUIDs for all records
- Outbox written in the same transaction as the change
- Idempotency key on every write, deduplicated on the server
- Server-issued cursor for pulls, with tombstones for deletes
- Push before pull, with a single sync run at a time
- Conflict rule written down and covered by a test
- Retry limit and a visible state for writes that keep failing
Wrapping up
Offline-first doesn't need a big framework. It needs a few firm decisions: the local database is the truth, writes go through an outbox, every request can be safely retried, and the server owns conflict resolution. Start with user-owned data on a single entity type and test the failure cases above. Then apply the same pattern to the rest of the app. If your app's core is truly shared, real-time data, that's the point to look at a dedicated sync service instead of building one.