Implementing Offline Mode in Mobile Apps

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
Implementing Offline Mode in Mobile Apps
Complex
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    858
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    743
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1159
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1034
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    968
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    562

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

  1. Audit domain logic — determine which data is critical for offline access.
  2. Design local schema — Room or CoreData with relationships and indexes.
  3. Implement Repository — abstraction layer switching between local and remote sources.
  4. Network monitoring — integrate ConnectivityManager / NWPathMonitor with StateFlow.
  5. Operation queue — PendingOperation + WorkManager / BGTaskScheduler.
  6. Synchronization and conflict resolution — last-write-wins with timestamps.
  7. Testing — on real devices with airplane mode and slow network (we use Charles Proxy to simulate conditions).
  8. 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.

How to Choose a Local Data Storage Solution (Room, Core Data, Realm, Isar)?

We've all seen the scenario: the app loses data when the network drops — and it's not just a bug, it's a failure of the use case. The user fills out a form, taps "Submit", gets a timeout, and loses everything. Or worse: data gets sent twice due to incorrect retry logic. A properly chosen and configured storage layer solves this problem once and for all. The wrong choice can cost teams months of rewriting code and up to 70% of time spent on synchronization. Our experience — 10+ years in mobile development, over 50 projects with offline storage — confirms: the storage choice determines 80% of future performance and synchronization issues.

In practice, storage selection is driven by two factors: data type and synchronization requirements, not library popularity.

Room (Android) — a wrapper over SQLite with compile-time verification of SQL queries. If a query is invalid, the build fails — better than a SQLiteException at runtime. Room integrates well with Kotlin Flow and LiveData, making reactive UI updates straightforward. The main challenge is schema migrations. @Database(version = N, exportSchema = true) with migration files in assets/databases/ is mandatory; otherwise, fallbackToDestructiveMigration() will simply delete the user's data on app update.

Core Data (iOS) — not a database, but an object graph management framework over SQLite (or XML, or in-memory). NSPersistentContainer with viewContext for reading on the main thread and newBackgroundContext() for writing is the basic setup. The trouble begins when a developer calls save() on viewContext from a background thread: EXC_BAD_ACCESS at a random moment, happens once a week, with almost nothing useful in the crash log. You must use performAndWait or perform for each context strictly on its own thread. Apple Core Data Programming Guide recommends this approach.

Realm wins where you need speed with large object sets and built-in reactivity through Results + observe(). Realm stores objects directly without ORM mapping, so reads require no deserialization. According to our measurements, Realm processes reads 2–3 times faster than Core Data for volumes over 10,000 objects. On Flutter, the Realm SDK (ex-MongoDB Realm) supports Device Sync — but that's a managed service with separate infrastructure.

Hive and Isar are Flutter-specific solutions. Hive is a key-value store, fast, simple, suitable for settings and caches. Isar is a full document-oriented database with indexes, written in Rust, compiled to native code. For Flutter apps with offline functionality, Isar is now preferred: built-in query builder with type-safe filters, transactions, watchObject/watchQuery for reactivity.

Platform Solution Reactivity Synchronization
Android Room + Flow LiveData/Flow WorkManager
iOS Core Data NSFetchedResultsController CloudKit
Flutter Isar Streams Custom / Realm Sync
Cross-platform Realm RealmResults.observe Device Sync
Flutter (simple) Hive ValueListenable None

Contact us for a free audit of your current storage and optimization recommendations — this will save you hundreds of development hours and up to 60% of server request traffic.

Why Is Offline Synchronization the Hardest Part?

Local storage itself is not complicated. The complexity lies in synchronizing with the server in the presence of conflicts.

The most common pattern is optimistic updates with rollback. The user edits a record, the UI reflects the change instantly, a background request goes to the server. If the server returns an error, we roll back the local state. Sounds simple. In practice: if the user has left the screen and returned before the rollback (which may take 3 seconds), the UX is broken. You need an explicit operation queue with states (PENDING, SYNCED, FAILED) in a separate table.

On Android, for background synchronization we use WorkManager with Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED). Don't forget setInputMerger(ArrayCreatingInputMerger::class) when batching tasks — otherwise, concurrent runs will overwrite data. A typical operation queue implementation:

class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
    override suspend fun doWork(): Result {
        val pendingOps = syncDao.getPendingOperations()
        for (op in pendingOps) {
            try {
                apiClient.send(op.payload)
                syncDao.markSynced(op.id)
            } catch (e: Exception) {
                syncDao.markFailed(op.id, e.message)
                return Result.retry()
            }
        }
        return Result.success()
    }
}

On iOS, the equivalent is BGTaskScheduler with BGProcessingTaskRequest. iOS limitations on background execution time (~30 seconds for refresh tasks) mean that synchronization must be incremental: not "sync everything," but "sync the next N records, save the cursor."

Conflicts in multi-device scenarios are resolved with one of three approaches:

  • Last-write-wins based on updated_at (simplest, loses data on concurrent edits)
  • Server-wins (client always accepts server version)
  • Three-way merge (complex, requires a common ancestor — suitable for documents)

For most B2C apps, last-write-wins with a user-level time vector is sufficient, but for collaborative editing, a CRDTs approach is needed — then look at Automerge or Yjs with mobile bindings.

How We Build the Storage Layer

The repository pattern is not optional — it's mandatory. UserRepository doesn't know where the data comes from: Room, Realm, or network. The ViewModel calls repository.getUser(id), gets a Flow/Stream, and displays data. Caching logic resides inside the repository.

For Flutter, a typical architecture: Isar for persistence, Riverpod for state management, ConnectivityPlus for network status, and a custom SyncService with an operation queue. Riverpod's AsyncNotifier conveniently covers the logic of "show cache, update from network, show new data." Example repository with caching:

class UserRepository {
  final Isar isar;
  final ApiClient api;

  Future<User> getUser(String id) async {
    // try from local storage first
    final cached = await isar.user.where().idEqualTo(id).findFirst();
    if (cached != null) return cached;
    // otherwise from network
    final remote = await api.fetchUser(id);
    // save locally
    await isar.writeTxn(() => isar.user.put(remote));
    return remote;
  }
}

Another important topic is encryption. If the app stores medical data, payment cards, or corporate documents, SQLCipher (Android) and NSFileProtection (iOS) are not optional. Realm supports encryption natively via a 64-byte key that must be stored in Keychain/Keystore, not in SharedPreferences. Skimping on security can lead to data leaks with serious consequences.

What the Work Includes

We guarantee a transparent process and document each stage:

Stage Result
Requirements audit Document analyzing data types, volumes, synchronization scenarios
Schema design ER diagram, migration files, conflict resolution plan
Repository layer development Code with unit tests (in-memory DB + network mocks)
Synchronization integration Operation queue, error handling, fallback logic
Profiling and optimization Report from Android Profiler / Core Data SQLDebug, recommendations
Deployment and documentation Deployment instructions, API description, repository access

Want to avoid common mistakes when designing storage? Contact us — we'll help design a reliable local storage from scratch or improve an existing one.

Stages of Work

We start with a requirements audit: what data, what volume, is synchronization needed, are conflicts possible. At this stage, it becomes clear whether Core Data or an SQLite-based solution is needed, whether Realm Sync is required or simple REST polling will suffice.

Next, we design the schema with migrations in mind. Schemas change in any project — the question is not "will there be migrations," but "how painful will they be." We export the schema as JSON, store it in the repository, and write tests for each version's migration.

Development includes unit test coverage for the repository layer: network layer mocks, a real in-memory database for query testing. Before release, we profile queries using Android Profiler (Database Inspector tab) or Core Data debug flags (-com.apple.CoreData.SQLDebug 1).

The implementation timeline for a storage layer with basic offline synchronization ranges from 2 to 6 weeks, depending on schema complexity and conflict resolution requirements. Contact us to get a consultation on choosing the optimal stack and migrations.