← All topics/Data persistence

Question 3

Handling migrations in production

You need to evolve your data model after shipping. How do you handle migrations safely without data loss or breaking existing users?

Follow-ups

  • Lightweight vs heavyweight migration?
  • How do you recover from a failed migration?

Answer outline

Treat schema migrations as release-critical. Version every schema, test upgrades from real historical stores, and never assume all users are on the latest schema.

Pick the migration mode by complexity. Lightweight migration handles compatible changes on its own, such as adding optional attributes or renaming a property when you supply its old name. A custom migration (heavyweight, in Core Data terms) is for structural transforms: splitting entities, merging fields, or computing derived values.

Always plan for failure. Back up the store before migrating where you can, and make each step idempotent so a retry is safe. Add telemetry so you see problems during rollout, and show a clear fallback screen if the migration can't finish on first launch.

Principles

  • Test against real old stores, because a user may be upgrading from several versions back in one update.
  • Ship incremental schema steps, one migration per release, so each one is easy to test and roll back.
  • Always have a recovery path: idempotent steps, a fallback screen, and a pre-migration backup where you can.
  • Instrument every migration, so failures show up during rollout rather than in App Store reviews.

A checklist to run before shipping a schema change:

Migration checklist
1) Add schema version N+1
2) Define the mapping and transforms
3) Test the upgrade from N-2, N-1, and N
4) Ship with telemetry and a fallback screen

Follow-up angles

  • For very large stores, migrate progressively in the background so first launch isn't blocked.
  • When a migration fails, fall back to the untouched original store or to the pre-migration backup. Then retry on the next launch, or rebuild from the server if the data is recoverable there.