Changing a live database without downtime: expand and contract
How to change database tables while the site keeps running: add the new structure first, move the data across in batches, switch the code over, then remove the old parts.
- Topic
- Engineering
- Published
- Updated
- Reading time
- 10 min read
There is a defining milestone in every digital product's lifecycle where the naive luxuries of early software development vanish forever. In the first year of a startup, shipping a major database change is trivial: you write an ActiveRecord or Prisma migration, add a column, drop an obsolete table, deploy your web containers, and run migrate:latest during the release pipeline. If a query stalls or an exclusive lock holds for eight seconds, nobody notices because traffic is light.
Then your application reaches product-market fit. You have active enterprise customers processing transactions across three continents, background workers ingesting webhook events around the clock, and marketing campaigns driving thousands of concurrent sessions to your web application. Suddenly, running an unhedged ALTER TABLE statement on a table with eight million rows is an existential business risk. The database engine acquires an ACCESS EXCLUSIVE lock, incoming write queries queue up behind the schema modification, the connection pool saturates in less than six seconds, and your public web tier begins serving 502 Bad Gateway errors to visitors.
To avoid outages, engineering teams often resort to scheduled midnight maintenance windows, freezing deployments and displaying static error pages while senior engineers nervously monitor database consoles at 2:00 AM. But in a modern SaaS business or global eCommerce platform, there is no such thing as an acceptable maintenance window. A scheduled 30-minute outage erodes customer trust, damages SEO rankings, and halts revenue flow. Busy web applications have to change their database structure while people are using them, without taking the site offline.
Why Standard ORM Migrations and Maintenance Windows Break Down
The root cause of migration-induced downtime is an architectural mismatch between how modern application code deploys and how relational databases manage concurrency. When teams adopt continuous integration and continuous deployment (CI/CD) pipelines, application updates are rolled out gradually using rolling container replacements or canary clusters. During a deployment, which can take several minutes, two different versions of your application code are running concurrently in production: the old version (Version N) and the newly deployed version (Version N+1).
Standard ORM migration tools, such as TypeORM, Django Migrations, or Rails ActiveRecord, encourage a dangerous anti-pattern: coupling schema mutations directly to application releases. When an engineer renames a column from account_name to organization_name, the standard migration tool runs an immediate ALTER TABLE users RENAME COLUMN account_name TO organization_name;. The moment that single query executes, every running container of Version N immediately crashes with runtime SQL errors because it continues attempting to read and write the now-nonexistent account_name field.
Furthermore, standard ORM abstraction layers conceal the aggressive locking mechanics of relational database engines like PostgreSQL and MySQL. Adding a column with a dynamic default value on older database engines, validating a foreign key constraint synchronously, or running an index creation command without the CONCURRENTLY directive will request an exclusive table lock. When many reads and writes are happening, waiting for that exclusive lock builds a queue that can take the site down: even lightweight SELECT queries are blocked from executing until the lock resolves, creating cascading timeouts across your entire web architecture.
The Three-Phase Expand-and-Contract Architecture
To change the schema without downtime, replace all-in-one migrations with the Expand-and-Contract Pattern (also widely known as Parallel Run or the Transition Model). This architectural pattern decouples database structural changes from application code changes by introducing intermediate, backward-compatible states.
The expand-and-contract lifecycle operates across three distinct operational phases:
1. The Expansion Phase: You augment the database schema with new capabilities without altering, restricting, or deleting any existing tables, columns, or constraints. The new structure exists alongside the old structure. The database remains completely backward-compatible with the active Version N application code.
2. The Dual-Write and Transition Phase: The application code is upgraded to write data to both the old structure and the new structure simultaneously. Background worker jobs are deployed to backfill historical records from the old schema into the new schema in controlled, throttled batches. Once the backfill reaches 100% parity and data integrity is verified, read traffic is deterministically switched to the new structure.
3. The Contraction Phase: Once the old structure is no longer read from or written to by any running application container, the application removes all reference to the deprecated database objects. In the final release step, the obsolete columns, triggers, or tables are safely dropped from the database schema.
Decoupling Schema Evolution from Code Deployments in Five Discrete Steps
To execute the Expand-and-Contract architecture safely in a production CI/CD environment, every breaking schema change must be decomposed into five discrete, independently verifiable deployment steps. Never combine two steps into a single release:
// Step 2 Example: Application Dual-Writing in TypeScript / Prisma
async function updateUserProfile(userId: string, data: { name: string; orgName: string }) {
return await prisma.$transaction(async (tx) => {
// Write to both the legacy column (account_name) and the new column (organization_name)
return await tx.user.update({
where: { id: userId },
data: {
name: data.name,
account_name: data.orgName, // Legacy field maintained for Version N
organization_name: data.orgName // Expanded field for Version N+1
}
});
});
}
Step 1: Expand the Database Schema. Deploy a migration that adds the new column as nullable or with a constant default value. No application code depends on it yet. If this migration fails, you can roll it back straight away without affecting the application.
Step 2: Deploy Dual-Writing Application Code. Update application logic so that all write operations mutate both the old column and the new column. Reads still come from the old column, which is known to work. Older containers still running can write to the old column without issue.
Step 3: Asynchronously Backfill Historical Data. Execute a background ETL script that iterates over historical records and copies data from the old column to the new column. Because live writes are already captured by dual-writing, the backfill job only needs to update rows where the new column remains null.
Step 4: Switch Reads to the New Schema. Deploy application code that reads exclusively from the new column while maintaining writes to both columns. Monitor error rates and query latencies. If an unexpected bug arises, rolling back application code immediately returns reads to the legacy column without data loss.
Step 5: Contract the Database Schema. Deploy application code that stops writing to the legacy column. Once your monitoring shows that no queries use the old column any more, execute a final migration to drop the column or archive the table.
Safe Index Creation, Non-Blocking Constraints, and Batched Backfilling
Even when following the expand-and-contract lifecycle, poorly structured DDL commands can stall production web traffic by acquiring prolonged locks. In relational systems like PostgreSQL, you must enforce strict defensive DDL conventions.
1. Non-Blocking Index Creation: Never execute a raw CREATE INDEX on an active production table. Standard index creation acquires a SHARE lock that blocks all incoming INSERT, UPDATE, and DELETE operations until the entire index is built. In PostgreSQL, always use CREATE INDEX CONCURRENTLY. Concurrent index builds execute in two separate transactions without locking out writes.
-- Safe PostgreSQL Non-Blocking Index Creation
SET lock_timeout = '2s';
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_org_id_active
ON users (organization_id) WHERE is_active = TRUE;
2. Two-Step Foreign Key Validation: Adding a foreign key constraint synchronously forces PostgreSQL to scan the entire referenced table while holding an exclusive lock. Instead, add the constraint with NOT VALID, which validates only newly inserted rows, and then validate historical rows concurrently in a secondary command:
-- Step A: Add constraint instantly without table scan
ALTER TABLE orders ADD CONSTRAINT fk_orders_customer_id
FOREIGN KEY (customer_id) REFERENCES customers(id) NOT VALID;
-- Step B: Validate historical rows in the background without exclusive lock
ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer_id;
3. Throttled Batched Backfilling: When backfilling millions of rows, running UPDATE users SET organization_name = account_name; in a single transaction will lock millions of table rows, exhaust memory, and inflate write-ahead log (WAL) replication lag. Instead, execute backfills in explicit primary-key batches of 1,000 to 5,000 records with a mandatory sleep pause between batches (e.g., 50 milliseconds) to allow live web traffic to process without lock contention.
Dual-Writing and Deterministic Read-Switching Strategies
Choosing where to enforce dual-writing is a pivotal architectural decision. There are two primary techniques: Application-Level Dual-Writing and Database-Level Trigger Synchronization.
Application-Level Dual-Writing: This is the most transparent and debuggable pattern for modern full-stack web architectures. Your application ORM or query layer explicitly writes to both old and new columns inside a single database transaction. The primary advantage is visibility: software engineers can inspect dual-write behavior in application logs, write unit tests against migration logic, and easily implement feature flags to toggle read paths dynamically.
Database Trigger Synchronization: If multiple heterogeneous microservices write to the same database and coordinating simultaneous code releases is impractical, database triggers provide an alternative synchronization mechanism. You create a temporary BEFORE INSERT OR UPDATE trigger that automatically copies data from the old column to the new column at the storage layer. However, triggers introduce hidden side effects, increase database CPU overhead, and require specialized DBA oversight to prevent deadlocks under high concurrency.
For most SaaS applications and high-performance websites, Application-Level Dual-Writing governed by runtime feature flags is superior. A feature flag enables you to direct 5% of internal read requests to the new schema, inspect telemetry for query plan regressions, and incrementally scale to 100% of global traffic with deterministic safety.
Practical Production Checklist and Migration Decision Matrix
Before approving any pull request that alters production database schemas, run your engineering team through this operational decision matrix and execution checklist:
- Lock Timeout Guards: Every migration script must configure an explicit lock timeout (e.g.,
SET lock_timeout = '3s';). If the migration cannot acquire its necessary lock within three seconds, it must abort immediately rather than blocking incoming web traffic. - Nullability Defaults: Never add a new column with
NOT NULLconstraint without an established default or dual-write mechanism. Always add new columns as nullable first, backfill data, and applyNOT NULLconstraints in a subsequent release. - Concurrent Indexing: Confirm that all new indexes utilize
CONCURRENTLYin PostgreSQL orALGORITHM=INPLACE, LOCK=NONEin MySQL/InnoDB. - Idempotent Migration Scripts: Ensure all DDL statements include safety clauses (
IF NOT EXISTS,IF EXISTS) so that failed or interrupted deployments can be safely retried without manual intervention. - Rollback Runbook: Document the exact rollback procedure for each of the five deployment steps. If step 4 (read-switch) reveals unexpected latency, the team must know how to flip the feature flag back within 30 seconds.
Architectural Trade-offs, Rollback Realities, and Next Steps
Changing a database without downtime has real costs, and it is worth knowing them up front. Adopting the expand-and-contract pattern increases development friction: a schema change that previously took twenty minutes in a single pull request now requires multiple coordinated releases spanning several days.
Additionally, dual-writing temporarily increases database storage usage, write latency, and index overhead while both legacy and new structures coexist. For early prototypes with negligible traffic, full expand-and-contract cycles may represent unnecessary engineering overhead. However, once your web application crosses into serious commercial traffic, the business cost of a 15-minute outage dwarfs the engineering effort required to execute phased releases.
Begin by integrating automated DDL linters (such as squawk or strong_migrations) into your GitHub Actions CI pipeline. These tools flag risky operations, such as building an index without CONCURRENTLY, rewriting a whole table or adding a constraint that locks it, before the code is merged. Making these checks part of every deployment means your web architecture will scale gracefully from thousands to millions of users without ever requiring a maintenance window.
Written by Lay Shah, an independent developer building websites and tools for small businesses. Discuss a brief More articles