A database migration can finish successfully, the application can pass its health checks, and the deployment pipeline can turn green — yet your production system may still be one rollback away from an outage.
The problem is often not whether the migration succeeded.
It is whether the old and new versions of your application can safely work with the database at the same time.
This becomes especially important when deploying applications through rolling deployments, where old instances are gradually replaced by new ones rather than stopped all at once.
Let's understand why this happens and how the expand-and-contract pattern helps manage schema changes safely.
1. The Problem: Application Deployments Are Not Atomic
Imagine an existing application with a PostgreSQL table:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
full_name VARCHAR(255),
email VARCHAR(255)
);Your application reads and writes the full_name column.
Now, a requirement arrives: split full_name into two separate fields:
first_namelast_name
A straightforward migration might look like this:
ALTER TABLE users
RENAME COLUMN full_name TO first_name;Then you update the application to use first_name and last_name.
It looks reasonable. But consider what happens during a rolling deployment.
| Deployment stage | Application version | Database |
|---|---|---|
| Before deployment | Version 1 | full_name |
| Migration executed | Version 1 | first_name |
| New instances starting | Version 1 + Version 2 | first_name |
| Deployment completed | Version 2 | first_name |
The old application instances still expect full_name.
The database no longer has that column.
Those instances can start failing immediately, even though the new application code is correct.
There is another problem: what happens if the new deployment fails and you roll back to Version 1?
The old application still cannot use the renamed column.
A successful migration does not automatically mean a safe deployment.
2. Understand the Expand-and-Contract Pattern
The expand-and-contract pattern separates one potentially risky schema change into multiple backward-compatible steps.
Instead of changing the database structure and application code simultaneously, we introduce the new structure first, migrate the data, switch application behavior, and remove the old structure only when it is no longer needed.
There are three main phases:
Phase 1: Expand
Add the new database columns without removing the existing ones.
ALTER TABLE users
ADD COLUMN first_name VARCHAR(100),
ADD COLUMN last_name VARCHAR(100);The old application continues using full_name.
The new columns are available, but existing application behavior does not depend on them yet.
Phase 2: Migrate and Switch
Deploy application code that understands both the old and new schema.
During the transition, the application can:
- Write to both old and new fields.
- Read from the old field when the new fields are not populated.
- Backfill existing records.
- Gradually move read operations to the new fields.
Once the data is verified and the new application version is fully deployed, the application can start treating the new fields as the primary source.
Phase 3: Contract
Only after confirming that no active application version depends on full_name should we remove it.
ALTER TABLE users
DROP COLUMN full_name;This should be a separate migration and deployment step, not part of the initial release.
The important principle is simple:
Add first. Migrate second. Remove last.
3. Implementing the Pattern with FastAPI and SQLAlchemy
Let's look at how this approach can work in a Python backend.
Assume the application currently stores a user's full name in one column.
After the expansion migration, the database contains all three fields:
users
├── id
├── full_name
├── first_name
└── last_nameStep A: Update the application to support both schemas
During the transition, the application should handle records that have not yet been migrated.
A simplified SQLAlchemy model:
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
full_name = Column(String(255), nullable=True)
first_name = Column(String(100), nullable=True)
last_name = Column(String(100), nullable=True)The application can use a compatibility layer:
def get_user_full_name(user):
if user.first_name or user.last_name:
return " ".join(
part for part in [
user.first_name,
user.last_name
]
if part
)
return user.full_name or ""This allows application code to work with both migrated and unmigrated records.
In a real system, the compatibility logic should also account for the business rules around names, including single-word names and empty values.
Step B: Write both old and new fields
During the transition, new updates should keep the old and new representations synchronized.
def update_user_name(user, first_name, last_name):
user.first_name = first_name
user.last_name = last_name
user.full_name = " ".join(
part for part in [first_name, last_name]
if part
)The important detail is that all three assignments should be persisted within the same database transaction.
Otherwise, a partial failure could leave the two representations inconsistent.
Also, dual-writing is a temporary compatibility strategy, not a permanent architecture. It introduces additional consistency responsibilities and should have a clear removal plan.
Step C: Backfill existing records
Adding new columns does not automatically populate existing data.
For a small table, a simple update might work:
UPDATE users
SET
first_name = split_part(full_name, ' ', 1),
last_name = NULLIF(
substring(full_name FROM position(' ' IN full_name) + 1),
''
)
WHERE first_name IS NULL
AND full_name IS NOT NULL;However, this is only an illustrative parsing rule. It does not correctly model every possible human name.
For large production tables, avoid treating one massive update as the default solution.
Instead, use a resumable batch process:
BATCH_SIZE = 1000
def backfill_users(session):
while True:
users = (
session.query(User)
.filter(
User.first_name.is_(None),
User.full_name.isnot(None)
)
.order_by(User.id)
.limit(BATCH_SIZE)
.all()
)
if not users:
break
for user in users:
parts = user.full_name.strip().split(maxsplit=1)
user.first_name = parts[0] if parts else None
user.last_name = parts[1] if len(parts) > 1 else None
session.commit()This example demonstrates the batching idea. A production implementation should use bounded transactions, handle concurrent updates, record progress, and make retries safe.
For very large datasets, keyset-based batching or worker coordination can be more appropriate than repeatedly loading ORM objects.
The goal is to avoid one long-running transaction that creates unnecessary database pressure.
4. Why Large Database Migrations Need More Attention
A migration that takes milliseconds on a development database may behave very differently on a production table containing millions of records.
There are three important considerations.
A. Database locks
Some schema operations require locks that can interfere with application traffic.
For PostgreSQL, you can configure a lock timeout for the migration session:
SET lock_timeout = '5s';
SET statement_timeout = '60s';A lock timeout prevents a migration from waiting indefinitely to acquire a lock.
It does not make every migration non-blocking, and a failed migration still needs a deliberate retry or investigation strategy.
B. Index creation
Creating an index on a heavily used table can affect normal database operations.
PostgreSQL supports:
CREATE INDEX CONCURRENTLY idx_users_first_name
ON users(first_name);This allows normal writes to continue during index creation, although the operation takes longer and has additional operational considerations.
One important detail: CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
If you use Alembic, you can use an autocommit block:
from alembic import op
def upgrade():
with op.get_context().autocommit_block():
op.create_index(
"idx_users_first_name",
"users",
["first_name"],
postgresql_concurrently=True
)Review the migration runner's transaction behavior before deploying this operation.
C. Constraint validation
Suppose the new column must eventually become mandatory.
Instead of immediately adding a NOT NULL constraint to a large existing table, you can separate the process.
For PostgreSQL:
ALTER TABLE users
ADD CONSTRAINT users_first_name_not_null
CHECK (first_name IS NOT NULL) NOT VALID;Then validate it separately:
ALTER TABLE users
VALIDATE CONSTRAINT users_first_name_not_null;After validation and appropriate checks, the column's NOT NULL property can be applied.
The exact locking and execution behavior depends on the PostgreSQL version and the operation. Always verify the database documentation and test against production-like data volumes.
5. A Safer Deployment Sequence
Let's put everything together.
For our full_name to first_name and last_name change, the deployment could follow this sequence:
| Step | Database change | Application change |
|---|---|---|
| 1 | Add new nullable columns | No change |
| 2 | Keep old column | Deploy compatibility and dual-write logic |
| 3 | Backfill existing records | Continue supporting both representations |
| 4 | Verify data completeness | Switch reads to new columns |
| 5 | Keep old column temporarily | Remove old-column dependencies |
| 6 | Drop old column | Deploy final simplified model |
Notice that the database cleanup happens last.
There may be several deployments between the first and final migration. That is intentional.
A production deployment is not always about minimizing the number of releases. Sometimes, separating changes makes the system easier to operate and recover.
6. What About Rollbacks?
This is where expand-and-contract becomes particularly useful.
Imagine the new application version has a bug after deployment.
If the old column still exists and the new schema remains compatible with the previous application version, you can roll back the application without immediately reversing the database migration.
That is a much safer recovery path than trying to undo a destructive schema change during an incident.
However, rollback safety must be designed, not assumed.
Before removing the old column, consider:
- Are any old application instances still running?
- Are background workers still using the old schema?
- Are scheduled jobs or external integrations querying the old column?
- Has the new data been verified?
- Does the rollback plan still work after the read switch?
- Are backups and recovery procedures available?
One more important point: after the contract migration drops the old column, rolling back to code that depends on it is no longer safe without a database restoration or another recovery procedure.
That is why the contract phase should happen only after the compatibility window has genuinely ended.
7. A Practical Migration Checklist
Before deploying a schema change to a live system, review these questions:
- Can the currently running application version work with the expanded schema?
- Can the new application version work while old data still exists?
- Are existing records backfilled in manageable batches?
- Is the backfill safe to retry?
- Are dual-writes performed consistently?
- Have database locks and index-building behavior been considered?
- Are migration timeouts configured appropriately?
- Are background workers and scheduled jobs included in compatibility checks?
- Has the new data been validated before switching reads?
- Is the old schema retained until rollback dependencies have ended?
- Is the final destructive migration separated from the initial deployment?
If several answers are unclear, the migration probably needs more planning before it reaches production.
Conclusion
Database migrations are often treated as a database team's responsibility or simply another step in a deployment pipeline.
But schema evolution is also an application architecture problem.
Your API code, background workers, database schema, deployment strategy, and rollback procedure all depend on one another.
The expand-and-contract pattern helps separate these concerns into smaller, manageable changes. It does not guarantee zero downtime by itself, but it provides a practical way to preserve compatibility while an application evolves.
The next time a database migration passes successfully, don't ask only:
"Did the migration run?"
Ask:
"Can every version of my application that is still running safely work with this database schema?"
That is a much better definition of a production-ready migration.
Key Takeaways
- A successful migration does not guarantee a safe deployment.
- Rolling deployments can run multiple application versions against the same database.
- Additive schema changes are generally safer than immediate renames or deletions.
- Backfills should be bounded, observable, and safe to retry.
- PostgreSQL lock behavior and index creation need deliberate planning.
- Destructive schema changes belong in a later contract phase.
- Application rollback and database rollback are separate concerns.
Suggested Technologies
Python · FastAPI · PostgreSQL · SQLAlchemy · Alembic · Docker · CI/CD · Database Migrations · Backend Architecture · Production Reliability
References
- PostgreSQL documentation — ALTER TABLE
- PostgreSQL documentation — CREATE INDEX
- PostgreSQL documentation — Lock Timeout
- Zero-downtime migrations: Expand and Contract
The examples are illustrative. Validate SQL behavior, lock characteristics, migration transaction settings, and data transformation rules against your PostgreSQL version and application requirements before using them in production.

Join the conversation! Your thoughts help the community grow.