TL;DR
- The UI reads and writes only the local database. A single sync engine owns the network.
- Every write saves the record and an outbox entry in one transaction, using a client-generated UUID and an idempotency key.
- A sync cycle pushes the outbox first, then pulls everything that changed since a server-side cursor.
- Conflicts are detected with a server-assigned version and merged field by field, with an explicit policy for fields both sides edited.
Why offline-first
Most mobile apps are built as if the network is always there. Then a user opens the app in an elevator, on a rural road, in a basement warehouse or at a border crossing, and every tap turns into a spinner or an error.
Offline-first flips the assumption: the app works fully without a connection, and the network is just a way to share changes with the server when it happens to be available. The user never waits for the network to read or write their own data.
This article walks through how to design that, including the hard part: bidirectional sync — pushing local changes up, pulling remote changes down, and resolving conflicts when both sides edited the same thing. Nothing here depends on a specific language or framework. The same design works in Kotlin, Swift, Flutter, React Native or anything else that has a local database and a background scheduler.
A note on the code: the examples are written in Kotlin, because it is my main language as an Android developer. They are intentionally framework-free (no Room, Retrofit or WorkManager APIs), so they read almost like pseudocode and translate directly to Swift, Dart or TypeScript.
What we will cover:
- The core principle: the local database is the source of truth for the UI
- The architecture and its moving parts
- A data model that makes sync possible
- Writing locally with the outbox pattern
- Pushing changes up and pulling changes down
- Resolving conflicts
- When to trigger sync, plus the pitfalls that bite in production
The core principle: the UI only talks to the local database
In a typical online-first app, the screen calls the API, waits, and renders the response. The network sits in the middle of every interaction.
In an offline-first app, the UI reads from and writes to the local database, and nothing else. A separate sync engine moves data between the local database and the server in the background. The UI observes the local database, so when sync brings new data in, the screen updates on its own.
| Online-first | Offline-first | |
|---|---|---|
| Source of truth for the UI | Server response | Local database |
| Read latency | Network round trip | Local disk read |
| Write with no signal | Fails or blocks | Succeeds locally, syncs later |
| Who handles the network | Every screen | One sync engine |
| Hardest problem | Loading and error states | Conflicts and consistency |
The trade is honest: you remove spinners and network errors from the UI, and in exchange you take on the job of keeping two databases consistent. The rest of this article is about doing that job well.
The architecture
The whole design fits in seven components, split across the device and the backend. The key idea is that there are two independent loops: the UI loop, which is always local and instant, and the sync loop, which runs in the background whenever it can.
On the device:
- UI / ViewModel — renders state and sends user intents. It observes queries on the local database and never calls the API.
- Repository — the only entry point for data. On a write, it saves the entity and records the change in the outbox, in one transaction.
- Local database — the source of truth for the UI. SQLite, Room, Core Data, SQLDelight, Realm, Isar, WatermelonDB — any of them work.
- Outbox — a table of pending changes waiting to be sent. It lives in the same database as the data.
- Sync engine — a background worker that pushes the outbox, pulls remote changes, resolves conflicts and writes the results to the local database.
On the backend:
- Sync API — two endpoints: one to receive a batch of changes (push) and one to return what changed since a cursor (pull).
- Server database + change log — the canonical data, plus an ordered record of every change so clients can ask "what happened since X?"
Notice what is missing: the UI has no arrow to the network. That single constraint is what makes the app feel instant offline and online alike.
A data model built for sync
Sync gets dramatically easier if every synced table carries a few extra columns from day one. Retrofitting them later is painful.
Why each one matters:
- Client-generated IDs (UUID v4 or v7). If the server assigns IDs, an entity created offline has no ID until it syncs, and every reference to it breaks. Generate the ID on the device and the server just accepts it. UUID v7 is sortable by time, which is a nice bonus for indexes.
-
version. A counter the server increments every time it accepts a change. The client sends the version it last saw; if the server has a newer one, someone else changed the row in the meantime. This is how you detect conflicts reliably. -
updated_at. Useful for display and for simple last-write-wins strategies. Do not rely on it alone to detect conflicts: device clocks drift and users change them. - Soft deletes (tombstones). If you hard-delete a row locally, there is nothing left to tell the server, and other devices never learn it was deleted. Mark it
deleted = true, sync the tombstone, and purge it later once every client has seen it. -
sync_status. A local-only column that lets the UI show a small "not synced yet" or "conflict" badge. It never goes to the server.
Writing locally: the outbox pattern
When the user saves something, the app writes it locally and returns immediately. To make sure the change eventually reaches the server, the repository also appends an entry to an outbox table. Both writes happen in one database transaction: either the entity and its outbox entry are both saved, or neither is. Without that, a crash between the two writes leaves a change that the server never hears about.
enum class Operation { CREATE, UPDATE, DELETE } data class OutboxEntry( val id: Long = 0, // auto-increment: preserves order val entityType: String, // "task" val entityId: String, // UUID of the record val operation: Operation, val payload: String, // JSON with the fields that changed val baseVersion: Int, // version the edit was based on val baseSnapshot: String, // JSON of the row before the edit (used to merge) val idempotencyKey: String, // unique per change val attempts: Int = 0, val createdAt: Long = System.currentTimeMillis(), ) suspend fun updateTask(id: String, changes: TaskChanges) { db.transaction { val task = taskDao.getById(id) val updated = task.applying(changes).copy( updatedAt = now(), syncStatus = SyncStatus.PENDING, ) taskDao.upsert(updated) outboxDao.insert( OutboxEntry( entityType = "task", entityId = id, operation = Operation.UPDATE, payload = json.encodeToString(changes), baseVersion = task.version, baseSnapshot = json.encodeToString(task), idempotencyKey = UUID.randomUUID().toString(), ) ) } syncScheduler.requestSync() // best effort; fine if offline } Two details that save you later:
- Idempotency keys. Mobile networks lose responses. The server may apply a change and the reply never arrives, so the client retries. The server stores each idempotency key it has processed and ignores duplicates, which makes retries safe.
- Coalescing. If the user edits the same task five times offline, you can merge those outbox entries into one before sending. It is optional, but it cuts traffic and conflict noise.
Push: sending local changes up
A sync cycle always runs in the same order: push first, then pull. Pushing first means the server sees your changes before you download its state, so the pull already includes the result of your own writes and any conflicts they caused.
Here is the full life of one write, from the tap to the server and back:
The push step drains the outbox in order, in batches:
suspend fun push() { while (true) { val batch = outboxDao.oldest(limit = 50) if (batch.isEmpty()) return val response = api.push(batch) // throws on network errors -> retried later db.transaction { for (result in response.results) { when (result) { is PushResult.Accepted -> { taskDao.markSynced(result.entityId, newVersion = result.version) outboxDao.delete(result.outboxId) } is PushResult.Conflict -> { // merges, clears this row's pending entries and re-enqueues if needed resolveConflict(server = result.serverTask) // see below } is PushResult.Rejected -> { // validation error, permanent taskDao.markFailed(result.entityId, result.reason) outboxDao.delete(result.outboxId) } } } } } } Rules that keep the push step healthy:
- Keep order per entity. A CREATE must reach the server before the UPDATE of the same row. Sending the outbox in insertion order is the simplest way to guarantee it.
- Separate transient from permanent errors. A timeout or a 503 means "try again later": leave the entry in the outbox and retry with exponential backoff plus jitter. A 400 or 422 means "this will never succeed": stop retrying, mark the record, and show it to the user.
- Cap the attempts. After a fixed number of failures, park the entry and surface it, instead of retrying forever and blocking everything behind it.
- Delete outbox entries only after the server confirms. The outbox is your durable promise. If the app dies mid-request, the entry is still there on the next run, and the idempotency key makes resending it harmless.
What the server does with a push
The client design only works if the server keeps its side of the deal. For each change in a pushed batch, it runs four steps inside one database transaction:
- Check the idempotency key. If the key was already processed, return the stored result and do nothing else. A retried request must never apply the same change twice.
- Compare versions. If the change's
baseVersionmatches the row's currentversion(or the row does not exist yet, for a CREATE), there is no conflict. If the server is ahead, return CONFLICT with the current server row so the client can merge. - Validate and apply. Run the normal business rules. If they fail, return REJECTED with a reason. Otherwise, save the row and increment its
version. - Append to the change log. Record the entity, the operation and the new version under the next sequence number. This is what other devices receive on their next pull.
fun handleChange(change: IncomingChange): PushResult = db.transaction { // 1. Already processed? Return the same answer again processedKeys.find(change.idempotencyKey)?.let { return@transaction it } // 2. Someone else changed the row since the client last saw it val current = tasks.findById(change.entityId) if (current != null && current.version != change.baseVersion) { return@transaction PushResult.Conflict(change.outboxId, serverTask = current) } // 3. Business rules validate(change)?.let { error -> return@transaction PushResult.Rejected(change.outboxId, change.entityId, error) } val saved = tasks.save(change.applyTo(current), version = (current?.version ?: 0) + 1) // 4. Make the change visible to every other device changeLog.append(entityId = saved.id, operation = change.operation, version = saved.version) PushResult.Accepted(change.outboxId, saved.id, saved.version) .also { processedKeys.store(change.idempotencyKey, it) } } Note that the change log is written by every path that modifies data: the sync API, an admin panel, a backend job. If something writes to the table without logging it, devices will never hear about it.
Pull: bringing remote changes down
Downloading the full dataset on every sync does not scale. Instead, the client stores a cursor — a bookmark of the last change it has seen — and asks the server only for what happened after it.
On the server, every accepted write (from any client, admin panel or backend job) appends a row to a change log with a monotonically increasing sequence number. The cursor is just the last sequence number the client processed.
GET /sync/pull?cursor=10482&limit=200 { "changes": [ { "type": "task", "id": "0193...", "op": "UPDATE", "version": 7, "data": { ... } }, { "type": "task", "id": "0193...", "op": "DELETE", "version": 3 } ], "next_cursor": 10682, "has_more": true } suspend fun pull() { var cursor = syncStateDao.getCursor() do { val page = api.pull(cursor = cursor, limit = 200) db.transaction { for (change in page.changes) { if (outboxDao.hasPendingFor(change.id)) { resolveConflict(server = change.toTask()) } else { taskDao.apply(change) // upsert, or store the tombstone } } syncStateDao.setCursor(page.nextCursor) // same transaction as the data } cursor = page.nextCursor } while (page.hasMore) } Three things to get right:
- Save the cursor in the same transaction as the data. If they are saved separately, a crash in between makes you skip changes or apply them twice.
- Use a server sequence, not timestamps. "Give me everything updated after 10:32:05" misses rows written in the same millisecond or committed late. A sequence number from the database has no such gaps.
- Do not overwrite pending local edits blindly. If a pulled row has a pending outbox entry, the user changed it locally and that change has not reached the server yet. That is a conflict, not an update.
Resolving conflicts
A conflict happens when two parties change the same record without seeing each other's change. With the version column, detecting it is mechanical: the client says "I edited version 5", and the server answers "I'm already at version 6".
Deciding what to do is a product decision, not a technical one. There are four common strategies, from simplest to most careful:
| Strategy | How it works | Good for | Risk |
|---|---|---|---|
| Last write wins (LWW) | The most recent write replaces the other | Settings, preferences, low-value fields | Silently loses one edit |
| Server wins | The server version is kept, the local edit is discarded | Data owned by the backend (prices, stock, statuses) | User loses offline work |
| Field-level merge | Changed fields from both sides are combined; only the same field edited on both sides is a real conflict | Forms and records with many independent fields | Needs per-field tracking |
| Ask the user | Both versions are kept and the user picks or merges | Documents, notes, anything a person typed with care | Extra UI and friction |
You do not have to pick one for the whole app. A good default is field-level merge, with LWW or server-wins as the fallback for fields both sides touched, and a manual resolution screen only for the entities where losing an edit really hurts.
// Three-way merge of one field: base = value before the local edit fun <T> mergeField(base: T, local: T, server: T, onConflict: (local: T, server: T) -> T): T = when { local == base -> server // only the server changed it server == base -> local // only we changed it else -> onConflict(local, server) // both changed it: a real conflict } suspend fun resolveConflict(server: Task) { val local = taskDao.getById(server.id) // Base = the row before the FIRST unsynced edit, so take the oldest pending entry val base = outboxDao.oldestPendingFor(server.id).baseSnapshot.toTask() val merged = server.copy( title = mergeField(base.title, local.title, server.title) { mine, _ -> mine }, // keep the user's text done = mergeField(base.done, local.done, server.done) { _, theirs -> theirs }, // server wins ) // Every pending entry for this row was based on an outdated version: drop them all outboxDao.deleteAllFor(server.id) val needsPush = merged != server taskDao.upsert(merged.copy(syncStatus = if (needsPush) SyncStatus.PENDING else SyncStatus.SYNCED)) if (needsPush) { // One fresh change, based on the version the server has now outboxDao.insert(OutboxEntry.update(merged, baseVersion = server.version, baseSnapshot = server)) } } Two lines matter most. First, every pending outbox entry for that row is dropped: they were all based on a version the server no longer has, so pushing them would only conflict again. Second, when the merged result differs from the server, it goes back through the outbox as one new change, based on the server's current version. That way the server and every other device converge on the same state.
If your data is collaborative in real time (several people editing the same text or list at once), look into CRDTs. They make merges automatic and order-independent, at the cost of more complexity. For most business apps, versions plus field-level merge are enough.
When to sync
The sync engine should run often enough that data feels fresh, but never in a way that drains the battery or fights with itself. Common triggers:
- After a local write — request a sync a few seconds later (debounced), so a burst of edits becomes one push.
- Connectivity regained — the moment the device goes from offline to online.
- App comes to the foreground — the user is about to look at data, so refresh it.
- Periodic background job — every 15 minutes or more, using the platform scheduler (WorkManager on Android, BGTaskScheduler on iOS, background fetch in cross-platform frameworks).
- Silent push notification — the server tells the device "something changed for you", which is the fastest way to get near-real-time updates without keeping a socket open.
Whatever triggers it, only one sync may run at a time. Use a mutex, or let the scheduler enforce a unique job name, so two overlapping cycles never push the same outbox entry twice or move the cursor out of order. Constrain background jobs to "network available", and on metered connections consider pulling only the essentials.
Pitfalls that show up in production
- Server-generated IDs. The number one reason offline creates break. Generate IDs on the client.
- Hard deletes. Deleted rows come back from the dead on the next pull. Use tombstones and purge them later.
- Trusting device clocks. Users travel across time zones and change the time by hand. Use server versions or sequence numbers for ordering.
- Entity and outbox written separately. A crash between the two loses the change forever. One transaction, always.
- Cursor saved outside the data transaction. Leads to skipped or duplicated changes.
- Retrying forever. One invalid record blocks the whole queue. Classify errors and cap attempts.
- Schema migrations. Old app versions keep syncing for months. Version your sync API and make the server tolerant of older payloads.
- Large first sync. A new device may need thousands of rows. Paginate the pull and consider a dedicated bootstrap snapshot.
- Auth expiring mid-sync. A token refresh in the middle of a batch must not drop the outbox. Treat 401 as transient: refresh, then retry.
A checklist before you ship:
- [ ] The UI never calls the API directly
- [ ] Every synced table has a client ID, version and deleted flag
- [ ] Local write and outbox entry share one transaction
- [ ] Every outbox entry has an idempotency key, and the server deduplicates on it
- [ ] Push runs before pull, and only one sync runs at a time
- [ ] Pull uses a server sequence cursor saved atomically with the data
- [ ] There is a conflict policy per entity, written down
- [ ] Users can see what is not synced yet and what failed
Wrapping up
Offline-first is less about a library and more about one discipline: the UI talks to the local database, and a single sync engine owns the network. Everything else follows from that — client IDs so records can exist before the server knows them, an outbox so no change is lost, versions so conflicts are detected instead of guessed, and a cursor so pulls stay small.
Start with one entity. Get push, pull and one conflict policy working end to end, test it in airplane mode and on a flaky connection, and only then extend it to the rest of your data model. Your users in elevators, basements and border crossings will never notice — and that is the whole point.
If you have built offline sync before, I would love to hear which conflict strategy worked for you in the comments.




