Skip to content

Zero-Downtime Deployments for Node Apps With Docker Compose · Part 10 of 11 in the series

Part 10: Changing the Database Without Downtime

During every swap two versions of the app share one database. Learn the rule that keeps both working, and rename a column in three small deploys instead of one risky one.

Quest objectives

  • Understand why the database is the hard part of a deploy without a gap
  • Tell safe database changes from unsafe ones
  • Use the pattern expand, switch, contract
  • Rename a column in three deploys while visitors keep writing
  • Know which step can still be rolled back, and make a backup before the last one

The app has been swapped without a gap many times by now, and every time the database stayed as it was. Sooner or later it has to change too: a new column, another name, a table that is no longer needed. That is the hard part of deploying without downtime, for two reasons you have already met.

  • During every swap, two versions run at once. For a few seconds the old container and the new one both run, and both talk to the one database. There is no second copy of the data.

  • After a rollback, old code runs on a newer database. Moving production back, as in part 9, brings back the old code. It does not bring back the old tables.

Both lead to the same rule, and it is the only one you need to remember from this part:

Every change to the database must work with the version of the app that ran before it.

The database is changed while it is in use: a new ring is added first, and the old one is taken away only when nobody needs it any more.
The database is changed while it is in use: a new ring is added first, and the old one is taken away only when nobody needs it any more.

Safe and unsafe changes

Remember the order in deploy.sh: the migrations of the new image run first, and only then does the new container start. So for a moment the old version runs on the new database. Whether that works depends on the change:

  • Safe: a new table, or a new column that may stay empty. The old version does not know about them and is not bothered.

  • Not safe in one step: renaming a column, removing a column, or making a column required. The old version still asks for the old name, or still writes rows without the new value, and the database answers with an error. Visitors see that error until the swap is over. And if the new version then fails its health check, the old one stays, broken.

Expand, switch, contract

The way out is to split an unsafe change into safe ones, each in its own deploy:

  1. Expand: add the new thing beside the old one. The app writes both.

  2. Switch: the app reads and writes only the new thing.

  3. Contract: remove the old thing, which nobody uses any more.

Three small deploys instead of one risky one. That sounds like more work, and it is a little. But each of the three is boring, and boring is what you want from a change to your data. Your pipeline makes a deploy cost one git push, so three of them are cheap.

The example: name becomes author

In the table entries, the column name holds who wrote an entry. Say you want it to be called author. A rename is the classic unsafe change: the moment the column is renamed, the running version asks for a column that is gone. These are the two functions in src/db.js that use it today:

src/db.js
export async function listEntries() {
  const { rows } = await pool.query(
    'select name, message, created_at from entries order by created_at desc limit 50',
  );
  return rows;
}

export async function addEntry({ name, message }) {
  await pool.query('insert into entries (name, message) values ($1, $2)', [name, message]);
}

You will change these two functions and nothing else. The rest of the app keeps calling the value name: the form field, the check in entries.js and the page stay as they are. Only the column in the database gets its new name.

Deploy 1: expand

The first migration adds the new column beside the old one and copies what is there. Create migrations/002-add-author.sql:

migrations/002-add-author.sql
alter table entries add column author text;
update entries set author = name;

The new column may be empty, so this is a safe change: the version that runs right now never mentions author and works as before. In src/db.js, replace the two functions:

src/db.js
export async function listEntries() {
  const { rows } = await pool.query(
    'select coalesce(author, name) as name, message, created_at from entries order by created_at desc limit 50',
  );
  return rows;
}

export async function addEntry({ name, message }) {
  await pool.query('insert into entries (name, author, message) values ($1, $1, $2)', [
    name,
    message,
  ]);
}

Two things changed:

  • Writing: a new entry puts the name into both columns. $1 appears twice, so the same value goes to name and to author.

  • Reading: coalesce(author, name) means: take author, and if it is empty, take name. as name hands the result to the app under the name it already uses.

Why the coalesce, when the migration just filled every row? Because of the swap. While the new container starts, the old one still answers visitors, and what it writes in those seconds has a name and no author. The new version must be able to show those rows too.

Commit and push, on your computer:

~/projects/guestbook
$ git add .$ git commit --message "Add the author column beside name"$ git push

The pipeline and the server do the rest. In the journal on the server (the journalctl command from part 8) you can see the migration run before the new container starts:

deploy@guestbook: ~
Nov 17 11:40:01 guestbook deploy.sh[7933]: 11:40:01 New image found, updating the databaseNov 17 11:40:02 guestbook deploy.sh[7933]: Applied 002-add-author.sqlNov 17 11:40:02 guestbook deploy.sh[7933]: Database is up to dateNov 17 11:40:02 guestbook deploy.sh[7933]: 11:40:02 Starting the new containerNov 17 11:40:05 guestbook deploy.sh[7933]: 11:40:05 Visitors now reach guestbook-web-6Nov 17 11:40:05 guestbook deploy.sh[7933]: 11:40:05 Version 51c7e2a is live

If this version turned out to be bad, you could roll back to the one before it without a second thought: the old code finds its name column exactly as it left it.

Deploy 2: switch

Now the app can let go of the old column. Create migrations/003-author-takes-over.sql:

migrations/003-author-takes-over.sql
update entries set author = name where author is null;
alter table entries alter column author set not null;
alter table entries alter column name drop not null;

Line by line:

  • The first line fills the gaps: the few rows the oldest version wrote during the last swap, with a name and no author.

  • The second makes author required. That is safe now, because the version running at this moment, the one from deploy 1, writes it with every entry.

  • The third makes name optional, because the new code is about to stop writing it.

And the two functions in src/db.js, which now know only author:

src/db.js
export async function listEntries() {
  const { rows } = await pool.query(
    'select author as name, message, created_at from entries order by created_at desc limit 50',
  );
  return rows;
}

export async function addEntry({ name, message }) {
  await pool.query('insert into entries (author, message) values ($1, $2)', [name, message]);
}

Check the rule once more. During this swap, the version from deploy 1 still runs for a few seconds on the changed database. It writes both columns and reads author first, so it keeps working. (To try the changed code on your own computer, run npm run migrate there first: your local database needs the new column too.) Commit and push:

~/projects/guestbook
$ git add .$ git commit --message "Read and write author only"$ git push

From here on, a rollback reaches one step back: the version from deploy 1 works with this database, the versions before it do not, because they write entries without an author. That is the price of moving on, and the reason to give each step a little time before the next.

Deploy 3: contract

The column name is still there, and no running version touches it. Removing it is the one step of the three that throws data away, so make a backup first. On the server, in ~/guestbook:

deploy@guestbook: ~/guestbook
$ docker compose exec -T db pg_dump --username guestbook guestbook > backup-$(date +%F).sql

pg_dump writes the whole database into one file, with today's date in its name. Then the last migration, migrations/004-drop-name.sql:

migrations/004-drop-name.sql
alter table entries drop column name;

The code does not change this time. The new image differs from the old one only by this file, and that is enough for the server to deploy it:

~/projects/guestbook
$ git add .$ git commit --message "Drop the name column"$ git push

After this deploy, the version from deploy 1 can no longer run: it still asks for name. So this step comes last, and it can wait. Nothing breaks if the old column stays for a few days, until you are sure you will not want to go back.

The table afterwards

On the server, ask the database what the table looks like now, and which migrations it has noted:

deploy@guestbook: ~/guestbook
$ docker compose exec db psql --username guestbook --command '\d entries'                                       Table "public.entries"   Column   |           Type           | Collation | Nullable |               Default------------+--------------------------+-----------+----------+------------------------------------- id         | integer                  |           | not null | nextval('entries_id_seq'::regclass) message    | text                     |           | not null | created_at | timestamp with time zone |           | not null | now() author     | text                     |           | not null |Indexes:    "entries_pkey" PRIMARY KEY, btree (id)$ docker compose exec db psql --username guestbook --command 'select name, applied_at from migrations'           name            |          applied_at---------------------------+------------------------------- 001-create-entries.sql    | 2026-11-17 09:58:50.517409+00 002-add-author.sql        | 2026-11-17 11:40:02.723909+00 003-author-takes-over.sql | 2026-11-17 11:52:02.190963+00 004-drop-name.sql         | 2026-11-17 12:03:02.324678+00(4 rows)

The column is called author, it is required, and name is gone. The table migrations is the list that migrate.js keeps, which is why each file ran exactly once.

Did anyone notice?

For this series, the three deploys were run one after the other while a load test kept reading the guestbook and signing it, connecting the way browsers do. Of about 34,000 requests, form posts included, not one failed. The column changed its name under the visitors' hands.

What you have now

A way to change the database that never leaves a running version without the columns it expects: add first, switch, remove last. With that, the last thing that could force a gap is gone.

One thing is still missing. The server deploys by itself, and nobody is watching when it does. In part 11 it tells you how each deploy went.

Comments

The comments are GitHub Discussions: sign in with GitHub to write one.

The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.