Changing a column in a database that is in use sounds like one statement. In practice the application cannot be stopped, old and new versions of it run side by side during every deployment, and the table has years of data in it. The standard answer is the expand and contract pattern, also called parallel change: add the new structure next to the old one, move over in small steps, remove the old one at the end.
This case does it with running code and measures each step. A payments table stores money as a floating point number; it should store whole cents as an integer. The code is on GitHub: chudovo/application-modernization, case 07.
At a glance
| Before | After | |
|---|---|---|
| Column | amount double precision | amount_cents bigint |
| 19.99 + 0.1 + 0.2 in the database | 20.290000000000003 | 2029 |
| Application | Release 1 | Release 4, after two releases in between |
| Schema changes | none | five steps, each safe on its own |
| Failed operations during the change | 0 |
The sequence
The schema changes in five steps and the application in four releases. They alternate, and each release works with the schema before and after the next step:
| Database | Application | |
|---|---|---|
| 1 | Expand: add amount_cents, nullable | Release 1 keeps running, then deploy Release 2: writes both columns, reads the old one |
| 2 | Backfill: make the new column agree with the old one | Release 2 only |
| 3 | Constrain: the new column becomes NOT NULL | then deploy Release 3: reads the new column, still writes both |
| 4 | Relax: the old column loses NOT NULL | then deploy Release 4: uses only the new column |
| 5 | Contract: drop the old column | Release 4 only |
-- Step 1, expand: a nullable column without a default. Only the catalog changes, no row is rewritten.
ALTER TABLE payments ADD COLUMN amount_cents bigint;
-- Step 2, backfill: in code, in small batches (see below).
-- Step 3, constrain: only when the backfill is complete and no Release 1 instance is left.
ALTER TABLE payments ADD CONSTRAINT payments_amount_cents_present CHECK (amount_cents IS NOT NULL) NOT VALID;
ALTER TABLE payments VALIDATE CONSTRAINT payments_amount_cents_present;
ALTER TABLE payments ALTER COLUMN amount_cents SET NOT NULL;
ALTER TABLE payments DROP CONSTRAINT payments_amount_cents_present;
-- Step 4, relax: Release 4 stops writing the old column, and the old column is NOT NULL.
ALTER TABLE payments ALTER COLUMN amount DROP NOT NULL;
-- Step 5, contract: only when no instance of Release 3 or older is left.
ALTER TABLE payments DROP COLUMN amount;
Every release hides the storage from the rest of the application. Amounts are decimals with two places at that boundary in all four. Release 2 looks like this:
/// Release 2: writes both columns, still reads the old one. Can run next to Release 1.
public async Task<long> RecordAsync(string customer, decimal amount) =>
await ScalarAsync<long>(
"INSERT INTO payments (customer, amount, amount_cents) VALUES ($1, $2, $3) RETURNING id",
customer, (double)amount, ToCents(amount));
public async Task<Payment?> GetAsync(long id) =>
(await QueryAsync("SELECT id, customer, amount FROM payments WHERE id = $1", Map, id)).SingleOrDefault();
Which release works with which schema
Nine behaviour checks describe what the application does with payments: read an existing one, record, adjust, total, refund, list. The test suite runs all nine for every release in every schema state, 20 combinations. The table shows how many pass:
| Legacy | 1 Expanded | 3 Constrained | 4 Relaxed | 5 Contracted | |
|---|---|---|---|---|---|
| Release 1 | 9 | 9 | 6 | 6 | 0 |
| Release 2 | 5 | 9 | 9 | 9 | 0 |
| Release 3 | 0 | 5 | 9 | 9 | 5 |
| Release 4 | 0 | 2 | 6 | 9 | 9 |
Read along a row: a release works in a band of schema states. Read down a column: in every state between the first and the last, at least two releases work, and that is what makes a rolling deployment possible. The rules of the sequence are the cells that are not 9:
- Release 1 after step 3 fails with a not-null violation on the new column. No Release 1 instance may be left when the constraint is added.
- Release 3 before the backfill reads empty values. Reads move only after step 2.
- Release 4 before step 4 fails with a not-null violation on the old column. This is why the relax step exists, and it is easy to forget: nothing about the new column needs it.
- Release 3 after step 5 fails because it still writes the dropped column.
The whole thing under load
A matrix proves that the states are compatible. It does not prove that the transitions are. So one test runs the entire sequence while eight clients record payments, adjust them and read totals without pause. Each client keeps its own books in decimals. The test deploys by replacing instances one at a time, so in three phases two releases are live together. At the end it requires zero failed operations and that the database agrees with every client’s books to the cent.
Result in the build: 5,579 operations, 0 failed, with 592 rows backfilled while the clients were writing. The counts vary from run to run; the zero does not.
What the load test found
The first version of the backfill filled the rows where the new column was empty. It finished without error, and then the gate before step 3 reported 4 rows that disagreed.
While Release 1 and Release 2 run side by side, Release 2 records a payment and writes both columns. Then Release 1 adjusts that payment and updates the only column it knows. The row is not empty. It is wrong, and a backfill that looks for empty rows never touches it.
-- The obvious backfill: fill what is empty. It reported success and left 4 wrong rows.
UPDATE payments SET amount_cents = round(amount * 100)::bigint WHERE amount_cents IS NULL;
-- The backfill of this case: compare, in small batches, skipping rows that are locked right now.
UPDATE payments SET amount_cents = round(amount * 100)::bigint
WHERE id IN (SELECT id FROM payments
WHERE amount_cents IS DISTINCT FROM round(amount * 100)::bigint
ORDER BY id LIMIT $1 FOR UPDATE SKIP LOCKED);
-- The gate before reads move to the new column. Must return 0.
SELECT count(*) FROM payments WHERE amount_cents IS DISTINCT FROM round(amount * 100)::bigint;
Until reads move to the new column, the old column is the truth, so recomputing from it is always right. The comparison is also the verification query, and the sequence does not continue until it returns zero. Without the gate, Release 3 would have shown four customers an amount that had been corrected weeks earlier.
How a one-millisecond change takes the application down
Adding a nullable column takes about a millisecond. It also needs an exclusive lock on the table. If any transaction that has touched the table is still open, the change waits, and every query that arrives after it waits behind it. One forgotten session is enough. The case reproduces it:
// Someone has a transaction open that has read the table: a report, a forgotten session.
await new NpgsqlCommand("SELECT count(*) FROM payments", reporting, transaction).ExecuteScalarAsync();
// The schema change is started without a lock timeout. It waits for that transaction.
var migration = Task.Run(async () => await database.Db.CreateCommand(AddColumn).ExecuteNonQueryAsync());
// And now an ordinary read from the application waits too, behind the schema change.
var read = new NpgsqlCommand("SET statement_timeout = '1s'; SELECT count(*) FROM payments", application);
var error = await Assert.ThrowsAsync<PostgresException>(() => read.ExecuteScalarAsync());
Assert.Equal(PostgresErrorCodes.QueryCanceled, error.SqlState);
The fix is a lock timeout and a retry. The schema change gives up after a moment, the queue dissolves, the application keeps reading, and the migration tries again until the long transaction is gone:
public async Task RunAsync(string sql, TimeSpan lockTimeout, int maxAttempts = 50)
{
for (Attempts = 1; ; Attempts++)
{
await using var connection = await db.OpenConnectionAsync();
try
{
await using var command = connection.CreateCommand();
command.CommandText = $"SET lock_timeout = '{(int)lockTimeout.TotalMilliseconds}ms'; {sql}";
await command.ExecuteNonQueryAsync();
return;
}
catch (PostgresException e) when (e.SqlState == PostgresErrorCodes.LockNotAvailable && Attempts < maxAttempts)
{
await Task.Delay(TimeSpan.FromMilliseconds(200)); // give way, let the queue dissolve, try again
}
}
}
Step 3 has a second lock problem: setting NOT NULL scans the whole table under that exclusive lock. Adding a check constraint as NOT VALID and validating it separately moves the scan to a lock that does not block reads or writes.
One thing that does change
Three existing payments are 100 / 3 each. Release 1 adds the floating point numbers and rounds the sum: 100.00. After the migration each row is 3333 cents and the sum is 99.99. Both are correct by their own definition. Amounts that were never whole cents cannot be converted without choosing one, and the choice shows up in totals. A test asserts both values. It is a question for whoever owns the numbers, and it should be asked before the backfill, not after the old column is gone.
Going back
Up to and including Release 3 the old column is complete and current, so any earlier release can be deployed again. Release 4 stops writing it. From then on, going back to Release 2 or 1 means filling the old column from the new one first. After step 5 there is nothing to go back to. Leave time between the steps; the pattern costs calendar days, not effort.
What is verified, and what is not
| Check | Result |
|---|---|
| 9 behaviour checks for each of 20 combinations of release and schema state | matrix as expected |
| The whole sequence under load from 8 clients, with rolling deployments | 5,579 operations, 0 failed |
| Lock queue, lock timeout, backfill restart, overlapping releases, changed sums | 6 / 6 |
- Not a large table. The backfill handles a few hundred to a few thousand rows here. Batch size, replication lag and bloat on hundreds of millions of rows are not explored.
- PostgreSQL only. Everything about locks is specific to it. MySQL and SQL Server behave differently for the same statements.
- No other readers. Reports, exports and replicas that read the old column directly are part of a real migration and not of this one.
- No real deployment. Deploying a release in the test means swapping which class handles requests.
Run it yourself
You need the .NET 10 SDK and a PostgreSQL server. The tests create and drop their own databases:
docker run -d -e POSTGRES_PASSWORD=local_dev_only -p 54320:5432 postgres:17
dotnet test tests/Payments.Tests
When this path fits
Expand and contract fits any change to a structure that running code depends on: a column type, a rename, a split table. It trades one risky release for several dull ones. The wider picture, from choosing a target database to moving the data, is in the legacy database modernization guide. A related case keeps the schema and replaces the data access library on top of it: Entity Framework 6 to EF Core on an existing database.
If you need a team for work like this, see our comparison of modernization vendors.