Offline-First Android Architecture with Kotlin, Room DB, and Coroutines
Field sales, delivery, and attendance apps in Pakistan cannot assume constant 4G connectivity. Here is the single-source-of-truth Room + WorkManager architecture we ship in production.
An Android app that shows an endless loading spinner whenever a user enters a basement warehouse or switches mobile towers is unusable in the real world. For logistics, retail POS, and field-inspection clients across Karachi and Lahore, unreliable cellular coverage is the default environment—not an edge case.
The Core Principle: Room Is Always the Single Source of Truth
In an offline-first architecture, your UI never renders data directly from a Retrofit network call. Instead, your UI observes a Kotlin Flow emitted by a local Room database. Network responses write to Room, and Room automatically notifies the UI.
@Dao
interface OrderDao {
@Query("SELECT * FROM orders ORDER BY createdAt DESC")
fun observeAllOrders(): Flow<List<OrderEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(orders: List<OrderEntity>)
@Query("SELECT * FROM orders WHERE syncStatus = 'PENDING'")
suspend fun getPendingSync(): List<OrderEntity>
}
Handling Writes While Offline
When a delivery rider marks an order as delivered with zero signal:
- Generate a client-side UUID (
localUuid) as an idempotency key so retrying the upload later never creates duplicate rows on your Laravel backend. - Save the record immediately into Room with
syncStatus = "PENDING". The rider sees instant confirmation on screen with zero wait. - Enqueue a
WorkManagerjob withNetworkType.CONNECTEDconstraints and exponential backoff.
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val syncWork = OneTimeWorkRequestBuilder<SyncOrdersWorker>()
.setConstraints(constraints)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
"sync_pending_orders",
ExistingWorkPolicy.KEEP,
syncWork
)
Backend Idempotency Matters Just as Much
Mobile networks frequently drop right after the server saves a POST request but before the Android client receives the HTTP 200 response. WorkManager will retry the exact same payload. Your API endpoint must check the local_uuid column (with a unique index in MySQL) and return the existing record instead of inserting a duplicate.
Once you build one app with Room as the source of truth and idempotent WorkManager sync, you never go back to fragile online-only screens.
Need help architecting a Laravel backend, Kotlin Android app, or joining our weekend engineering cohort?