Why synchronize: true Corrupts Your Production Schema
A deploy went out on a Friday afternoon. Nobody wrote a migration — the team never had — and within seconds of the new pods coming up, support tickets started: profile pages rendering half-empty, a fullName field returning null for every user in the database. There was no failed query in the logs, no exception, no alert from the migration step, because there was no migration step. What actually happened is buried in the application’s own startup output: TypeORM booted with synchronize: true, diffed the freshly renamed fullName entity property against the live full_name column, decided they were two different columns, and ran ALTER TABLE "user" DROP COLUMN "full_name" followed by ADD "fullName" — destroying every value in the process. This page is for the engineer staring at that startup log trying to understand how a schema mutated itself with no migration and no warning. The mechanism is synchronize, the fix is to turn it off, and the durable answer is the reviewed migration history the parent TypeORM Migration Workflows guide establishes.
Symptom / Error Signatures
synchronize almost never raises an error — that is precisely what makes it dangerous. The tell is in the DDL TypeORM emits at boot when query logging is on, not in an exception stack. The clearest signature is destructive DDL appearing in your application’s own startup logs, unattached to any migration command:
# TypeORM startup log (logging: true) — DDL emitted at application boot, NOT by a migration.
query: ALTER TABLE "user" DROP COLUMN "full_name"
query: ALTER TABLE "user" ADD "fullName" character varying
query: ALTER TABLE "order" ALTER COLUMN "total" TYPE numeric
query: DROP INDEX "idx_order_customer"
When a running instance is on the old code and a newly-deployed instance with synchronize: true reshapes the schema underneath it, the old instance starts throwing the inverse — a column it expects has vanished:
QueryFailedError: column "full_name" does not exist
QueryFailedError: column User.fullName does not exist
On a cold boot against an empty database synchronize looks harmless because it only issues CREATE TABLE; the corruption surfaces the first time an entity diverges from the live catalog. Any of these confirm you are on the right page:
- A
DROP COLUMN,ALTER COLUMN ... TYPE, orDROP INDEXin the logs whose timestamp matches a pod start, not a deploy migration step. - Data present before a deploy and
null(or the column gone) immediately after, with no migration in version control that would explain it. column ... does not existerrors from instances still running the previous image during a rolling deploy.
Root Cause Analysis
TypeORM’s SchemaBuilder runs whenever a DataSource initializes with synchronize: true. It introspects the live database catalog, derives the schema your @Entity classes describe, computes the difference, and immediately executes whatever DDL it believes will make the database match the entities — no SQL file, no review, no ledger row, no transaction you approved. It is the same diff engine that powers migration:generate, but with the output piped straight into the database instead of into a file a human reads first. That single difference — draft-for-review versus execute-on-boot — is the whole story, because the diff cannot infer intent. A renamed property is indistinguishable from a dropped column plus a new one, so synchronize renders every rename as DROP + ADD, exactly the destructive inference the Idempotent Script Design guide warns generated SQL is prone to.
The blast radius depends on the engine, and this is where the two databases diverge sharply. On PostgreSQL each synchronize run wraps its DDL in a transaction, so a failed reconciliation rolls back — but a successful DROP COLUMN still commits and the data is gone; transactional DDL protects consistency, not your columns. On MySQL 8.0 there is no transactional DDL at all: each ALTER TABLE implicitly commits, so a synchronize pass that dies halfway leaves the schema partially mutated with no way to roll back, a hazard the Transactional vs Non-Transactional Databases guide treats in depth. The two approaches to reconciling entities and schema diverge on every axis that matters in production:
| Property | synchronize: true |
Generated migrations |
|---|---|---|
| When DDL runs | Every application boot, automatically | Explicit migration:run deploy step |
| Human review | None — SQL is never seen | Migration file read and committed first |
| Rename handling | DROP COLUMN + ADD COLUMN (data loss) |
Author corrects to in-place rename |
| History / audit | None | migrations ledger row per change |
| Rollback | Impossible — no reverse recorded | Authored down() / re-deploy previous image |
| Multi-instance rollout | Racing instances reshape live schema | Schema changed once, before app rolls |
The multi-instance row is the quiet killer. During a rolling deploy several pods boot near-simultaneously; each independently runs synchronize against the same database, so the schema is being rewritten while old-image instances are still serving queries against the shape it used to have — the source of the column does not exist errors above. The correct contract is the additive, deploy-before-code sequence the Expand and Contract Methodology defines, which synchronize violates by design.
Immediate Mitigation
If you have just discovered synchronize: true live in a shared environment, the priority order is: stop it firing again, assess damage, and only then baseline into migrations. Do not restart the service until step 1 is deployed — every boot risks another reconciliation.
1. Set synchronize and migrationsRun to false in every non-local DataSource. This is the one change that stops boot-time DDL. Deploy it before any further restart.
// data-source.ts · TypeScript · loaded by both the app and the CLI · deploy this BEFORE restarting.
// synchronize:false stops boot-time DDL; migrationsRun:false stops migrations firing at boot too.
import { DataSource } from "typeorm";
export const AppDataSource = new DataSource({
type: "postgres", // or "mysql"
url: process.env.DATABASE_URL,
synchronize: false, // NEVER true outside a throwaway local database
migrationsRun: false, // apply migrations as an explicit step, never at boot
migrationsTableName: "migrations",
entities: ["dist/entity/*.js"],
migrations: ["dist/migration/*.js"],
});
Verify before proceeding: grep the built config and assert no synchronize: true survives in any environment file, including test and staging — a single true anywhere reintroduces the risk.
2. Assess what was already dropped. Before touching anything else, capture the current live schema so you know the real starting point, using a read-only role.
-- PostgreSQL · read-only role · safe any time · lists the live columns so you can spot what synchronize removed.
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'user'
ORDER BY ordinal_position;
Verify before proceeding: compare the column list against your last known-good schema or a backup. If synchronize dropped a column with live data, restoring that data is a point-in-time recovery task, not a migration — do that first, outside this workflow.
3. Baseline the existing schema as the first migration. Generate a migration against the current database and mark it applied without running it, so the migration history starts from reality rather than trying to recreate it.
# bash · run against a scratch clone of production · migration DB role · writes a file, applies nothing yet.
# Generate the full current schema as one baseline migration, then edit its up() to be idempotent.
npm run build
npx typeorm migration:generate ./src/migration/Baseline -d ./dist/data-source.js
Verify before proceeding: open the generated Baseline file and confirm its up() describes the schema you already have. Wrap each CREATE TABLE with IF NOT EXISTS so it is safe to record against the live database.
4. Record the baseline as applied without executing it. Insert the ledger row directly so migration:run treats the existing schema as already migrated and never tries to recreate it.
-- PostgreSQL · migration role · run once against production · marks the baseline applied without running its DDL.
-- The timestamp MUST match the Baseline class name's numeric prefix exactly.
INSERT INTO migrations ("timestamp", name)
VALUES (1721800000000, 'Baseline1721800000000');
Verify before proceeding: run npx typeorm migration:show and confirm Baseline shows as [X] applied and nothing is unexpectedly pending. From here every schema change is an explicit, reviewed migration.
Permanent Fix / Long-Term Pattern
The durable fix is not merely synchronize: false — it is making boot-time DDL structurally impossible and replacing it with the reviewed migration workflow the parent TypeORM Migration Workflows guide lays out end to end: edit entities, run migration:generate against a scratch database, read every queryRunner.query(...) call, and apply the committed class with migration:run as a discrete deploy step before the new image rolls. Two hardening habits keep synchronize from ever creeping back. First, fail the build if the string reappears — a one-line CI grep is cheaper than a restored backup. Second, keep the migration role and the runtime role separate so the application connection has no DDL rights at all; even if synchronize: true were reintroduced, the runtime role’s ALTER would be denied rather than silently succeeding.
# bash · CI gate · runs on every push · fails the build if synchronize:true reaches a shared environment.
if grep -rn "synchronize:\s*true" src/ | grep -v "// local-only"; then
echo "BLOCKED: synchronize:true found outside a throwaway local config"; exit 1
fi
Reviewing the SQL a generated migration emits is its own discipline — a rename still arrives as DROP + ADD in the generated file, so the safety comes from a human catching it, covered in generating safe TypeORM migrations from entities. And because a migration history spans branches, the ordering trap that surfaces after a merge is handled in resolving TypeORM out-of-order migration errors. For a destructive change — the very thing synchronize did blindly — the additive path is to ship the expand step first and defer the drop until after the backfill and new code are live, following Backfill Optimization and the broader Expand and Contract Methodology.
Verification Checklist
Up one level: TypeORM Migration Workflows.
Related
- Generating Safe TypeORM Migrations from Entities
- Resolving TypeORM Out-of-Order Migration Errors
- Prisma Migration Strategies — the sibling framework runbook.
Frequently Asked Questions
Does synchronize: true delete data, or just change the schema?
It changes the schema, and changing the schema is what deletes the data. TypeORM cannot tell a renamed property from a removed-plus-added one, so it reconciles a rename by issuing DROP COLUMN "old" followed by ADD COLUMN "new" — and the DROP discards every value the old column held. A type change that requires a rewrite, or a removed entity property, is equally destructive. There is no confirmation prompt and usually no error; the loss only shows up as null data or a missing column after a boot. Treat any shared database running synchronize: true as one deploy away from data loss.
Is it safe to just flip synchronize to false on a database it has been managing?
Flipping it off is safe and urgent, but it leaves you with a database that has no migration history, so the next migration:run may try to recreate objects that already exist. The correct move is to baseline: generate a single migration describing the current schema, make its up() idempotent with IF NOT EXISTS, and record its row directly in the migrations ledger so TypeORM treats the existing schema as already applied. From that point every change is an explicit, reviewed migration. Do this against a scratch clone first, then apply the ledger insert to production.
How do I stop a teammate from re-enabling synchronize later?
Make it structurally impossible rather than a matter of discipline. Add a CI gate that greps for synchronize:\s*true outside an explicitly-marked local config and fails the build, so the string can never reach a shared branch. Then enforce it at the database: give the application runtime a least-privilege role with no DDL rights, so even a reintroduced synchronize: true would have its ALTER and DROP denied instead of silently succeeding. The two layers together mean the mistake is caught at commit time and blocked at run time.