Skip to content
Kavindu's Blog
Go back

The Rollback That Would Have Emptied Every Tenant's Database: Migrating Many Postgres Databases on Deploy

Kavindu Manahara

The Rollback That Would Have Emptied Every Tenant's Database: Migrating Many Postgres Databases on Deploy

I was writing this post about how safely my deploy migrates every tenant database, and I wanted to quote the rollback step. The script takes a schema snapshot of each tenant before migrating it, and if any tenant fails, it restores the snapshot on all the others. It looked careful. So before quoting it, I tested it.

I made a table with 1,000 rows, took the snapshot the same way the script does, changed the schema, and ran the restore. The schema came back exactly as it was. Then I ran SELECT count(*). It returned 0.

The rollback had been sitting in a production deploy pipeline since July. It never fired, because no deploy had ever failed on one tenant while succeeding on another. If one had, every tenant that migrated successfully would have lost every row it had, and the log would have printed a green tick next to each one.

So this post changed. It’s still about running one schema change across many tenant databases on every deploy. It’s also about the two places that pipeline could quietly delete data, and what I replaced them with.

How do you migrate many tenant databases on every deploy?

You run one job before the new app version starts. It reads the list of tenants from a control-plane database and applies the schema to each tenant’s database in turn. If any tenant fails, it exits non-zero, and the deploy stops with the old version still running. In my setup that job is an ArgoCD PreSync hook.

This is the same cluster from the multi-tenant post: one CloudNativePG cluster, one Postgres database per tenant, and a control-plane database that knows where each tenant lives. In that post I said I’d picked the manual path, a button that migrates one tenant so you can check it before running the rest. That button exists, but it isn’t the whole story. Every deploy also runs a fleet-wide pass before the new version starts, and it had been doing that since June. Writing this post is how I noticed I’d only described half of my own setup.

The deploy flow looks like this:

flowchart TD
    Push([Merge to release branch]) --> Image[CI builds image, bumps tag in Git]
    Image --> Sync[ArgoCD sync starts]
    Sync --> Hook[PreSync Job: migrate control plane, then every tenant]
    Hook --> Ok{All tenants OK?}
    Ok -->|yes| Rollout[New pods roll out]
    Ok -->|no| Stop([Sync aborted, old version keeps running])

The hook itself is an ordinary Kubernetes Job with two ArgoCD annotations:

apiVersion: batch/v1
kind: Job
metadata:
  name: app-migrate
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/hook-delete-policy: HookSucceeded,BeforeHookCreation
spec:
  backoffLimit: 1
  activeDeadlineSeconds: 300

HookSucceeded deletes the Job when it passes, so you won’t find it afterwards (which confused me when I went looking for its logs while writing this). BeforeHookCreation clears out a failed one before the next sync tries again.

One gotcha is worth knowing if you use Vault. The Job gets its secrets from a Vault agent, and by default that agent runs as a sidecar that never exits. The migration finished, the sidecar kept running, the Job never completed, and activeDeadlineSeconds killed it at 300 seconds. Then it retried. The fix is one annotation, vault.hashicorp.com/agent-pre-populate-only: "true", which runs the agent as an init container that writes the secrets and leaves.

What the job actually does for each tenant

For each tenant, the script decrypts the stored connection string, deletes rows that would block the schema change, and runs prisma db push against that tenant’s database. It collects failures instead of stopping at the first one, so one broken tenant shows up next to everything else that went wrong in the same run.

Trimmed down, the loop is this:

for (const tenant of tenants) {
  const url = decryptUrl(tenant.dbConnectionUrl, encKey);

  await cleanupLegacyRows(url); // see the enum section below

  const result = spawnSync("npx", pushArgs, {
    env: { ...process.env, TENANT_DATABASE_URL: url },
    stdio: "inherit",
  });

  if (result.status === 0) {
    await controlPlane.tenant.update({
      where: { id: tenant.id },
      data: { schemaVersion: CURRENT_SCHEMA_VERSION },
    });
  } else {
    failures.push({ slug: tenant.slug, error: `exit ${result.status}` });
  }
}

if (failures.length > 0) process.exitCode = 1; // ArgoCD aborts the sync

The schemaVersion update is new as of this week. The platform dashboard compares each tenant’s stamp with the current version and marks the mismatches as outdated. Only the manual button wrote that stamp, so after every normal deploy the dashboard showed tenants as outdated even though they weren’t. That’s a small bug, but it’s the kind that teaches people to ignore a dashboard.

On the last production deploy, the two tenant stamps landed 14 seconds apart. On dev, three tenants took about 6 seconds each. I haven’t profiled where that time goes. At that rate the 300-second deadline fits roughly 40 tenants before I need to raise it or run tenants in parallel.

Why a schema-only pg_dump is not a rollback

A schema-only dump made with --clean contains a DROP TABLE and a CREATE TABLE for every table, and no data. Restoring it puts the structure back and leaves every table empty. It’s a recipe for rebuilding an empty database, not for undoing a migration on a full one.

This is the snapshot the script used to take:

pg_dump --schema-only --clean --if-exists --no-owner --no-acl -f rollback.sql "$TENANT_URL"

And this is the whole test that caught it, against a throwaway Postgres 17 container:

CREATE TABLE lead (id int PRIMARY KEY, name text);
INSERT INTO lead SELECT g, 'x' FROM generate_series(1, 1000) g;
-- snapshot taken here with the pg_dump command above
ALTER TABLE lead ADD COLUMN score int;
-- "rollback": psql -f rollback.sql
SELECT count(*) FROM lead;  -- 0

I think the original intent was “put the schema back the way it was”, and for an empty database that’s exactly what it does. The trap is that --clean makes the dump safe to replay by dropping things first, and dropping a table drops its rows. Nothing in the output warns you. psql runs it cleanly and the script printed Rolled back for each tenant.

Do you even need an automatic rollback?

For this setup, no. I deleted the rollback instead of fixing it. When a tenant fails, the hook exits 1, ArgoCD stops the sync, and the old pods keep serving. The tenants that already migrated stay on the new schema, and once you fix the failing tenant you run the same job again.

A real rollback would mean a full dump per tenant, schema and data, restored with pg_restore --clean. That brings back the data too, but it also throws away anything written between the snapshot and the restore, and it adds a full dump of every tenant to a job with a 300-second deadline. I’d rather have a deploy that stops and waits for me than one that confidently rewinds customer data.

What makes this safe is the rule in the next two sections. The new schema has to work with the old code, because for a while the old code runs on top of it. And the push must never be allowed to delete data on its own.

The flag that made every deploy allowed to delete data

prisma db push refuses any change that would lose data unless you pass --accept-data-loss, and my script passed it on every deploy. That meant a dropped column, a dropped table, or a removed enum value deleted tenant data during the deploy, and nobody had to approve it.

I checked what Prisma 7.8 does without the flag before changing anything. With one row in a column the new schema drops, the push stops like this and changes nothing:

⚠️  There might be data loss when applying the changes:

  • You are about to drop the column `score` on the `Lead` table, which still contains 1 non-null values.

Error: Use the --accept-data-loss flag to ignore the data loss warnings like prisma db push --accept-data-loss

Exit code 1, column and data untouched. That’s exactly the behaviour I want from a deploy: stop and tell a person.

Sometimes you do mean to drop data, though. So the flag is still there, behind a constant that has to match the schema version being deployed:

// schema-versions.ts
export const CURRENT_SCHEMA_VERSION = "2026.09.14-001";

// Set this to the new CURRENT_SCHEMA_VERSION, in the same change that drops
// the data, after checking the data is safe to lose.
export const DATA_LOSS_APPROVED_FOR_SCHEMA_VERSION: string | null = null;
const acceptDataLoss =
  DATA_LOSS_APPROVED_FOR_SCHEMA_VERSION === CURRENT_SCHEMA_VERSION;
const pushArgs = ["prisma", "db", "push", `--config=${configPath}`];
if (acceptDataLoss) pushArgs.push("--accept-data-loss");

Approving data loss is now a line in a pull request, which means someone reviews it. And because the approval names one version, it stops applying as soon as the version is bumped again. An environment variable would have done the same job, until someone forgot to turn it off.

Why you can’t drop a Postgres enum value that’s still in use

Postgres can’t remove a value from an enum type, so Prisma rebuilds the type without it. That rebuild fails if any row still holds the removed value. I hit this when two dashboard widget types were retired. The push failed on any tenant that still had widgets of those types.

The fix lives in the same loop, before the push: delete the rows that hold the retired values.

DELETE FROM "DashboardWidget"
WHERE "systemWidgetType"::text IN ('KPI_OPEN_LEADS', 'KPI_PIPELINE_VALUE');

The ::text cast matters more than it looks. On a tenant that was already migrated, those values no longer exist in the enum, and comparing the column against an unknown enum literal is an error. Comparing it as text just matches nothing. With the new guard, this cleanup is also the step that makes the push data-loss-free, so it doesn’t need the approval flag at all.

How do you change a schema without downtime when old code still runs?

You make every change in two releases. First you add what the new code needs while keeping what the old code needs, and you copy data across. Only in a later release, once no running code reads the old shape, do you remove it. This pattern is usually called expand and contract.

It’s not optional with a PreSync hook. The migration runs while the old pods are still serving, and if a tenant fails, the old pods keep serving on top of whatever already migrated. So every schema change has to be one the previous version of the app can live with.

Change Safe in one release? How I’d do it
Add a nullable column or a new table Yes Just ship it
Add a NOT NULL column Only with a default Add it with a default, or nullable first and tighten later
Rename a column No Add the new column, backfill, switch reads, drop the old one later with approval
Drop a column or table No Stop using it in one release, drop it in the next (needs the approval constant)
Remove an enum value No Stop writing it, clean up rows, then remove it

The backfill step is the one people skip. When opportunity names started living in a custom-field table, the app began writing to both the old title column and the new table, and reads fell back to title for rows that didn’t have the new value yet. Then a one-off script looped over every tenant, the same way the migration does, and copied the missing values across. That’s the expand half. It’s boring code, and it’s the only reason a later “drop the old column” release could ever be safe to approve.

What I’d still change

The manual migration button and new-tenant provisioning still pass --accept-data-loss. Provisioning only ever pushes to an empty database, so that one’s harmless. The button is a deliberate admin action, but it deserves the same guard, and it’s next on the list.

db push also isn’t a migration history. There are no migration files to review, just a diff between the schema and whatever is in each database right now. For a dozen tenants that has been fine, and it means a tenant that drifted gets pulled back to the schema on the next deploy. If this ever grows to hundreds of tenants, I’d want reviewed migration files and a record of which ones ran where.

The fixed pipeline went to production on the same day I found the bug. Both production tenants were migrated and stamped by the new job 14 seconds apart, and the pods came up clean. The test that caught all of this took four SQL statements and a throwaway container, which is about the cheapest insurance I’ve ever bought.


References


Share this post: