Skip to content

Database migrations behind feature flags: expand, dual write, switch reads, contract

How to run database schema migrations with feature flags: the expand/contract pattern, a flag with migration stages, backfills under live traffic, and where rollback stops being safe, with a migration we ran on PostgreSQL 17 under concurrent writes, including a stale app instance.

8 min read

Short answer: Change the schema in steps that old and new code can both live with: add the new structure, write to both, backfill, compare reads, switch reads, stop writing the old one, then drop it. A feature flag moves the application between those steps, so rolling back is a flag change, up to the moment you stop writing the old column.

What is the expand/contract pattern?

Danilo Sato's article on Martin Fowler's site calls it parallel change, "also known as expand and contract": first "augment the interface to support both the old and the new versions", then update every client to the new version, then "remove the old version". It notes that "most database refactorings follow the parallel change pattern", and that a feature flag "can be used to control which version of the interface is used" (ParallelChange).

Stripe described the same idea for moving data at scale in four steps: dual writing to the old and new tables, changing all read paths, changing all write paths, and removing old data, using GitHub's Scientist library to compare old and new reads before switching (Stripe: online migrations at scale, 2017).

Which stages should the migration flag have?

One flag with a stage per step keeps the application code in one place. LaunchDarkly's migration flags define the stages; the same names work with any flag tool that supports string flags:

Stage Writes go to Reads return Roll back by flag?
off Old Old —
dualwrite Old and new Old Yes
shadow Old and new Old, compared with new Yes
live Old and new New, compared with old Yes
rampdown Old and new New Yes: the old copy is still written
complete New only New No: the old copy goes stale
Contract (a schema change, not a stage) New only New Old structure dropped

LaunchDarkly's migrations use two, four or six of these stages (off and complete; then shadow and live; then dualwrite and rampdown). They need a server-side SDK (.NET, Go, Java, Node.js, PHP, Python, Ruby, Rust, plus edge SDKs), and the SDK's migration API runs the reads and writes for the current stage, checks whether reads match, and tracks errors and latency (migration flags, migration guide, SDK migrations). LaunchDarkly says migration flags aren't available in its federal or EU instances. With other tools, a string flag with these values and your own read comparison does the same job. rampdown exists for the window before complete: every instance reads the new copy while the old one is still written, so turning off writes to the old copy can't strand an instance that still reads it.

What does a flag-driven migration look like in practice?

We renamed users.name to users.display_name on a 200,000-row table in PostgreSQL 17.12, with the stage held in a flag and changed at runtime (an OpenFeature in-memory provider), three times on 15 November 2026. The application code is the only place that knows about both columns; this example uses five stages, with live doing the job of LaunchDarkly's rampdown and without its read comparison:

async function renameUser(id, value) {
  const s = await stage()
  if (s === 'off') return db.query('UPDATE users SET name = $1 WHERE id = $2', [value, id])
  if (s === 'complete') return db.query('UPDATE users SET display_name = $1 WHERE id = $2', [value, id])
  return db.query('UPDATE users SET name = $1, display_name = $1 WHERE id = $2', [value, id]) // dualwrite, shadow, live
}
async function createUser(id, value) {
  const s = await stage()
  if (s === 'off') return db.query('INSERT INTO users (id, name) VALUES ($1, $2)', [id, value])
  if (s === 'complete') return db.query('INSERT INTO users (id, display_name) VALUES ($1, $2)', [id, value])
  return db.query('INSERT INTO users (id, name, display_name) VALUES ($1, $2, $2)', [id, value])
}
let shadowMismatches = 0
async function readUser(id) {
  const s = await stage()
  const { rows } = await db.query('SELECT name, display_name FROM users WHERE id = $1', [id])
  const { name, display_name } = rows[0]
  if (s === 'shadow' && name !== display_name) shadowMismatches++ // compare, still return the old value
  return s === 'live' || s === 'complete' ? display_name : name
}

What happened at each stage (all three runs):

Step Result
Expand: ADD COLUMN display_name text 0.6 to 0.7 ms; table not rewritten
dualwrite, then backfill in batches of 5,000 while 4,000 renames and 200 new users were dual-written 0 rows out of sync
Then 300 renames from a second app instance still on off 300 rows out of sync
Batched repair pass once every instance dual-writes 0 rows out of sync
shadow: 2,000 reads compared while 1,000 dual-write renames ran 0 mismatches
live, then back to shadow by flag Both returned the latest value: rollback was safe
ALTER COLUMN name DROP NOT NULL, then complete with 500 renames and 50 inserts Inserts succeeded; the old column differed on 549 to 550 rows, so reading it again would serve stale data
Contract: DROP COLUMN name 1.0 ms

The migration script, its runner and the raw output of the three runs are published; it needs Docker and Node.js. The timings come from an idle database, so they show that no rewrite happened, not how long a busy production table would take to lock (see below).

Two things this example makes easy, and a real migration may not:

  • The dual write is atomic. Both columns are in the same row and written by one UPDATE, so a write can't land in one copy and fail in the other, and the shadow comparison reads both from one row. Moving data to another table or another database means two writes that can partly fail; you need retries and idempotent writes, or a transactional outbox or change-data-capture to copy changes, and separate shadow reads that can also catch replication lag.
  • The backfill must not overwrite newer values. Ours copies only rows whose new column is still empty (display_name IS NULL), so dual writes made during the backfill win. Backfills should also be resumable, batched and throttled.

Why did a stale app instance break the backfill?

Flag changes don't reach every server at the same instant. An instance still on off writes only the old column; for rows whose new column is already filled, by the backfill or by an earlier dual write, the new column keeps the old value. In our runs, the stale instance wrote after the backfill, so every one of its 300 renames left a row out of sync; during a backfill, only the rows already copied are affected.

Two safeguards:

  • Start the backfill only after every instance is dual-writing: wait longer than your flag SDK's update interval (or check from each instance) before backfilling.
  • Verify, then repair: after the backfill, count rows where the columns differ (IS DISTINCT FROM) and copy them again, in batches. Only move to shadow when that count is zero and stays zero.

The same holds at the other end. Before writes to the old column stop (complete), every instance must already read the new one, which is what rampdown (our live) is for; an instance still reading the old column after it stops being written serves stale data. Rolling back from complete has the same problem.

Which schema changes lock the table?

The expand and contract steps are where a migration can block traffic. Most ALTER TABLE forms take an ACCESS EXCLUSIVE lock, which blocks reads and writes (ALTER TABLE). Even a change that finishes in a millisecond has to wait for that lock behind any long-running transaction, and every query that arrives meanwhile queues behind it. Set a short lock_timeout (a few seconds) for migrations and retry, rather than letting one stuck ALTER stall the table; strong_migrations recommends a short lock timeout with a longer statement timeout.

Change What happened in our test / what the docs say
ADD COLUMN without a default, or with a constant default 0.6 to 0.9 ms on 200,000 rows; the table wasn't rewritten (same file node)
ADD COLUMN ... DEFAULT gen_random_uuid() (volatile default) 254 to 268 ms; the table was rewritten under the lock, which grows with table size
SET NOT NULL on an existing column Scans the whole table under the lock, unless a valid CHECK (col IS NOT NULL) constraint already proves it: add that constraint NOT VALID, VALIDATE CONSTRAINT (a weaker lock), then SET NOT NULL
Unique constraint CREATE UNIQUE INDEX CONCURRENTLY, then ADD CONSTRAINT ... UNIQUE USING INDEX
CREATE INDEX Blocks writes; CREATE INDEX CONCURRENTLY doesn't, but does more work, can't run in a transaction, and can leave an invalid index behind if it fails (CREATE INDEX)
Stopping writes to a NOT NULL column Drop its NOT NULL first (ALTER COLUMN ... DROP NOT NULL), or inserts that skip it fail
DROP COLUMN Fast, but only after no deployed code references the column: ORMs that cache column lists (Rails' Active Record, per strong_migrations) or SELECT * with prepared statements can fail until restarted
Backfilling with one big UPDATE Locks many rows and creates a long transaction; batch it, as above

Tools that check migrations help: strong_migrations for Rails flags operations that block reads or writes or are likely to cause errors (removing or renaming columns, changing types, non-concurrent indexes, volatile defaults, setting NOT NULL and others), and says it "does not detect dangerous backfills". pgroll automates expand/contract for PostgreSQL 14+ by serving old and new schema versions at once through views, with triggers keeping both columns in sync and instant rollback; it doesn't need a flag, because clients choose the schema version. For a plain rename inside one database, a view or pgroll can be simpler than application-level dual writes.

When is this worth the effort?

Expand/contract takes several deploys and some extra code: dual writes, a backfill, comparisons and cleanup. It pays off when the table is large or busy, when you can't afford downtime, or when you need a way back. For a small table with no concurrent writers, a single migration in a maintenance window can be simpler.

When the migration is done, remove the migration flag and the code for the old stages (stale feature flags), and test both code paths while they exist (testing code that uses flags). For flags in your pipeline, see feature flags in CI/CD. All tools are in the directory.