But note: We might want to have the ability to roll back from any state until we contract.
However, once we contract (remove old schema) we cannot go back without data loss, so we should be cautious.
We'll define:
Migration: A set of changes to the database schema and data that are atomic in terms of the application's view.
We'll have a migration table that tracks:
code
migration_id (unique for each migration)
name (human readable)
state (one of: PENDING, EXPANDED, MIGRATING, MIGRATED, SWITCHED, CONTRACTED, FAILED, ABORTED)
started_at, expanded_at, migrated_at, switched_at, contracted_at, failed_at, aborted_at
error_message (if any)
Steps:
PENDING: Migration is defined but not started.
EXPANDED: We have run the expand step (created new schema). At this point, the old schema is still in use.
MIGRATING: We are in the process of migrating data (backfilling). We might be doing this in batches.
MIGRATED: All data has been backfilled and we have done shadow reads (if needed) and are confident.
SWITCHED: The application has been switched to use the new schema for all operations.
CONTRACTED: The old schema has been removed.
FAILED: The migration failed at some point and we are in a failed state (might need manual intervention).
ABORTED: The migration was aborted (maybe due to auto-abort) and we have rolled back to the previous state.
However, note that after expanding, we might not be able to roll back the schema changes (like adding a column) without dropping it, which might be acceptable until we contract.
But what if we want to roll back the expand step? We can drop the new columns/tables. But if we have already written data to them, we lose that data.
So we must be cautious:
Until we switch, we can roll back the expand by dropping the new schema. But if we have written to the new schema, we lose that data.
Therefore, we should only allow rollback (auto-abort) if we haven't written to the new schema? Or we must have a way to recover?
Alternatively, we can design the framework to only allow rollback if we haven't switched and haven't written to the new schema? But how do we know?
Perhaps we should have two types of migrations:
code
- Additive (only adding new columns/tables) which are reversible by dropping them (but data loss).
- Data migrations (backfilling) which are not reversible in terms of data.
But note: the pattern is for additive changes first, then data migration, then removal.
So the expand step is additive and reversible until we contract? Actually, if we drop the new column, we lose the data that was written to it.
So we must decide:
Option 1: Do not allow rollback after we have written to the new schema (i.e., after the application has started writing to the new schema). But how do we track that?
Option 2: Allow rollback but with the understanding that we might lose data written to the new schema.
Since the pattern is for zero-downtime migrations, we might accept that we cannot rollback after the switch because the old schema might be gone.
Let's define:
Until we are in the EXPANDED state (meaning we have added the new schema but the application hasn't been changed to write to it), we can safely roll back by dropping the new schema.
Once we are in MIGRATING (or beyond), we have started writing to the new schema? Not necessarily: we might be only reading and backfilling.
Actually, in the expand step, we might change the application to write to both (dual writes) immediately? That depends on the migration.
We need to be more specific:
For a column addition:
code
Step 1 (Expand): Add the new column. The application code is updated to write to both the old and new column (if we are doing dual writes) or only to the new column?
Typically, in the expand step we only add the column and make the application write to both? Not necessarily: we might add the column and then in the migrate step we backfill and then switch reads.
Let's break down for a column addition:
code
Expand:
- Add new column (nullable, or with default) so that we can write to it without breaking old code.
- Update application to write to both old and new column (dual writes) for a transition period?
OR
only write to the old column and then backfill to the new column?
But if we only write to the old column, then the new column will be empty until we backfill. Then when we switch reads to the new column, we have the old data? Not until backfill.
So:
Option A (dual writes from the start):
- Expand: add column, update code to write to both.
- Then, backfill the old column to the new column (for existing rows) and then switch reads to the new column.
Option B (only write to old, then backfill and switch writes too):
- Expand: add column, but code still only writes to old.
- Then backfill from old to new.
- Then switch reads to new (and then switch writes to new, and then remove old).
But note: the pattern says "expand" (add new) and then "migrate" (backfill and switch) and then "contract".
We'll design a framework that can handle both, but we need to define the steps for a given migration.
We'll let each migration define:
code
- A set of SQL statements for each step (expand, migrate, contract).
- Possibly, a way to verify the migration (shadow reads, data checks).
And the framework will:
code
- Run the expand step, then mark as EXPANDED.
- Then run the migrate step (which might be a long-running batch job). We might break the migrate step into multiple batches and track progress.
- Then run the switch step (which might be a code change, not a SQL step). But we can have a step that marks the switch (maybe a config change in the app).
- Then run the contract step.
But the switch step might be external (deployment of new code). So we need a way to coordinate.
Alternatively, we can have:
code
- The migration framework only handles database changes and data backfill.
- The switch is a separate process (like updating a feature flag) that the framework does not control.
However, for auto-abort, we want to monitor the migration and if something goes wrong, we want to roll back.
Let's define the steps that the framework controls:
code
1. Expand: Run SQL to add new schema.
2. Migrate: Run a data backfill (could be multiple batches). We might have a way to pause and resume.
3. Verify: Run checks to ensure data consistency (shadow reads, checksums, etc.). This might be part of the migrate step or separate.
4. Switch: This is the point where we mark that the application is now using the new schema. We might do this by setting a flag in the database (like a version) or by deploying code. The framework might not do the code deployment, but it can wait for a signal (like a table update) that the switch has occurred.
5. Contract: Run SQL to remove old schema.
We can make the switch step a manual step (or automated via deployment) and then the framework waits for a signal (e.g., a row in a migration_control table) that the switch has been done.
Alternatively, we can have the framework do:
code
- Expand: SQL
- Migrate: SQL (backfill) and then set a flag in the database to indicate that the new schema is ready for reads.
- Then, we wait for the application to be deployed (which will start using the new schema for reads and writes). We might have a way to detect that (e.g., by checking a log, or by having the application set a flag when it starts using the new schema).
- Then, once we detect that the application is using the new schema, we run the contract step.
But note: the application might be using the new schema for reads but still writing to the old? That would be a problem.
So we need to ensure that the application writes to the new schema after the switch.
We can have:
code
Step 1: Expand (add new column, and update the application to write to both old and new?).
But if we update the application to write to both, then we have dual writes from the moment we deploy the new code (which might be after expand, or at the same time).
Alternatively, we can do:
- Expand: add column, but do not change the application code (so it still writes only to old).
- Then, deploy a new version of the application that writes to both (dual writes). At this point, we are in the "migrate" phase: we have dual writes, and we backfill the old data to the new column.
- Then, when backfill is done, we switch the reads to the new column (by changing the application code again, or by a config flag) and then eventually remove the old column.
This is more complex because it involves multiple deployments.
Given the complexity, we design the framework to be flexible and let the migration define the exact steps.
We'll have:
code
Migration:
id: string
name: string
expand_sql: string (or list of strings) # to be run to expand
migrate_sql: string (or list) # to backfill data (if any)
contract_sql: string (or list) # to remove old schema
# optional: verify_sql? or a script to run checks?
But the switch is not in the SQL. It might be:
code
- A deployment that changes the application to use the new schema.
We can have a table migration_switch that the application checks to see which schema to use.
Example for a column addition:
code
Table: users
id, name, email (old), email_new (new)
Steps:
1. Expand:
ALTER TABLE users ADD COLUMN email_new VARCHAR(255);
2. Deploy code that writes to both email and email_new (dual writes). But we haven't changed the reads yet.
3. Migrate:
UPDATE users SET email_new = email WHERE email_new IS NULL;
4. Then, we need to switch the reads: change the application to read from email_new. This could be done by:
- Changing the code to use email_new instead of email.
- Or, we can have a view that selects email_new if not null, else email. Then we change the view.
5. Then, after we are confident, we change the code to write only to email_new (and remove the dual write). Then we can contract.
6. Contract:
ALTER TABLE users DROP COLUMN email;
But note: step 4 and 5 are code changes, not database changes.
We can have the framework manage the database part and then have a manual step for the code change? But we want auto-abort.
Alternatively, we can have the framework manage a flag in the database that the application checks to decide which column to use.
Example:
code
Create a table: migration_flags
migration_name VARCHAR(255) PRIMARY KEY,
flag ENUM('EXPANDED', 'MIGRATED', 'SWITCHED', 'CONTRACTED')
Then:
After expand: set flag to 'EXPANDED'.
After migrate: set flag to 'MIGRATED'.
Then, we deploy code that checks the flag: if flag is 'MIGRATED', then read from email_new, else read from email.
Also, the code might write to both until the flag is 'SWITCHED', then write only to email_new.
Then, after we are confident, we set the flag to 'SWITCHED' (via the framework? or manually?).
Then, we contract: remove old column and set flag to 'CONTRACTED'.
But the framework should be able to set the flag at the appropriate times.
We can have:
code
Each migration has:
expand:
- run expand_sql
- set migration_flags.flag = 'EXPANDED'
migrate:
- run migrate_sql
- set migration_flags.flag = 'MIGRATED'
switch:
- This step is not in the framework? Because the application must be deployed to respect the flag.
contract:
- run contract_sql
- set migration_flags.flag = 'CONTRACTED'
But the switch step is the point at which the application starts using the new schema. We can have the framework wait until the application sets a different flag? Or we can have the framework set the flag to 'SWITCHED' only after we have verified that the application is using the new schema.
Alternatively, we can have the application set the flag when it has switched? But then the framework would be reacting to the application.
Let's change:
code
The framework sets the flag to 'MIGRATED' after the backfill.
Then, we have a separate process (or the framework) that waits for the application to be deployed and then sets the flag to 'SWITCHED'. But how does the framework know the application is deployed?
We might not want the framework to control the application deployment. So we can have:
code
- The framework runs until the backfill is done and sets the flag to 'MIGRATED'.
- Then, a human (or an automated deployment) deploys the new code that uses the new schema (reads and writes) and then sets the flag to 'SWITCHED' (via an API call to the framework?).
- Then, the framework runs the contract step.
But then the framework is not fully automated.
Alternatively, we can have the framework do:
code
After backfill, it sets the flag to 'MIGRATED' and then waits for a condition:
Condition: All application instances have been restarted with the new code? We can have the application register its version in a table.
This is getting complex.
Let's simplify:
We design the framework to handle the database changes and the data backfill, and then we have a manual step for the code switch? But we want auto-abort.
We can have:
code
The framework runs the expand and migrate steps, and then it runs a verification step (shadow reads) to ensure data consistency.
Then, it sets the flag to 'READY_FOR_SWITCH'.
Then, we have an external process (like a deployment script) that:
- Deploys the new code (which reads from the new schema and writes to both? or only to new?).
- Then, after deployment, it sets the flag to 'SWITCHED' (via the framework's API).
Then, the framework, upon seeing the flag 'SWITCHED', runs the contract step.
But what if the deployment fails? We don't set the flag, and the framework will not contract.
And if we want auto-abort, we might want to roll back if the verification fails.
So:
code
Steps in the framework:
1. Expand: run expand_sql, set state to EXPANDED.
2. Migrate: run migrate_sql (backfill), set state to MIGRATED.
3. Verify: run checks (maybe shadow reads). If checks fail, set state to FAILED and abort (roll back the migrate step? and expand step?).
4. Wait for switch: we wait until the flag is set to 'SWITCHED' by an external process (or until a timeout?).
5. Contract: run contract_sql, set state to CONTRACTED.
But how do we roll back?
We need to store the SQL to roll back each step? Or we have a separate set of SQL for rollback?
Alternatively, we can have:
code
expand_sql and expand_rollback_sql
migrate_sql and migrate_rollback_sql
contract_sql and contract_rollback_sql
Then, if we fail at any step, we can roll back the steps that were done, in reverse order.
Example:
code
If we fail during migrate, we rollback migrate (if possible) and then rollback expand.
But note: the migrate step might be a long-running batch update. We might not be able to rollback an update easily (unless we have a log of changes).
So we might not be able to rollback the migrate step if it's a data update that is not reversible.
Therefore, we must design the migrate step to be idempotent and safe to run again? And then if we fail, we can retry? But we want to abort if we detect inconsistency.
Alternatively, we can do:
code
The migrate step should be done in a way that it can be rolled back by restoring from backup? That's heavy.
Given the complexity, we might accept that the migrate step (data backfill) is not reversible and if we fail, we have to manually fix.
But the requirement says auto-abort. So we want to detect failure early and stop.
We can design:
code
The migrate step is broken into small batches, and after each batch we run a verification.
If a batch fails verification, we stop and set state to FAILED.
Then, we can roll back the last batch? But the previous batches are already applied.
Alternatively, we can do the backfill in a new table and then swap? That's more complex.
Given the time, let's assume:
code
The framework will:
- Run the expand step (which is reversible by running the expand_rollback_sql).
- Then, run the migrate step in a single transaction? But if the table is big, we cannot.
We might break the migrate step into multiple transactions (batches) and have a way to resume.
But if we fail in the middle of migrate, we have partially migrated data.
We can have:
migrate_sql is actually a stored procedure that does the backfill in a transactional way (if possible) or in batches and records progress.
We'll have a table `migration_progress` that tracks the current batch for each migration.
Then, if we fail, we can either:
- Retry the migration (which will skip already migrated rows) if the migrate_sql is idempotent.
- Or, we can roll back the entire migrate step if we have a way to undo? But we don't.
So we design the migrate step to be idempotent: we update only rows that haven't been migrated (by checking a flag, or by using a condition).
Example:
UPDATE users SET email_new = email WHERE email_new IS NULL;
This is idempotent: running it again will not change anything.
Then, if we fail, we can retry from the beginning? But that might be inefficient.
We can break it into batches by id:
UPDATE users SET email_new = email WHERE id BETWEEN ? AND ? AND email_new IS NULL;
And we record the last id we processed.
Then, if we fail, we can resume from the last successful batch.
But if we want to abort, we might want to roll back the entire migrate? We can't without a backup.
So we might accept that if we fail during migrate, we have to manually clean up and then restart the migration.
But the requirement is auto-abort: meaning if something goes wrong, we stop and roll back to the previous state (which is expanded, with no data migrated).
To achieve that, we must not have written any data to the new column until we are sure we can complete the entire migration?
That is not feasible for large tables.
Given the real-world constraints, we might have to accept that the migrate step is not fully reversible and we rely on idempotency and the ability to resume.
But then, what does auto-abort mean?
It might mean that if the verification after a batch fails, we stop and set the state to FAILED, and then we do not proceed to switch.
And then we might need to manually clean up.
Alternatively, we can design the migration to use a shadow table:
code
Step 1: Create a new table with the new schema.
Step 2: Migrate data from old table to new table (in batches, with verification).
Step 3: Switch the application to use the new table (by changing the code to point to the new table, or by renaming tables).
Step 4: Drop the old table.
This is more reversible because we can switch back to the old table if we keep it until we are sure.
But the requirement says "expand→migrate→contract", which might be for column changes, but we can also apply to table changes.
expand: create new table (with the new schema)
migrate: backfill data from old table to new table (idempotent, using a progress table)
contract: drop old table
But for table, the switch might be:
code
Rename old table to backup, rename new table to the old table's name? Or change the application to use the new table.
We can have:
code
expand: create new table (with a different name, or with a suffix)
migrate: copy data from old table to new table (in batches, with checksums to verify)
switch: rename tables? or change the application's configuration to point to the new table.
contract: drop the old table.
But if we rename tables, we can do:
code
Step 1: create new_table (like users_new)
Step 2: backfill users -> users_new
Step 3: rename users to users_old, users_new to users
Step 4: after a while, drop users_old.
This is a common pattern.
Then, the switch is a runtime operation (rename) that is quick.
And we can roll back by renaming back if we notice a problem? But that would require keeping the old table.
So:
code
expand: create new table (users_new)
migrate: backfill users -> users_new (in batches, with verification after each batch)
switch: rename users to users_old, users_new to users (this is atomic)
contract: after a safe period, drop users_old.
And if we need to abort after the switch, we can rename back? But then we have to stop the application.
Given the requirement of auto-abort, we might want to detect issues before the switch.
So we do:
code
expand: create new table.
migrate: backfill with verification after each batch. If a batch fails, we stop and set state to FAILED.
Then, when all batches are done, we run a final verification (checksum on entire table?).
If final verification passes, we set state to READY_FOR_SWITCH.
Then, we run the switch (rename) and set state to SWITCHED.
Then, after a period, we run the contract (drop old table).
And if at any point we fail, we set state to FAILED and we do not proceed.
And we can have a rollback for expand (drop the new table) and for migrate (truncate the new table) if we are before the switch.
But after the switch, we cannot rollback because the old table is renamed and the application is using the new table (which is the old table's name). We can rollback by renaming back, but that would require downtime? Not necessarily if we do it quickly.
However, the pattern is for zero-downtime, so we want to avoid downtime.
So we design:
code
Until we do the switch, we can roll back by dropping the new table (if expand and migrate haven't written to the old table? they haven't).
After the switch, we can roll back by renaming back? But we have to stop the application from writing during the rename? Actually, the rename is atomic, so if we do:
rename users to users_old, users_new to users
then, if we want to rollback:
rename users to users_new, users_old to users
But during the rollback rename, the application might be writing to the current users table (which is the new one). So we would lose those writes?
So after the switch, we are committed.
Therefore, we must be very sure before the switch.
Hence, the verification steps are critical.
Now, for shadow reads: during the migrate step, we might want to read from both tables and compare.
We can have a shadow read query that reads from both and returns differences.
The framework can run such a query periodically during the backfill to ensure consistency.
Now, let's design the tables:
code
We'll have a table `migrations`:
id: primary key
name: string (unique)
type: 'column' or 'table'
state: enum('PENDING', 'EXPANDED', 'MIGRATING', 'MIGRATED', 'READY_FOR_SWITCH', 'SWITCHED', 'CONTRACTED', 'FAILED', 'ABORTED')
started_at, expanded_at, migrating_at, migrated_at, ready_at, switched_at, contracted_at, failed_at, aborted_at
error_message: text
And a table `migration_progress` for tracking batch progress (for table migrations):
migration_id (foreign key to migrations.id)
batch_id: integer (or we can use the last primary key id we processed)
last_processed_id: bigint (for the old table's primary key)
total_rows: bigint (optional, for progress)
created_at, updated_at
And a table `migration_flags` (if we use the flag approach for column migrations):
migration_name: string (foreign key to migrations.name)
flag: enum('EXPANDED', 'MIGRATED', 'SWITCHED', 'CONTRACTED')
But we might not need the migration_flags table if we use the state in the migrations table.
However, the application might need to know which column to use without querying the migrations table? We can have a separate table for flags that the application can read.
Alternatively, we can have the framework update a configuration table that the application reads.
We'll design:
code
The framework will:
- For a column migration:
1. Run expand_sql (add column)
2. Update state to EXPANDED.
3. Run migrate_sql (backfill) in batches, updating a progress table.
4. After each batch, run a verification (shadow reads: compare old and new column for a sample?).
5. If all batches done and verification passes, set state to MIGRATED.
6. Then, wait for the switch: we don't do the switch in the framework, but we can have a step that sets a flag in the migration_flags table to 'MIGRATED' (which we already did by setting state?).
7. Then, we wait for an external signal (like an API call) that the switch has been done. When we get that signal, we set state to SWITCHED.
8. Then, we run the contract_sql (drop column) and set state to CONTRACTED.
But note: the application must be updated to read from the new column only after the state is MIGRATED? We can have the application check the state in the migrations table? That might be heavy.
Alternatively, we can have a separate table `active_schema` that the application reads to know which column to use.
We can have:
Table: active_schema
table_name: string
column_name: string (the current active column for that table)
Then, during expand, we add the new column and set active_schema.column_name to the old column? Then during migrate, we set it to the new column? But then the application would switch at that point.
We want the application to switch only after we backfill and verify.
So:
After expand: active_schema.column_name = old_column (unchanged)
After migrate and verify: active_schema.column_name = new_column
Then the application will start reading from the new column.
And then after contract, we remove the old column and remove the active_schema entry? Or leave it.
But then the switch is done by the framework by updating active_schema.
And the application must be coded to check active_schema for each column? That might be too dynamic.
Alternatively, we can have a feature flag per migration.
Given the complexity, let's stick to:
The framework does not control the application's read/write path. It only sets the state in the migrations table.
The application is deployed in multiple stages:
Stage 1: Deploy code that writes to both old and new (dual writes) but reads from old. (This happens after expand, before migrate? Or during migrate?)
Stage 2: After migrate (backfill) and verification, we deploy code that reads from new (and still writes to both?).
Stage 3: After switch, we deploy code that writes only to new.
But then the framework must coordinate with the deployments.
We might need to accept that the framework only handles the database part and the verification, and then the deployments are separate.
Given the time, I'll design a framework that:
code
1. Manages the state of migrations in a `migrations` table.
2. Provides an API to run the steps (expand, migrate, contract) and to verify.
3. For column migrations, we assume the application will be deployed separately to change the read/write behavior, and the framework will set the state to MIGRATED when the backfill is done and verified, and then wait for an external signal (like a manual API call) to set the state to SWITCHED (meaning the application has been deployed to use the new column). Then the framework will run the contract.
4. For table migrations, we do the switch by renaming tables (which is a database operation) and then set the state to SWITCHED. Then after a period, we contract.
But then for table migrations, the switch is done by the framework, so we don't need an external signal.
We can have:
code
For table migrations:
expand: create new table (with a name like table_name_new)
migrate: backfill from old table to new table (in batches, with verification)
switch: rename old table to table_name_old, new table to table_name (atomic)
contract: drop table_name_old
And for column migrations:
expand: add column
migrate: backfill column (idempotent update)
switch: (external) we wait for the application to be deployed to use the new column. We don't do anything in the database for switch? Or we can set a flag in a table that the application checks? But the application might not check the flag until it is restarted.
We can have a table `migration_switch_flags`:
migration_name: string
switch_flag: boolean (default false)
Then, after migrate, we set switch_flag to true. The application, upon restart (or periodically) checks this flag and if true, it switches to the new column.
Then, after a while, we set the state to SWITCHED (when we see that the application has switched? or we just assume after a timeout?).
Then, we contract.
This is getting very complex.
Given the scope, let's simplify:
code
We design two types of migrations:
Type 1: Table migration (with table rename for switch)
Type 2: Column migration (with application-managed switch)
And for column migration, the switch is not done by the framework. The framework only does:
expand: add column
migrate: backfill
then set state to MIGRATED.
Then, we wait for an external signal (like an API call) that the application has been deployed and is using the new column. Then we set state to SWITCHED and then contract.
But how does the framework know that the application is using the new column? We can have the application set a flag in the database when it starts using the new column? Or we can have a health check that the framework runs to verify that new writes are going to the new column.
We can have a verification step after we set the state to MIGRATED:
code
We wait for a while and then check:
- Are there any new rows written to the old column? If yes, then the application hasn't switched.
We can have a trigger on the old table that logs if a write happens? Or we can check the recent rows.
But if we have dual writes, then both columns are being written. We want to see that the old column is not being written anymore.
We can have:
We set a time T. After T, we check the old column for any updates (or inserts) that happened after we set the state to MIGRATED.
If we find any, then the application hasn't switched. We can keep waiting.
But if we wait too long, we might time out.
Alternatively, we can have the application set a flag in the migration_switch_flags table when it starts using the new column.
Then, the framework can wait for that flag.
We'll design:
code
For column migrations:
expand: add column, set state to EXPANDED.
migrate: backfill, set state to MIGRATED.
Then, we wait for the application to set the flag in `migration_switch_flags` for this migration to true.
When we see the flag, we set state to SWITCHED and then run contract.
But what if the application never sets the flag? We can have a timeout and then fail.
Now, let's write the SQL for the tables:
code
Table: migrations
id: bigint primary key auto_increment
name: varchar(255) unique not null
type: enum('table', 'column') not null
state: enum('PENDING','EXPANDED','MIGRATING','MIGRATED','READY_FOR_SWITCH','SWITCHED','CONTRACTED','FAILED','ABORTED') not null
started_at: datetime
expanded_at: datetime
migrating_at: datetime
migrated_at: datetime
ready_at: datetime
switched_at: datetime
contracted_at: datetime
failed_at: datetime
aborted_at: datetime
error_message: text
Table: migration_progress (for table migrations, and also for column migrations if we do batches? we might not need for column)
id: bigint primary key auto_increment
migration_id: bigint not null (foreign key to migrations.id)
batch_number: int not null
last_processed_id: bigint (for the old table's primary key) -- for table migration, we track the last id we processed in the old table.
rows_processed: int
created_at: datetime
updated_at: datetime
We might also have a table for column migration progress? We can use the same table, but for column we might track the last id of the table we updated.
Table: migration_switch_flags (for column migrations, but we can also use for table? not needed for table because switch is done by the framework)
migration_name: varchar(255) primary key (foreign key to migrations.name)
switch_flag: boolean default false
updated_at: datetime
Steps for table migration:
code
1. Create the migration record with state PENDING.
2. Run the expand_sql (which creates the new table). Then set state to EXPANDED.
3. Run the migrate_sql in batches. For each batch, update the migration_progress table.
- We might have a stored procedure that does:
WHILE (there are more rows) DO
UPDATE ... WHERE id > last_processed_id AND id <= last_processed_id + batch_size;
record progress.
END WHILE
- After each batch, run a verification (like count of rows in new table vs old table, or checksum on a sample).
- If verification fails, set state to FAILED and stop.
4. When all batches are done, set state to MIGRATED.
5. Then, run the switch:
RENAME TABLE old_table TO old_table_old, new_table TO old_table;
This is atomic.
Then set state to SWITCHED.
6. Wait for a safe period (maybe a few days) and then run the contract_sql (DROP TABLE old_table_old) and set state to CONTRACTED.
Steps for column migration:
code
1. Create the migration record with state PENDING.
2. Run the expand_sql (add column). Then set state to EXPANDED.
3. Run the migrate_sql (backfill) in batches if needed. For a column, we might do:
UPDATE table SET new_column = old_column WHERE new_column IS NULL LIMIT batch_size;
and track the last id? But there might not be an id. We can use a condition on the old_column? Or we can do without batching if the table is not too big.
We'll assume we do batching by primary key if available.
4. After each batch, verify: for a sample of rows, check that new_column equals old_column.
5. When done, set state to MIGRATED.
6. Then, we wait for the application to set the switch_flag in migration_switch_flags for this migration.
We can poll the flag every few seconds.
7. When the flag is set, we set state to SWITCHED.
8. Then, run the contract_sql (drop the old column) and set state to CONTRACTED.
Auto-abort:
code
If at any point a step fails (SQL error, or verification fails), we set the state to FAILED.
We also need a way to rollback:
For table migration:
If we fail during expand, we drop the new table (if created) and set state to ABORTED.
If we fail during migrate (before switch), we can drop the new table (if we haven't switched) and set state to ABORTED.
If we fail after switch, we cannot rollback automatically? We might have to rename back? But that would require downtime.
So we might not allow failure after switch? Or we have a manual process.
For column migration:
If we fail during expand, we drop the new column (if added) and set state to ABORTED.
If we fail during migrate, we can leave the new column partially filled? Then we might want to drop the column? But we might have written some data.
We can decide: if we fail during migrate, we rollback by dropping the new column? But then we lose the data that was backfilled.
Alternatively, we can leave it and let the user decide.
Given the complexity, we might not provide automatic rollback for the migrate step (because it's a data migration and might be irreversible). Instead, we stop and let the user decide.
But the requirement says auto-abort, meaning we stop the migration and don't proceed to the next step.
We can have:
When we fail, we set state to FAILED and we do not proceed.
And we provide a way to reset the migration (which would delete the migration record and drop the new schema if it exists) for a fresh start.
We'll design:
code
The framework will:
- For each migration, run the steps in order.
- If a step fails, set state to FAILED and stop.
- Provide an API to abort a migration (which would set state to ABORTED and try to rollback the last step? or all steps?).
We can have:
abort_migration(migration_id):
if state is EXPANDED: rollback expand (run expand_rollback_sql) and set state to ABORTED.
if state is MIGRATING or MIGRATED:
We cannot easily rollback the migrate step? We can truncate the new table (for table migration) or set the new column to NULL? But that would lose data.
So we might not rollback the migrate step. Instead, we set state to ABORTED and leave the new schema as is? Then the user can decide.
Alternatively, we can have the migrate step be done in a transaction? But for large tables, we cannot.
Given the trade-offs, we decide:
The framework will only auto-rollback the expand step (if we are before migrate). Once we start migrate, we cannot rollback automatically.
And for column migration, we might not be able to rollback the migrate step either.
So:
Abort:
If state is PENDING or EXPANDED: rollback expand (if expanded) and set state to ABORTED.
If state is MIGRATING or MIGRATED: set state to ABORTED and do nothing else (the new schema remains).
If state is READY_FOR_SWITCH or SWITCHED: we cannot abort easily? We might have to switch back? That's dangerous.
So we might not allow abort after READY_FOR_SWITCH.
This is a very complex design.
Given the time, I'll outline the framework API:
code
class MigrationFramework:
def create_migration(name, type, expand_sql, migrate_sql, contract_sql, expand_rollback_sql=None, migrate_rollback_sql=None, contract_rollback_sql=None):
# create a migration record with state PENDING
def expand(migration_id):
# run expand_sql
# set state to EXPANDED
def migrate(migration_id):
# run migrate_sql in batches (if table migration) or in one go (if column and small)
# after each batch, run verification (optional, but recommended)
# if any batch fails, set state to FAILED
# if all batches succeed, set state to MIGRATED
def wait_for_switch(migration_id, timeout=None):
# for column migrations: wait until the switch_flag is set in migration_switch_flags
# for table migrations: we don't wait, because switch is done by the framework in the switch step.
def switch(migration_id):
# for table migrations: run the switch (rename tables) and set state to SWITCHED.
# for column migrations: this step is not needed because the switch is done by the application.
def contract(migration_id):
# run contract_sql
# set state to CONTRACTED
def abort(migration_id):
# if state is EXPANDED: rollback expand (if expand_rollback_sql provided) and set state to ABORTED.
# if state is MIGRATING or MIGRATED: set state to ABORTED (and leave the new schema as is? or try to rollback migrate? We might not have a safe way.)
# if state is READY_FOR_SWITCH or SWITCHED: we might not allow abort? Or we try to switch back? Not recommended.
def verify(migration_id):
# run shadow reads and data checks to ensure consistency.
And we have a background process that runs the migrate in batches and updates the progress.
This is a very high-level design.
Given the complexity and the fact that every migration is different, we might want to make the framework more declarative and let the user define the steps and the rollback steps.
But we have provided a basic structure.
Let me know if you have any questions or if you want to adjust the design.
I'll design a comprehensive database migration framework with the requested features. This framework follows industry best practices for zero-downtime migrations.
// Pseudocode for the migration controller
class MigrationController {
async executeMigration(migration) {
const state = this.getState(migration);
switch(state) {
case 'PENDING':
await this.expand(migration);
await this.updateState(migration, 'EXPANDED');
case 'EXPANDED':
await this.migrate(migration);
await this.updateState(migration, 'MIGRATED');
case 'MIGRATED':
await this.verifyShadowReads(migration);
await this.updateState(migration, 'READY_FOR_SWITCH');
// Manual or automated switch point
case 'READY_FOR_SWITCH':
await this.waitForSwitchSignal(migration);
await this.updateState(migration, 'SWITCHED');
case 'SWITCHED':
await this.contract(migration);
await this.updateState(migration, 'CONTRACTED');
}
}
async expand(migration) {
// 1. Create new schema objects (tables, columns, indexes)
// 2. Add triggers for dual-write if needed
// 3. Update connection pool to use new schema for writes
// 4. Run DDL in transaction where possible
}
async migrate(migration) {
// 1. Backfill data in batches
// 2. Track progress in migration_progress
// 3. Run verification after each batch
// 4. Auto-abort on verification failure
}
async verifyShadowReads(migration) {
// 1. Read from both old and new schemas
// 2. Compare results (checksums, row counts, sample data)
// 3. Log discrepancies
// 4. Auto-abort if variance exceeds threshold
}
}
3. Shadow Read Implementation
sql
-- Shadow read view pattern (for column additions)
CREATE OR REPLACE VIEW users_shadow AS
SELECT
id,
name,
COALESCE(new_email, email) as email, -- Switch point
CASE
WHEN new_email IS NOT NULL THEN 'NEW'
ELSE 'OLD'
END as source_schema,
created_at,
updated_at
FROM users
LEFT JOIN users_new ON users.id = users_new.id;
-- Shadow read function (for complex comparisons)
CREATE OR REPLACE FUNCTION verify_migration(
table_name TEXT,
batch_size INT DEFAULT 1000
) RETURNS TABLE (
old_count BIGINT,
new_count BIGINT,
mismatch_count BIGINT,
sample_mismatch JSONB
) AS $$
DECLARE
old_checksum TEXT;
new_checksum TEXT;
BEGIN
-- Get counts
EXECUTE format('SELECT COUNT(*) FROM %I', table_name) INTO old_count;
EXECUTE format('SELECT COUNT(*) FROM %I_new', table_name) INTO new_count;
-- Get checksums for random sample
EXECUTE format(
'SELECT md5(array_agg(t::text)::text)
FROM (SELECT * FROM %I ORDER BY random() LIMIT %s) t',
table_name, batch_size
) INTO old_checksum;
EXECUTE format(
'SELECT md5(array_agg(t::text)::text)
FROM (SELECT * FROM %I_new ORDER BY random() LIMIT %s) t',
table_name, batch_size
) INTO new_checksum;
mismatch_count := CASE
WHEN old_checksum = new_checksum THEN 0
ELSE 1
END;
sample_mismatch := jsonb_build_object(
'old_checksum', old_checksum,
'new_checksum', new_checksum,
'batch_size', batch_size
);
RETURN QUERY;
END;
$$ LANGUAGE plpgsql;
-- Trigger for dual-write during expansion phase
CREATE OR REPLACE FUNCTION dual_write_trigger()
RETURNS TRIGGER AS $$
BEGIN
-- Write to both old and new schemas
IF (TG_OP = 'INSERT') THEN
INSERT INTO users_new SELECT NEW.*;
RETURN NEW;
ELSIF (TG_OP = 'UPDATE') THEN
UPDATE users_new
SET name = NEW.name,
email = NEW.email,
updated_at = NOW()
WHERE id = NEW.id;
RETURN NEW;
ELSIF (TG_OP = 'DELETE') THEN
DELETE FROM users_new WHERE id = OLD.id;
RETURN OLD;
END IF;
END;
$$ LANGUAGE plpgsql;
-- Enable dual-write
CREATE TRIGGER users_dual_write
BEFORE INSERT OR UPDATE OR DELETE ON users
FOR EACH ROW EXECUTE FUNCTION dual_write_trigger();
6. Connection Routing for Shadow Reads
python
class SmartConnectionRouter:
def __init__(self, migration_state):
self.migration_state = migration_state
self.read_strategy = self.determine_strategy()
def determine_strategy(self):
"""Determine which schema to read from based on migration state"""
state = self.migration_state.current_state
strategies = {
'EXPANDED': 'read_old_write_both',
'MIGRATING': 'shadow_reads', # Read both, compare
'MIGRATED': 'read_new_write_both',
'SWITCHED': 'read_new_write_new',
'CONTRACTING': 'read_new_write_new'
}
return strategies.get(state, 'read_old_write_old')
def get_connection(self, query_type='read'):
"""Route connection based on query type and migration state"""
if query_type == 'read':
if self.read_strategy == 'shadow_reads':
return self.get_shadow_connections()
elif 'new' in self.read_strategy:
return self.new_schema_connection
return self.old_schema_connection
7. Batch Migration with Checkpointing
sql
-- Batch processing with id ranges
DO $$
DECLARE
batch_size INT := 10000;
last_max_id BIGINT := 0;
min_id BIGINT;
max_id BIGINT;
BEGIN
LOOP
SELECT MIN(id), MAX(id)
INTO min_id, max_id
FROM users
WHERE id > last_max_id
AND id <= last_max_id + batch_size;
EXIT WHEN min_id IS NULL;
-- Migrate batch
INSERT INTO users_new (id, name, email, created_at)
SELECT id, name, email, created_at
FROM users
WHERE id BETWEEN min_id AND max_id
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name,
email = EXCLUDED.email;
-- Verify batch
PERFORM verify_batch('users', min_id, max_id);
-- Update progress
INSERT INTO migration_progress
(migration_id, table_name, batch_number, last_processed_id, rows_processed)
VALUES
(123, 'users', batch_number, max_id, (max_id - min_id) + 1);
last_max_id := max_id;
batch_number := batch_number + 1;
END LOOP;
END $$;
-- Point-in-time rollback using pg_rewind for PostgreSQL
-- Or use logical replication for other databases
-- Save state before migration
CREATE TABLE migration_rollback_state AS
SELECT
'users' as table_name,
pg_size_pretty(pg_total_relation_size('users')) as size,
(xpath('//row/text()', query_to_xml('SELECT COUNT(*) FROM users', false, true, '')))[1]::text as row_count
FROM pg_class
WHERE relname = 'users';
-- Rollback procedure
CREATE OR REPLACE PROCEDURE rollback_migration(migration_id BIGINT)
LANGUAGE plpgsql AS $$
DECLARE
rollback_sql TEXT;
BEGIN
SELECT rollback_sql INTO rollback_sql
FROM schema_migrations
WHERE id = migration_id
AND state IN ('MIGRATING', 'MIGRATED', 'READY_FOR_SWITCH');
IF rollback_sql IS NULL THEN
RAISE EXCEPTION 'No rollback available for state';
END IF;
-- Execute rollback in transaction
BEGIN
EXECUTE rollback_sql;
UPDATE schema_migrations
SET state = 'ABORTED',
aborted_at = NOW(),
error_message = 'User initiated rollback'
WHERE id = migration_id;
EXCEPTION
WHEN OTHERS THEN
UPDATE schema_migrations
SET state = 'FAILED',
error_message = SQLERRM
WHERE id = migration_id;
RAISE;
END;
END;
$$;
Atomic State Transitions: Each phase has clear entry/exit conditions
Observability: Comprehensive logging, metrics, and audit trails
Safety First: Multiple verification layers before proceeding
Reversibility: Every expansion has a documented rollback path
Incremental: Batch processing with checkpointing
Zero-Downtime: Dual-write, shadow reads, and gradual cutover
Automated Guardrails: Auto-abort on anomaly detection
Usage Example:
bash
# Start migration
migrate start --name add_user_email_column \
--expand "ALTER TABLE users ADD COLUMN email_new VARCHAR(255)" \
--migrate "UPDATE users SET email_new = email WHERE email_new IS NULL" \
--contract "ALTER TABLE users DROP COLUMN email" \
--rollback "ALTER TABLE users DROP COLUMN IF EXISTS email_new"
# Monitor progress
migrate status --name add_user_email_column
# Force switch (if using manual switch)
migrate switch --name add_user_email_column
# Abort if issues detected
migrate abort --name add_user_email_column --reason "Data mismatch detected"
This framework provides enterprise-grade safety for database schema changes while enabling zero-downtime deployments through careful staging, continuous verification, and automated rollback capabilities.