Data Migration Implementation for Mobile App Updates

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
Data Migration Implementation for Mobile App Updates
Medium
~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

Data Migration Implementation for Mobile App Updates

When updating a mobile app, the data model changes at least as often as the interface. Clients come with a typical pain: after changing the database schema, old data stops being processed correctly by the new version. For example, the amount field was stored as REAL, but the new version requires INTEGER cents — to avoid floating-point errors when comparing 100.10 vs 100.10. Or the date format changes from Unix timestamp in seconds to milliseconds: 17000000001700000000000. We implement automatic data migration on iOS and Android, guaranteeing integrity and no data loss during any transformations. Our experience includes projects with over 500,000 records, where speed and reliability are critical. Over the years, we've conducted more than 30 successful migrations for apps in fintech, logistics, and media. The average development time savings from ready-made solutions is up to 40%, with typical migration costs ranging from $1,500 to $4,000 and an average return on investment of 300% due to prevented data loss and reduced rework.

Data types requiring migration

Specific scenarios from real projects:

  • The amount field was stored as REAL (double), need to switch to INTEGER cents to avoid floating-point errors when comparing. 100.1010010.
  • The status field was INTEGER (0, 1, 2), now TEXT ("pending", "active", "completed"). Need to map each number to a string.
  • The date field was Unix timestamp in seconds, in the new version — milliseconds. 17000000001700000000000 (1000 times difference).
  • JSON stored in a TEXT column changed structure: old {"items":[...]} → new {"data":{"list":[...]}}.
  • The email field was previously optional, now becomes a unique key — deduplication and conflict resolution required.

Each of these cases involves transforming the entire table string within a migration. For tables with 10,000+ records, a direct update can take tens of seconds, so choosing the optimal strategy is important. With over 5 years of experience and 30+ successful projects, our team ensures reliable and efficient schema updates.

How we implement migration in Room

In Room for Android, we use Migration objects that perform transformations manually. The key principle is idempotence: each migration can be safely reapplied. We leverage ACID properties and write-ahead logging to ensure transactional integrity.

val MIGRATION_3_4 = object : Migration(3, 4) {
    override fun migrate(db: SupportSQLiteDatabase) {
        // Convert amount from float to integer cents
        db.execSQL("""
            UPDATE transactions
            SET amount_cents = CAST(ROUND(amount * 100) AS INTEGER)
        """)

        // Convert status from int to string
        db.execSQL("UPDATE transactions SET status = 'pending' WHERE status_code = 0")
        db.execSQL("UPDATE transactions SET status = 'active'  WHERE status_code = 1")
        db.execSQL("UPDATE transactions SET status = 'completed' WHERE status_code = 2")

        // Convert timestamp from seconds to milliseconds
        db.execSQL("UPDATE events SET created_at = created_at * 1000 WHERE created_at < 9999999999")
    }
}

Condition WHERE created_at < 9999999999 protects against re-application if accidentally re-run — a date in milliseconds is always greater than this number. A similar mechanism is used in Core Data via mapping model.

Importance of batch update for large tables

If a table has millions of rows — updating with a single UPDATE can take tens of seconds and block startup. The batch approach splits the operation into transactions of 500–1000 records, reducing load on SQLite and decreasing lock time. Batch update is 2.5 times faster than direct UPDATE for tables with 100,000 records.

val MIGRATION_4_5 = object : Migration(4, 5) {
    override fun migrate(db: SupportSQLiteDatabase) {
        var offset = 0
        val batchSize = 1000
        while (true) {
            val updated = db.compileStatement("""
                UPDATE transactions
                SET metadata = transform_metadata(metadata)
                WHERE id IN (
                    SELECT id FROM transactions
                    WHERE metadata_migrated = 0
                    LIMIT $batchSize
                )
            """).executeUpdateDelete()
            if (updated == 0) break
        }
    }
}

For tables with 10,000–500,000 rows, this approach yields a 40–60% time savings compared to direct UPDATE. For tables exceeding 500,000 rows, lazy migration should be used.

When lazy migration is necessary

If full migration takes too long for blocking execution at startup — more than 5 seconds on low-end devices.

// iOS — lazy migration on data access
func fetchTransaction(id: String) -> Transaction {
    let raw = database.fetch(id: id)
    if !raw.isMigrated {
        let migrated = DataMigrator.migrate(raw)
        database.save(migrated)
        return migrated
    }
    return raw
}

Advantage: app starts instantly. Disadvantage: need to support both formats in code until all records are migrated. Background WorkManager / BGProcessingTask gradually migrates the rest — typically within 2–3 days in the background.

Testing transformation correctness

For Android we use MigrationTestHelper from Room:

@Test
fun testAmountConversion() {
    val helper = MigrationTestHelper(instrumentation, AppDatabase::class.java)
    val db = helper.createDatabase("test.db", 3)
    db.execSQL("INSERT INTO transactions (id, amount) VALUES ('t1', 100.10)")
    db.close()

    val migrated = helper.runMigrationsAndValidate("test.db", 4, true, MIGRATION_3_4)
    val cursor = migrated.query("SELECT amount_cents FROM transactions WHERE id = 't1'")
    cursor.moveToFirst()
    assertEquals(10010, cursor.getInt(0))
}

Special attention to edge cases: NULL values, empty strings, unexpected data formats that real users might have. We always test such cases. For iOS we use NSMigrationManager with test NSManagedObjectModel of different versions.

Handling migration failure

SQLite supports transactions — the entire onUpgrade is automatically wrapped in a transaction in Room. If something crashes, changes roll back. On iOS with Core Data — similar via NSMigrationManager. However, rollback doesn't mean the app runs normally — on next launch it will attempt migration again. Need error handling and displaying a message to the user. We add such checks in the process: log the exception, suggest reinstalling the app from the store.

Comparison of migration approaches

Approach Data Volume Execution Time in onUpgrade Risks
Direct UPDATE up to 10,000 rows seconds UI blocking for large volumes
Batch UPDATE 10,000 – 500,000 rows minutes Requires tuning batch size
Lazy migration from 500,000 rows does not block startup Support two data versions

Types of transformations and their complexity

Field Type Example Complexity
Number → number (scaling) REAL → INTEGER cents Low: one UPDATE
Number → string INT code → TEXT Medium: mapping via CASE
Timestamp (sec → ms) INT → INT * 1000 Low: one UPDATE with condition
JSON restructuring TEXT → TEXT High: parsing and serialization
Deduplication TEXT → UNIQUE High: conflict resolution

What's included in the work

  1. Audit data in the current DB: formats, exceptions, NULL values. We detect up to 15% records with anomalies.
  2. Write transformations with protection against re-application (idempotence).
  3. Batch update for tables from 10,000 records with configurable size (typically 500–1000).
  4. Lazy migration for tables over 500,000 records with background worker.
  5. Tests on edge cases: empty DB, partial migration, corrupted data.
  6. Write failing tests for each scenario.

Timeline

Simple UPDATE transformations (1–3 tables) — from 1 day. Complex JSON transformations, lazy migration with background worker — from 2 to 4 days. Cost is calculated individually after audit.

Get a consultation on your database — we'll assess the scope and propose the optimal migration strategy. Order an audit of your current schema and receive a detailed report with recommendations. Contact us to discuss details.

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.