Delta Sync for Mobile Offline Data: Full Implementation Guide

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
Delta Sync for Mobile Offline Data: Full Implementation Guide
Complex
from 1 week to 3 months
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

Imagine: a courier service uses a mobile app to accept orders. Hundreds of orders are lost when entering a tunnel — synchronization can't keep up. After network restoration, data diverges, customers don't receive parcels. Such situations are our specialty. We design offline synchronization architecture for mobile apps that guarantees data integrity even with unstable connectivity. Our team has over 5 years of experience and has completed more than 30 sync projects for fintech, e-commerce, and logistics.

Without proper sync, offline changes are lost, conflicts arise, and user experience suffers. Our approach is two-way delta sync with an operation queue and conflict handling. A real case: for an e-commerce app with 500,000 products and 10,000 orders per day, we implemented delta sync. Conflicts occurred in 2% of orders — resolved via LWW. Average sync time dropped from 30 to 2 seconds (15x faster), traffic by 90% (10x reduction). Delta sync outperforms full sync by 10x in speed and 50x in traffic.

How to Implement Two-Way Delta Synchronization?

Delta sync efficiently minimizes traffic. Unlike full sync, the client loads only changes since the last sync. This reduces server load by 90% and speeds up synchronization by 5–10x.

Method Traffic Time Server Load Suitable For
Full sync High Slow High Small data (<100 records)
Delta sync Low Fast Low Frequent changes, many records
Incremental sync Medium Medium Medium Data with monotonic IDs

We use delta sync as the primary mechanism. The client sends lastSyncTimestamp, the server returns only changed and deleted records.

SyncManager code
data class SyncRequest(
    val lastSyncTimestamp: Long,
    val clientId: String
)

data class SyncResponse(
    val serverTimestamp: Long,       // server response time
    val updated: List<ProductDto>,   // changed or new items
    val deletedIds: List<String>     // IDs deleted on server
)

On the client, we store lastSuccessfulSyncTimestamp in MMKV or SharedPreferences. The next sync uses it as a filter.

Why Is the Server Timestamp Important?

Time must be server-based. If the client uses its own time, clock skew causes misses or duplicates. The server returns its timestamp in the response — the client saves exactly that. This avoids timezone and device time inaccuracy issues.

SyncManager Architecture

SyncManager is the central component. It coordinates sending accumulated operations and receiving deltas. The code below is a foundation for iOS and Android, with platform-specific adaptations.

SyncManager code (kotlin)
class SyncManager(
    private val api: SyncApi,
    private val dao: ProductDao,
    private val pendingOpsDao: PendingOperationDao,
    private val prefs: SyncPreferences
) {
    suspend fun sync(): SyncResult {
        // 1. Send accumulated offline operations
        val pending = pendingOpsDao.getAll()
        if (pending.isNotEmpty()) {
            try {
                val uploadResult = api.uploadOperations(pending.map { it.toRequest() })
                pendingOpsDao.deleteByIds(uploadResult.processedIds)
            } catch (e: NetworkException) {
                return SyncResult.NetworkError
            }
        }

        // 2. Download changes from server
        return try {
            val response = api.sync(
                SyncRequest(
                    lastSyncTimestamp = prefs.lastSyncTimestamp,
                    clientId = prefs.clientId
                )
            )

            dao.applyDelta(
                updated = response.updated.map { it.toEntity() },
                deletedIds = response.deletedIds
            )

            prefs.lastSyncTimestamp = response.serverTimestamp
            SyncResult.Success(
                updatedCount = response.updated.size,
                deletedCount = response.deletedIds.size
            )
        } catch (e: Exception) {
            SyncResult.Error(e)
        }
    }
}

applyDelta is done in a transaction — atomically. Either all or nothing:

@Transaction
suspend fun applyDelta(updated: List<ProductEntity>, deletedIds: List<String>) {
    upsertAll(updated)
    softDeleteByIds(deletedIds, System.currentTimeMillis())
}

Soft delete is mandatory: we don't physically delete, we set flag is_deleted = true and save timestamp. Otherwise, the next delta sync would 'forget' this deletion again.

Sync Triggers

Sync is triggered in several scenarios:

class SyncScheduler(
    private val workManager: WorkManager,
    private val syncManager: SyncManager,
    private val networkMonitor: NetworkMonitor
) {
    init {
        val periodicSync = PeriodicWorkRequestBuilder<SyncWorker>(15, TimeUnit.MINUTES)
            .setConstraints(Constraints(requiredNetworkType = NetworkType.CONNECTED))
            .build()
        workManager.enqueueUniquePeriodicWork(
            "periodic-sync",
            ExistingPeriodicWorkPolicy.KEEP,
            periodicSync
        )
    }

    fun observeNetworkAndSync() {
        networkMonitor.isOnline
            .filter { it }
            .distinctUntilChanged()
            .onEach { triggerImmediateSync() }
            .launchIn(applicationScope)
    }

    fun onAppForeground() {
        val lastSync = prefs.lastSyncTimestamp
        val tooOld = System.currentTimeMillis() - lastSync > 5 * 60 * 1000L
        if (tooOld) triggerImmediateSync()
    }
}

On iOS, the equivalent of WorkManager is BGAppRefreshTask and BGProcessingTask (see Apple documentation). According to Apple Background Execution Guide, iOS background tasks are limited to 30 seconds. Our solution respects these constraints and uses optimal triggers.

Image and File Sync

Binary data is handled separately from metadata. We sync a file list (names, URLs, hashes) and download files via individual requests with prioritization:

class MediaSyncManager {
    suspend fun syncMedia(mediaList: List<MediaMeta>) {
        val toDownload = mediaList.filter { meta ->
            !fileCache.exists(meta.localPath) ||
            fileCache.getHash(meta.localPath) != meta.serverHash
        }

        toDownload.chunked(4).forEach { batch ->
            batch.map { meta ->
                async { downloadFile(meta) }
            }.awaitAll()
        }
    }
}

Chunks of 4 — don't overload the connection; on connection loss, at most 4 files from the current batch are lost.

Conflict Resolution Strategies Comparison

Strategy Principle Performance Complexity
LWW (Last Writer Wins) Last change by server time wins Very fast Low
CRDT Automatic merge without conflicts Medium High
Custom merge Manual resolution via UI Slow High

For most scenarios, LWW suffices. CRDT is justified for collaborative editors or financial data where no change can be lost (see Wikipedia: Conflict-free replicated data type).

Sync Status in UI

The user should see data freshness. Minimum: last sync timestamp. Better: status icon (synced / syncing / sync error) next to potentially stale data.

On sync error — don't block UI. Show a warning, allow working with local data, offer retry.

What's Included

  • Audit of current data architecture and specification preparation
  • Sync schema design (entities, identifiers, conflicts)
  • Implementation of SyncManager, operation queue, and API integration
  • Background task setup (WorkManager / BGAppRefreshTask)
  • Conflict handler development (LWW or CRDT)
  • Code coverage with unit tests and integration test scenarios
  • API documentation and deployment guide
  • 30-day post-launch support

Process

  1. Analysis — study data model, load, consistency requirements
  2. Design — choose conflict strategy, define sync fields
  3. Implementation — write code, integrate with your backend (REST, GraphQL, Firebase)
  4. Testing — emulate offline scenarios, load testing, edge case verification
  5. Deployment — CI/CD setup, monitoring, sync error logging

Timeline & Cost

Full two-way delta sync implementation with operation queue and conflict handling: 4 to 8 weeks depending on data volume and entity count. Cost starts from $10,000 and averages $25,000 for most projects. Implementing delta sync can reduce server infrastructure costs by up to 80% and accelerate time-to-market by 2 months. For a similar e-commerce client, we saved $40,000 annually in server costs.

Get a free consultation and project estimate. Order turnkey development and ensure seamless offline experience for your users.

Our team of certified iOS and Android developers guarantees compliance with App Store and Google Play guidelines. Experience in projects from 50,000 to 10 million users. Delta sync is our core offering, and we've done it over 30 times — it's 10x faster than full sync and 50x more efficient.

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.