STATUS: CONNECTING
LATENCY: --

Database Migrations: Why Every Schema Change Should Be a File


Code has version control. I can see every change, who made it, and why, and I can rebuild any past version from nothing. A database has none of that by default. It has state: whatever the last person to touch it left behind.

A migration is how the schema gets the same discipline as the code. Both of my posts on deploying with Podman, the pattern and the worked example, lean on one sentence: migrations are an explicit step. This post is the explanation behind that sentence.

The Problem Without Them

Without migrations, the schema lives in exactly one place: the running database. That works until there is a second database, and there is always a second database.

Production is not usually where it goes wrong. When a release needs a manual schema change, I make it at the time of the deploy, right beside the code that needs it, so it is hard to forget. The trouble is everywhere else.

Tests need a database with the current schema, built from nothing, on every run. Without migrations, that database comes from an old dump or a setup script that someone has to remember to keep current, and it quietly falls behind. Then add a second developer. Each of us changes the schema on our own machine while working on our own branch, and neither change exists anywhere the other can see. When the branches merge, the code assumes both changes, no database has both, and the only record of either is in someone’s memory.

The schema has become folklore. Nobody can answer “what should this database look like” except by inspecting one and hoping it is the right one.

What a Migration Is

A migration is a file that changes the schema once. The files are numbered, and they run in order.

-- migrations/001_notes.sql
CREATE TABLE notes (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    body text NOT NULL
);
-- migrations/002_notes_created_at.sql
ALTER TABLE notes ADD COLUMN created_at timestamptz NOT NULL DEFAULT now();

The database itself keeps a small table recording which files it has already applied. A migration tool does one thing: it compares the files on disk with that table and runs whatever is missing, in order.

That gives a simple definition. The schema is the result of applying every migration, in order, to an empty database. It is no longer whatever a database happens to contain. It is something I can read, review, and rebuild.

What That Buys

Every environment arrives by the same path. My laptop, the test run, and production all apply the same files in the same order. They cannot drift, because there is no other way for the schema to change.

A fresh database is one command. This is the benefit I use most. Tests start from an empty database and migrate it. Development fixtures are built on top of a migrated database. Throwing a database away stops being a loss, because another one is seconds away.

The schema change travels with the code that needs it. The migration is in the same commit as the query that uses the new column. They are reviewed together and released together. Nobody has to remember to run something by hand. When two people change the schema on separate branches, both migrations arrive with the merge, and every database that pulls the merge gets both.

The history explains itself. When I wonder why a column exists, the migration that added it has a date, a commit message, and usually a comment.

A deploy knows what it is about to do. Before changing anything, I can ask which migrations are pending. A release with none is a code-only release. A release with a destructive one gets more care.

Numbered SQL, Embedded in the Binary

That is the general case. The rest of this post is how I apply it in Tapper Hub, the Go server behind Atlas, which runs on PostgreSQL.

Tapper Hub uses goose. Migrations are plain SQL files with a number and a name, and there are more than a hundred and thirty of them now.

-- 00003_notes_title.sql
-- +goose Up
ALTER TABLE notes ADD COLUMN title text NOT NULL DEFAULT '';

-- +goose Down
ALTER TABLE notes DROP COLUMN title;

The files are compiled into the binary. That matters more than it sounds. A given version of the server carries exactly the migrations it was written against, so there is no directory of SQL to ship beside it and no way to pair a binary with the wrong set. The container image that runs the service is also the tool that migrates for it.

A few changes cannot be expressed in SQL, such as converting stored data from one format to another. Those are Go functions registered with goose under a number of their own, and they run in sequence with the SQL files.

Never on Startup

Many applications migrate when they start. It is convenient, and I avoid it.

Tapper Hub has two separate commands. tapper-hub serve checks that the database is ready and exits immediately if it is not. tapper-hub migrate up applies pending migrations and does nothing else. The server never chooses between migrating and trusting. It always trusts, and an operator, or a deploy script acting as one, always migrates.

The reasons are practical:

  • A schema change becomes a step with a position. The deploy decides when it happens, relative to the backup and to stopping the old version. Migrate-on-start gives that decision to whichever process boots first.
  • A crash loop cannot touch the schema. If the new version fails to start, the service manager will retry it. I do not want each retry to take another run at a half-applied change.
  • Several instances do not race. Two copies of a server starting together would both try to migrate.
  • Failing fast is clearer. A server that refuses to start on an unmigrated database produces one obvious error. A server that limps along produces many confusing ones.

In development the same rule holds. The task that starts my local stack runs migrate up before it starts the backend, for the same reason the deploy does.

Where the Deploy Puts It

In production, the migration sits at one fixed point in the deploy.

  sequenceDiagram
    participant Deploy as Deploy
    participant Old as Old version
    participant DB as PostgreSQL
    participant New as New version

    Deploy->>Old: stop
    Deploy->>DB: dump, verify, copy off the host
    Deploy->>DB: migrate up (run from the new image)
    Deploy->>New: start
    New->>DB: check ready, then serve

The old version is stopped before the schema changes, and the new one starts only after it has.

Nothing is serving while the schema changes, so a migration that reshapes a table cannot break a running binary that still expects the old shape. The backup comes first, and it is verified before the migration runs. The deploy walkthrough covers the rest of that sequence.

Some releases need no downtime at all, because their migrations only add things. Others need the service stopped for the duration. The release notes say which, so the choice is made before the deploy and not during it.

Released Migrations Are Frozen

One rule protects everything above: a migration that has shipped in a release is never edited.

The tool tracks migrations by number. If a database has applied number 40, it will never run number 40 again, whatever the file now says. Editing a shipped migration therefore changes the schema for new databases and leaves existing ones alone. The two have silently forked, which is the exact problem migrations exist to prevent. A mistake in a released migration is fixed with a new migration.

The freeze starts at the release tag, not at the commit. Migrations written since the last release are still mine to edit, renumber, or fold together, because the only databases that have run them are disposable development ones. I use that freedom to tidy a series of small steps into one clear migration before it ships.

Going Back Is a Restore

Every migration file has a Down section, and the server’s command line offers no way to run one. It has migrate up and migrate status. That is deliberate.

On its own, a down migration can reverse a change to structure. It cannot bring back data. Dropping a column and then re-adding it yields an empty column. The first migration in the project says so in its own Down section: undoing it would destroy every account, and a per-migration rollback is the wrong tool for that.

There is a technique that narrows that gap: have the migration keep a copy of what it is about to destroy. Before dropping a column, the Up section saves it to a backup table, and the Down section puts it back.

-- 00004_notes_drop_title.sql
-- +goose Up
CREATE TABLE notes_title_backup AS SELECT id, title FROM notes;
ALTER TABLE notes DROP COLUMN title;

-- +goose Down
-- +goose StatementBegin
DO $$
BEGIN
    IF to_regclass('notes_title_backup') IS NULL THEN
        RAISE EXCEPTION 'notes_title_backup is missing, so titles cannot be restored'
            USING HINT = 'Restore a database backup, or roll back by hand if losing titles is acceptable.';
    END IF;
END $$;
-- +goose StatementEnd
ALTER TABLE notes ADD COLUMN title text NOT NULL DEFAULT '';
UPDATE notes n SET title = b.title FROM notes_title_backup b WHERE n.id = b.id;
DROP TABLE notes_title_backup;

Now the down migration is a real undo for that one change. Rolling back restores every title that existed when the migration ran, without restoring the whole database and losing everything written since.

The check at the top of Down matters. Without it, a missing backup table produces the worst kind of rollback. The column comes back, the UPDATE fails, and depending on how the migration runs, either the whole step aborts with an unhelpful error or the database is left with an empty column that looks restored. With the check, the down migration refuses before it changes anything and says why. goose runs each SQL migration inside a transaction by default, so a refusal leaves the database exactly as it was.

A refusal is the right default because the choice it forces belongs to a person. The titles are gone from this database. Either they come back from a real backup, or someone decides that losing them is acceptable and rolls back by hand. A migration should never make that decision silently.

The backup table also has to go eventually, and that creates a boundary. Once the release has proven itself, a later migration drops the backup. Its own Down cannot recreate the data, so it should refuse too:

-- 00009_drop_notes_title_backup.sql
-- +goose Up
DROP TABLE notes_title_backup;

-- +goose Down
-- +goose StatementBegin
DO $$
BEGIN
    RAISE EXCEPTION 'notes_title_backup was dropped; rolling back past this point needs a database restore';
END $$;
-- +goose StatementEnd

That makes the boundary visible. Rolling back across the cleanup migration stops with a clear message instead of reaching the earlier Down and failing there. Tapper Hub uses the same kind of refusal in one of its own down migrations: it will not run while data exists that the rollback would destroy.

The technique has other limits worth stating. Rows created after the migration were never in the backup, so they come back with the default. And it only covers what the migration thought to copy. It is a good fit for a column or table being removed or reshaped, not a substitute for a real backup.

For anything broader, the way back is the recovery point the deploy took minutes earlier: restore the database and the previous image together. Data is never rolled back automatically. I would rather make that choice by hand, knowing what will be lost, than have a script make it for me.

Privileges Split in Two

The last practice is about who is allowed to change what.

Creating extensions and schemas needs a privileged database role. Creating tables and indexes inside those schemas does not, and neither does running the service. migrate up therefore takes two connections. The privileged one is used for the short bootstrap phase. The versioned migrations run as the ordinary role the service itself uses.

The server also checks its own role at startup and refuses to run with one that could bypass the database’s access rules. A migration tool is often the most privileged thing an application owns. Keeping that privilege to one brief phase means a bug in a migration, or in the service, has less to work with.

Rules I Keep

  1. Every schema change is a file. If I catch myself typing ALTER TABLE into a console against a real database, I stop and write the migration.
  2. Never edit what has shipped. Fix forward with a new number.
  3. Migrate explicitly. The server checks and refuses. It does not repair.
  4. Back up first, and verify the backup. The migration is the riskiest moment in a deploy, and the recovery point is the only real undo.
  5. Keep locks short. A migration runs against a database that holds real data. Add a constraint as NOT VALID and validate it afterwards, and backfill in small batches, so no step holds a busy table for long.
  6. Run the whole set from empty, constantly. Every test run does this. A migration that only works on my laptop’s database is found within minutes.

None of this is sophisticated. It is bookkeeping, done the same way every time, so that the database stops being the one part of the system I cannot rebuild.


Copyright 2026 Jared Rickert. All rights reserved. ยท