ARTICLE

Database migrations need an order, and the pipeline has to keep it

A database migration changes the schema running code depends on, so schema and code must ship in order. Three ways pipelines keep it, and the lock to watch.

Andrei Gaspar9 min read

Two tracks merge into one on a black background; a flat white slab has already reached the merge on the lower track, while a white block on the upper track waits behind a lowered green barrier

A database migration is a versioned change to a database schema, such as adding a column or dropping a table, applied by a tool so every environment ends up with the same structure. The term also covers moving data between database systems. In a deploy pipeline, it is the schema change that ships with the code that needs it.

On September 30, 2026, Railway merged a change to its routing control plane after testing it in staging. The change bundled a database schema update with a new version of the routing service, which tells Railway's proxies where to send traffic for every domain the platform hosts. The two pieces went out through separate pipelines, and according to Railway's incident report, "a race in the configuration ran the schema update pipeline in parallel with the deployment pipeline." The new service won the race. It came online in every region and started querying columns that did not exist yet, every route lookup failed, and the proxies treated each failure as a domain with no routes. Between roughly 07:35 and 07:40 UTC, new connections to domains hosted on Railway returned HTTP 404 in all regions. When the migration finished, the lookups succeeded again, and no rollback was needed.

Nothing in that change was wrong on its own. The schema update was correct, the new service was correct, and both had passed staging. What failed was the order in which they reached production, and nothing in the pipeline was checking it. That is the question every database migration has to answer before it runs, and it is the subject of this piece.

What a database migration is, and the two meanings of the term

Wikipedia's article on schema migration gives the definition most engineers work with. A schema migration manages version-controlled, incremental and sometimes reversible changes to a relational schema, and a migration tool applies them in sequence until the database reaches the version the code expects. Rails, Django, Flyway, Liquibase and Alembic all work this way. Each migration is a file in the repository with an order, and the tool records which ones have already run.

The second meaning covers moving a whole database, for example from an on-premise server to a managed cloud service or from one engine to another. That kind of project usually happens once, with a cutover plan and a maintenance window. This piece is about the first meaning, because that one happens every week and goes through the same pipeline as the code.

The line between the two is not sharp. In 2017 Stripe described how it moved hundreds of millions of Subscriptions objects out of its Customers table into a table of their own, without stopping the service. That was a change to the data model inside a live database, and it needed the same thing a small schema change needs, which is a plan for which code reads and writes which shape at every step. We come back to it below.

Why the schema and the code have to ship in an order

A schema change and a code change depend on each other in one direction or the other. New code that reads a new column fails if the column is not there yet. Old code that reads a column fails if a migration has already removed it. Wikipedia states the constraint directly, noting that "one version of an application only understands one version of a schema." The simplest way to respect it is to stop the application, run the migration and start the new version, and that works as long as you can accept the downtime.

Most teams that deploy several times a day cannot accept it, so for a period both the old and the new version of the code run against one database. During a rolling or canary deploy that period lasts minutes. On a platform that runs in many regions it can last much longer. Whatever runs during that period has to work against whatever schema is in place at that moment.

Railway's report explains how the guarantee disappeared. When the routing service was part of a larger monolith, "a single pipeline enforced that order." Railway split the service out into a distributed control plane to make it more resilient, and the split ran the whole system in parallel. The schema update and the service rollout became two jobs in two pipelines, and the order between them came down to which job finished first.

Should the schema or the code deploy first? Three ways to keep the order

Teams answer that question in one of three ways. The table summarizes them, and the sections that follow show each one in a real pipeline.

ApproachWhat enforces the orderWhat happens when it slipsExample
One pipeline runs the migration, then the codeThe pipeline's stage orderEverything waiting on the branch ships with the migrationGoodBarber, Railway's monolith
Every change works in either orderThe shape of the change (expand, migrate, contract)Usually nothing, at the cost of more releasesParallel change
Migrations run before or after the deploy, by typeA separate post-deploy stageRemovals wait until the new code is outGitLab

One pipeline runs the migration, then the code

The simplest guarantee puts the migration and the code in the same pipeline, with the migration as an earlier stage. GoodBarber's backend team works this way. Their migrations run from the same Docker image as the application, the team applies them before the code goes live, and every migration has to be additive. Old code runs fine on the new schema because each new column is nullable or has a default in the database, so a schema that arrives first breaks nothing.

The weakness is coupling. GoodBarber's image is built from master, so a migration can only reach production together with everything else on master. Pierre-Laurent Medori, who runs backend engineering there, describes the day he applied a migration that added a single table nobody read yet. In his words, "one new table took everything master held," including a task from a colleague's session that had not been reviewed. The order held, but a small schema change carried a release with it.

Every change works in either order

The second answer removes the dependency on order altogether. Each change is split into steps that can ship in any sequence, a pattern Danilo Sato named parallel change, also known as expand and contract. You first add the new shape without removing the old one, then move readers and writers to the new shape, and remove the old one in a release of its own. Sato points out that the code can be released at any of the three phases, which is exactly the property a rolling deploy needs.

Our piece on rollback as a pipeline feature covers the expand and contract steps in detail, together with a migration linter that rejects drops and renames in a release that also ships code. The relevant point here is that expand and contract makes the order safe in both directions. The cost is more releases per change, and a team has to remember the contract step, which has no deadline.

Migrations before and after the deploy

The third answer accepts that some migrations have to run before the code and some after it, and gives the second kind a stage of its own. GitLab's development documentation calls these post-deployment migrations. They are ordinary Rails migrations kept in a separate directory and skipped by the normal deploy. GitLab uses them for changes that, in its words, "mutate state that an existing version of GitLab depends on."

The documentation uses the removal of a column as its example. Removing a column in the same deploy as the code would need downtime, because the running version still reads it. With a post-deployment migration, GitLab deploys the new version first, which no longer uses the column, and removes the column afterwards. On GitLab.com these migrations run on a daily basis, at the discretion of release managers, through a separate post-deploy migration pipeline. The removal waits for the new code because it lives in a different stage, and that stage only runs once the deploy is out.

Why a migration locks a table, and how to keep it from stalling production

Getting the order right is half of a safe migration. The other half is what the migration does to the database while it runs, because a schema change that is perfectly additive can still hold up every query on a busy table.

In PostgreSQL, many forms of ALTER TABLE take an ACCESS EXCLUSIVE lock. The documentation says this mode "guarantees that the holder is the only transaction accessing the table in any way," and it is the only lock mode that blocks a plain SELECT. Adding a nullable column does not rewrite the table, so once the lock is granted the change itself is quick. The danger is the wait before it. An ALTER TABLE that cannot get its lock because a long transaction is still reading the table sits in the queue. Medori explains what that meant on GoodBarber's busiest table, where "every query that arrives after it waits behind it." A migration that would have finished in milliseconds can stop reads and writes for as long as the oldest open transaction keeps running.

PostgreSQL's guard against this is lock_timeout, which aborts a statement that has waited too long for a lock. Its default value is zero, which means no timeout at all. GoodBarber's deploy checklist for that migration set a five-second timeout and planned a second run if it fired.

docker compose run --rm -e PGOPTIONS='-c lock_timeout=5s' web python manage.py migrate

A migration that times out has done nothing and can be retried, which is a far better outcome than one that freezes the table. Our deploy pipeline anatomy lists "a migration that takes a table lock for 40 seconds" among the failures staging exists to catch. A lock timeout catches the same failure in production, where staging's small tables could not.

MySQL teams faced the same problem at a larger scale, and GitHub built a tool for it. In 2016 Shlomi Noach announced gh-ost, GitHub's online schema migration tool. GitHub ran schema changes several times a day, and with the trigger-based tools it had used for years, the team had come to consider many migrations "risky operations." Some could only run off-peak or at weekends, and others caused MySQL outages. gh-ost copies the table in the background, follows changes through the binary log instead of triggers, and can pause all of its writes when the database is under load. GitHub's point was the same as GoodBarber's. Whether a migration is safe depends on how it behaves against production traffic as much as on what it changes.

How to run a data migration without downtime

Some migrations move data rather than structure, and they need the same ordering discipline over a much longer period. Stripe's Subscriptions migration is the best-documented example. Jacqueline Xu's post sets out the pattern in four phases. Stripe first wrote every change to both the old and the new table and backfilled existing records with an offline job, then moved all reads to the new table, then moved all writes, and finally removed the old data.

Two details make the pattern work in practice. Before switching reads, Stripe ran both read paths side by side with GitHub's Scientist library, which compares the results of two code paths in production and raises an alert when they differ. In the last phase it made the old accessor raise an error, so that any code still using the old shape would fail loudly instead of reading stale data. The post also shows why such a migration cannot run as one sequential job. Its own illustration asks the reader to imagine one second per object, in which case migrating one hundred million objects one after another would take over three years.

This is expand and contract applied to data. Every phase is a separate deploy, every phase works against both shapes, and the old shape is removed only after a check has shown that nothing still depends on it.

What to check in the pipeline before a migration runs

The three approaches differ, but the checks a pipeline can run are much the same. Each of the following turns a rule that people have to remember into one the pipeline enforces.

The service should check the schema version itself when it starts. This is the change Railway made after the incident. Its routing service now "refuses to go live until the matching database schema is in place," so a deploy that gets ahead of its migration fails a health check instead of serving errors. The order no longer depends on which pipeline finishes first.

Every migration should run with a lock timeout and be safe to run twice. A migration that gives up after a few seconds and is retried later costs a delay. A migration that waits for its lock without limit can cost an outage.

Destructive changes should wait for their own stage. Drops, renames and type changes should not ship in a release that also ships code. They belong in a post-deploy stage, as at GitLab, or in the contract step of an expand and contract sequence. A linter that rejects them in mixed releases is cheap to write, and the rollback piece shows one.

Large data changes should be compared before they are trusted. A backfill or a dual write is finished when a comparison on production data shows the two shapes agree, as Stripe did with Scientist, and not when the job reports success.

On Monday

Find where your pipeline decides the order between a migration and the code that needs it. In some pipelines it is a stage in a single file. In others, as at Railway after the split, it is two jobs that happen to finish in the usual order. Then look for the newest service in your system, because that is where the order is most likely to depend on timing. Check whether that service would start against a schema it does not expect, and whether your migrations run with a lock timeout.

Railway's outage lasted about five minutes because the migration happened to finish about five minutes after the code went live. The fix was to stop relying on that gap and have the service refuse to start until its schema was in place. It is one check in a service's startup path, and once it is there, the order between schema and code no longer depends on which job finishes first.

COMMENTS

Comments

Loading comments…

READY FOR MORE?

The Weekly Rollback

One email each Friday. Field notes, no funnels. ~4,200 engineers who own the pipeline already read it.

We’ll email you a confirmation first. Your address is used only to send you this newsletter, and every issue has an unsubscribe link. Privacy policy

SPONSORS

This blog exists thanks to the support of our sponsors:

GitdailiesQA.techAppSignalSuperlinked
Become a sponsor
Back to all articles