Runs a DDL on a hot Postgres table and limits how long the table can be paused.
It comes as a Ruby gem and as a single binary. Both follow the same steps and talk plain SQL to the server.
Current state: prototype.
DDL locks on busy tables can lead to lock contention.
A DDL such as ALTER TABLE needs a strong lock. While it waits for that lock, every new query on the table queues behind it. On a busy table the queue grows fast, connections pile up and the application slows down or fails.
The usual answer is to ask for the lock with a short timeout and retry. Each request still stops the table for a moment. After hundreds of requests the migration gives up without running, and the contention happened anyway.
Think of a bridge that needs a quick repair. The cars are the queries. The repair event is the DDL.
To do the repair, the worker lowers the gate. No new car gets in, and he waits for the cars already on the bridge to leave. Then he performs the repair and reopens the bridge. Lowering the gate that blocks the bridge is the "strong lock".
The problem is a slow truck in the middle of the bridge. That is a long transaction. If the worker lowers the gate while the truck is there, he needs to wait for the truck to pass. Meanwhile the cars pile up at the gate.
The usual fix is to go to the entrance of the bridge and lower the gate. If a slow vehicle is still crossing and it takes too long, the worker raises the gate and returns later to try again. Every attempt piles up cars, and the truck is still there.
lockwise does this instead.
- The worker watches the bridge. Is there a slow truck? Then he waits, away from the entrance. Cars keep crossing.
- When only fast cars are left, he hangs a sign at the entrance, "maintenance scheduled". The sign is the weak lock. Cars ignore it and keep crossing. The sign is for other maintenance crews. The street sweeper, which is autovacuum, leaves the bridge and stays away. Another worker with another repair waits for his turn.
- He looks at the bridge once more and lowers the gate. The cars on the bridge leave in a moment. He performs the repair and reopens the bridge.
The gate still goes down once. It stays down for a short time, because the worker chose the moment.
It does four things, in this order.
- Looks before it asks. It checks who is using the table and for how long. If there is a long transaction, it waits for it to end. During this wait it holds no lock and no transaction. The table keeps working.
- Takes a weak lock. In one short transaction it takes
SHARE UPDATE EXCLUSIVE. This lock does not block reads or writes. It moves autovacuum out of the way and puts DDLs in a queue. - Looks once more. With the weak lock held, it checks the table again. If another session waits behind the weak lock, or a transaction has become long, it releases everything and starts again.
- Runs the DDL with a deadline. The DDL asks for its own operational lock. If the lock comes in time, the DDL runs and everything is released. If it does not, lockwise releases everything, waits a moment and starts again. If a gap never shows up, it gives up and tells you who is blocking.
With an autovacuum on the table. A regular autovacuum holds the same kind of lock, so the weak lock request queues behind it. When deadlock_timeout passes, Postgres takes the autovacuum off the table and gives the weak lock to lockwise. Traffic is not paused while this happens.
The cancel is Postgres behaviour. lockwise only waits. It sends no signal and needs no special privilege. From there the flow is the same, and the DDL runs in the transaction that already holds the weak lock.
With an anti-wraparound vacuum on the table. Postgres does not cancel this one. lockwise waits for it to end before it asks for any lock.
With two runs on the same table. Each run takes an advisory lock per table and keeps it until it ends. The runs go one at a time, in order of arrival.
flowchart TD
start([Start]) --> age{Table needs a freeze?}
age -- yes --> refused([Throw an error and stop])
age -- no --> turn[Wait for its turn on the table]
turn --> look[Look at who is using the table. No lock held]
look --> long{Long transaction or anti-wraparound vacuum?}
long -- yes --> wait[Wait for it to end. Traffic keeps running]
wait --> look
wait -. time is up .-> gaveup([Throw an error with the name and pid of the blockers])
long -- no --> ask[Open a short transaction. Ask for the weak lock, SHARE UPDATE EXCLUSIVE]
ask --> vacuum{Autovacuum on the table?}
vacuum -- yes --> cancel[Wait for deadlock_timeout. Postgres cancels the autovacuum]
cancel --> weak[Weak lock taken]
vacuum -- no --> weak
weak --> again{Someone waiting behind the weak lock, or a new long transaction?}
again -- yes --> release[Release everything and wait a moment]
again -- no --> ddl[Run the DDL with a deadline. The DDL asks for its own operational lock]
ddl --> got{Lock in time?}
got -- yes --> done([Commit. Success])
got -- no --> release
release --> look
release -. too many attempts .-> gaveup
The weak lock is SHARE UPDATE EXCLUSIVE. It conflicts with itself and with every stronger lock. The locks that traffic uses are weaker, so traffic passes.
These run while lockwise holds the weak lock.
| Operation | Lock it uses |
|---|---|
SELECT, COPY TO, pg_dump |
ACCESS SHARE |
REFRESH MATERIALIZED VIEW CONCURRENTLY of a view that reads the table |
ACCESS SHARE |
SELECT ... FOR UPDATE |
ROW SHARE |
INSERT, UPDATE, DELETE, MERGE |
ROW EXCLUSIVE |
These wait until lockwise releases the weak lock.
| Operation | Lock it uses |
|---|---|
VACUUM, ANALYZE |
SHARE UPDATE EXCLUSIVE |
CREATE INDEX CONCURRENTLY, REINDEX CONCURRENTLY, DROP INDEX CONCURRENTLY |
SHARE UPDATE EXCLUSIVE |
VALIDATE CONSTRAINT, CREATE STATISTICS |
SHARE UPDATE EXCLUSIVE |
CREATE INDEX |
SHARE |
CREATE TRIGGER, adding a foreign key |
SHARE ROW EXCLUSIVE |
ALTER TABLE ADD COLUMN, TRUNCATE, DROP TABLE, VACUUM FULL, CLUSTER, REINDEX TABLE |
ACCESS EXCLUSIVE |
A regular autovacuum does not wait. It skips the table. The DDL that lockwise runs is not blocked either, because it runs in the transaction that holds the weak lock.
- The long wait holds nothing. While it waits for long transactions, lockwise has no lock, no transaction, no XID and no snapshot. Vacuum and other maintenance keep running.
- The weak lock is held for seconds. A transaction that holds only the weak lock has no transaction ID. It does not hold back the vacuum horizon and does not grow the snapshots of other sessions.
- The wait does not block traffic. Reads and writes keep running, and their locks stay on the fast path.
- Autovacuum yields by itself. A regular autovacuum on the table is cancelled after
deadlock_timeout. No extra privilege is needed. - An anti-wraparound vacuum finishes first. lockwise waits for it with no lock, and refuses a table that needs a freeze.
- DDLs run in order. Two runs on the same table go one at a time, in order of arrival.
- The DDL takes only the lock it needs. A foreign key stops writes for a moment and lets reads run.
- The pause has a limit. A lock request waits for at most
max_pause, and always less thandeadlock_timeout, so no session is ended by a deadlock with the DDL. - The transaction has a limit. If the migration hangs, Postgres ends the transaction after
max_transaction_timeand releases the locks. - Blockers are named. When it gives up, lockwise lists the sessions in the way.
- The strong lock request takes an XID. A request for
ACCESS EXCLUSIVEgets a transaction ID before it waits. While it waits, that XID grows the snapshots of other sessions and holds back the vacuum horizon. This also applies to a strong lock request from another session that waits behind the weak lock. - A strong lock request behind the weak lock queues traffic. If another session asks for a strong lock while lockwise holds the weak lock, new queries queue behind that request. lockwise looks for such a request before the DDL and starts over when it finds one. A request that arrives after that look waits until the DDL ends.
- Maintenance on the table waits. While the weak lock is held,
VACUUM,ANALYZEandCREATE INDEX CONCURRENTLYon that table wait. This lasts a few seconds. - Each attempt cancels a regular autovacuum again. The number of attempts is limited by
max_attempts. - A run that waits for its turn holds a snapshot. When two runs share a table, the second one waits on an advisory lock. During that wait it holds back the vacuum horizon, for at most
max_runtime. - The table is still paused. The pause lasts until the transactions in flight end, up to
max_pause. A request that times out pauses the table too.
What kind of transaction gets in the way?
Any transaction that holds a lock on the table and stays open. A long job, an idle in transaction session, a long read.
What happens when an autovacuum is running on the table?
lockwise asks for SHARE UPDATE EXCLUSIVE and waits. After deadlock_timeout, Postgres cancels the autovacuum and lockwise gets the lock. Reads and writes keep running during that wait. Then lockwise runs the DDL, which asks for its own lock in the same transaction.
Does lockwise cancel the autovacuum?
No. Postgres does. A session that waits for a lock longer than deadlock_timeout and finds a regular autovacuum in its way makes Postgres cancel that autovacuum. lockwise sends no cancel command and needs no extra privilege.
Autovacuum only yields after deadlock_timeout. How is this different from a retry with a short lock_timeout?
A retry asks for the strong lock, so it has to give up fast, usually before deadlock_timeout, and the autovacuum never yields. lockwise waits on the weak lock, which does not queue traffic, so it can wait longer than deadlock_timeout.
What is deadlock_timeout?
A Postgres setting. It is how long a session waits for a lock before it checks for a deadlock. The default is 1 second.
What about an anti-wraparound vacuum?
Postgres never cancels it. lockwise waits for it to end, holding no lock, and then goes on. If the time runs out first, it gives up with the reason wraparound_vacuum and names the vacuum as the blocker.
What about a table that needs a freeze?
lockwise reads the age of the table, of its partitions and of its TOAST table before it asks for any lock. Above max_table_age it does not try, and raises Lockwise::TableMaxAgeReachedError. The vacuum of that table has to run first.
What happens when two migrations run on the same table at the same time?
The second one waits for the first one to end. Each run holds an advisory lock per table, so they go one at a time, in order of arrival.
Can the DDL end a session of the application with a deadlock?
A lock request of the DDL waits for less than deadlock_timeout. It gives up before Postgres looks for a deadlock, and lockwise tries again later.
What does a cancelled autovacuum cost?
It starts over the next time. On a table where a vacuum takes hours, that is expensive. Lower autovacuum thresholds on the busiest tables make each run shorter, so a cancelled run costs less.
Does it help when the traffic is only fast queries?
The strong lock request still waits for the transactions in flight. With only fast queries, that wait is short.
gem 'lockwise', git: 'https://gitlab.com/l.rosa/lockwise', glob: 'ruby/*.gemspec'Pass the connection and the table, and run the DDL in the block. In a Rails migration the transaction belongs to lockwise, so the migration turns its own off.
class AddNoteToAccounts < ActiveRecord::Migration[8.0]
disable_ddl_transaction!
def up
Lockwise.with_lock(connection, 'accounts') do
add_column :accounts, :note, :text
end
end
endThe connection can be an ActiveRecord connection or a PG::Connection.
The block can run more than once. When its lock request times out, lockwise rolls the transaction back and calls the block again. Keep only the DDL in it.
Pass a list. lockwise takes the weak lock on all of them and waits for long transactions on any of them.
Without an option, the DDL asks for its own strong lock, and Postgres chooses the order of the tables.
To choose the order yourself, use one of the _in_order options. lockwise then takes that lock before the block runs, on the tables in the order of the list. Put the busiest table first.
Lockwise.with_lock(connection, %w[owners accounts], share_row_exclusive_in_order: true) { ... }
# locks owners first, then accounts| Option | Who takes the strong lock | Lock | Order of the tables |
|---|---|---|---|
| none | the DDL | the one it needs | chosen by Postgres |
share_row_exclusive_in_order: true |
lockwise, before the block | SHARE ROW EXCLUSIVE |
the order of the list |
access_exclusive_in_order: true |
lockwise, before the block | ACCESS EXCLUSIVE |
the order of the list |
Use share_row_exclusive_in_order to add a foreign key or create a trigger. Use access_exclusive_in_order to remove a foreign key or swap two tables.
Adding a foreign key needs SHARE ROW EXCLUSIVE on both tables. Reads keep running.
class AddOwnerForeignKeyToAccounts < ActiveRecord::Migration[8.0]
disable_ddl_transaction!
def up
Lockwise.with_lock(connection, %w[owners accounts], share_row_exclusive_in_order: true) do
add_foreign_key :accounts, :owners, validate: false
end
validate_foreign_key :accounts, :owners
end
endRemoving a foreign key needs ACCESS EXCLUSIVE on both tables.
class RemoveOwnerForeignKeyFromAccounts < ActiveRecord::Migration[8.0]
disable_ddl_transaction!
def up
Lockwise.with_lock(connection, %w[owners accounts], access_exclusive_in_order: true) do
remove_foreign_key :accounts, :owners
end
end
end| Option | Default | Meaning |
|---|---|---|
max_pause |
3.0 |
the longest a lock request of the DDL may wait, in seconds |
max_runtime |
120.0 |
total time before giving up, in seconds |
max_attempts |
6 |
how many times it takes the weak lock before giving up |
cooldown |
10.0 |
time between attempts, in seconds |
poll |
0.2 |
how often it looks at the blockers, in seconds |
max_transaction_time |
60.0 |
the longest the transaction with the locks may last, in seconds |
max_table_age |
1_000_000_000 |
the oldest a table may be, in transactions |
The value that matters most is max_pause. A shorter pause does less harm and needs a larger gap in traffic. lockwise keeps the pause at 90% of the deadlock_timeout of the server or less.
Lockwise.with_lock(connection, 'accounts', max_pause: 1, max_runtime: 300) do
add_column :accounts, :note, :text
end| Error | When |
|---|---|
Lockwise::GaveUpError |
The time or the attempts ran out. reason says why and blockers lists the sessions in the way. |
Lockwise::TableMaxAgeReachedError |
A table is older than max_table_age. table and age say which one. |
Lockwise::TransactionOpenError |
The connection was already in a transaction. |
The reason of a GaveUpError is one of these.
| Reason | What was in the way |
|---|---|
another_run |
another lockwise run on the same table |
long_blockers |
a long transaction that did not end |
wraparound_vacuum |
an anti-wraparound vacuum that did not end |
prelock_timeout |
a session that kept the weak lock from being taken |
waiters_behind_weak_lock |
a session that waited behind the weak lock |
attempt_failed |
the DDL did not get its lock, and there was no time for another attempt |
attempts_exhausted |
all the max_attempts attempts failed |
cd rust
cargo build --release
target/release/lockwise run \
--conn "host=localhost user=migrator dbname=app" \
--preset presets/c1-window-3000ms.toml \
--table accounts \
--sql "ALTER TABLE accounts ADD COLUMN note text"Repeat --table for several tables. Add --share-row-exclusive or --access-exclusive to take that lock before the SQL runs, on the tables in the order given.
The preset is a TOML file with the same settings as the gem.
name = "c1-window-3000ms"
max_runtime_s = 120
[window]
max_pause_ms = 3000
cooldown_ms = 10000
poll_ms = 200
prelock_hold_s = 60The binary writes one JSON event per line.
| Event | Meaning |
|---|---|
queued |
Started. |
prelocked |
Got the weak lock. |
waiting |
Waiting. Lists who is blocking. |
acquired |
The SQL got its lock and ran. |
result |
Finished, with success or gave up. |
The exit code is 0 for success, 2 for gave up and 1 for error.
The database user needs the pg_monitor role, to see the transactions of other users. Use a direct connection to Postgres, because lockwise keeps a session lock for the whole run.
rust/bin/test # the binary
ruby/bin/test # the gemEach script starts a throwaway Postgres and runs the tests against it. They look for the Postgres binaries in ~/.local/share/mise/installs/postgres/17.8/bin. Set PG_ROOT and VER to use another location.


