Zero-downtime Postgres schema migrations: why the order of steps matters more than the tooling
When a Node.js microservice needs to change a column in production, the tempting shortcut is to handle it as a single migration: an ALTER TABLE to add the column, a script that walks the existing rows, done. On a single instance with low traffic, that can work. In a system with several replicas running different code versions mid-rollout, the same plan breaks writes partway through a deploy, and the symptom almost never points straight at the migration: it shows up as intermittent NOT NULL constraint errors, half-written rows, or a service reading null where it expected a value and falling into a code path nobody tested for that case.
The pattern that avoids this is called expand-contract, and what actually matters isn't any particular tool, it's the strict order in which the steps run. We've had the pattern well understood on paper and still broken it by swapping two steps that, read in isolation, looked interchangeable.
The underlying problem: two code versions always coexist
During a normal rollout with Kubernetes or any orchestrator doing progressive deploys, there's a window — anywhere from seconds to several minutes, depending on how many replicas the service has — where pods running the old code and pods running the new code serve traffic at the same time, against the same database. Any migration that assumes "everyone is on the new code" or "everyone is on the old code" at the moment of the ALTER TABLE is assuming something false during that window.
That rules out, from the start, any strategy where the schema change and the code change deploy as a single atomic unit. There's no such atomicity between a database migration and a pod rollout — they're two systems with their own timing, and the plan has to survive them running out of sync.
The steps of the pattern, in the order that matters
Say orders has a total_cents column as an integer, and a business change asks us to store the total as an object with currency, total_amount (jsonb like { "value": 4999, "currency": "COP" }), because the service started operating in more than one country.
Step 1 — Expand: add the new column, always nullable.
ALTER TABLE orders ADD COLUMN total_amount jsonb;
Nullable isn't a minor detail: a NOT NULL column added without a default locks the ALTER TABLE until it scans and validates the entire table, and one added with a default computed per row has the same cost on Postgres versions before 11. Adding it nullable is a catalog-only operation, effectively instant regardless of table size.
Step 2 — Backfill in the background, in batches.
async function backfillTotalAmount(db, batchSize = 1000) {
let lastId = 0;
while (true) {
const rows = await db.query(
`SELECT id, total_cents FROM orders
WHERE id > $1 AND total_amount IS NULL
ORDER BY id LIMIT $2`,
[lastId, batchSize]
);
if (rows.length === 0) break;
await db.query(
`UPDATE orders SET total_amount = jsonb_build_object(
'value', total_cents, 'currency', 'COP'
) WHERE id = ANY($1::int[])`,
[rows.map(r => r.id)]
);
lastId = rows[rows.length - 1].id;
await sleep(50);
}
}
The critical point of this step is that it runs against old code, which keeps writing only to total_cents. If the backfill finishes and nobody ever writes to total_amount afterward, every new row that lands while the old code is still deployed will have total_amount back at null. That's why this step is never the end of the story — it's a historical cleanup that gets repeated (or left running) until step 3 is live on 100% of the replicas.
Step 3 — Dual write, deployed before touching any reads.
async function createOrder(db, order) {
const totalAmount = { value: order.totalCents, currency: 'COP' };
await db.query(
`INSERT INTO orders (customer_id, total_cents, total_amount)
VALUES ($1, $2, $3)`,
[order.customerId, order.totalCents, totalAmount]
);
}
The code still reads from total_cents everywhere. The only change is that it now also writes to total_amount. This deploy has to be confirmed at 100% of replicas before moving on. If any old replica (without dual write) is still serving traffic when the next step goes live, it will keep producing rows with total_amount stuck at null.
Step 4 — Switch reads to the new column.
Only after confirming that 100% of replicas are doing the dual write and that the backfill covered the full historical data, the code that reads total_amount instead of total_cents gets deployed. This is another separate deploy, with its own coexistence window between the old version (reads total_cents) and the new one (reads total_amount), but by this point it no longer matters which one runs, because both columns hold the correct value in any row, old or new.
Step 5 — Contract: stop writing to the old column, then drop it.
ALTER TABLE orders DROP COLUMN total_cents;
First the write to total_cents is removed from the code (another deploy, confirmed at 100%), and only then is the column dropped. Dropping it before the last pod running old code finishes rolling out breaks that pod on the spot.
The mistake that actually causes the incident
The most common cause of an incident with this pattern isn't skipping a step, it's swapping two of them: turning on dual write (step 3) in the same deploy that kicks off the backfill (step 2), or worse, switching reads (step 4) before confirming the backfill actually finished. If an old row hasn't gone through the backfill yet and the code already reads from total_amount, the result is reading null where a valid total used to be, in production, for real orders created before the change.
We hit exactly this inversion once on a user profile field migration: we deployed the code that read the new column trusting that "the backfill should be done by now," based on elapsed time rather than an explicit check against the database. The backfill ran in small batches to avoid saturating the read replica, and at that rate it still had almost two hours left. During those two hours, any profile the backfill hadn't reached yet showed up empty in the UI. What fixed it afterward was adding a verification query — SELECT count(*) FROM users WHERE new_field IS NULL AND old_field IS NOT NULL — as an explicit gate before deploying step 4, instead of relying on a time estimate.
What we check before closing out a migration like this
Before moving to the next step of the pattern, we confirm with a direct query that the previous step is 100% complete — never based on elapsed time or assumption. We verify that each code deploy (dual write, switching reads, dropping the old write) is confirmed as live across all replicas before advancing to the next step, using the orchestrator's actual state rather than how long it should have taken. And we keep the old column intact, undropped, until no pod is left running code that still needs it, which we check against the deployment history, not against anyone's memory on the team.