Data & Access Control · 7 min read

Postgres migrations: why reset lock_timeout after SET?

Background: what lock_timeout is for

AllyOS is the business system I built with Claude Code and a team of AI agents. It runs on PostgreSQL, and every schema change ships as a migration file, a SQL script applied in order. As of 2026-12-04 the repository holds 1,671 of them.

Changing a table, for example adding a column, needs an exclusive lock on it. If a long query is holding that table, the migration waits in line. Worse, every ordinary query that arrives after the migration waits behind it, so from the outside the whole table looks frozen.

Think of a checkout lane: one person wants to close the lane to mop it, so they wait for the current shoppers to leave, and everybody who lines up behind them is stuck too.

lock_timeout puts a ceiling on that wait. set lock_timeout = '5s'; means "if you cannot get the lock in five seconds, give up." A failed deploy you can retry beats a stalled production database. The setting is documented under client connection defaults in the PostgreSQL manual, and plenty of teams use it.

The trouble is its scope. I hit two traps with it in AllyOS, and here is what they are and the guard that now catches them.

Why must SET be followed by RESET?

Short answer: a plain SET lasts until the connection ends or something undoes it. Without a reset, every later statement in the same migration file inherits the five-second ceiling, including statements that should wait their turn.

The classic case: a migration adds a column (fast, so five seconds is right), then backfills old rows into it. The backfill touches many rows; if one row is locked by another transaction, waiting a few seconds would be fine. But it inherited the limit, so it is cancelled, the deploy fails, and the statement that failed is the one nobody meant to limit.

I checked it on a local PostgreSQL 16.15 (table names generalized for this post). A second session locked one row of orders for eight seconds; one second later I ran the migration:

set lock_timeout = '5s';
alter table customers add column tier text;  -- DDL: failing fast is right
reset lock_timeout;                          -- drop this line and the next one gets cancelled
update orders set note = 'backfilled';       -- backfill: should wait its turn
  • Without reset: the backfill failed at 5.03 s with "canceling statement due to lock timeout", taking the migration down with it.
  • With reset: the backfill waited for the other session, finished at 7.04 s, UPDATE 1000.

Two shapes are both fine, depending on what the ceiling protects. To protect one DDL statement, wrap it: set, change, reset. To make every statement in the file fail fast, set it at the top and reset on the last line. The only shape I refuse is a file that ends with the ceiling still in force.

Isn't SET LOCAL simpler?

No. SET LOCAL only lives inside a transaction, and whether your migration runner sends the whole file as one query or one statement per query is invisible to the person writing the file. The two paths give opposite results.

I ran both with psql against the same local database on 2026-12-04:

  • Two statements sent as two queries: set local lock_timeout = '11s'; then show lock_timeout;. Result: a warning, "SET LOCAL can only be used in transaction blocks", and the value is still 0, meaning nothing was set, even though the first line still answered "SET".
  • The same two statements sent as one query: 11s, no warning at all.

Same file, same server, opposite outcome, decided by a protocol detail nobody chose and nobody can see. A plain SET has no such ambiguity: it applies on every path, and a following RESET writes its scope into the file. The SET command reference says the same: SET LOCAL outside a transaction block emits a warning and otherwise has no effect.

One more detail: set lock_timeout = 0; is not a reset. Zero means "no limit", not "back to what this connection had."

Why isn't a written convention enough?

Because people forget. I turned the rule into a guard that runs before every push.

On 2026-12-03 we wrote a one-off data repair migration, the kind that fixes a single bad row in production. The author followed the convention and put set lock_timeout = '5s'; at the top, then forgot the reset at the end. A two-line follow-up commit added it three minutes later. On 2026-12-04 I fed the earlier version back to the guard, and it pointed at line 27, the unpaired set.

The core idea (generalized): blank out comments, string literals and function bodies, look only at top-level statements, find the last set lock_timeout, and check that a reset follows it.

RESETS = {"reset lock_timeout", "reset all", "discard all",
          "set lock_timeout to default"}

def unreset_line(sql: str):
    stmts = split_top_level(strip_comments_strings_bodies(sql))
    last = None
    for i, (line, stmt) in enumerate(stmts):
        if is_session_set(stmt, "lock_timeout"):
            last = i
    if last is None:
        return None
    later = [s for _, s in stmts[last + 1:]]
    return None if any(normalize(s) in RESETS for s in later) else stmts[last][0]

Why blank function bodies? create function ... set lock_timeout = '2s' configures that function's calls, not the current session, and a set local inside a function body runs in its caller's transaction, where it is correct. Skip that step and the guard cries wolf.

What about old files that already got it wrong?

Applied migrations must not be edited, so they go on a baseline list, and the list is only allowed to shrink.

When the rule went live on 2026-10-07, 28 of 922 migrations ended with the ceiling still set, and the count was growing by about one file a day. The mechanics:

  1. Those 28 files go on the baseline list, and the guard lets them through.
  2. If a listed file turns out to be fine, or no longer exists, the guard fails until the entry is removed.
  3. A ceiling constant in the script must equal the number of entries, and a test pins that constant at 28 or below. Raising it means editing a test, which needs human review.

Re-measured on 2026-12-04: the repository has grown to 1,671 migrations, and the unpaired files are still exactly those 28. Not one new case in two months. It is the same approach I described in adding static analysis to a legacy codebase with a baseline: freeze the old debt, allow no new debt.

Measured numbers

MetricValueHow it was measured
Migration files1,6712026-12-04, counted SQL files in the migrations directory
Migrations with a top-level set lock_timeout6982026-12-04, per-file match after blanking comments, literals and bodies
Files ending with the ceiling still set28 (baseline; 28 of 922 at launch)2026-12-04 guard run and recount; launch figure from the 2026-10-07 rule doc
Guard self-tests39 test functions2026-12-04, counted in the test file
Backfill cancelled without reset5.03 s2026-12-04, local PostgreSQL 16.15, other session held a row lock for 8 s
Backfill finished with reset7.04 s, 1,000 rowssame setup
SET LOCAL sent as separate queriesvalue 0, plus a warning2026-12-04, psql with two -c flags
SET LOCAL sent as one queryvalue 11s, no warning2026-12-04, psql with one -c flag
Migration-adding commits co-authored by AI607 of 671 (about 90%)2026-12-04, co-author trailers on commits adding migrations since 2026-10-07
From missing reset to fix3 minutes, 2-line patch2026-12-04, timestamps and diff size of the two commits

A checklist you can copy

  1. In migrations, use plain set lock_timeout = '5s';, never set local.
  2. Protecting one DDL statement: wrap it with set, change, reset lock_timeout;.
  3. Every statement should fail fast: set at the top, reset on the last line.
  4. Count only reset lock_timeout, reset all, discard all or set lock_timeout to default as a reset; = 0 does not count.
  5. Put statements that should wait (backfills, index builds, constraint validation) after the reset.
  6. Write a guard: blank comments, literals and function bodies, check that the last set is followed by a reset, and run it before push and in CI.
  7. Leave old files alone, list them in a baseline, make "entries = ceiling constant" and pin the ceiling in a test so it only goes down.
  8. Before trusting any of this, test it locally with a second session holding a lock. The explicit locking chapter lists which statement takes which lock.

FAQ

How is lock_timeout different from statement_timeout?

lock_timeout only limits time spent waiting for a lock; once the lock is granted it does not care how long the statement runs. statement_timeout limits the whole statement. To keep a migration from freezing production you want the former. The guard here only checks lock_timeout; I have not measured anything about statement_timeout.

My runner wraps the whole file in a transaction. Do I still need RESET?

Yes. The transaction only means the file's changes commit or roll back together. A plain SET still holds until the end of that transaction, so the backfill at the bottom still gets cut off at five seconds. Writing the reset into the file makes its scope independent of how the runner sends it.

Is a guard worth it for a small team?

If humans write a few dozen migrations a year, a code review checklist item is enough. In AllyOS most migrations are written by AI agents, and more than 700 were added in two months; human eyes alone will miss one. Any rule a machine can check should not live only in a doc. If you want checks like this built into your own team's release process, see services and process.

About the author

Morningstar Lucifer (晨星·路西法) is an AI engineering systems architect based in Chengdu, China, with 12 years in front-end architecture and team leadership. Using Claude Code and a multi-agent development pipeline, he built AllyOS, the system that runs AllyNutra's entire business, in 118 days. He also built TeacherCopilot, a profitable AI product.

Written by the author together with AI. All numbers were measured in the AllyOS repository on the dates shown; code samples and paths are rewritten generic versions to protect client and company information.

Want guardrails like this? Email me The AllyOS case study (in Chinese)