Skip to content
masdzub.com
~/articles/kubernetes — one from the notebook

Running Database Migrations Safely in Kubernetes Deployments

Practical patterns for running database migrations in Kubernetes without downtime, data loss, or race conditions.

masdzub@website:~$ cat ~/articles/running-database-migrations-safely-in-kubernetes-deployments.aspx.md
# 1 file · 20 min read · topic: kubernetes · status: published

Introduction

Database migrations in Kubernetes fail in ways that surprise teams used to single-server deployments. The core problem: Kubernetes runs multiple replicas, performs rolling updates, and restarts pods unpredictably. If your migration runs inside your application startup, two pods can execute the same migration simultaneously. If it runs before the deployment, a failed migration can leave your schema half-applied while the old application version still serves traffic. This article covers the concrete patterns, tooling, and failure modes you need to handle migrations safely in a Kubernetes environment, with working manifests and commands you can adapt today.

Why Application-Startup Migrations Break in Kubernetes

Many frameworks (Rails, Django, Laravel, Alembic) run pending migrations on application boot. On a single server, this works because only one process starts at a time. In Kubernetes, a Deployment with replicas: 3 starts three pods concurrently during a rollout. Each pod checks for pending migrations and attempts to run them.

The consequences depend on your migration tool’s locking behavior. Some tools acquire an advisory lock (Django’s migrate command acquires a PostgreSQL advisory lock since Django 4.0). Others do not. Even with advisory locks, you face these problems:

Race conditions on DDL. Two pods both see migration 0042 as pending. Both attempt ALTER TABLE users ADD COLUMN email_verified BOOLEAN. The first succeeds. The second fails with column "email_verified" already exists. Depending on your framework, this either crashes the pod (restart loop) or silently marks the migration as applied without verifying the schema matches expectations.

Extended startup time. A migration that takes 90 seconds blocks the pod from passing its readiness probe. Kubernetes marks the pod as unhealthy and kills it, potentially interrupting the migration mid-transaction. If the migration was not wrapped in a transaction (large table alterations in PostgreSQL cannot be), you end up with a partially applied schema change.

Blocked rollbacks. If the new code requires the new schema and the migration fails, your rolling update stalls. Old pods still serve traffic on the old schema, but the new pods crash-loop. Your Deployment is stuck at 1/3 READY until someone intervenes manually.

The fix is straightforward: separate the migration step from the application startup. Run migrations exactly once, before the new application version starts serving traffic.

Pattern 1: Init Containers

The simplest approach uses a Kubernetes init container. Init containers run sequentially before the main container starts. If the init container fails, Kubernetes retries it (with backoff) and never starts the main container.

apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
initContainers:
- name: run-migrations
image: myapp:v2.4.0
command: ["python", "manage.py", "migrate", "--no-input"]
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: myapp-db
key: url
containers:
- name: myapp
image: myapp:v2.4.0
ports:
- containerPort: 8000
readinessProbe:
httpGet:
path: /healthz
port: 8000
initialDelaySeconds: 5
periodSeconds: 10

The concurrency problem with init containers

This manifest has a flaw: with replicas: 3, three init containers run the migration simultaneously. You still have the race condition.

Mitigations:

Advisory locks in the migration tool. Django, Flyway, and Liquibase acquire database-level locks before running. If your tool does this, concurrent init containers are safe: one acquires the lock, runs migrations, and releases it. The others wait, then find no pending migrations and exit cleanly.

Reduce replicas during migration. Set replicas: 1 for the migration deploy, then scale up afterward. This is operationally clunky but eliminates concurrency entirely.

Use a separate Job instead. This is the better pattern for most teams, covered next.

When init containers work well

Init containers are a reasonable choice when all of these are true:

  • Your migration tool acquires advisory locks.
  • Migrations are fast (under 30 seconds).
  • You can tolerate the startup delay on every pod.
  • Your migration tool handles “already applied” states gracefully.

If any of those conditions do not hold, use a Job.

Pattern 2: Kubernetes Jobs (Pre-Deploy Migration Job)

A Kubernetes Job runs a pod to completion exactly once (or a configurable number of times on failure). By running migrations as a Job before updating the Deployment, you guarantee the migration completes before any new application pod starts.

apiVersion: batch/v1
kind: Job
metadata:
name: myapp-migrate-v2-4-0
labels:
app: myapp
migration-version: v2.4.0
spec:
backoffLimit: 3
activeDeadlineSeconds: 300
ttlSecondsAfterFinished: 3600
template:
metadata:
labels:
app: myapp-migrate
spec:
restartPolicy: Never
containers:
- name: migrate
image: myapp:v2.4.0
command: ["python", "manage.py", "migrate", "--no-input"]
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: myapp-db
key: url
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi

Key settings:

backoffLimit: 3 retries the migration up to 3 times on failure. activeDeadlineSeconds: 300 kills the Job if it runs longer than 5 minutes, preventing a stuck migration from blocking your pipeline indefinitely. ttlSecondsAfterFinished: 3600 cleans up the completed Job after an hour. restartPolicy: Never ensures a failed migration pod is not restarted (the Job controller handles retries by creating a new pod).

Orchestrating Job-then-Deployment

The Job must complete before the Deployment updates. Several approaches:

CI/CD pipeline sequencing. Your pipeline applies the Job manifest, waits for completion, then applies the Deployment manifest.

In a GitHub Actions workflow:

jobs:
migrate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Configure kubectl
uses: azure/k8s-set-context@v4
with:
kubeconfig: ${{ secrets.KUBECONFIG }}
- name: Run migration job
run: |
kubectl apply -f k8s/migration-job.yaml
kubectl wait --for=condition=complete \
job/myapp-migrate-v2-4-0 \
--timeout=300s
- name: Deploy application
run: |
kubectl apply -f k8s/deployment.yaml

The kubectl wait --for=condition=complete command blocks until the Job succeeds. If the Job fails, the pipeline fails and the Deployment never updates.

Helm hooks. If you use Helm, a pre-upgrade hook runs before the chart’s main resources are applied:

apiVersion: batch/v1
kind: Job
metadata:
name: {{ .Release.Name }}-migrate
annotations:
"helm.sh/hook": pre-upgrade,pre-install
"helm.sh/hook-weight": "-1"
"helm.sh/hook-delete-policy": hook-succeeded,before-hook-creation
spec:
backoffLimit: 3
activeDeadlineSeconds: 300
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
command: ["python", "manage.py", "migrate", "--no-input"]
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: {{ .Release.Name }}-db
key: url

helm.sh/hook-delete-policy: hook-succeeded,before-hook-creation deletes the previous Job before creating a new one (Job names are immutable in Kubernetes, so a stale Job with the same name blocks the new one). hook-succeeded cleans up after a successful run.

Argo CD with sync waves. Argo CD supports sync waves via annotations. Set the migration Job to wave -1 and the Deployment to wave 0:

metadata:
annotations:
argocd.argoproj.io/sync-wave: "-1"

Argo CD applies resources in wave order and waits for each wave’s resources to become healthy before proceeding.

Pattern 3: Expand-and-Contract Migrations

The patterns above handle when to run migrations. This pattern handles what the migration contains, which matters more for zero-downtime deployments.

A naive migration might rename a column:

ALTER TABLE users RENAME COLUMN name TO full_name;

The moment this runs, every running pod that references users.name breaks. Even with a Job that runs before the Deployment update, old pods still serve traffic during the rolling update window.

Expand-and-contract (also called parallel change) splits this into phases:

Phase 1: Expand. Add the new column alongside the old one. Deploy code that writes to both columns but reads from the old one.

ALTER TABLE users ADD COLUMN full_name VARCHAR(255);
UPDATE users SET full_name = name WHERE full_name IS NULL;

Application code (v2.4.0):

# Write to both columns
user.name = value
user.full_name = value
user.save()
# Read from old column
display_name = user.name

Deploy v2.4.0. Both old and new pods work because the name column still exists and is still the source of truth.

Phase 2: Migrate reads. Deploy code that reads from the new column.

# Write to both columns (still)
user.name = value
user.full_name = value
user.save()
# Read from new column
display_name = user.full_name

Deploy v2.5.0. Old pods (if any still draining) read from name, which is still populated. New pods read from full_name.

Phase 3: Contract. Once all pods run v2.5.0 and no rollback to v2.4.0 is planned, drop the old column.

ALTER TABLE users DROP COLUMN name;

Application code (v2.6.0) removes all references to user.name.

This is more work. Three deployments instead of one. The trade-off: zero downtime, safe rollback at every phase, and no coordination between migration timing and pod lifecycle. For production systems serving real traffic, this trade-off is almost always worth it.

When expand-and-contract is mandatory

You need this pattern whenever:

  • The migration changes a column that existing running code depends on (renames, type changes, NOT NULL additions with no default).
  • The migration drops a table or column.
  • The migration changes an index that existing queries rely on for performance.
  • Your rolling update takes more than a few seconds (large clusters, slow image pulls).

You can skip it for additive-only changes: adding a new table, adding a nullable column, adding an index. These are backward-compatible by nature.

Handling Long-Running Migrations

Some migrations take minutes or hours. Adding an index to a table with 50 million rows. Backfilling a new column across a large dataset. These need special handling in Kubernetes.

PostgreSQL: CREATE INDEX CONCURRENTLY

A standard CREATE INDEX locks the table against writes for the duration. On a large table, this means downtime.

CREATE INDEX idx_users_email ON users (email);, Does not block writes. Use this.
CREATE INDEX CONCURRENTLY idx_users_email ON users (email);

CREATE INDEX CONCURRENTLY cannot run inside a transaction. Most migration tools wrap each migration in a transaction by default. You need to disable this per-migration.

In Django, use SeparateDatabaseAndState or set atomic = False on the migration:

from django.db import migrations
class Migration(migrations.Migration):
atomic = False
operations = [
migrations.RunSQL(
sql="CREATE INDEX CONCURRENTLY idx_users_email ON users (email);",
reverse_sql="DROP INDEX idx_users_email;",
),
]

In Flyway, use non-transactional migrations by naming the file with V prefix and setting executeInTransaction=false in the migration metadata.

In Alembic:

from alembic import op
def upgrade():
op.execute("COMMIT") # End the implicit transaction
op.create_index(
"idx_users_email",
"users",
["email"],
postgresql_concurrently=True,
)

Job timeout considerations

If your migration takes 30 minutes, set activeDeadlineSeconds accordingly. But also consider: what happens if the Job is killed mid-migration?

For transactional migrations, the database rolls back. No harm done.

For non-transactional migrations (CREATE INDEX CONCURRENTLY, large UPDATE statements), a killed Job leaves partial state. CREATE INDEX CONCURRENTLY that gets interrupted leaves an invalid index:

SELECT indexrelid::regclass, indisvalid
FROM pg_index
WHERE NOT indisvalid;

Clean up with:

DROP INDEX CONCURRENTLY idx_users_email;

Then rerun the migration.

For large backfills, batch the work:

import time
def backfill_full_name(batch_size=5000):
while True:
updated = cursor.execute("""
UPDATE users
SET full_name = name
WHERE full_name IS NULL
LIMIT %s
""", [batch_size])
if updated == 0:
break
time.sleep(0.1) # Ease pressure on replication

Run this as a separate Job from the schema migration. The schema migration adds the column; the backfill Job populates it. This separation means a killed backfill Job can be restarted without re-running DDL.

Locking and Concurrency Control

Even with a single migration Job, concurrent deploys (triggered by rapid git pushes, or multiple environments sharing a database) can cause conflicts. Database-level locking is your safety net.

PostgreSQL advisory locks

SELECT pg_advisory_lock(12345);, run migrations
SELECT pg_advisory_unlock(12345);

Django’s migrate command acquires an advisory lock automatically (using the hash of the database alias as the lock ID). Flyway and Liquibase maintain their own lock tables (flyway_schema_history and DATABASECHANGELOGLOCK respectively).

If a migration Job is killed while holding an advisory lock, the lock is released when the database connection closes. This is safe. If your tool uses a lock table (Liquibase), a killed Job can leave a stale lock row. You will see:

Waiting for changelog lock....
Waiting for changelog lock....
Liquibase Update Failed: Could not acquire change log lock.

Fix:

UPDATE DATABASECHANGELOGLOCK SET LOCKED = FALSE, LOCKGRANTED = NULL, LOCKEDBY = NULL WHERE ID = 1;

Or with the Liquibase CLI:

Terminal window
liquibase releaseLocks

Kubernetes-level locking with leader election

For extra safety, you can use Kubernetes leader election to ensure only one migration pod runs at a time, even across multiple Deployments or namespaces sharing a database.

A lightweight approach uses a ConfigMap-based lease:

apiVersion: coordination.k8s.io/v1
kind: Lease
metadata:
name: myapp-migration-lock
namespace: default
spec:
holderIdentity: ""
leaseDurationSeconds: 300

Your migration wrapper script acquires the lease before running:

#!/bin/bash
set -euo pipefail
# Attempt to acquire lease
HOLDER=$(kubectl get lease myapp-migration-lock -o jsonpath='{.spec.holderIdentity}')
if [ -n "$HOLDER" ]; then
echo "Migration lock held by $HOLDER. Exiting."
exit 1
fi
kubectl patch lease myapp-migration-lock \
--type=merge \
-p "{\"spec\":{\"holderIdentity\":\"$(hostname)\",\"acquireTime\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}}"
# Run migration
python manage.py migrate --no-input
EXIT_CODE=$?
# Release lease
kubectl patch lease myapp-migration-lock \
--type=merge \
-p '{"spec":{"holderIdentity":""}}'
exit $EXIT_CODE

This is not bulletproof (no fencing token, no automatic expiry enforcement), but it prevents the common case of two CI pipelines racing to run migrations.

Rollback Strategies

Migrations are the hardest part of a rollback. Code rolls back easily (update the Deployment image tag). Schema changes do not.

Reversible migrations

Write every migration with a down or reverse operation:

# Django
class Migration(migrations.Migration):
operations = [
migrations.AddField(
model_name='user',
name='email_verified',
field=models.BooleanField(default=False),
),
]
# Django auto-generates the reverse (RemoveField) for AddField
ALTER TABLE users ADD COLUMN email_verified BOOLEAN DEFAULT FALSE;, Flyway: U42__add_email_verified.sql (undo migration)
ALTER TABLE users DROP COLUMN email_verified;

Test your reverse migrations. Many teams write them and never run them until an incident, at which point they discover the reverse migration references a column that was already modified by a later migration.

When rollback is not possible

Some changes cannot be reversed:

  • Dropping a column (data is gone).
  • Changing a column type with data loss (e.g., TEXT to INTEGER).
  • Deleting rows.

For these, take a backup before the migration:

Terminal window
pg_dump --format=custom --file=pre-migration-v42.dump myapp_production

In your CI pipeline:

- name: Backup database
run: |
kubectl exec deploy/postgres, \
pg_dump --format=custom --file=/tmp/pre-migrate.dump myapp
kubectl cp default/postgres-0:/tmp/pre-migrate.dump ./pre-migrate.dump
- name: Run migration
run: |
kubectl apply -f k8s/migration-job.yaml
kubectl wait --for=condition=complete job/myapp-migrate-v2-4-0 --timeout=300s

If the migration fails or the new code has a critical bug, restore from the backup. This is the nuclear option and involves downtime, but it is the only safe path when destructive migrations go wrong.

Schema Versioning and Migration State

Your migration tool maintains a table tracking which migrations have been applied. This table is the source of truth.

Django: django_migrations Flyway: flyway_schema_history Liquibase: DATABASECHANGELOG Alembic: alembic_version

Inspect it when debugging:

SELECT * FROM django_migrations ORDER BY applied DESC LIMIT 10;, Flyway
SELECT installed_rank, version, description, success
FROM flyway_schema_history
ORDER BY installed_rank DESC
LIMIT 10;

A common failure mode: someone manually applies a SQL change to production without creating a migration file. The migration tool does not know about it. The next migration that touches the same object fails with a conflict.

Prevention: never modify production schemas outside the migration tool. If an emergency hotfix requires a manual SQL change, create a migration file afterward that matches the change, and mark it as already applied:

Terminal window
# Django: create an empty migration and mark it applied
python manage.py makemigrations --empty myapp --name emergency_hotfix_0043
python manage.py migrate --fake myapp 0043
Terminal window
# Flyway: baseline or repair
flyway repair

Network Policies and Database Access

Migration Jobs need network access to the database. If you use Kubernetes NetworkPolicies, ensure the migration Job’s pods can reach the database.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-migration-to-db
spec:
podSelector:
matchLabels:
app: myapp-migrate
policyTypes:
- Egress
egress:
- to:
- podSelector:
matchLabels:
app: postgres
ports:
- protocol: TCP
port: 5432

If your database is external (RDS, Cloud SQL), the egress rule targets the external IP or CIDR:

egress:
- to:
- ipBlock:
cidr: 10.0.1.0/24
ports:
- protocol: TCP
port: 5432

For Cloud SQL with the Auth Proxy, the migration Job needs the proxy sidecar:

spec:
template:
spec:
containers:
- name: migrate
image: myapp:v2.4.0
command: ["python", "manage.py", "migrate", "--no-input"]
env:
- name: DATABASE_URL
value: "postgresql://user:pass@127.0.0.1:5432/myapp"
- name: cloud-sql-proxy
image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.8.2
args:
- "--structured-logs"
- "--port=5432"
- "project:region:instance"
securityContext:
runAsNonRoot: true

One catch: the Cloud SQL Proxy sidecar does not terminate when the migration container finishes. The Job hangs in Running state. Fix this with a shared process namespace and a lifecycle hook, or use the --quitquit flag with a signal from the migration container:

#!/bin/bash
python manage.py migrate --no-input
EXIT_CODE=$?
# Signal the proxy to quit
curl -s http://localhost:9091/quitquitquit || true
exit $EXIT_CODE

With Cloud SQL Proxy v2, the --quitquit endpoint is available at localhost:9091/quitquitquit by default.

Monitoring and Alerting

Migration failures should trigger alerts, not sit silently in Job logs.

Prometheus metrics

If you run Prometheus, the kube-state-metrics exporter provides Job status metrics:

# Failed migration jobs in the last hour
kube_job_status_failed{job_name=~".*migrate.*"} > 0

Alert rule:

groups:
- name: migration-alerts
rules:
- alert: MigrationJobFailed
expr: kube_job_status_failed{job_name=~".*migrate.*"} > 0
for: 1m
labels:
severity: critical
annotations:
summary: "Migration job {{ $labels.job_name }} failed"
description: "The migration job has failed {{ $value }} time(s). Check logs with: kubectl logs job/{{ $labels.job_name }}"

Checking Job logs

Terminal window
# Get logs from the migration Job
kubectl logs job/myapp-migrate-v2-4-0
# If the pod was replaced (backoffLimit retries), get logs from all pods
kubectl logs job/myapp-migrate-v2-4-0 --all-containers=true

Slack/PagerDuty integration

Use a post-migration step in your CI pipeline:

- name: Notify on migration failure
if: failure()
run: |
curl -X POST "$SLACK_WEBHOOK" \
-H 'Content-Type: application/json' \
-d "{\"text\":\"Migration job failed for v2.4.0. Deployment halted. Logs: kubectl logs job/myapp-migrate-v2-4-0\"}"

Troubleshooting Common Failures

Error: “relation already exists”

django.db.utils.ProgrammingError: relation "users_email_idx" already exists

Cause: a previous migration run created the index but the migration was not recorded as applied (killed mid-run, or manual intervention).

Fix:

Terminal window
# Verify the index exists
psql -c "SELECT indexname FROM pg_indexes WHERE tablename = 'users';"
# If it exists, fake the migration
python manage.py migrate --fake myapp 0042

Error: “lock timeout”

ERROR: canceling statement due to lock timeout

Cause: the migration tried to acquire a table lock while a long-running query held a conflicting lock.

Fix: set a statement timeout on the migration connection and retry:

SET lock_timeout = '10s';
ALTER TABLE users ADD COLUMN verified BOOLEAN DEFAULT FALSE;

Or run the migration during a low-traffic window. For high-traffic tables, use CREATE INDEX CONCURRENTLY and expand-and-contract patterns.

Error: “Job has reached the specified backoff limit”

$ kubectl describe job myapp-migrate-v2-4-0
...
Warning BackoffLimitExceeded 2m job-controller Job has reached the specified backoff limit

Cause: the migration failed 3 times (or whatever backoffLimit is set to).

Fix:

  1. Check the pod logs: kubectl logs job/myapp-migrate-v2-4-0
  2. Fix the migration code or database state.
  3. Delete the failed Job: kubectl delete job myapp-migrate-v2-4-0
  4. Reapply: kubectl apply -f k8s/migration-job.yaml

Error: “Job already exists”

Error from server (AlreadyExists): jobs.batch "myapp-migrate-v2-4-0" already exists

Cause: Kubernetes Job names are immutable. A previous Job with the same name exists (completed or failed).

Fix: delete the old Job first, or use unique names:

Terminal window
kubectl delete job myapp-migrate-v2-4-0 --ignore-not-found=true
kubectl apply -f k8s/migration-job.yaml

Or generate unique names in your pipeline:

metadata:
name: myapp-migrate-{{ .Values.image.tag | replace "." "-" }}

Sidecar containers preventing Job completion

Symptom: kubectl get jobs shows the Job as 1/1 completions but the pod stays in Running state.

Cause: a sidecar (Istio proxy, Cloud SQL Proxy, log shipper) keeps the pod alive after the main container exits.

Fix for Istio:

spec:
template:
metadata:
annotations:
sidecar.istio.io/inject: "false"

Disable the Istio sidecar for migration Jobs. Migrations do not need mesh routing.

Fix for generic sidecars (Kubernetes 1.28+ with sidecar containers feature):

initContainers:
- name: cloud-sql-proxy
image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.8.2
restartPolicy: Always # Makes this a sidecar container
args: ["--port=5432", "project:region:instance"]

With restartPolicy: Always on an init container, Kubernetes treats it as a native sidecar that terminates when the main container exits.

Complete Example: Django on GKE with Cloud SQL

Putting it all together. A Django application on GKE with Cloud SQL PostgreSQL, deployed via Helm.

Directory structure:

chart/
Chart.yaml
values.yaml
templates/
deployment.yaml
migration-job.yaml
service.yaml
secrets.yaml

templates/migration-job.yaml:

apiVersion: batch/v1
kind: Job
metadata:
name: {{ .Release.Name }}-migrate-{{ .Values.image.tag | replace "." "-" }}
annotations:
"helm.sh/hook": pre-upgrade,pre-install
"helm.sh/hook-weight": "-1"
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
backoffLimit: 3
activeDeadlineSeconds: 600
template:
metadata:
labels:
app: {{ .Release.Name }}-migrate
annotations:
sidecar.istio.io/inject: "false"
spec:
restartPolicy: Never
serviceAccountName: {{ .Release.Name }}-migrate
initContainers:
- name: cloud-sql-proxy
image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.8.2
restartPolicy: Always
args:
- "--structured-logs"
- "--port=5432"
- "{{ .Values.cloudsql.instance }}"
resources:
requests:
cpu: 50m
memory: 64Mi
containers:
- name: migrate
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
command: ["python", "manage.py", "migrate", "--no-input"]
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: {{ .Release.Name }}-db
key: url
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi

templates/deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ .Release.Name }}
spec:
replicas: {{ .Values.replicas }}
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
selector:
matchLabels:
app: {{ .Release.Name }}
template:
metadata:
labels:
app: {{ .Release.Name }}
spec:
containers:
- name: app
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
command: ["gunicorn", "myapp.wsgi", "--bind", "0.0.0.0:8000", "--workers", "4"]
ports:
- containerPort: 8000
readinessProbe:
httpGet:
path: /healthz
port: 8000
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
httpGet:
path: /healthz
port: 8000
initialDelaySeconds: 30
periodSeconds: 15
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: {{ .Release.Name }}-db
key: url
- name: cloud-sql-proxy
image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.8.2
args:
- "--structured-logs"
- "--port=5432"
- "{{ .Values.cloudsql.instance }}"

Deploy:

Terminal window
helm upgrade --install myapp ./chart \
--set image.tag=v2.4.0 \
--set cloudsql.instance=myproject:us-central1:mydb \
--wait --timeout=10m

Helm runs the pre-upgrade hook (migration Job), waits for it to complete, then applies the Deployment update. If the migration fails, Helm rolls back the release and the Deployment stays on the previous version.

Comparison of Migration Patterns

PatternConcurrency safeRollback safeLong migrationsComplexity
App startupOnly with advisory locksNo (pods crash-loop)Poor (probe timeout)Low
Init containerOnly with advisory locksNo (pods crash-loop)Poor (probe timeout)Low
Pre-deploy JobYes (single pod)Yes (deploy blocked)Good (configurable timeout)Medium
Helm hook JobYes (single pod)Yes (Helm rollback)Good (configurable timeout)Medium
Argo CD sync waveYes (single pod)Yes (sync fails)Good (configurable timeout)Medium
Operator (custom)Yes (custom logic)Yes (custom logic)Best (custom logic)High

For most teams, the pre-deploy Job (whether via CI pipeline, Helm hook, or Argo CD sync wave) gives the best balance of safety and operational simplicity.

Checklist Before Running Migrations in Production

Run through this list before every production migration:

  1. The migration has been tested against a copy of the production schema (not just the dev database).
  2. The migration has a reverse operation, and the reverse has been tested.
  3. For destructive changes (column drops, type changes), a database backup has been taken and verified.
  4. Large table operations use non-locking alternatives (CREATE INDEX CONCURRENTLY, batched updates).
  5. The migration Job has appropriate backoffLimit and activeDeadlineSeconds values.
  6. The CI pipeline blocks the Deployment update until the migration Job succeeds.
  7. Monitoring alerts on migration Job failures.
  8. The new application code is backward-compatible with the old schema (expand-and-contract for breaking changes).
  9. If using sidecars, the migration Job either disables them or handles their lifecycle.
  10. The migration has been applied to staging first, with the same orchestration (Job, then Deployment) that production uses.

Skipping any of these steps is how teams end up debugging a half-migrated production database at 2 AM. The migration itself is usually simple. The hard part is the operational discipline around when and how it runs.

found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.