skip to content

On-Device Migrations

An installed app may skip several releases, so the on-device schema migrates step by step, is tested from every shipped version, and has no way back. Interviewers ask what happens when one fails.

on this pageshow

explore

questions

5

In a health-diary app's on-device database, how does a user who jumps from a three-year-old build reach the current schema safely?

level: middleimportance: must knowfreq 44%

answer

  1. the file knows its own version
  2. compare at open, before any query
  3. one frozen step per schema change
  4. commit the step with its bump
  5. test from every shipped version

basics

~20 s

The database stores its own schema version. At open the app compares it with the build's version and runs each single-step migration in order, 3 to 4, 4 to 5 and on, each committed with its version bump.

solid answer

~50 s

The database file carries a `schema version`, written when it was created and bumped by every migration. At open, before any screen queries it, the app reads that number and applies the steps from there up, one per schema change: 3→4, 4→5, up to 8→9. Each release that changes the schema adds exactly one step, written against the shape of that moment, and never edits a shipped step; steps use their own literal statements, not the current app's models, because those already expect the newest shape. One `from anything` rewrite would have to understand every historical shape at once and grows harder each release; small frozen steps compose. Each step runs in a transaction with its version bump. Tests start from every schema version ever shipped, with real-shaped data, and check that the upgraded file matches one created fresh.

code

pseudocode · 21 lines
pseudocode
current = 9
steps = { 1: step_1_to_2, 2: step_2_to_3, 3: step_3_to_4, 4: step_4_to_5,
          5: step_5_to_6, 6: step_6_to_7, 7: step_7_to_8, 8: step_8_to_9 }

function open_store(db):
  v = db.read_schema_version()          // 0 for a brand-new file
  if v == 0:
    create_current_schema(db)
    db.set_schema_version(current)
    return opened
  if v > current:
    return refuse_newer_schema(v)       // no step leads downward
  while v < current:
    if steps[v] is missing:
      return fail_no_path(v)            // never delete device-only data
    begin transaction
      steps[v](db)
      db.set_schema_version(v + 1)
    commit                              // a kill here leaves v or v + 1
    v = v + 1
  return opened

go deeper

for a junior

Recall the two pieces: a schema version stored in the database and checked at open, and a migration step per schema change run in order.

for a middle

Explain why single frozen steps beat one rewrite from any version, why each step commits with its version bump, and why steps avoid the app's current models.

for a senior

Show the testing discipline: fixtures for every shipped version with real-shaped data, upgraded through the full chain and compared with a freshly created database.

for a principal

Weigh how long the chain is kept, when old steps may be squashed, and who owns the fixture library as the app's schema history grows across teams.

## The problem: users skip releases A mobile app cannot assume users install every release. People who use a health diary to log a daily symptom and a pill may update once every few years, so on the day a three-year-old build is replaced, the new code opens a database written under **schema version 3** while it expects **version 9**. Nothing on the server can help: until the user opts into backup, the diary entries exist only on this phone. Two pieces solve it: a **stored schema version** and a **chain of single-step migrations**. ## The stored version The database file records which schema it holds, either in a header field the embedded database provides or in a one-row metadata table. The number is written when the file is created and changed only by a migration. At open, before any screen runs a query, the app reads it and decides: - **equal to the build's version**: open normally; - **lower**: run the migration chain from that number; - **zero or absent** on a brand-new install: create the current schema directly; - **higher**: a newer build has already touched this file, which is a separate problem, since no step leads downward. ## A chain of single steps Every release that changes the schema ships exactly **one step**, from N to N+1. Upgrading from 3 to 9 runs six steps in order: 3→4, 4→5, 5→6, 6→7, 7→8, 8→9. | Approach | What each release writes | What goes wrong | |---|---|---| | One step per schema change | a small step from the previous shape | little: steps are frozen and composed | | One `from anything` rewrite | code that understands every historical shape | grows every release, tested mostly from recent versions | | Diff the current schema against the file | nothing by hand | cannot express data changes such as splitting a field | Why steps win: 1. **Each step is written once**, against a shape the author can see, and is never edited after it ships. Editing a shipped step changes what some devices already ran. 2. **Steps compose**: any shipped version reaches the current one by running the tail of the chain. 3. **Steps are self-contained.** They use literal statements, not the current app's models or shared query constants, because the current models describe version 9 and would be wrong while the file is at version 5. One platform's migration guide makes the same point about using full queries instead of constants. Each step and its version bump commit **in one transaction**, so a crash between steps leaves the file at a clean version from which the chain resumes. ## Testing the chain A step that works from version 8 can still fail from version 3, because the data a version-3 user carries was written by older bugs and older rules. So: - keep a **fixture database for every schema version ever shipped**, filled with real-shaped data: years of rows, nulls, very long notes, values an old bug wrote; - in CI, upgrade each fixture to the current version through the full chain; - compare the upgraded schema with a database **freshly created** by the current build; they must match, or the migrated users and new users are running different apps; - check that the rows survived with their meaning, not only that the tables exist. The test-design craft of upgrade suites is its own subject; the design point is that the chain is only as good as its oldest tested starting point. ## Why the open path stays simple The open path is boring on purpose: read the version, refuse a newer file, run the missing steps in order, each committed with its bump. All the risk lives inside individual steps, where it can be tested from every version that ever existed. The same discipline applies to stores that are not relational. A persisted key-value blob or a JSON settings file carries its own `version` field, and the app runs one small transformation per version on the decoded value before anything reads it. Without transactions, the safe write is a new file that replaces the old one only once it is complete, so a kill mid-write leaves the old version intact. What interviewers listen for is the word *every*: every shipped version has a path, every step is frozen, and every starting point is tested.

  • Can the chain ever be shortened?
    Yes, by replacing a run of old steps with one combined step that is tested from every version it covers. What you cannot do for device-only data is drop a starting version that installed apps may still hold; a user on version 2 needs some path, or their history is gone.
  • A developer fixes a bug in the shipped 5-to-6 step. What should they do instead?
    Leave 5-to-6 as shipped and add a new step that repairs the data it got wrong. Devices that already ran the old step would never run the edited one, so editing it leaves two populations with different data under the same version number.
  • Why read the version before any screen queries the database?
    Screens and their queries are written for the current schema. If one runs against a version-3 file it reads missing columns or misreads moved data, so the migration must finish, or the app must decide not to open, before any reader touches the file.

  • Users always install each release, so one step from the previous version is enough.
  • A shipped migration step can be edited later to fix a bug in it.
  • Steps should use the app's current data models to read old rows.
  • Testing the newest step from the previous version proves the whole chain works.
  • Comparing the current schema with the file can generate every migration needed.
open as a page

In a health-diary app whose entries exist only on the phone, what should happen when an on-device schema migration fails or finds no path?

level: seniorimportance: must knowfreq 38%

basics

~20 s

The failed step's transaction rolls back, leaving the file at its last good version. The app never wipes device-only entries: it stops the crash loop, explains, offers an export and waits for a fix. Only restorable data may be rebuilt destructively.

open as a page

In a health-diary app, when an update changes the local data's shape, which on-device data must be migrated and which may simply be dropped?

level: juniorimportance: should knowfreq 35%

basics

~20 s

Data that exists only on the phone (diary entries, unsent edits, the user's settings) must be migrated. Copies the server or the app bundle can rebuild, like a downloaded reference list, may be dropped and refetched.

open as a page

In a health-diary app, an on-device migration must split a free-text dose field across three years of entries, taking 40 seconds on old phones; how do you run it?

level: seniorimportance: should knowfreq 31%

basics

~20 s

Split it: a fast schema step adds the new columns at open, then a resumable backfill converts rows in transactional batches with a committed progress marker while readers handle both shapes. Block with progress only if old rows cannot be shown.

open as a page

In a health-diary app, what should an older build do when it opens an on-device database already migrated by a newer build, as after a rolled-back release?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

It must not migrate down or delete anything. Seeing a stored version above the highest it knows, it leaves the file untouched and asks for the current build, unless the newer build marked the file safe for older code.

open as a page