Running TypeORM Migrations Without a Transaction
A TypeORM migration builds an index on the orders table with CREATE INDEX CONCURRENTLY, exactly as the zero-downtime guides recommend, and typeorm migration:run fails at once: QueryFailedError: CREATE INDEX CONCURRENTLY cannot run inside a transaction block. By default TypeORM wraps all pending migrations in a single transaction — convenient for atomicity, fatal for the handful of PostgreSQL statements that must run on their own. TypeORM can run a specific migration outside a transaction, but only with the right combination of data-source setting and migration property, and running without a transaction changes how a failure must be handled. This guide shows the configuration, a retry-safe migration, and the checks that keep it from leaving debris. It extends TypeORM Migration Workflows.
each plus a per-migration transaction = false isolates the one migration that needs it, and keeps every other migration atomic.Symptom / Error Signatures
The failure when a non-transactional statement meets TypeORM’s default mode:
query failed: CREATE INDEX CONCURRENTLY "IDX_orders_customer_ref" ON "orders" ("customer_ref")
error: error: CREATE INDEX CONCURRENTLY cannot run inside a transaction block
Migration "AddOrdersCustomerRefIndex1758190000000" failed, error: CREATE INDEX CONCURRENTLY cannot run inside a transaction block
query: ROLLBACK
After switching to a non-transactional run, a different symptom can follow a failure: the next run fails with relation "IDX_orders_customer_ref" already exists, or the index exists but pg_index.indisvalid is false and queries ignore it.
Root Cause Analysis
TypeORM’s migrationsTransactionMode data-source option controls transactions: "all" (the default) wraps every pending migration in one transaction, "each" wraps each migration separately, and "none" uses none. In addition, a migration class can set transaction = false (TypeORM 0.3.x) to opt out of the per-migration transaction when the mode is "each". The CLI also accepts --transaction each|all|none for migration:run.
Concurrent index builds, DROP INDEX CONCURRENTLY, REINDEX CONCURRENTLY and a few other PostgreSQL statements commit internally and are rejected inside any transaction block. So they need a migration that runs with no transaction at all. The price is atomicity: if such a migration fails midway, nothing is rolled back and TypeORM does not record it in its migrations table, so the next run executes it again. A concurrent build that failed leaves an INVALID index behind, which blocks a naive rerun — the problem covered in cleaning up invalid indexes after a failed build.
| Mode | Default wrapping | Per-migration transaction = false honoured? |
|---|---|---|
all |
one transaction for all pending migrations | no — the outer transaction still exists |
each |
one transaction per migration | yes |
none |
none | not needed |
Immediate Mitigation
1. Switch the data source to per-migration transactions.
// TypeScript · src/data-source.ts · used by the migration CLI and the deploy step
// WARNING: "each" changes failure granularity from the whole run to one migration.
import { DataSource } from "typeorm";
export default new DataSource({
type: "postgres",
url: process.env.MIGRATION_URL,
entities: ["dist/entities/*.js"],
migrations: ["dist/migrations/*.js"],
migrationsTransactionMode: "each",
extra: { options: "-c lock_timeout=3000" },
});
2. Mark the index migration as non-transactional and make it retry-safe. Keep only the concurrent statement in it, and drop an invalid leftover before building.
// TypeScript · src/migrations/1758190000000-AddOrdersCustomerRefIndex.ts · PostgreSQL
// WARNING: runs without a transaction; a failure is not rolled back, so the up() must be rerunnable.
import { MigrationInterface, QueryRunner } from "typeorm";
export class AddOrdersCustomerRefIndex1758190000000 implements MigrationInterface {
transaction = false as const;
public async up(queryRunner: QueryRunner): Promise<void> {
const invalid = await queryRunner.query(
`SELECT 1 FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
WHERE c.relname = 'IDX_orders_customer_ref' AND NOT i.indisvalid`);
if (invalid.length > 0) {
await queryRunner.query(`DROP INDEX CONCURRENTLY IF EXISTS "IDX_orders_customer_ref"`);
}
await queryRunner.query(
`CREATE INDEX CONCURRENTLY IF NOT EXISTS "IDX_orders_customer_ref" ON "orders" ("customer_ref")`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP INDEX CONCURRENTLY IF EXISTS "IDX_orders_customer_ref"`);
}
}
// ROLLBACK PATH: migration:revert runs down(), dropping the index concurrently.
3. Run the migrations once from the pipeline.
# Shell · deploy job · compiled JS in dist/ · migration credentials in MIGRATION_URL
npx typeorm migration:run -d dist/data-source.js
npx typeorm migration:show -d dist/data-source.js # confirm nothing is pending
4. Verify validity after the run. A successful run with a valid index is the only acceptable outcome for an index migration.
Permanent Fix / Long-Term Pattern
Set migrationsTransactionMode: "each" as the project default and keep transaction = false for the small set of migrations that need it, each containing a single statement and written to be rerunnable. Never set migrationsRun: true to run migrations on application startup in production; run them from one pipeline step before the rollout, as described in TypeORM Migration Workflows, and never rely on synchronize — see disabling TypeORM synchronize in production.
TypeORM’s generator (migration:generate) emits plain CREATE INDEX for new @Index decorators, so treat every generated index as a draft: move it into a non-transactional migration with the concurrent form. A CI check that fails on CREATE INDEX without CONCURRENTLY in new migration files enforces the habit; a pipeline check for invalid indexes after each deploy catches the rare failure. The general mechanics of non-transactional steps across tools are collected in running concurrent index builds outside migration transactions.
Be deliberate about ordering within a run, too. In "each" mode migrations still execute in timestamp order, so a non-transactional index build sits between its neighbours and a slow build delays everything after it. When a large build is involved, many teams run it as its own deploy step — migrations before it, the build, then migrations after — so that a timeout on the build does not leave unrelated later migrations unapplied and the pipeline can report exactly which stage stalled. Record the duration of each migration from the run’s log output; the index builds will dominate, and knowing their cost on production-sized data is what lets you schedule them sensibly.
Finally, keep the entity decorators and the migrations in agreement. After moving an @Index into a hand-written concurrent migration, run migration:generate again on a clean database; it should produce no new migration. If it does, the decorator and the hand-written index differ in name, columns or options, and the next generated migration would try to “fix” the difference with a blocking drop and create.
migration:run make non-transactional migrations as safe to operate as transactional ones.Verification Checklist
Frequently Asked Questions
Why doesn’t transaction = false work with the default mode?
In "all" mode TypeORM opens one transaction around the entire run, so there is no per-migration transaction to disable. Switch the data source (or the CLI invocation) to "each" so each migration gets its own transaction, which transaction = false can then skip.
Is migrationsTransactionMode: "none" simpler?
It is simpler to configure and worse to operate: every migration then loses atomicity, so any failure can leave partial changes. Use "each" and opt out only where required.
What happens to the TypeORM migrations table if a non-transactional migration fails?
The migration is not recorded, so the next migration:run executes it again. That is why its up() must detect and handle whatever a failed attempt left behind.
Does this apply to MySQL?
Less so. MySQL DDL is never transactional, and InnoDB builds most indexes online with ALGORITHM=INPLACE, LOCK=NONE. The concern on MySQL is instead that multi-statement migrations cannot be rolled back, so keep one DDL statement per migration there too.