Why we do not run Alembic migrations on deploy
Our pipeline deploys the backend and never runs Alembic. That is deliberate. A deploy that runs `alembic upgrade head` on start applies whatever schema change is in the image at the moment the container starts, with nobody watching the database. For a CRM that agencies use all day, we wanted applying a migration to be an act somebody decides on and can read back in a log.
The risk also runs the other way. If code that queries a new column is deployed before the migration has been applied, every request touching that table fails. So the order is fixed: migrate first, then merge and deploy. CI comments on any pull request that adds a migration to say so, and the production deploy has a guard. It reads the revision the database is actually on, from inside the running backend container, and refuses to deploy if the database is behind the head the code expects.
The guard fails open in two cases, on purpose. If there is no running container to ask, or the revision cannot be read, it warns and carries on, because a safety check that blocks a recovery deploy does more harm than it prevents. A readable answer that is genuinely behind does stop the release.
How we apply a migration: dry run first, then upgrade
Migrations are applied by a manually triggered GitHub Actions workflow. You choose the environment (staging or production), the revision to upgrade to, and the branch or commit that holds the migration files. The dry-run option is ticked by default, so the first run changes nothing.
The workflow runs Alembic inside the already-running backend container, where the database connection is already configured, so the credentials stay on the server. That container's image predates the new revision files, so the workflow first copies in only the files the branch adds relative to the default branch. Copying files in only adds revisions and changes no data, which is why it is safe on a dry run as well. Before anything is applied, the run prints:
- the revision the database is on now, with a loud warning if there is none: an empty answer means no version row, and an upgrade would try to start from the beginning of history
- the heads, and the revisions that would run, oldest first, so you read the plan before it happens instead of being told afterwards
- a check that the container can actually see the target revision
- two runs against the same environment never overlap
Alembic multiple heads: why they happen and how we merge them
Two branches each add a migration on top of the same parent. Each branch is a clean, single-headed chain on its own, so each passes its own checks. Merge both and the graph has two heads, and `alembic upgrade head` refuses to choose between them. With several people changing the schema at once, this happens often.
We catch it in CI with a small script that uses only the standard library and needs no database. It reads the `revision` and `down_revision` of every file and fails unless there is exactly one head and no `down_revision` pointing at a file that does not exist. On a pull request it runs against the merge of the branch and the current base, so a branch that has fallen behind sees the other head.
The fix is an empty merge revision whose `down_revision` is a tuple of the heads. It changes nothing in the database and only joins the graph. The alternative is to rebase one migration onto the other, which is simpler while neither has been applied anywhere. Once a revision has run in an environment, rewriting its parent is not safe, so we join instead. A merge revision is a revision like any other: it has to be applied, and it becomes the head the deploy guard compares against.
# alembic/versions/xxxx_join_heads.py
revision = "join_heads_1"
down_revision = ("add_viewing_index", "add_note_column") # the two heads
def upgrade():
pass # joins the graph, changes nothing in the database
def downgrade():
passWhat alembic stamp does, and why we almost never use it
`alembic stamp` records a revision as applied without running it. Our workflow exposes it as an optional input, and the input's own description is a warning. Use it only for a revision that changes no schema and must not run in that environment, such as a one-off data cleanup written for a different environment. Stamping a revision that does change the schema leaves the database claiming a shape it does not have.
The same reasoning rules out a shortcut for fresh installs. We do not build a local database with `create_all` and then stamp head, because some tables exist only as raw SQL inside migrations and the result would be silently incomplete. An empty database goes through `alembic upgrade head`, and the README documents that path. Our finance runbook puts the production rule in two words: never stamp.
What makes a migration safe on a live Postgres database
Most of the safety is in how each migration is written. These are the habits we have settled on, and each one is visible in the repository:
- Additive first. A new nullable column or a new table can be applied while the old code is still serving, because the old code does not know it exists.
- Idempotent. `ADD COLUMN IF NOT EXISTS` and `CREATE INDEX IF NOT EXISTS` mean a re-run, or a run after someone applied part of it by hand, does no harm.
- A short lock timeout. `SET lock_timeout = '5s'` makes the migration give up instead of queuing for a lock, because a queued `ALTER TABLE` can block every query that arrives behind it.
- Indexes built concurrently. `CREATE INDEX CONCURRENTLY` does not block writes, but it cannot run inside a transaction, so it goes in Alembic's `autocommit_block`. If a build is interrupted Postgres leaves an invalid index of the same name, which `IF NOT EXISTS` then skips: drop it and run again.
- Constraints in two steps. Add a `CHECK` as `NOT VALID`, then `VALIDATE` it separately, so existing rows are checked without a heavy lock.
def upgrade():
op.execute("SET lock_timeout = '5s'")
op.execute("ALTER TABLE viewings ADD COLUMN IF NOT EXISTS reminded_at TIMESTAMPTZ")
# CONCURRENTLY cannot run inside a transaction block
with op.get_context().autocommit_block():
op.execute(
"CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_viewings_reminded_at "
"ON viewings (reminded_at)"
)How we handle data backfills in a migration
Backfills need more care than schema changes. A migration that rewrites data should not import application code. It runs inside the container that is already running, which does not yet contain the new code, and a migration should not change behaviour when the application code changes later. One of ours embeds a frozen copy of its planning logic for exactly that reason, and ships with a dry-run report that is read before the migration is applied.
Reversibility is stated, not assumed. Some downgrades delete data, and the migration or runbook says so, with a database snapshot taken first. One drop migration is marked irreversible because it cannot recreate what it removed.
Zero-downtime migrations: what we claim and what we do not
We do not claim zero downtime. The production deploy recreates the backend container, so there is a short restart during which requests can fail. What the process does give us is narrower and real: a migration applied before the code is merged, that holds no long locks, and that the version of the code still running can survive.
Destructive changes follow a different order. We add the new shape, ship the code that uses it, and drop the old one only once nothing reads it. One of our drop migrations records that check in its docstring, and it inspects the catalogue first, because `ALTER TABLE ... IF EXISTS` still queues for an exclusive lock even when there is nothing to drop.
Two lessons came from mistakes. Do not edit a revision that has been applied anywhere: one of ours kept its id when its content changed, so a database already stamped at the first version never received the new columns that the application then selected on every read. Add a new revision instead. And read the dry run: the no-current-revision warning exists because an empty answer is the one result that looks like success.
Where this fits in Propily
This process is how schema changes reach the database behind Propily, the CRM we build for UK estate and letting agencies. If you want to see the product rather than the plumbing, the real estate CRM page covers what it does, and a demo is the place to see it on your own data.
Questions people ask
How do I fix Alembic multiple heads?
Run `alembic heads` to see them, then either create a merge revision with `alembic merge` and the heads, or rebase one migration onto the other. A merge revision has a tuple for `down_revision`, does nothing in the database, and leaves one head for `alembic upgrade head`.
What does alembic stamp do?
It writes a revision into the version table without running its migration. Use it only for a revision that changes no schema, or to tell Alembic about a database whose schema already matches. Stamping a revision that does change the schema leaves the database claiming a shape it does not have.
Should Alembic migrations run automatically on deploy?
It depends on how much you trust review and rollback. We do not run them on deploy: we apply them with a manual, logged workflow before the code is merged, and the production deploy refuses to proceed if the database is behind.
Can Alembic do zero-downtime migrations?
Alembic only runs the SQL you write, so it depends on that SQL. Additive changes, a short lock timeout and concurrent index builds avoid long locks. We do not claim zero downtime for the deploy that follows a migration.