Resolving TypeORM Out-of-Order Migration Errors

A long-lived feature branch merged into main last week, and the deploy that shipped it ran green. Today an unrelated deploy runs typeorm migration:run and stops on QueryFailedError: column "status_flag" of relation "users" already exists — for a column your migration definitely added days ago, on a database that definitely already has it. Nothing is corrupted, and neither migration is individually wrong. The problem is order: TypeORM sorts pending migrations by the numeric timestamp baked into each class name, not by the order you merged or authored them. A migration written weeks ago on a slow branch carries an older timestamp than migrations that were authored, merged, and applied to production in the meantime — so when it finally lands, TypeORM slots it in behind changes that are already live and replays it against a schema that has moved on. This page is the fix: recognise the error, read the migrations ledger to prove the history ran out of order, apply a right-now reconciliation, and adopt the merge-time habit that keeps two branches from ever diverging into a broken sequence again.

The failure is deploy-blocking but recoverable, and it does not touch your data on PostgreSQL because the whole batch rolls back inside a transaction. It is the TypeORM cousin of the fork that produces Alembic multiple heads after a branch merge, and it sits squarely inside the linear, reviewable-history discipline the parent TypeORM Migration Workflows guide is built on.

Symptom / Error Signatures

The primary signature comes from migration:run and names an object that already exists — because a stale, low-timestamp migration is being replayed on top of a schema a newer migration already changed:

QueryFailedError: column "status_flag" of relation "users" already exists
    at PostgresQueryRunner.query (.../driver/postgres/PostgresQueryRunner.js)
    query: ALTER TABLE "users" ADD "status_flag" character varying
    migration: AddUserStatus1721000000000

The inverse also happens: a late-arriving migration assumes an object a newer migration has already renamed or dropped, and the driver reports it missing instead:

QueryFailedError: column "legacy_state" does not exist
    query: ALTER TABLE "users" ALTER COLUMN "legacy_state" SET NOT NULL
    migration: BackfillLegacyState1720990000000

On MySQL 8.0 the same root cause surfaces with the engine’s own error number rather than a Postgres string:

QueryFailedError: ER_DUP_FIELDNAME: Duplicate column name 'status_flag'
    (errno: 1060, sqlState: 42S21)
    migration: AddUserStatus1721000000000

The confirming tell is not the error text but the ledger. Run typeorm migration:show and watch for a migration marked pending whose timestamp is lower than migrations already marked applied — TypeORM is about to run history backwards:

[X] AddOrderDiscount1721500000000
[X] AddUserEmailIndex1721300000000
[ ] AddUserStatus1721000000000

An applied [X] with a newer timestamp sitting above a pending [ ] with an older one is the unambiguous signature that a migration was authored on a branch that started before the applied work and is now landing late. Any of these confirms you are on the right page: the sequence diverged, and the fix is a reconciliation of order, not an edit to the failing SQL alone.

Root Cause Analysis

TypeORM encodes order in a single integer. Every migration class is named <Name><timestamp> — the trailing millisecond epoch stamped in by migration:generate or migration:create at authoring time. When migration:run executes, it loads every compiled migration, reads the timestamp from each, subtracts the set already recorded in the migrations ledger table, sorts the remainder ascending by timestamp, and applies them in that order. There is no parent pointer and no linear chain the way Flyway’s schema history enforces a strict version sequence; TypeORM trusts that a larger timestamp always means “authored later,” and that assumption breaks the moment two branches overlap in time.

Picture engineer A branching on June 1 and generating AddUserStatus1721000000000. Her branch lives for three weeks. Meanwhile engineer B branches on June 15, generates AddUserEmailIndex1721300000000, merges, and ships — that migration is now [X] applied in production with a higher timestamp than A’s unmerged work. When A finally merges, TypeORM sees her migration is unrecorded, sorts it by its June 1 timestamp, and — because that timestamp is lower than B’s already-applied one — the ledger now contains a newer applied migration than a still-pending one. TypeORM does not detect this as an error the way it would a checksum mismatch; it simply runs A’s migration next, against a schema B already advanced. If A’s up() adds a column B’s migration also touched, you get already exists; if A’s up() assumes a column a third migration later dropped, you get does not exist. The divergence is semantic, in the timeline, and Git never saw it because the two branches added different files with no text to collide.

There are two legitimate ways out, and they differ in what history they leave behind. Idempotent reconciliation rewrites the failing migration’s SQL to tolerate the state the schema is actually in — ADD COLUMN IF NOT EXISTS, guarded index creation — so replaying it in its awkward slot is a safe no-op, and the recorded order stays as-is. Re-timestamping instead renames the late migration’s class to carry a timestamp higher than every applied migration, so TypeORM sees it as genuinely newest and runs it last, restoring a linear authored-order sequence. The table is the decision surface:

Approach What it does History left behind When it is safe Cost
Idempotent reconciliation Adds IF NOT EXISTS / existence guards so the stale migration is a no-op where already applied Ledger keeps the out-of-order slot; SQL survives re-runs Always — including when the migration already ran on some databases Migration order stays non-linear forever
Re-timestamp the class Renames the class to a timestamp above every applied one so it sorts last Straight, linear authored order Only if the migration has not been recorded in any database’s ledger yet Rewrites identity; breaks the ledger on any DB that already ran the old name

The rule that follows is the same one that governs a divergent git branching strategy for schema version control: if the migration has already been recorded in any shared ledger — staging, a preview environment, a teammate’s database — you must reconcile idempotently, because renaming a class that a migrations row already references makes TypeORM treat the renamed file as a brand-new migration and try to run it a second time. Re-timestamping is safe only for a migration that has never left your workstation. Idempotent guards are the safe default; the same reasoning underpins the broader idempotent script design discipline.

Why a late merge sorts behind an applied migration Branch A forks June 1 with timestamp 1721000000000 but merges late; branch B forks June 15 with timestamp 1721300000000 and ships to production first. TypeORM sorts pending migrations by timestamp, placing A's older stamp behind B's applied one, colliding on the same column. main Jun 1 Jun 15 Jun 22 branch A AddUserStatus …1721000000000 low stamp · merges LATE branch B AddUserEmailIndex …1721300000000 merges FIRST TypeORM sorts pending by timestamp ascending [X] AddUserEmailIndex 1721300000000 — applied to prod [ ] AddUserStatus 1721000000000 — runs BEHIND, collides
Branch A carries an older timestamp but lands after branch B is already applied — so TypeORM slots A behind live work and replays it against a schema that moved on.

Immediate Mitigation

The following restores a working migration:run without losing data. Run it against a checkout that has every branch’s compiled migration present under dist/migration/, using the migration database role, as a discrete deploy step before the application fleet rolls.

1. Read the ledger to prove the order actually diverged. Never patch blind — confirm a lower-timestamp migration is pending behind a higher-timestamp applied one.

# bash · any environment · read-only · [X] marks applied, [ ] marks pending in timestamp order.
npx typeorm migration:show -d ./dist/data-source.js

Verify before proceeding: a pending [ ] migration prints with a timestamp numerically lower than one already marked [X]. Note the offending class name and its full timestamp.

2. Inspect the ledger table directly to see the recorded order. The migrations table records the timestamp and name of every applied class; the newest row should be your most recently authored change, and if it is not, history ran out of order.

-- PostgreSQL · read-only · safe any time against production.
SELECT id, "timestamp", name
FROM migrations
ORDER BY "timestamp" DESC
LIMIT 10;

Verify before proceeding: the largest timestamp belongs to genuinely recent work. A gap where the pending migration’s timestamp would fall below existing rows confirms the divergence.

3. Make the failing migration idempotent so replaying it is a safe no-op. Edit the late migration’s up() (and its down()) to guard every statement against the state the schema is already in. This is the always-safe path because it never assumes the object is absent.

-- PostgreSQL · migration role · additive and guarded · safe to replay against an already-changed schema.
-- Reconciles the out-of-order slot without rewriting the ledger. Run inside the normal batch transaction.
ALTER TABLE users ADD COLUMN IF NOT EXISTS status_flag VARCHAR(32);
CREATE INDEX IF NOT EXISTS idx_users_status ON users (status_flag);
-- MySQL 8.0 · migration role · MySQL lacks ADD COLUMN IF NOT EXISTS, so guard in application/procedure logic.
-- Check information_schema first; each ALTER implicitly commits, so run this at a low-write window.
SELECT COUNT(*) INTO @exists FROM information_schema.columns
  WHERE table_name = 'users' AND column_name = 'status_flag';
-- Only issue the ALTER when @exists = 0 (drive this from the migration's queryRunner in TypeScript).

Verify before proceeding: re-running the migration against a database that already has the change now succeeds without error. Guard the down() the same way so a reversal cannot fail on an absent object.

4. If the migration has never been applied anywhere, re-timestamp it instead. Only when migration:show proves the class is [ ] pending on every environment, rename it to sort after all applied work, restoring a linear order.

# bash · workstation only · NEVER on a migration already recorded in any shared ledger.
# Rename the class + file so its timestamp exceeds every applied migration, then rebuild.
git mv src/migration/1721000000000-AddUserStatus.ts \
       src/migration/1721600000000-AddUserStatus.ts
# Update the class name suffix inside the file to match: AddUserStatus1721600000000
npm run build

Verify before proceeding: migration:show now lists the renamed class last, with the highest timestamp and still pending, and no ledger row references the old name.

5. Apply the reconciled history forward-only. Run migration:run as the migration role ahead of the rollout; already-recorded migrations are skipped and only the reconciled class runs.

# bash · production deploy step · migration role · runs BEFORE the new app image · applied migrations are skipped.
npx typeorm migration:run -d ./dist/data-source.js

Verify before proceeding: the command exits 0, prints one has been executed successfully line for the reconciled migration, and the schema now matches the entities.

The five-step out-of-order reconciliation flow Step 1 migration:show spots the low-timestamp pending row. Step 2 SELECT on the migrations ledger confirms the divergence. The path forks: idempotent guard when the migration already ran somewhere, or re-timestamp when it has never been applied. Both rejoin at step 5, migration:run. 1 migration:show spot low-stamp [ ] 2 SELECT ledger confirm the gap applied anywhere? 3 Idempotent guard ADD COLUMN IF NOT EXISTS safe: replay is a no-op YES — recorded on a shared DB 4 Re-timestamp rename above newest safe: never applied yet NO — workstation only 5 migration:run forward-only apply
Prove the divergence first, then fork on one question — has the migration touched a shared ledger? Yes means guard it idempotently; no means re-timestamp. Both roads rejoin at a forward-only migration:run.

Permanent Fix / Long-Term Pattern

Reconciliation is the cure; the prevention is stopping two branches from ever producing a timestamp that lies about authoring order. Because Git cannot see a semantic conflict between two migration files with different names, the guard must live above Git — in a merge-time habit and a CI gate, exactly as the parent TypeORM Migration Workflows guide prescribes for keeping a linear, reviewable history.

The habit is to treat the migration timeline like a fast-moving shared resource. Before merging a feature branch, pull the latest main, and if a newer migration landed there since you branched, regenerate — or re-timestamp — your migration while it is still unapplied anywhere so its timestamp sits above the current newest. This keeps the ledger’s recorded order identical to the authored order and removes the ambiguity at the source. When two branches genuinely developed in parallel and both are already applied on shared environments, skip the rename and reconcile idempotently instead; the deciding factor, as always, is whether the migration has already been recorded in a migrations ledger.

The gate makes the invariant non-negotiable. A CI step that applies the branch’s migrations against a scratch database built from main, then asserts the ledger’s newest timestamp is the branch’s own migration, fails the pull request the moment a stale timestamp would slot in behind applied work:

# bash · CI step on every pull request · runs against a THROWAWAY database seeded from main.
# Fails the build if the branch migration's timestamp is not the newest, catching the divergence pre-merge.
npx typeorm migration:run -d ./dist/data-source.js
NEWEST=$(psql "$SCRATCH_URL" -tAc 'SELECT name FROM migrations ORDER BY "timestamp" DESC LIMIT 1')
case "$NEWEST" in
  *"$BRANCH_MIGRATION"*) echo "ok: branch migration sorts last" ;;
  *) echo "OUT OF ORDER: $BRANCH_MIGRATION would run behind $NEWEST"; exit 1 ;;
esac

Pair this with the additive, forward-only sequencing of the expand and contract methodology: when every migration is additive and backward-compatible, an out-of-order apply degrades from a hard QueryFailedError to a harmless replay, because an additive step guarded with IF NOT EXISTS is safe in any order. The transactional guarantees that make a failed out-of-order run recoverable in the first place — a clean rollback on PostgreSQL versus a half-applied ALTER TABLE on MySQL — are the subject of the transactional vs non-transactional databases guide.

Prevention: re-timestamp habit versus the CI gate that catches divergence Top lane: re-timestamp the branch migration before merge so the ledger's recorded order stays a straight line matching authored order, reaching deploy cleanly. Bottom lane: parallel branches merge and produce a low-timestamp migration that the CI ledger-order gate fails before it reaches deploy. Re-timestamp before merge …100 …300 …600 branch DEPLOY order intact Parallel branches merged …300 applied …100 stale sorts behind applied CI ledger gate: FAIL blocked
Re-timestamping before merge keeps recorded order a straight line to deploy. When branches truly ran in parallel, the CI ledger-order gate fails the stale, low-timestamp migration before it ever reaches production.

Verification Checklist

Up one level: TypeORM Migration Workflows.

Frequently Asked Questions

Why does TypeORM run an older migration after a newer one instead of blocking? TypeORM decides what to run purely by comparing each migration class’s timestamp against the migrations ledger and executing every unrecorded class in ascending timestamp order. It has no parent-pointer chain and does not treat “a pending migration older than an applied one” as an error the way it treats a checksum mismatch. So a migration authored on a branch that started before some now-applied work carries a lower timestamp, sorts before that applied work, and runs against a schema that has already moved past it — surfacing as already exists or does not exist rather than a clear ordering warning.

Should I re-timestamp the migration or make it idempotent? Make it idempotent unless the migration has not been recorded in any database’s ledger yet. Renaming a class to a higher timestamp rewrites its identity, and TypeORM keys the ledger on the class name — so on any database that already ran the old name, the renamed file looks brand-new and TypeORM tries to apply it a second time. If the migration only ever ran on your workstation, re-timestamping restores a clean linear order; the instant it has touched a shared environment, guard it with ADD COLUMN IF NOT EXISTS (or an information_schema check on MySQL) so replaying it in its awkward slot is a harmless no-op.

Can this corrupt data or leave the schema half-changed? On PostgreSQL, no: with the default transaction: "all", a failed out-of-order migration:run rolls the whole batch back and writes no ledger row, so you fix the ordering and re-run against an untouched schema. On MySQL 8.0 there is no transactional DDL — each ALTER TABLE implicitly commits — so a migration that fails partway can leave one column added and the ledger row missing; confirm the real table state with SHOW CREATE TABLE and hand-reconcile before re-running, exactly as the transactional-versus-non-transactional guidance warns.