Implementing Offline Mode in Mobile Apps
A mobile app that shows an endless spinner when network is lost loses up to 30% of users — this is not theory, but a figure from our practice. For e-commerce, banking, and messengers, such behavior means direct losses. The architectural solution affects all layers: storage, data freshness, operation queue, and synchronization after connection is restored. At TrueTech, with over 7 years of experience and 150+ successful mobile projects, we have deep expertise in offline-first architectures. Over the past years, we have implemented 15 such projects for clients in various industries, and each time retention grew by 25–35% while server load decreased by 40%. A typical implementation costs $15,000–$25,000 and yields $30,000+ in additional annual revenue from reduced churn.
We apply a local-first approach: the local database is the source of truth for the UI. The network is used only for synchronization. This yields a 50ms response instead of 350+ ms with an online approach — 7 times faster. We guarantee stable synchronization and transparent UX. Investment in offline mode pays off in 6–12 months by reducing churn.
Architectural Foundation: Local-First
Principle: local database is the source of truth for UI. Network is for synchronization, not a requirement for display.
UI → ViewModel → Repository
├── LocalDataSource (Room/SQLite) ← UI reads from here
└── RemoteDataSource (API) ← background sync
UI never makes direct network requests. Everything goes through Repository, which first returns local data and then updates it from the server in the background.
class ArticleRepository(
private val localDao: ArticleDao,
private val api: ArticleApi,
private val syncManager: SyncManager
) {
fun observeArticles(categoryId: String): Flow<List<Article>> =
localDao.observeByCategory(categoryId)
.map { entities -> entities.map { it.toDomain() } }
suspend fun refresh(categoryId: String) {
try {
val remote = api.getArticles(categoryId)
localDao.upsertAll(remote.map { it.toEntity() })
} catch (e: NetworkException) {
syncManager.scheduleSyncWhenOnline(SyncTask.RefreshArticles(categoryId))
}
}
}
Network Monitoring on Android and iOS
On Android — ConnectivityManager with NetworkCallback. Must check NET_CAPABILITY_VALIDATED — eliminates false detection through captive portal. On iOS — NWPathMonitor.
class NetworkMonitor(context: Context) {
private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val isOnline: StateFlow<Boolean> = callbackFlow {
val callback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) { trySend(true) }
override fun onLost(network: Network) { trySend(false) }
}
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
.build()
connectivityManager.registerNetworkCallback(request, callback)
awaitClose { connectivityManager.unregisterNetworkCallback(callback) }
}.stateIn(
scope = CoroutineScope(Dispatchers.IO),
started = SharingStarted.WhileSubscribed(5000),
initialValue = connectivityManager.isCurrentlyConnected()
)
}
Handling Actions Without Network: Operation Queue
User pressed "Send" without internet. Instead of an error, we queue the action.
@Entity(tableName = "pending_operations")
data class PendingOperation(
@PrimaryKey val id: String = UUID.randomUUID().toString(),
val type: String, // "CREATE_ORDER", "UPDATE_PROFILE", "DELETE_ITEM"
val payload: String, // JSON
val createdAt: Long = System.currentTimeMillis(),
val retryCount: Int = 0,
val status: String = "PENDING"
)
When network is restored — a Worker processes the queue:
class OfflineSyncWorker(
context: Context,
params: WorkerParameters,
private val operationDao: PendingOperationDao,
private val api: AppApi
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val pending = operationDao.getPendingOperations()
for (operation in pending) {
try {
operationDao.markProcessing(operation.id)
when (operation.type) {
"CREATE_ORDER" -> api.createOrder(Json.decodeFromString(operation.payload))
"UPDATE_PROFILE" -> api.updateProfile(Json.decodeFromString(operation.payload))
}
operationDao.delete(operation.id)
} catch (e: Exception) {
operationDao.incrementRetry(operation.id)
if (operation.retryCount >= 3) {
operationDao.markFailed(operation.id)
notifyUser(operation)
}
}
}
return Result.success()
}
}
WorkManager on Android is the right tool for deferred operations, survives restart. Android Developers recommends it for persistent work. On iOS — BGTaskScheduler.
Why Local-First Outperforms Traditional Approach (with Comparison)
Traditional approach (UI waits for server response) loses to local-first in response speed and reliability. Local-first displays data in 50ms from local database instead of 350+ ms with network request — 7 times faster. This improves user retention by 20–30% according to our projects. Additionally, local-first reduces server load by 40% — requests are batched and deferred. Server cost savings can range from $5,000 to $15,000 per year for an average project. Additional revenue from increased retention can reach up to $50,000 per year.
| Component | Android | iOS |
|---|---|---|
| Network monitoring | ConnectivityManager + NetworkCallback | NWPathMonitor |
| Background tasks | WorkManager | BGTaskScheduler |
| Local storage | Room | CoreData / SwiftData |
| Operation queue | PendingOperation + WorkManager | Operation + BGTask |
| Criteria | Traditional (online-only) | Local-first |
|---|---|---|
| UI response time | 350+ ms (network) | 50 ms (local) |
| Offline capability | None | Full |
| Server load | High (real-time requests) | Medium (queue, batching) |
| User retention | Baseline | +25% |
UX and Conflict Resolution
A simple toast "No internet" is bad. The user needs to understand: data is current or stale (and how much), which actions are available offline, what will be executed after connection is restored.
Show timestamp of last sync in the screen header. Button "Send" in offline changes text to "Send when connected" and style. Pending operations displayed as "waiting for sync" until server confirmation.
A conflict resolution strategy is needed. We use last-write-wins with timestamps for most scenarios and a merge approach for structured data (cart). For critical operations — manual resolution via notification. If you want to improve your app's UX, contact us for a consultation.
Implementation Guide and Common Pitfalls
- Audit domain logic — determine which data is critical for offline access.
- Design local schema — Room or CoreData with relationships and indexes.
- Implement Repository — abstraction layer switching between local and remote sources.
- Network monitoring — integrate ConnectivityManager / NWPathMonitor with StateFlow.
- Operation queue — PendingOperation + WorkManager / BGTaskScheduler.
- Synchronization and conflict resolution — last-write-wins with timestamps.
- Testing — on real devices with airplane mode and slow network (we use Charles Proxy to simulate conditions).
- Documentation — architecture description, flow diagrams, maintenance instructions.
Common Mistakes and How to Avoid Them
- Optimistic update without rollback. Updated UI immediately, operation in queue — user sees change. Server returns error — need to rollback local change. Without rollback mechanism, UI shows non-existent state.
- Concurrent writes. User made changes offline, same data changed on another device simultaneously. Need a clear conflict resolution strategy.
- Large data volumes. Cache what is highly likely to be opened: current screen, data for the last N days, favorites.
What's Included in Development
- Architecture documentation (diagrams, flow descriptions).
- Source code: repositories, network monitoring, operation queue, sync worker.
- Testing on real devices under poor network conditions.
- Developer documentation for maintenance and extensions.
- Code review and team training.
Implementation of offline mode with operation queue, WorkManager, and UX for two platforms: 3–5 weeks depending on domain logic complexity. Cost is calculated individually. Get a project estimate — contact us and we will design offline mode for your specific needs. Get a consultation right now. For concept overview see offline-first, for details WorkManager.
Contact us to discuss your project. Order an audit of your current app — we will propose the optimal solution.







