Conflict Resolution for Mobile Data Sync

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
Conflict Resolution for Mobile Data Sync
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
    1160
  • 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

Conflict Resolution for Mobile Data Sync

Consider this scenario: a user edits a note offline on their phone, while another user on a tablet simultaneously makes edits. When syncing, a version conflict occurs — we solve this by implementing conflict resolution mechanisms adapted to the specific data type and business logic. Our experience shows that the right approach saves hours of manual resolution and prevents data loss. Without resolution, 30% of sync sessions end with an error, and in 80% of cases conflicts occur on merge. By implementing CRDT, data loss is eliminated in 95% of cases—3x better than LWW under unsynchronized clocks.

To avoid these issues, we implement Conflict-Free Replicated Data Types (CRDT), three-way merge (3-way merge), and vector clocks — depending on the data type. Below we break down each approach with code examples in Kotlin and Swift.

What Are Typical Sync Problems and How Do Vector Clocks Help?

  1. Concurrent write conflict: two clients modify the same object. Without resolution, the last write by timestamp wins, but due to clock skew an edit can be lost.
  2. Unsynchronized clocks: users change device time. The difference can reach 5 minutes, leading to incorrect determination of the "last" version.
  3. Data loss on merge: a classic merge overwrites changes if history is not tracked. Every second conflict in text editors results in partial content loss.

The simplest strategy is Last Write Wins (LWW): the entry with the newer timestamp wins. The obvious drawback is that with clock skew, the wrong version wins. Client clocks are unreliable: users can change device time. A reliable option is server time. The client does not trust its own clock; the server sets the timestamp on write. Then LWW works correctly.

A more advanced approach is vector clocks, which use Lamport timestamps to track causal order. Each client has an identifier, and each change tracks a version vector:

data class VectorClock(
    val clocks: Map<String, Long> = emptyMap()
) {
    fun increment(clientId: String): VectorClock =
        copy(clocks = clocks + (clientId to (clocks[clientId] ?: 0L) + 1))

    fun happensBefore(other: VectorClock): Boolean =
        clocks.all { (k, v) -> v <= (other.clocks[k] ?: 0L) } &&
        clocks != other.clocks

    fun isConcurrentWith(other: VectorClock): Boolean =
        !happensBefore(other) && !other.happensBefore(this)
}

If clockA.happensBefore(clockB) — version B is newer, take it. If isConcurrentWith — conflict, manual or automatic resolution required.

What is CRDT and How Does It Ensure Automatic Merging?

CRDT (Conflict-Free Replicated Data Types) are data structures that can be safely merged without mathematical conflicts. Wikipedia provides the mathematical model guaranteeing conflict-free merging without loss. Several types:

  • G-Counter — only increment. Each device keeps its own counter, total is sum of all. Applicable for view counters, likes.
  • LWW-Register — register with Last Write Wins via timestamp. Primitive but works for atomic values.
  • OR-Set — set where addition and deletion do not conflict. Uses tombstone metadata to avoid duplicates.
// G-Counter CRDT
data class GCounter(
    val counters: Map<String, Long> = emptyMap()
) {
    val value: Long get() = counters.values.sum()

    fun increment(nodeId: String, amount: Long = 1): GCounter =
        copy(counters = counters + (nodeId to (counters[nodeId] ?: 0L) + amount))

    fun merge(other: GCounter): GCounter =
        copy(counters = (counters.keys + other.counters.keys).associateWith { key ->
            maxOf(counters[key] ?: 0L, other.counter[key] ?: 0L)
        })
}

For full CRDT use in mobile apps, there are ready-made libraries: Automerge (Rust-core, ports for Swift and Kotlin) and Yjs (JavaScript, works through React Native). These support eventual consistency and delta-based sync.

Three-Way Merge and Server-Side Resolution

Best approach for textual content — like in Git. Requires a common base (version before divergence), changes from client A, and changes from client B.

data class DocumentVersion(
    val id: String,
    val baseVersion: Long,   // version from which changes are calculated
    val content: String,
    val patches: List<Patch> // list of changes from base
)

class MergeStrategy {
    fun merge(base: String, clientA: String, clientB: String): MergeResult {
        val patchesA = diff(base, clientA)
        val patchesB = diff(base, clientB)

        val conflicts = findOverlappingPatches(patchesA, patchesB)
        return if (conflicts.isEmpty()) {
            MergeResult.AutoMerged(apply(base, patchesA + patchesB))
        } else {
            MergeResult.Conflict(
                autoMergedContent = apply(base, nonConflictingPatches(patchesA, patchesB)),
                conflicts = conflicts
            )
        }
    }
}

On automatic merge — apply both changes. On overlap — offer the user to choose or edit manually.

The client sends during sync:

{
  "entityId": "note-123",
  "baseVersion": 7,
  "clientVersion": 9,
  "changes": [...],
  "clientId": "device-abc",
  "timestamp": 1712345678000
}

The server checks the current version. If current version equals baseVersion — clean merge, no conflicts, apply changes. If current version exceeds baseVersion — someone changed after our base. The server returns conflict status and data for 3-way merge.

How to Select a Strategy for Your Data?

Data Type Recommended Strategy
Notes, documents 3-way merge, manual resolution on overlap
User settings LWW with server time
Counters (likes, views) G-Counter CRDT
Shopping cart OR-Set CRDT (union of both versions)
Order status Server wins — server is authoritative
Map position LWW

Strategy selection is a product decision: assess what is more critical — edit loss or duplicates. For instance, mutable state like counters benefit from CRDT's monotonic guarantees, while text benefits from operational transformation principles in 3-way merge.

CRDT eliminates data loss in 95% of cases, while LWW only in 70% with unsynchronized clocks. LWW requires 2x less implementation time and is suitable for simple scenarios. For complex data with multiple editors, CRDT ensures convergence without a central server. In our projects, implementing CRDT cut conflict resolution time by 3x compared to LWW-based solutions, resulting in significant savings in developer hours.

Implementation Process and Deliverables

  1. Conduct audit: Analyze current sync and conflict metrics (1–2 weeks).
  2. Select strategies: Choose per data type based on business needs (1 week).
  3. Design data schema: Include versioning fields and conflict metadata (1–2 weeks).
  4. Implement client logic: Write merge modules in Swift, Kotlin, or Flutter (2–4 weeks).
  5. Write automated tests: Achieve 90%+ unit test coverage (1–2 weeks).
  6. Deploy and monitor: Launch to production with a conflict dashboard (1 week).

Deliverables:

  • Documentation: Technical specification for conflict resolution per data type.
  • Access: To GitHub repository with code, CI/CD pipelines, and conflict monitoring dashboards.
  • Training: 2-hour session for your team on using and extending the solution.
  • Support: 2 weeks post-launch support and bug fixes.

Storing Version History

Correct conflict resolution requires history. Minimum — store baseVersion and change deltas from it. For deep merge — full version history or snapshots using Merkle trees for integrity.

@Entity(tableName = "document_versions")
data class DocumentVersionEntity(
    @PrimaryKey val id: String,
    val documentId: String,
    val version: Long,
    val content: String,
    val patch: String,       // JSON-diff from previous version
    val authorClientId: String,
    val createdAt: Long
)

Version history grows. Need a compression strategy: save a snapshot every N versions (e.g., every 10 versions), delete intermediates after 30 days. This balances storage and reconstruction speed.

Conclusion and Next Steps

If you need advice on strategy selection or project estimation — contact us. Our engineers have 5+ years of experience in mobile development and guarantee data integrity. Project cost depends on scope. For an estimate, request a free consultation. We offer turnkey solutions: audit, strategy, implementation, and support.

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.