TL;DR
DROP TABLEtakesAccessExclusiveLockon the dropped table and on every table its foreign keys reference.- While it held one referenced table and waited for the next, a worker read them in the opposite order. Deadlock.
- A Flyway
beforeEachMigratecallback now takes all those locks at once withNOWAIT. If it can’t, it releases everything, sleeps briefly, and tries again for up to 30 seconds.
One release, migrate failed with deadlock detected. Running it again failed the same way. The migration was a single DROP TABLE of an old table.
A one-line DROP TABLE stopped the release twice
The setup is common. The backend uses PostgreSQL, and schema changes go in as Flyway migrations. Every deploy runs flyway migrate, and workers keep reading the database the whole time.
The dropped table belonged to a retired feature. I’ll call it legacy_grants. It had foreign keys to members and projects.
DROP TABLE legacy_grants;
PostgreSQL can run a migration inside a transaction, so a failure leaves nothing half-done. Both attempts rolled back and the database was unchanged. But the release didn’t move.
DROP TABLE also takes the strongest lock on the referenced tables
DROP TABLE drops the foreign key constraints with the table. Dropping a constraint removes its triggers from the referenced table, so the referenced table gets an AccessExclusiveLock too. That lock conflicts even with the AccessShareLock a plain SELECT takes.
On a local PostgreSQL 17, pg_locks right after DROP TABLE showed AccessExclusiveLock on every referenced table.
The locks are taken one by one. In production it jammed in this order:
When a lock wait passes deadlock_timeout (1 second by default), PostgreSQL checks for deadlocks. migrate had started waiting first, so it ran the check and was aborted. The worker finished its read as if nothing happened.
Neither lock_timeout nor a fixed read order was enough
I tried the usual advice first.
Set lock_timeout. A short lock_timeout before schema changes is the standard way to keep a lock wait from stalling the service. But if it is longer than deadlock_timeout, the deadlock aborts the transaction before the timeout fires. Locally, with 3 seconds, I still got deadlock detected.
With 800ms it fails with LockNotAvailable instead. Flyway does not retry that, so something outside has to rerun migrate. And while it waits, workers that arrive later queue up behind migrate.
Just rerun it. The transaction makes that safe, but success depends on worker timing. It failed twice in a row.
Make workers read in one order. Code that reads members and projects is everywhere. Keeping all of it in one order is not realistic.
Add LOCK TABLE to the migration file. Flyway records checksums of applied migrations. Where DROP TABLE is already applied, changing the file makes validate fail.
Taking every lock up front in beforeEachMigrate
One condition for a deadlock is “hold a lock while waiting for the next one”. So I made migrate never wait.
Flyway’s beforeEachMigrate callback runs SQL right before each migration. There I take the locks on the dropped table and its referenced tables in one statement, with NOWAIT.
DO $$
DECLARE
deadline timestamptz := clock_timestamp() + interval '30 seconds';
BEGIN
LOOP
BEGIN
LOCK TABLE legacy_grants, members, projects
IN ACCESS EXCLUSIVE MODE NOWAIT;
RETURN;
EXCEPTION WHEN lock_not_available THEN
IF clock_timestamp() >= deadline THEN
RAISE;
END IF;
END;
PERFORM pg_sleep(0.05 + random() * 0.1);
END LOOP;
END;
$$;
Three points:
NOWAITreturns an error instead of waiting when a lock is not available.- A
BEGINblock withEXCEPTIONis a subtransaction. When the error rolls the block back, any locks taken inside it are released too. The next try starts holding nothing. - Tries are spaced with jitter, and it gives up after 30 seconds.
The real callback reads the tables from pg_constraint: the dropped table plus its foreign key targets, ordered by oid. If the table to drop is already gone, it does nothing.
From the worker’s side, migrate backs off right away, so reads never queue behind it. Once every lock is held, DROP TABLE has nothing new to wait for and commits at once. In the local reproduction, the worker’s reads returned immediately and migrate went on to commit.
Pinning with a test that the callback’s locks last until DROP TABLE
This only works if the callback and the migration run in the same transaction. In separate transactions, the locks would be gone when the callback ends.
Flyway’s docs disagree on this. The Event API reference says BEFORE_EACH_MIGRATE runs “within the same transaction (if any)” as the migration. The SQL callbacks page says callbacks are “executed in their own transactions”.
So I added a test pinned to the production versions of Flyway and PostgreSQL. It runs migrate while a worker is reading members, and checks that the worker can still read projects and that DROP TABLE completes after the worker commits. If a Flyway upgrade breaks the assumption, this test fails.
While the old table exists, the same locks are taken before other migrations too. Once the table is gone, the callback does nothing.