All ArticlesMobile•November 18, 2026•10 min read

Zero-Downtime Database Migrations for Mobile at Scale

Design safe schema evolution across mobile clients and distributed backends using expand-contract, compatibility windows, and production-grade migration runners. Learn how to ship database changes without breaking old app versions, offline queues, or live traffic.

Zero-Downtime Database Migrations for Mobile at ScaleAI Generated with Qwen 3.0 via CometAPI

Mobile clients make schema evolution a distributed-systems problem. A backend migration is not complete when the database accepts DDL; it is complete when old app versions, new app versions, background sync workers, and offline devices can all operate safely. This playbook covers the compatibility model, expand-contract execution, production migration runners, on-device SQLite/Room migrations, and rollout gates that keep mobile releases safe.

Mobile Makes Every Migration a Distributed Systems Problem

In a web deployment, the server and client are usually refreshed together. In mobile, the client fleet is a long tail: users on old binaries, devices that have not synced for weeks, app stores throttling rollout, and offline queues replaying writes against a schema that may already have changed. A migration that is safe for the current API can still break a three-month-old app.

Treat every schema change as a compatibility contract across four moving parts: the relational schema, the API payload, the on-device SQLite/Core Data store, and the sync protocol. Keep a support matrix: for example, backend supports app schema versions 3 through 6; on-device DB supports forward migrations from the last two major releases; API rejects clients below schema version 3 with a structured upgrade response.

Expand-Contract: The Only Safe Default

Use expand-contract, also known as parallel change. Never remove or rename a field in one step. The sequence is:

  1. Expand: add nullable columns, new tables, new indexes, and new API fields. Old readers ignore them.
  2. Dual write: write both old and new representations from a single authoritative transaction or an outbox.
  3. Backfill: copy historical rows in small, idempotent batches.
  4. Switch reads: turn on new read paths behind flags, then ramp traffic.
  5. Contract: remove old columns and fields only after telemetry proves no supported client or job still reads them.

For mobile, the contract phase is a product decision, not only an engineering one. Gate it on app version adoption, sync error rates, migration crash-free sessions, and support-ticket volume. If the minimum supported version is still receiving traffic, keep the old column.

Backend Expand/Contract in SQL

The safest DDL is additive and idempotent. In PostgreSQL, adding a nullable column avoids a table rewrite; use concurrent index creation outside a transaction. Set lock_timeout and statement_timeout so a migration does not queue behind or block production traffic indefinitely.

sql
-- Phase 1: expand. Safe for old and new application versions.
ALTER TABLE orders
  ADD COLUMN IF NOT EXISTS fulfillment_state text;

-- Backfill separately in batches; do not update the whole table in one transaction.
-- CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_fulfillment_state
  ON orders (fulfillment_state)
  WHERE fulfillment_state IS NOT NULL;

-- Phase 5: contract only after the compatibility window closes.
-- ALTER TABLE orders DROP COLUMN IF EXISTS legacy_status;

Make the migration runner reject checksum changes for already-applied migrations. That prevents the classic failure where one pod applies a modified file on a fresh database while another pod runs the old checksum.

A Production-Grade Migration Runner

The runner below uses a PostgreSQL advisory lock to serialize migration execution across pods, records checksums, supports transactional and non-transactional DDL, and releases the lock in finally. Non-transactional migrations must be idempotent because a crash can occur between the DDL and the migration-record insert.

ts
import { createHash } from 'node:crypto';
import type { Pool } from 'pg';

export interface Migration {
  id: string;
  sql: string;
  transactional: boolean;
}

interface AppliedMigration {
  id: string;
  checksum: string;
}

export class MigrationRunner {
  constructor(
    private readonly pool: Pool,
    private readonly migrations: Migration[],
    private readonly lockKey: number,
    private readonly log: (event: string, meta?: Record<string, unknown>) => void,
  ) {}

  private checksum(sql: string): string {
    return createHash('sha256').update(sql).digest('hex');
  }

  async run(): Promise<void> {
    const client = await this.pool.connect();
    let locked = false;
    try {
      await client.query('SELECT pg_advisory_lock($1)', [this.lockKey]);
      locked = true;
      await client.query(`
        CREATE TABLE IF NOT EXISTS schema_migrations (
          id text PRIMARY KEY,
          checksum text NOT NULL,
          applied_at timestamptz NOT NULL DEFAULT now()
        )
      `);
      const applied = await client.query<AppliedMigration>(
        'SELECT id, checksum FROM schema_migrations',
      );
      const appliedById = new Map(applied.rows.map((row) => [row.id, row.checksum]));

      for (const migration of this.migrations) {
        const existing = appliedById.get(migration.id);
        const expected = this.checksum(migration.sql);
        if (existing !== undefined) {
          if (existing !== expected) {
            throw new Error(
              `Checksum mismatch for ${migration.id}: applied=${existing} expected=${expected}`,
            );
          }
          continue;
        }

        this.log('migration.start', { id: migration.id });
        if (migration.transactional) {
          await client.query('BEGIN');
        }
        try {
          await client.query(migration.sql);
          await client.query(
            'INSERT INTO schema_migrations (id, checksum) VALUES ($1, $2)',
            [migration.id, expected],
          );
          if (migration.transactional) {
            await client.query('COMMIT');
          }
          this.log('migration.complete', { id: migration.id });
        } catch (error) {
          if (migration.transactional) {
            await client.query('ROLLBACK');
          }
          this.log('migration.failed', { id: migration.id, error: String(error) });
          throw error;
        }
      }
    } finally {
      if (locked) {
        await client
          .query('SELECT pg_advisory_unlock($1)', [this.lockKey])
          .catch((error: unknown) => {
            this.log('migration.unlock_failed', { error: String(error) });
          });
      }
      client.release();
    }
  }
}

Run this as a dedicated job, not from every application replica. Keep the advisory lock session alive on the same client; a pool-level lock on another connection will not protect the migration.

On-Device SQLite and Room Migrations

On-device migrations face different failure modes: process death mid-migration, low storage, encrypted databases, OS-level app suspension, and millions of devices that will never get a clean reinstall. Prefer additive migrations with explicit Migration objects. Avoid destructive fallbacks unless the product formally accepts data loss.

kotlin
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

@Database(entities = [Note::class], version = 3, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
  abstract fun noteDao(): NoteDao

  companion object {
    val MIGRATION_2_3 = object : Migration(2, 3) {
      override fun migrate(db: SupportSQLiteDatabase) {
        db.execSQL("ALTER TABLE notes ADD COLUMN sync_state TEXT NOT NULL DEFAULT 'pending'")
        db.execSQL("CREATE INDEX IF NOT EXISTS index_notes_sync_state ON notes(sync_state)")
        db.query("SELECT COUNT(*) FROM notes WHERE sync_state IS NULL").use { cursor ->
          check(cursor.moveToFirst() && cursor.getInt(0) == 0) {
            "sync_state backfill validation failed"
          }
        }
      }
    }
  }
}

Test every on-device migration against exported schemas and real anonymized database snapshots using Room's MigrationTestHelper. Keep migrations small enough to finish inside Android and iOS background windows; if a backfill is large, make it resumable with a progress table rather than doing it inside the schema migration transaction.

Sync Protocols and Backwards-Compatible Payloads

Mobile sync payloads need tolerant readers. Include a schemaVersion and cursor in every envelope, ignore unknown fields, and let the server upconvert old records. For offline writes, store an idempotency key and the client schema version in the outbox. If the server cannot understand an old client, return a structured 426 Upgrade Required response with a minimum version; do not fail with an opaque 500.

ts
type SyncEnvelope = {
  schemaVersion: number;
  cursor: string | null;
  records: Array<Record<string, unknown>>;
  tombstones: string[];
};

function assertSupported(schemaVersion: number): void {
  const min = 3;
  const max = 6;
  if (!Number.isInteger(schemaVersion) || schemaVersion < min || schemaVersion > max) {
    throw new Error(`Unsupported schema version: ${schemaVersion}`);
  }
}

Dual writes belong in a single database transaction or an outbox table. Do not write the old and new stores from two independent network calls in the mobile client; a crash between calls creates permanent divergence.

Rollout, Rollback, and Operational Gates

Ship backend expand migrations before the app release that depends on them. Use remote config to enable new read paths gradually: internal users, 1%, 10%, 50%, 100%. Contract only after the app-version telemetry shows unsupported clients below your agreed threshold.

Monitor migration duration, lock wait time, replication lag, error rate, sync conflict rate, and mobile migration crash-free sessions. For MySQL, use gh-ost or pt-online-schema-change for large tables and throttle by replication lag. For PostgreSQL, use lock_timeout, concurrent indexes, and batched backfills with checkpoints. Keep a rollback plan that does not require reversing DDL: disable the feature flag, restore the old read path, and leave additive columns in place.

Production Checklist

  • Backend supports at least two prior mobile schema versions.
  • Every DDL is additive, idempotent, and reviewed for lock behavior.
  • Backfills are batched, checkpointed, observable, and rate-limited.
  • Dual writes are transactional or outbox-backed.
  • On-device migrations are tested against real snapshots and run in bounded time.
  • Migration runner uses a distributed lock and immutable checksums.
  • Contract phase is gated by adoption and error telemetry, not calendar dates.
  • Rollback is a flag flip plus compatibility, not a destructive down migration.

Sources & Technical References

4 views•0 comments

Discussion (0)

Join the conversation

Loading comments...

Continue Reading

More production-grade engineering deep dives and architectural guides

Explore all articles
Zero-Downtime DB Migrations for Mobile at Scale | Prasanga Pokharel