Zero-downtime deploys and schema changes
Change Taskboard's database while two versions of the API run at once, using expand and contract, a backfill, and a rolling deploy that never breaks old code.
Database hosting, backups and restoresDeploying the three tiersDesigning the schema from features
Zero-downtime deploys and schema changes
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- During a rolling deploy the old and new API versions run at the same time against one database, so every schema change must work for both.
- A one-step column rename breaks the old code the instant it runs, which is why renames and drops are split into expand, migrate and contract steps.
- Expand first by adding the new column as nullable, keep both columns in sync while code moves over, backfill old rows, and drop the old column only after nothing reads it.
- Backfill in small batches so you do not hold long locks or flood the database, and make the job safe to rerun.
- Browsers keep old client bundles open, so the API must keep serving the old request shape for a while after the client changes.
The situation that makes this hard
You change tasks.title to tasks.name because the new design calls the field a name. Locally it is one line. In production it is a trap, because a deploy is not instant. A rolling deploy starts new instances, waits until they are healthy, then stops the old ones, so for a minute or more version 1 and version 2 of the API are both serving traffic against the same database. Meanwhile some users have a browser tab open on the old client.
The core problem is that your schema must be valid for two versions of your code at once. A migration cannot be “deploy the code, then change the database” or the other way round, because either order has a gap where one side is wrong.
What goes wrong with the direct rename
I tried it on PGlite with Taskboard’s schema:
alter table tasks rename column title to name;
old code after rename -> column "title" does not exist
Every request from an old instance now fails, from the moment the migration runs until the last old instance stops. That is your outage. The same applies to dropping a column, changing its type, or adding not null to a column old code does not fill in.
Expand, migrate, contract
The fix is to never make a breaking change in a single step. Split it into releases where each state works with both the previous and next code.
1. Expand. Add the new structure without removing the old. The database now has both title and name:
alter table tasks add column name text; -- nullable: old inserts still work
alter table tasks alter column title drop not null; -- so new code may omit it
2. Keep both in step. While old and new code coexist, a write through either must fill both columns. A trigger does that without touching application code:
create function sync_name() returns trigger as $$ begin
if new.name is null then new.name := new.title; end if;
if new.title is null then new.title := new.name; end if;
return new; end $$ language plpgsql;
create trigger t_sync before insert or update on tasks
for each row execute function sync_name();
I inserted one row as old code would (title only) and one as new code would (name only). Both rows came out with the two columns equal. Application-level dual writes work too. The trigger is simply the one that cannot be forgotten by a code path.
3. Backfill. Copy values for the existing rows:
update tasks set name = title where name is null;
After mine, select count(*) filter (where name is null) returned 0 across 502 rows.
4. Move the code. Deploy the API version that reads and writes name. Old instances still work, because title is still filled in.
5. Contract. In a later release, once nothing reads title, drop the trigger and the old column, then add not null to name if you want it. I did not run this last step. It is the irreversible one, so take a backup first (see database hosting, backups and restores) and check your logs and slow-query list for any remaining use of the old column.
That is five steps for one rename. It is slower than the one-liner, and that is the price. For a small internal tool with a maintenance window, the one-liner is fine. The pattern is for when users are online and you cannot stop them.
Backfills on a real table
My table had 500 rows. Yours might have 50 million. A single update over that holds row locks, writes a huge amount of log, and can stall the live app. Do it in batches:
update tasks set name = title
where id in (select id from tasks where name is null limit 1000);
Run that in a loop until it updates zero rows, pausing a little between batches. Make the job safe to rerun, since where name is null already is. And do it as a separate script or job, not inside the migration that holds up the deploy.
Other changes and their safe forms
| Change | Safe form |
|---|---|
| Add a column | Add nullable (or with a constant default), fill later |
Make a column not null |
Backfill first, then add the constraint |
| Drop a column | Stop reading it, deploy, then drop in a later release |
| Add an index on a big table | create index concurrently so writes are not blocked |
| Change a type | Add a new column, copy, switch, drop the old |
| Rename a table | Same as a column: add, sync, switch, drop |
create index concurrently is a Postgres feature, from its documentation, and I did not run it here. It cannot run inside a transaction block, which matters because many migration tools wrap each migration in one. Check how yours handles that.
The client side of the same problem
The database is not the only thing with two versions alive. A user who loaded Taskboard an hour ago still has the old JavaScript, which sends { title }. If the new API requires { name }, that tab breaks. Treat your API like a public contract during the transition: accept both shapes for a while, or version the endpoint (see API versioning strategies). Only remove the old shape once old clients are gone, which you can measure from request logs.
Make the deploy itself safe
Zero downtime also depends on the platform doing its part: start new instances before stopping old ones, wait for a real readiness check, and give old instances time to finish in-flight requests. The application side of that is in health checks and graceful shutdown. For the migration tooling itself, see schema migrations and change management. Feature flags help here too, by letting you ship code dark and switch it on separately, as in feature flags in practice.
What the video covers
Software Developer Diaries’ “Every engineer should know this.. (Expand-Contract Pattern)” is about six and a half minutes, three months old, and by its title explains the expand and contract pattern. That is this lesson’s central idea, and the sections above add a worked example that I ran. I could not read a transcript, so I do not know whether it covers backfills or the client side. Web Dev Cody’s video on zero-downtime migrations is linked as a second take, although it is three years old.
Where this fits
You can now change the schema without taking the app down. Before the next thing breaks in production, you want to be able to see what is happening, which is what the next lesson covers: observability across layers.
Check yourself
Why does alter table tasks rename column title to name cause an outage in a rolling deploy?
Instances still running the old code query title, which no longer exists, so they fail with a missing-column error until they are replaced.
What are the three phases of expand and contract?
Expand by adding the new structure alongside the old, migrate by moving writes, reads and existing data to the new structure, and contract by removing the old structure once nothing uses it.
Why must the contract step wait for a later release?
Until every old API instance and every open browser tab has stopped using the old column, dropping it would break them, and you cannot undo a drop without a restore.
Why backfill in batches rather than one update?
A single update over a large table holds locks and generates a lot of load at once, while small batches let normal traffic keep flowing and can be stopped and resumed.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.