Offline-first flows: letting users finish the job without a connection
Most apps treat a missing connection as an error. A spinner, then a banner, then the user gives up. For a feature people open in elevators, basements and airplanes, that isn't good enough. I built an offline flow that lets a user finish a complete multi-step task with no connectivity at all, and syncs the result on its own once the phone is back online. This is how I'd build it again.
The one decision everything follows from
The local database is the source of truth. The screen reads from it and writes to it, and nothing else. The network becomes a background job that keeps the database and the server in agreement.
Once you accept that, a lot of questions answer themselves. The UI doesn't wait on a request, because it never makes one. "Offline" stops being a mode with its own code path. It's the normal path, and being online is what lets the queue drain.
Write the change and the intent together
When the user does something offline, two things have to be recorded: the new state, and the fact that the server doesn't know yet. If those are two separate writes, a crash between them leaves you with a change that will never sync, or a sync for a change that never happened.
So they go in one transaction. The second table is usually called an outbox.
@Entity(tableName = "outbox")data class PendingOperation( @PrimaryKey val id: String, // also sent to the server as the idempotency key val type: String, val payloadJson: String, val createdAt: Long, val attempts: Int = 0,)@Daoabstract class DraftDao { @Transaction open suspend fun completeOffline(draft: DraftEntity, op: PendingOperation) { upsert(draft.copy(syncState = SyncState.PENDING)) enqueue(op) } @Upsert abstract suspend fun upsert(draft: DraftEntity) @Insert abstract suspend fun enqueue(op: PendingOperation)}Let the system decide when to sync
You don't want your own connectivity listener and retry loop. WorkManager already knows when the network is back, survives process death and reboots, and backs off when the server is struggling.
@HiltWorkerclass SyncWorker @AssistedInject constructor( @Assisted context: Context, @Assisted params: WorkerParameters, private val outbox: OutboxRepository,) : CoroutineWorker(context, params) { override suspend fun doWork(): Result = when (outbox.drain()) { DrainResult.Done -> Result.success() DrainResult.RetryLater -> Result.retry() }}val request = OneTimeWorkRequestBuilder<SyncWorker>() .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() ) .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS) .build()WorkManager.getInstance(context) .enqueueUniqueWork("outbox-sync", ExistingWorkPolicy.KEEP, request)Unique work matters. Without it, every offline action schedules another worker and they race each other through the same queue.
Assume every request is sent twice
The request goes out, the server applies it, and the response is lost when the train enters the next tunnel. The app can't tell that from a request that never arrived, so it retries. If the server isn't ready for that, the user's action happens twice.
The fix is an idempotency key. Each operation gets an ID when it's created on the device, and that ID travels with every attempt. The server remembers the IDs it has applied and answers a repeat with the original result. I use the outbox row's primary key for this, so there's one identifier from the tap to the database on the other side.
Decide about conflicts before you have one
Two devices, or a device and the web, will eventually change the same thing. There isn't one right policy. There's a right policy per kind of data, and you want to have chosen it on purpose:
- For settings and preferences, last write wins is usually fine.
- For lists, merge by item. An item added offline shouldn't erase one added elsewhere.
- For a completed user action, never drop it silently. If the server can't accept it any more, keep the user's work on the device, tell them plainly, and give them a way forward.
That last one is the rule I'd fight for. Someone finished a task in good faith with no signal. Losing it without a word is the fastest way to teach them never to trust the app offline again.
Show the state, quietly
People are fine with "saved, will sync when you're back online". What unsettles them is not knowing. Each item carries a sync state in the database, and the UI renders it like any other field: a small pending mark, then nothing once it's synced. Failures that need the user get a clear message. Failures that will fix themselves on retry stay out of their way.
The parts that are easy to forget
- The session can expire while you're offline. The first request after reconnecting may be a 401. Refresh, then drain, and don't throw the queue away because one call was rejected.
- Offline data sits on the device longer. That raises the stakes for storage. Anything sensitive the flow keeps locally should be encrypted under a hardware-backed key.
- Order matters. Drain the queue in the order it was written, and stop at the first operation that fails for a reason a retry won't fix.
- Watch the queue. The two numbers I'd put on a dashboard are how many operations are waiting and how old the oldest one is. A queue that only grows is a bug you won't see in crash reports.
Why the architecture made this cheap
In the app I worked on, features were already split into ui, domain and data modules. That turned out to matter a lot. The domain module owned a repository interface. Going offline-first meant changing what stood behind that interface, from "call the API" to "write locally and enqueue". The ViewModels and screens didn't change, because they had never known where the data came from.
It also makes the whole thing testable without a device. Give the repository a fake API that fails, times out or answers twice, and you can replay every awkward network story as a plain unit test, including the one where the process dies halfway through.
If I had to reduce it to one sentence: save first, sync later, and make the sync safe to repeat.