The Recommended Trade‑off
To achieve zero‑downtime deployments and reliable rollbacks, disable synchronize: true and adopt explicit migration scripts that run as part of your deployment pipeline, rather than automatically on application startup.
Why Synchronization Fails Production Constraints
The synchronize flag is a development convenience, not a deployment strategy. It attempts to align the database schema with your TypeScript entities automatically, which introduces two critical risks for production environments:
- Destructive Changes: TypeORM may drop columns or tables to match a changed entity definition, leading to data loss.
- Lack of Versioning: Without a migration history, there is no programmatic way to undo a specific change without restoring a full backup.
Implementing a Safe Migration Workflow
Shift the operational overhead to the CI/CD pipeline with these steps:
- Generate: Use the TypeORM CLI to create a migration file based on entity changes:
typeorm migration:generate -n MigrationName
- Review: Inspect the generated
up and down methods to ensure no destructive actions (e.g., DROP COLUMN) occur without a data migration strategy.
- Deploy: Execute migrations before the new application code is rolled out, ensuring the schema is ready for the new version.
- Rollback: If the deployment fails, run
typeorm migration:revert to trigger the down method of the last applied migration.
Execution Timing: Pipeline vs. Startup
Running migrations automatically in main.ts or onModuleInit can cause race conditions when multiple instances start simultaneously, potentially locking tables or causing crashes.
Verification and Assumptions
This recommendation assumes a relational database (e.g., PostgreSQL or MySQL) and a standard TypeORM configuration. Verify your current state by checking the TypeOrmModule options:
{
synchronize: false, // Must be false for production
migrationsRun: false, // Handle this in the pipeline, not the app
migrations: [__dirname + '/migrations/*.ts'],
}
Missing Diagnostic: Are you using a Blue/Green or Canary deployment strategy? If so, migrations must be strictly additive (non‑breaking) because two different application versions will share the same database during the transition.