TL;DR: Achieve zero-downtime deployments in Kubernetes by decoupling PostgreSQL schema changes from Node.js application rollouts using the Expand and Contract pattern. Instead of running migrations in your container's
CMD, use a Helm pre-upgrade hook Job to run non-breaking schema expansions before new pods roll out.
Key Takeaways
- Implement the 4-phase Expand and Contract pattern to support concurrent
v1andv2application pods during Kubernetes rolling updates. - Omit strict constraints like
NOT NULLwithout defaults during the "Expand" phase so legacy pods can continue inserting rows without crashing. - On PostgreSQL 11+, adding a column with a non-volatile
DEFAULTis a metadata-only change with no table rewrite, though it still takes a briefACCESS EXCLUSIVElock, so setlock_timeout. - Avoid running migrations from the container
CMD, where every starting pod competes to migrate and a failed migration can crash-loop the rollout. - Use a Helm hook (
"helm.sh/hook": pre-upgrade) so the migration Job must complete before Helm updates the Deployment.
You hit kubectl apply or merge your PR to trigger the deployment pipeline. Kubernetes dutifully spins up your new Node.js pods. Simultaneously, your migration job executes against your PostgreSQL database, dropping a legacy column to match the new application code.
Until the rollout finishes, your error rate spikes.
During a rolling update, old pods are still receiving traffic, and they now return 500 Internal Server Error because the column they query no longer exists. The new version is live, but requests served by the old pods fail and any transactions they had in flight are rolled back.
Rolling updates mean two application versions share one database for a while. You cannot deploy an application change and a breaking schema change atomically, so the schema has to work with both versions at every step.
The standard way to do that is the Expand and Contract pattern (also called parallel change).
The Expand and Contract Pattern Explained
The core philosophy of zero-downtime migrations is backward and forward compatibility. If a Kubernetes deployment runs v1 and v2 pods concurrently during a rollout, the database schema must simultaneously support both application versions.
The Expand and Contract pattern breaks a single breaking schema change (like renaming a column or changing a relationship type) into four distinct, non-breaking phases:
- Expand: Add the new schema elements without removing the old ones.
- Deploy: Ship the new application code (
v2) that writes to both old and new schema elements, and reads from the new ones with a fallback to the old until the backfill is done. - Backfill: Migrate the historical data in the background.
- Contract: Deploy
v3of the app that ignores the old schema, then drop the legacy database elements.
Let's walk through a classic breaking change: splitting a full_name column into first_name and last_name in a PostgreSQL database serving a Node.js backend.
-- The naive, downtime-causing approach:
ALTER TABLE users
ADD COLUMN first_name VARCHAR(255),
ADD COLUMN last_name VARCHAR(255);
UPDATE users SET
first_name = split_part(full_name, ' ', 1),
last_name = split_part(full_name, ' ', 2);
-- The moment this executes, v1 pods crash on INSERTs or SELECTs requiring full_name
ALTER TABLE users DROP COLUMN full_name;
Phase 1: The Expand Migration (PostgreSQL)
In the expand phase, only add the new columns. Avoid constraints such as NOT NULL without a default, which would make every v1 insert fail because v1 does not know about the new columns.
-- V1 Migration: Expand
ALTER TABLE users
ADD COLUMN first_name VARCHAR(255) DEFAULT NULL,
ADD COLUMN last_name VARCHAR(255) DEFAULT NULL;
Production Note: Before PostgreSQL 11, adding a column with a
DEFAULTrewrote the whole table while holding anACCESS EXCLUSIVElock. From PostgreSQL 11 onwards, a non-volatile default (a constant, ornow()) is stored in the catalog and no rewrite happens. Volatile defaults such asclock_timestamp(), stored generated columns and identity columns still rewrite the table. EveryALTER TABLE ... ADD COLUMNstill needs anACCESS EXCLUSIVElock briefly, so a long-running query on the table can make it queue; uselock_timeouthere too.
By executing this migration, the database now supports both the v1 application (which continues to read and write full_name) and the incoming v2 application.
Orchestrating Pre-Rollout Migrations in Kubernetes
To make sure the database is expanded before the new Node.js pods start, run the migration as its own step in the deployment. Running npm run migrate from the container CMD is risky: several new pods start at once and compete to migrate. Most migration tools (Prisma Migrate, Knex, Flyway) take a lock so only one wins, but the others still block or fail, startup time grows, and a failed migration leaves pods crash-looping halfway through a rollout.
A cleaner approach is a Helm hook or a separate Kubernetes Job that your pipeline runs before updating the Deployment. If you want help setting this up in your pipeline, our DevOps and Cloud Deployment Services cover it.
Here is a Helm hook that runs your database migrations (using a tool like Prisma, Flyway or Knex) before the Deployment is modified:
apiVersion: batch/v1
kind: Job
metadata:
name: 'db-migrate-expand-{{ .Release.Revision }}'
annotations:
# Runs before Helm upgrades the chart's other resources
'helm.sh/hook': pre-upgrade
'helm.sh/hook-weight': '-5'
'helm.sh/hook-delete-policy': before-hook-creation,hook-succeeded
spec:
template:
spec:
containers:
- name: db-migrate
image: 'your-registry.com/node-app:{{ .Values.image.tag }}'
command: ['node', './scripts/migrate.js']
envFrom:
- secretRef:
name: pg-credentials
restartPolicy: Never
backoffLimit: 1
Helm treats a hook Job as blocking: it waits until the Job completes before applying the rest of the upgrade, and if the Job fails the release fails, leaving your v1 Deployment untouched. This does not depend on --wait, which only controls whether Helm waits for the upgraded resources to become ready. Two caveats: hook resources are not managed as part of the release, so a Secret the Job needs must already exist (it cannot be created by the same chart in the same upgrade), and on a first install you need pre-install as well, or a separate bootstrap step. Set --timeout high enough for your slowest migration.
Phase 2: Updating the Node.js Application
With the database expanded, we deploy v2 of our Node.js application. This version acts as a bridge. It must read from the new columns, but write to both the old and new columns.
Why write to both? Because during the Kubernetes rolling update, v1 pods are still alive and serving requests. If a v2 pod creates a user without a full_name, a v1 pod might immediately query that user and crash due to a missing expected field.
Here is dual-writing with the pg library in Node.js:
// user.repository.js
const { Pool } = require('pg');
const pool = new Pool();
async function createUser(userData) {
const { firstName, lastName, email } = userData;
// Fallback for v1 backward compatibility
const fullName = `${firstName} ${lastName}`.trim();
const query = `
INSERT INTO users (email, first_name, last_name, full_name)
VALUES ($1, $2, $3, $4)
RETURNING id, email, first_name, last_name;
`;
const values = [email, firstName, lastName, fullName];
try {
const res = await pool.query(query, values);
return res.rows[0];
} catch (err) {
console.error('Error creating user:', err);
throw err;
}
}
Rows created by v2 pods remain usable by v1 pods for as long as the rollout takes. On the read side, v2 should fall back to the old column until the backfill finishes, for example SELECT COALESCE(first_name, split_part(full_name, ' ', 1)) AS first_name ..., because older rows still have NULL in the new columns. If v1 pods can also update full_name during the rollout, those changes will not reach the new columns; either rerun the backfill afterwards or keep the columns in sync with a temporary trigger.
Graceful Connection Draining in Kubernetes
Even with a compatible schema, rolling updates can still drop requests if old pods exit while they are serving them.
When Kubernetes terminates an old pod, it sends SIGTERM. If your Node.js app exits immediately, in-flight HTTP requests and database queries fail. The app needs a graceful shutdown that stops taking new work, finishes what it has, and closes the PostgreSQL pool.
First, add a preStop hook to the Deployment. When a pod is deleted, Kubernetes removes it from Service endpoints and runs the preStop hook at roughly the same time, and endpoint removal takes a few seconds to reach kube-proxy and Ingress controllers. A short sleep in preStop delays SIGTERM until routers have stopped sending new requests. The sleep counts against terminationGracePeriodSeconds.
apiVersion: apps/v1
kind: Deployment
metadata:
name: nodejs-backend
spec:
replicas: 3
template:
spec:
terminationGracePeriodSeconds: 30
containers:
- name: nodejs-app
image: your-registry.com/node-app:v2
lifecycle:
preStop:
exec:
# Give kube-proxy and Ingress controllers time to stop routing here
command: ['/bin/sh', '-c', 'sleep 10']
If your image has no shell (for example distroless), recent Kubernetes versions support a native preStop: { sleep: { seconds: 10 } } handler executed by the kubelet.
Next, configure your Node.js application to intercept the SIGTERM signal, stop accepting new HTTP connections, and gracefully close the PostgreSQL pool. It is also a best practice to include a timeout fallback so the process doesn't hang indefinitely if a query is stuck:
// server.js
const http = require('http');
const { Pool } = require('pg');
const app = require('./app'); // your Express app
const pool = new Pool();
const server = http.createServer(app);
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
process.on('SIGTERM', () => {
console.log('SIGTERM received. Starting graceful shutdown...');
// Fallback timeout in case connections hang
const timeout = setTimeout(() => {
console.error('Graceful shutdown timed out. Forcing exit.');
process.exit(1);
}, 15000);
// 1. Stop accepting new HTTP requests
server.close(async () => {
console.log('HTTP server closed.');
try {
// 2. Wait for active queries to finish, then close the DB pool
await pool.end();
console.log('PostgreSQL pool drained.');
clearTimeout(timeout);
process.exit(0);
} catch (err) {
console.error('Error closing PostgreSQL pool:', err);
clearTimeout(timeout);
process.exit(1);
}
});
});
Phase 3: Background Data Backfilling
Now that v2 is running and gracefully handling connections, newly created users have both full_name and the split first_name/last_name fields. However, your historical data still contains NULL values for the new columns.
Now migrate the old data. Run the backfill after the rollout has finished, so no v1 pods are still writing rows with only full_name. A single UPDATE across millions of rows holds row locks on every row until it commits, creates one dead tuple per updated row (PostgreSQL's MVCC), and produces a burst of WAL that can lag replicas.
Instead, backfill in small batches from a Kubernetes Job or a background worker, committing each batch and pausing briefly between them.
-- Execute this in batches (e.g., via a Node script looping through IDs)
WITH batch AS (
SELECT id FROM users
WHERE first_name IS NULL
AND full_name IS NOT NULL
ORDER BY id ASC
LIMIT 1000
FOR UPDATE SKIP LOCKED
)
UPDATE users
SET
first_name = split_part(full_name, ' ', 1),
last_name = split_part(full_name, ' ', 2)
WHERE id IN (SELECT id FROM batch);
Production Note:
FOR UPDATE SKIP LOCKEDmakes the backfill skip rows that a user request currently has locked instead of waiting on them, so the backfill does not stall live traffic and several workers can run in parallel. Skipped rows still matchfirst_name IS NULLand are picked up by a later batch. Thefull_name IS NOT NULLfilter stops the loop from selecting rows it can never fill. Loop until the statement updates zero rows.
Phase 4: The Contract Phase (Cleanup)
Once the backfill is complete, every row in the database has populated first_name and last_name columns. You can now deploy v3 of your application.
v3 removes all references to full_name. The application only reads and writes to the new split columns.
// V3 user.repository.js - Cleaned up
async function createUser(userData) {
const { firstName, lastName, email } = userData;
const query = `
INSERT INTO users (email, first_name, last_name)
VALUES ($1, $2, $3)
RETURNING id, email, first_name, last_name;
`;
// ... execution logic
}
After v3 is deployed and stable, you can drop the legacy column. DROP COLUMN itself is fast because PostgreSQL only marks the column as dropped, but it needs an ACCESS EXCLUSIVE lock on the table. If a long-running SELECT holds a lock on users, the DROP COLUMN waits for it, and every new query on users then queues behind the waiting DROP COLUMN. The result is a stall on that table for as long as the original query runs.
To contract the database safely, set a strict lock timeout in your migration script:
-- V3 Migration: Contract
-- Abort the migration if it can't acquire the lock within 2 seconds
SET lock_timeout = '2s';
ALTER TABLE users DROP COLUMN full_name;
If the migration hits the 2-second timeout, the statement fails and nothing changes. Your pipeline flags the failure while the application keeps running, and you can retry the job, ideally automatically a few times or during lower traffic.
Architecting for Stability
Zero-downtime database migrations require discipline. You trade a single quick schema change for several smaller deployments, and in return each step is reversible and safe to run while traffic flows. Expand and contract, migrations as a blocking Helm hook, lock timeouts, batched backfills and graceful connection draining together remove the most common causes of migration-induced outages.
Sources
- PostgreSQL documentation: ALTER TABLE (non-volatile defaults without rewrite,
DROP COLUMNbehavior, lock levels) - Helm documentation: Chart Hooks (blocking hook Jobs, delete policies)
- Kubernetes documentation: Pod Lifecycle (termination sequence and grace period)
- Kubernetes documentation: Container Lifecycle Hooks (
preStopexec and sleep handlers)
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
What is the expand and contract pattern?
You change the schema in steps that are each compatible with both the old and new application versions. First add new columns or tables, then deploy code that uses them, then backfill data, and only remove the old structure once nothing reads it.
Where should migrations run in a Kubernetes deployment?
Run them as a separate Kubernetes Job, or a pre-deployment hook such as a Helm pre-upgrade hook, before the new pods roll out. Running them inside every application pod at startup risks several pods migrating at once.
How do you backfill a large table without locking it?
Update rows in small batches with a short pause between them, outside the deployment, and make the job resumable. Large single UPDATE statements hold locks and generate a burst of write-ahead log that can slow replicas.
How do you avoid dropped requests during a rolling deploy?
Handle SIGTERM in Node.js so the pod stops accepting new requests and finishes in-flight ones, add a short preStop delay so the load balancer stops routing to it first, and use readiness probes so new pods only get traffic when ready.
